<template>
  <div class="students-page">
    <a-card class="mb-4">
      <template #title>学生管理</template>
      <template #extra>
        <a-space>
          <a-select
            v-model:value="searchParams.classId"
            placeholder="选择班级"
            allow-clear
            style="width: 200px"
            @change="handleSearch"
          >
            <a-select-option
              v-for="cls in classOptions"
              :key="cls.id"
              :value="cls.id"
            >
              {{ cls.grade?.name }} - {{ cls.name }}
            </a-select-option>
          </a-select>
          <a-button
            v-permission="'student: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 === 'user'">
          <a-space>
            <span>{{ record.user?.nickname || "-" }}</span>
            <span style="color: #999">({{ record.user?.username }})</span>
          </a-space>
        </template>
        <template v-if="column.key === 'class'">
          <span
            >{{ record.class?.grade?.name }} - {{ record.class?.name }}</span
          >
        </template>
        <template v-if="column.key === 'gender'">
          <a-tag v-if="record.gender === 1" color="blue">男</a-tag>
          <a-tag v-else-if="record.gender === 2" color="pink">女</a-tag>
          <span v-else>-</span>
        </template>
        <template v-if="column.key === 'interestClasses'">
          <a-tag v-for="ic in record.interestClasses" :key="ic.id" class="mr-1">
            {{ ic.class.name }}
          </a-tag>
          <span
            v-if="
              !record.interestClasses || record.interestClasses.length === 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 === 'action'">
          <a-space>
            <a-button
              v-permission="'student:update'"
              type="link"
              size="small"
              @click="handleEdit(record)"
            >
              编辑
            </a-button>
            <a-button
              v-permission="'student: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="700px"
    >
      <a-form
        ref="formRef"
        :model="form"
        :rules="rules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
      >
        <template v-if="!editingId">
          <a-form-item label="用户名" name="username">
            <a-input
              v-model:value="form.username"
              placeholder="请输入用户名"
              :maxlength="50"
            />
          </a-form-item>
          <a-form-item label="密码" name="password">
            <a-input-password
              v-model:value="form.password"
              placeholder="请输入密码"
              :maxlength="100"
            />
          </a-form-item>
          <a-form-item label="确认密码" name="confirmPassword">
            <a-input-password
              v-model:value="form.confirmPassword"
              placeholder="请再次输入密码"
              :maxlength="100"
            />
          </a-form-item>
        </template>
        <a-form-item label="昵称" name="nickname">
          <a-input
            v-model:value="form.nickname"
            placeholder="请输入昵称"
            :maxlength="50"
          />
        </a-form-item>
        <a-form-item label="邮箱" name="email">
          <a-input
            v-model:value="form.email"
            placeholder="请输入邮箱"
            :maxlength="100"
          />
        </a-form-item>
        <a-form-item label="行政班级" name="classId">
          <a-select
            v-model:value="form.classId"
            placeholder="请选择行政班级"
            :options="classOptions"
          />
        </a-form-item>
        <a-form-item label="学号" name="studentNo">
          <a-input
            v-model:value="form.studentNo"
            placeholder="请输入学号"
            :maxlength="50"
          />
        </a-form-item>
        <a-form-item label="联系电话" name="phone">
          <a-input
            v-model:value="form.phone"
            placeholder="请输入联系电话"
            :maxlength="20"
          />
        </a-form-item>
        <a-form-item label="性别" name="gender">
          <a-radio-group v-model:value="form.gender">
            <a-radio :value="1">男</a-radio>
            <a-radio :value="2">女</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="出生日期" name="birthDate">
          <a-date-picker
            v-model:value="form.birthDate"
            placeholder="请选择出生日期"
            style="width: 100%"
            value-format="YYYY-MM-DD"
          />
        </a-form-item>
        <a-form-item label="入学日期" name="enrollmentDate">
          <a-date-picker
            v-model:value="form.enrollmentDate"
            placeholder="请选择入学日期"
            style="width: 100%"
            value-format="YYYY-MM-DD"
          />
        </a-form-item>
        <a-form-item label="家长姓名" name="parentName">
          <a-input
            v-model:value="form.parentName"
            placeholder="请输入家长姓名"
            :maxlength="50"
          />
        </a-form-item>
        <a-form-item label="家长电话" name="parentPhone">
          <a-input
            v-model:value="form.parentPhone"
            placeholder="请输入家长电话"
            :maxlength="20"
          />
        </a-form-item>
        <a-form-item label="家庭地址" name="address">
          <a-input
            v-model:value="form.address"
            placeholder="请输入家庭地址"
            :maxlength="200"
          />
        </a-form-item>
        <a-form-item label="兴趣班" name="interestClassIds">
          <a-select
            v-model:value="form.interestClassIds"
            mode="multiple"
            placeholder="请选择兴趣班（可选）"
            :options="interestClassOptions"
            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-item v-if="editingId" label="状态" name="validState">
          <a-radio-group v-model:value="form.validState">
            <a-radio :value="1">有效</a-radio>
            <a-radio :value="2">失效</a-radio>
          </a-radio-group>
        </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 {
  studentsApi,
  type Student,
  type CreateStudentForm,
  type UpdateStudentForm,
} from "@/api/students"
import { classesApi, type Class } from "@/api/classes"
import { useListRequest } from "@/composables/useListRequest"
import { useAuthStore } from "@/stores/auth"
import dayjs, { type Dayjs } from "dayjs"

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 classesLoading = ref(false)
const classOptions = ref<Array<{ label: string; value: number }>>([])
const interestClassOptions = ref<Array<{ label: string; value: number }>>([])

