<template>
  <div class="classes-page">
    <a-card class="mb-4">
      <template #title>班级管理</template>
      <template #extra>
        <a-space>
          <a-select
            v-model:value="searchParams.gradeId"
            placeholder="选择年级"
            allow-clear
            style="width: 150px"
            @change="handleSearch"
          >
            <a-select-option
              v-for="grade in gradeOptions"
              :key="grade.id"
              :value="grade.id"
            >
              {{ grade.name }}
            </a-select-option>
          </a-select>
          <a-select
            v-model:value="searchParams.type"
            placeholder="选择类型"
            allow-clear
            style="width: 120px"
            @change="handleSearch"
          >
            <a-select-option :value="1">行政班级</a-select-option>
            <a-select-option :value="2">兴趣班</a-select-option>
          </a-select>
          <a-button
            v-permission="'class:create'"
            type="primary"
            @click="handleAdd"
            >新增班级</a-button
          >
        </a-space>
      </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 === 'grade'">
          <span>{{ record.grade?.name || "-" }}</span>
        </template>
        <template v-if="column.key === 'type'">
          <a-tag :color="record.type === 1 ? 'blue' : 'green'">
            {{ record.type === 1 ? "行政班级" : "兴趣班" }}
          </a-tag>
        </template>
        <template v-if="column.key === 'studentCount'">
          <span v-if="record.type === 1"
            >{{ record._count?.students || 0 }}人</span
          >
          <span v-else>{{ record._count?.studentInterestClasses || 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="'class:update'"
              type="link"
              size="small"
              @click="handleEdit(record)"
            >
              编辑
            </a-button>
            <a-button
              v-permission="'class: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="gradeId">
          <a-select
            v-model:value="form.gradeId"
            placeholder="请选择年级"
            :options="gradeOptions"
            :loading="gradesLoading"
          />
        </a-form-item>
        <a-form-item label="班级名称" name="name">
          <a-input
            v-model:value="form.name"
            placeholder="请输入班级名称，如：一年级1班"
            :maxlength="50"
          />
        </a-form-item>
        <a-form-item label="班级编码" name="code">
          <a-input
            v-model:value="form.code"
            placeholder="请输入班级编码"
            :maxlength="50"
          />
        </a-form-item>
        <a-form-item label="班级类型" name="type">
          <a-radio-group v-model:value="form.type">
            <a-radio :value="1">行政班级</a-radio>
            <a-radio :value="2">兴趣班</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="班级容量" name="capacity">
          <a-input-number
            v-model:value="form.capacity"
            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, onMounted } from "vue"
import { message, Modal } from "ant-design-vue"
import type { TableColumnsType, FormInstance } from "ant-design-vue"
import {
  classesApi,
  type Class,
  type CreateClassForm,
  type UpdateClassForm,
} from "@/api/classes"
import { gradesApi, type Grade } 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 gradesLoading = ref(false)
const gradeOptions = ref<Array<{ label: string; value: number }>>([])

const searchParams = reactive<{ gradeId?: number; type?: number }>({})

const {
  loading,
  dataSource,
  pagination,
  handleTableChange,
  refresh: refreshList,
  search,
} = useListRequest<Class, { gradeId?: number; type?: number }>({
  requestFn: classesApi.getList,
  errorMessage: "获取班级列表失败",
  defaultSearchParams: {},
})

const form = reactive<CreateClassForm>({
  gradeId: 0,
  name: "",
  code: "",
  type: 1,
  capacity: undefined,
  description: "",
})

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

const columns: TableColumnsType = [
  { title: "ID", dataIndex: "id", key: "id", width: 80 },
  { title: "年级", key: "grade", width: 120 },
  { title: "班级名称", dataIndex: "name", key: "name" },
  { title: "班级编码", dataIndex: "code", key: "code" },
  { title: "班级类型", dataIndex: "type", key: "type", width: 120 },
  { title: "学生数量", key: "studentCount", width: 100 },
  { title: "容量", dataIndex: "capacity", key: "capacity", width: 80 },
  { 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 fetchGrades = async () => {
  gradesLoading.value = true
  try {
    const response = await gradesApi.getList({ page: 1, pageSize: 100 })
    gradeOptions.value = response.list.map((grade: Grade) => ({
      label: grade.name,
      value: grade.id,
    }))
  } catch (error) {
    message.error("获取年级列表失败")
  } finally {
    gradesLoading.value = false
  }
}

const handleSearch = () => {
  search(searchParams)
}

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

  modalTitle.value = "新增班级"
  editingId.value = null
  modalVisible.value = true
  nextTick(() => {
    formRef.value?.resetFields()
    form.gradeId = 0
    form.name = ""
    form.code = ""
    form.type = 1
    form.capacity = undefined
    form.description = ""
  })
}

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

  try {
    const detail = await classesApi.getDetail(record.id)
    form.gradeId = detail.gradeId
    form.name = detail.name
    form.code = detail.code
    form.type = detail.type
    form.capacity = detail.capacity || undefined
    form.description = detail.description || ""
  } catch (error) {
    message.error("获取班级详情失败")
    modalVisible.value = false
  }
}

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

  Modal.confirm({
    title: "确认删除",
    content: `确定要删除班级 "${record.name}" 吗？删除前需先转移或删除所有学生。`,
    okText: "确定",
    okType: "danger",
    cancelText: "取消",
    onOk: async () => {
      try {
        await classesApi.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 classesApi.update(editingId.value, form as UpdateClassForm)
      message.success("编辑成功")
    } else {
      await classesApi.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()
}

onMounted(() => {
  fetchGrades()
})
</script>

<style scoped></style>
