<template>
  <div class="teachers-page">
    <a-card class="mb-4">
      <template #title>教师管理</template>
      <template #extra>
        <a-space>
          <a-select
            v-model:value="searchParams.departmentId"
            placeholder="选择部门"
            allow-clear
            style="width: 200px"
            @change="handleSearch"
          >
            <a-select-option
              v-for="dept in departmentOptions"
              :key="dept.id"
              :value="dept.id"
            >
              {{ dept.name }}
            </a-select-option>
          </a-select>
          <a-button
            v-permission="'teacher: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 === 'department'">
          <span>{{ record.department?.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 === '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="'teacher:update'"
              type="link"
              size="small"
              @click="handleEdit(record)"
            >
              编辑
            </a-button>
            <a-button
              v-permission="'teacher: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="departmentId">
          <a-select
            v-model:value="form.departmentId"
            placeholder="请选择部门"
            :options="departmentOptions"
          />
        </a-form-item>
        <a-form-item label="工号" name="employeeNo">
          <a-input
            v-model:value="form.employeeNo"
            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="hireDate">
          <a-date-picker
            v-model:value="form.hireDate"
            placeholder="请选择入职日期"
            style="width: 100%"
            value-format="YYYY-MM-DD"
          />
        </a-form-item>
        <a-form-item label="任教科目" name="subject">
          <a-input
            v-model:value="form.subject"
            placeholder="请输入任教科目"
            :maxlength="50"
          />
        </a-form-item>
        <a-form-item label="职称" name="title">
          <a-input
            v-model:value="form.title"
            placeholder="请输入职称"
            :maxlength="50"
          />
        </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 {
  teachersApi,
  type Teacher,
  type CreateTeacherForm,
  type UpdateTeacherForm,
} from "@/api/teachers"
import { departmentsApi, type Department } from "@/api/departments"
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 departmentsLoading = ref(false)
const departmentOptions = ref<Array<{ label: string; value: number }>>([])

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

const {
  loading,
  dataSource,
  pagination,
  handleTableChange,
  refresh: refreshList,
  search,
} = useListRequest<Teacher, { departmentId?: number }>({
  requestFn: teachersApi.getList,
  errorMessage: "获取教师列表失败",
  defaultSearchParams: {},
})

const form = reactive<
  CreateTeacherForm & {
    confirmPassword?: string
    birthDate?: Dayjs
    hireDate?: Dayjs
    validState?: number
  }
>({
  username: "",
  password: "",
  confirmPassword: "",
  nickname: "",
  email: "",
  avatar: "",
  departmentId: 0,
  employeeNo: "",
  phone: "",
  idCard: "",
  gender: undefined,
  birthDate: undefined,
  hireDate: undefined,
  subject: "",
  title: "",
  description: "",
  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" }],
  departmentId: [{ required: true, message: "请选择部门", trigger: "change" }],
}

const columns: TableColumnsType = [
  { title: "ID", dataIndex: "id", key: "id", width: 80 },
  { title: "教师", key: "user", width: 150 },
  { title: "工号", dataIndex: "employeeNo", key: "employeeNo", width: 120 },
  { title: "部门", key: "department", width: 150 },
  { title: "性别", dataIndex: "gender", key: "gender", width: 80 },
  { title: "联系电话", dataIndex: "phone", key: "phone", width: 120 },
  { title: "任教科目", dataIndex: "subject", key: "subject", width: 120 },
  { title: "职称", dataIndex: "title", key: "title", width: 120 },
  { title: "状态", dataIndex: "validState", key: "validState", width: 80 },
  { title: "操作", key: "action", width: 150, fixed: "right" },
]

const fetchDepartments = async () => {
  departmentsLoading.value = true
  try {
    const tree = await departmentsApi.getTree()
    const flatten = (depts: Department[]): Department[] => {
      const result: Department[] = []
      depts.forEach((dept) => {
        result.push(dept)
        if (dept.children) {
          result.push(...flatten(dept.children))
        }
      })
      return result
    }
    const flatList = flatten(tree)
    departmentOptions.value = flatList.map((dept: Department) => ({
      label: dept.name,
      value: dept.id,
    }))
  } catch (error) {
    message.error("获取部门列表失败")
  } finally {
    departmentsLoading.value = false
  }
}

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

const handleAdd = () => {
  if (!authStore.hasPermission("teacher: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.departmentId = 0
    form.employeeNo = ""
    form.phone = ""
    form.idCard = ""
    form.gender = undefined
    form.birthDate = undefined
    form.hireDate = undefined
    form.subject = ""
    form.title = ""
    form.description = ""
    form.validState = 1
  })
}

const handleEdit = async (record: Teacher) => {
  modalTitle.value = "编辑教师"
  editingId.value = record.id
  modalVisible.value = true

  try {
    const detail = await teachersApi.getDetail(record.id)
    form.nickname = detail.user?.nickname || ""
    form.email = detail.user?.email || ""
    form.avatar = detail.user?.avatar || ""
    form.departmentId = detail.departmentId
    form.employeeNo = detail.employeeNo || ""
    form.phone = detail.phone || ""
    form.idCard = detail.idCard || ""
    form.gender = detail.gender
    form.birthDate = detail.birthDate ? dayjs(detail.birthDate) : undefined
    form.hireDate = detail.hireDate ? dayjs(detail.hireDate) : undefined
    form.subject = detail.subject || ""
    form.title = detail.title || ""
    form.description = detail.description || ""
    form.validState = detail.validState
  } catch (error) {
    message.error("获取教师详情失败")
    modalVisible.value = false
  }
}

const handleDelete = (record: Teacher) => {
  if (!authStore.hasPermission("teacher:delete")) {
    message.error("您没有删除教师的权限")
    return
  }

  Modal.confirm({
    title: "确认删除",
    content: `确定要删除教师 "${
      record.user?.nickname || record.user?.username
    }" 吗？删除后无法恢复。`,
    okText: "确定",
    okType: "danger",
    cancelText: "取消",
    onOk: async () => {
      try {
        await teachersApi.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: CreateTeacherForm | UpdateTeacherForm = {
      nickname: form.nickname,
      email: form.email || undefined,
      avatar: form.avatar || undefined,
      departmentId: form.departmentId,
      employeeNo: form.employeeNo || undefined,
      phone: form.phone || undefined,
      idCard: form.idCard || undefined,
      gender: form.gender,
      birthDate: form.birthDate
        ? form.birthDate.format("YYYY-MM-DD")
        : undefined,
      hireDate: form.hireDate ? form.hireDate.format("YYYY-MM-DD") : undefined,
      subject: form.subject || undefined,
      title: form.title || undefined,
      description: form.description || undefined,
      validState: form.validState,
    }

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

<style scoped></style>