const searchParams = reactive<{ classId?: number }>({})

const {
  loading,
  dataSource,
  pagination,
  handleTableChange,
  refresh: refreshList,
  search,
} = useListRequest<Student, { classId?: number }>({
  requestFn: studentsApi.getList,
  errorMessage: "获取学生列表失败",
  defaultSearchParams: {},
})

const form = reactive<
  CreateStudentForm & {
    confirmPassword?: string
    birthDate?: Dayjs
    enrollmentDate?: Dayjs
    validState?: number
  }
>({
  username: "",
  password: "",
  confirmPassword: "",
  nickname: "",
  email: "",
  avatar: "",
  classId: 0,
  studentNo: "",
  phone: "",
  idCard: "",
  gender: undefined,
  birthDate: undefined,
  enrollmentDate: undefined,
  parentName: "",
  parentPhone: "",
  address: "",
  description: "",
  interestClassIds: [],
  validState: 1,
})

const rules = {
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    {
      pattern: /^[a-zA-Z][a-zA-Z0-9_]*$/,
      message: "用户名只能包含字母、数字和下划线，且必须以字母开头",
      trigger: "blur",
    },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, message: "密码长度不能少于6位", trigger: "blur" },
  ],
  confirmPassword: [
    { required: true, message: "请再次输入密码", trigger: "blur" },
    {
      validator: (_rule: any, value: string) => {
        if (value !== form.password) {
          return Promise.reject("两次输入的密码不一致")
        }
        return Promise.resolve()
      },
      trigger: "blur",
    },
  ],
  nickname: [{ required: true, message: "请输入昵称", trigger: "blur" }],
  email: [{ type: "email", message: "请输入正确的邮箱地址", trigger: "blur" }],
  classId: [{ required: true, message: "请选择行政班级", trigger: "change" }],
}

const columns: TableColumnsType = [
  { title: "ID", dataIndex: "id", key: "id", width: 80 },
  { title: "学生", key: "user", width: 150 },
  { title: "学号", dataIndex: "studentNo", key: "studentNo", width: 120 },
  { title: "班级", key: "class", width: 200 },
  { title: "性别", dataIndex: "gender", key: "gender", width: 80 },
  { title: "联系电话", dataIndex: "phone", key: "phone", width: 120 },
  { title: "家长姓名", dataIndex: "parentName", key: "parentName", width: 120 },
  {
    title: "家长电话",
    dataIndex: "parentPhone",
    key: "parentPhone",
    width: 120,
  },
  { title: "兴趣班", key: "interestClasses", width: 200 },
  { title: "状态", dataIndex: "validState", key: "validState", width: 80 },
  { title: "操作", key: "action", width: 150, fixed: "right" },
]

