<template>
  <div class="grades-page">
    <a-card class="mb-4">
      <template #title>年级管理</template>
      <template #extra>
        <a-button
          v-permission="'grade:create'"
          type="primary"
          @click="handleAdd"
          >新增年级</a-button
        >
      </template>
    </a-card>
    <a-table
      :columns="columns"
      :data-source="dataSource"
      :loading="loading"
      :pagination="pagination"
      @change="handleTableChange"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'level'">
          <a-tag color="blue">{{ record.level }}级</a-tag>
        </template>
        <template v-if="column.key === 'classCount'">
          <span>{{ record._count?.classes || 0 }}个班级</span>
        </template>
        <template v-if="column.key === 'validState'">
          <a-tag :color="record.validState === 1 ? 'green' : 'red'">
            {{ record.validState === 1 ? "有效" : "失效" }}
          </a-tag>
        </template>
        <template v-if="column.key === 'createTime'">
          <span>{{ formatDate(record.createTime) }}</span>
        </template>
        <template v-if="column.key === 'action'">
          <a-space>
            <a-button
              v-permission="'grade:update'"
              type="link"
              size="small"
              @click="handleEdit(record)"
            >
              编辑
            </a-button>
            <a-button
              v-permission="'grade:delete'"
              type="link"
              size="small"
              danger
              @click="handleDelete(record)"
            >
              删除
            </a-button>
          </a-space>
        </template>
      </template>
    </a-table>

    <!-- 新增/编辑年级弹窗 -->
    <a-modal
      v-model:open="modalVisible"
      :title="modalTitle"
      :confirm-loading="submitLoading"
      @ok="handleSubmit"
      @cancel="handleCancel"
      width="600px"
    >
      <a-form
        ref="formRef"
        :model="form"
        :rules="rules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
      >
        <a-form-item label="年级名称" name="name">
          <a-input
            v-model:value="form.name"
            placeholder="请输入年级名称，如：一年级"
            :maxlength="50"
          />
        </a-form-item>
        <a-form-item label="年级编码" name="code">
          <a-input
            v-model:value="form.code"
            placeholder="请输入年级编码，如：grade_1"
            :maxlength="50"
          />
        </a-form-item>
        <a-form-item label="年级级别" name="level">
          <a-input-number
            v-model:value="form.level"
            placeholder="请输入年级级别，用于排序"
            :min="1"
            style="width: 100%"
          />
        </a-form-item>
        <a-form-item label="年级描述" name="description">
          <a-textarea
            v-model:value="form.description"
            placeholder="请输入年级描述"
            :rows="3"
            :maxlength="500"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick } from "vue"
import { message, Modal } from "ant-design-vue"
import type { TableColumnsType, FormInstance } from "ant-design-vue"
import {
  gradesApi,
  type Grade,
  type CreateGradeForm,
  type UpdateGradeForm,
} from "@/api/grades"
import { useListRequest } from "@/composables/useListRequest"
import { useAuthStore } from "@/stores/auth"

const authStore = useAuthStore()

const submitLoading = ref(false)
const modalVisible = ref(false)
const modalTitle = ref("新增年级")
const formRef = ref<FormInstance>()
const editingId = ref<number | null>(null)

const {
  loading,
  dataSource,
  pagination,
  handleTableChange,
  refresh: refreshList,
} = useListRequest<Grade>({
  requestFn: gradesApi.getList,
  errorMessage: "获取年级列表失败",
})

const form = reactive<CreateGradeForm>({
  name: "",
  code: "",
  level: 1,
  description: "",
})

const rules = {
  name: [{ required: true, message: "请输入年级名称", trigger: "blur" }],
  code: [
    { required: true, message: "请输入年级编码", trigger: "blur" },
    {
      pattern: /^[a-zA-Z][a-zA-Z0-9_]*$/,
      message: "编码只能包含字母、数字和下划线，且必须以字母开头",
      trigger: "blur",
    },
  ],
  level: [{ required: true, message: "请输入年级级别", trigger: "blur" }],
}

const columns: TableColumnsType = [
  { title: "ID", dataIndex: "id", key: "id", width: 80 },
  { title: "年级名称", dataIndex: "name", key: "name" },
  { title: "年级编码", dataIndex: "code", key: "code" },
  { title: "年级级别", dataIndex: "level", key: "level", width: 100 },
  { title: "班级数量", key: "classCount", width: 120 },
  { title: "状态", dataIndex: "validState", key: "validState", width: 80 },
  { title: "创建时间", dataIndex: "createTime", key: "createTime", width: 180 },
  { title: "操作", key: "action", width: 150, fixed: "right" },
]

const formatDate = (dateStr?: string) => {
  if (!dateStr) return "-"
  const date = new Date(dateStr)
  return date.toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
  })
}

const handleAdd = () => {
  if (!authStore.hasPermission("grade:create")) {
    message.error("您没有创建年级的权限")
    return
  }

  modalTitle.value = "新增年级"
  editingId.value = null
  modalVisible.value = true
  nextTick(() => {
    formRef.value?.resetFields()
    form.name = ""
    form.code = ""
    form.level = 1
    form.description = ""
  })
}

const handleEdit = async (record: Grade) => {
  modalTitle.value = "编辑年级"
  editingId.value = record.id
  modalVisible.value = true

  try {
    const detail = await gradesApi.getDetail(record.id)
    form.name = detail.name
    form.code = detail.code
    form.level = detail.level
    form.description = detail.description || ""
  } catch (error) {
    message.error("获取年级详情失败")
    modalVisible.value = false
  }
}

const handleDelete = (record: Grade) => {
  if (!authStore.hasPermission("grade:delete")) {
    message.error("您没有删除年级的权限")
    return
  }

  Modal.confirm({
    title: "确认删除",
    content: `确定要删除年级 "${record.name}" 吗？删除前需先删除所有班级。`,
    okText: "确定",
    okType: "danger",
    cancelText: "取消",
    onOk: async () => {
      try {
        await gradesApi.delete(record.id)
        message.success("删除成功")
        refreshList()
      } catch (error: any) {
        const errorMessage = error?.response?.data?.message || "删除失败"
        message.error(errorMessage)
      }
    },
  })
}

const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
    submitLoading.value = true

    if (editingId.value) {
      await gradesApi.update(editingId.value, form as UpdateGradeForm)
      message.success("编辑成功")
    } else {
      await gradesApi.create(form)
      message.success("新增成功")
    }

    modalVisible.value = false
    refreshList()
  } catch (error: any) {
    if (error?.errorFields) {
      return
    }
    const errorMessage =
      error?.response?.data?.message ||
      (editingId.value ? "编辑失败" : "新增失败")
    message.error(errorMessage)
  } finally {
    submitLoading.value = false
  }
}

const handleCancel = () => {
  modalVisible.value = false
  formRef.value?.resetFields()
}
</script>

<style scoped></style>