const fetchClasses = async () => {
  classesLoading.value = true
  try {
    // 获取所有行政班级
    const adminClasses = await classesApi.getList({
      page: 1,
      pageSize: 100,
      type: 1,
    })
    classOptions.value = adminClasses.list.map((cls: Class) => ({
      label: `${cls.grade?.name || ""} - ${cls.name}`,
      value: cls.id,
    }))

    // 获取所有兴趣班
    const interestClasses = await classesApi.getList({
      page: 1,
      pageSize: 100,
      type: 2,
    })
    interestClassOptions.value = interestClasses.list.map((cls: Class) => ({
      label: `${cls.grade?.name || ""} - ${cls.name}`,
      value: cls.id,
    }))
  } catch (error) {
    message.error("获取班级列表失败")
  } finally {
    classesLoading.value = false
  }
}

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

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

  modalTitle.value = "新增学生"
  editingId.value = null
  modalVisible.value = true
  nextTick(() => {
    formRef.value?.resetFields()
    form.username = ""
    form.password = ""
    form.confirmPassword = ""
    form.nickname = ""
    form.email = ""
    form.avatar = ""
    form.classId = 0
    form.studentNo = ""
    form.phone = ""
    form.idCard = ""
    form.gender = undefined
    form.birthDate = undefined
    form.enrollmentDate = undefined
    form.parentName = ""
    form.parentPhone = ""
    form.address = ""
    form.description = ""
    form.interestClassIds = []
    form.validState = 1
  })
}

const handleEdit = async (record: Student) => {
  modalTitle.value = "编辑学生"
  editingId.value = record.id
  modalVisible.value = true

  try {
    const detail = await studentsApi.getDetail(record.id)
    form.nickname = detail.user?.nickname || ""
    form.email = detail.user?.email || ""
    form.avatar = detail.user?.avatar || ""
    form.classId = detail.classId
    form.studentNo = detail.studentNo || ""
    form.phone = detail.phone || ""
    form.idCard = detail.idCard || ""
    form.gender = detail.gender
    form.birthDate = detail.birthDate ? dayjs(detail.birthDate) : undefined
    form.enrollmentDate = detail.enrollmentDate
      ? dayjs(detail.enrollmentDate)
      : undefined
    form.parentName = detail.parentName || ""
    form.parentPhone = detail.parentPhone || ""
    form.address = detail.address || ""
    form.description = detail.description || ""
    form.interestClassIds =
      detail.interestClasses?.map((ic) => ic.class.id) || []
    form.validState = detail.validState
  } catch (error) {
    message.error("获取学生详情失败")
    modalVisible.value = false
  }
}

const handleDelete = (record: Student) => {
  if (!authStore.hasPermission("student:delete")) {
    message.error("您没有删除学生的权限")
    return
  }

  Modal.confirm({
    title: "确认删除",
    content: `确定要删除学生 "${
      record.user?.nickname || record.user?.username
    }" 吗？删除后无法恢复。`,
    okText: "确定",
    okType: "danger",
    cancelText: "取消",
    onOk: async () => {
      try {
        await studentsApi.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

    const data: CreateStudentForm | UpdateStudentForm = {
      nickname: form.nickname,
      email: form.email || undefined,
      avatar: form.avatar || undefined,
      classId: form.classId,
      studentNo: form.studentNo || undefined,
      phone: form.phone || undefined,
      idCard: form.idCard || undefined,
      gender: form.gender,
      birthDate: form.birthDate
        ? form.birthDate.format("YYYY-MM-DD")
        : undefined,
      enrollmentDate: form.enrollmentDate
        ? form.enrollmentDate.format("YYYY-MM-DD")
        : undefined,
      parentName: form.parentName || undefined,
      parentPhone: form.parentPhone || undefined,
      address: form.address || undefined,
      description: form.description || undefined,
      interestClassIds: form.interestClassIds || [],
      validState: form.validState,
    }

    if (editingId.value) {
      await studentsApi.update(editingId.value, data as UpdateStudentForm)
      message.success("编辑成功")
    } else {
      await studentsApi.create({
        ...data,
        username: form.username,
        password: form.password!,
      } as CreateStudentForm)
      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(() => {
  fetchClasses()
})
</script>

<style scoped></style>
