<template>
  <el-dialog
    v-model="visible"
    :title="isEdit ? '编辑学生' : '新增学生'"
    width="600px"
    :close-on-click-modal="false"
    destroy-on-close
    @open="handleOpen"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="姓名" prop="name">
        <el-input v-model="form.name" placeholder="请输入学生姓名" maxlength="20" />
      </el-form-item>
      <el-form-item label="学号" prop="studentNo">
        <el-input v-model="form.studentNo" placeholder="请输入学号" maxlength="30" />
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-radio-group v-model="form.gender">
          <el-radio value="1">男</el-radio>
          <el-radio value="2">女</el-radio>
          <el-radio value="0">未知</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="出生日期" prop="birthday">
        <el-date-picker
          v-model="form.birthday"
          type="month"
          placeholder="请选择出生年月"
          format="YYYY-MM"
          value-format="YYYY-MM"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="学校信息" prop="schoolPath" required>
        <el-cascader
          v-model="form.schoolPath"
          :options="schoolTree"
          :props="{
            value: 'id',
            label: 'label',
            children: 'children',
            checkStrictly: false
          }"
          placeholder="请选择学校/年级/班级"
          clearable
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="学科" prop="subject">
        <el-select v-model="form.subject" placeholder="请选择学科" clearable style="width: 100%">
          <el-option v-for="item in subjectList" :key="item.id" :label="item.name" :value="item.name" />
        </el-select>
      </el-form-item>
      <el-form-item label="归属用户" prop="userId">
        <el-input v-model="form.userNickname" placeholder="请输入用户昵称搜索" readonly>
          <template #append>
            <el-button @click="handleSelectUser">选择</el-button>
          </template>
        </el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
/**
 * 学生新增/编辑弹窗
 * @author pangu
 */
import { addStudent, getStudent, updateStudent } from '@/api/pangu/student'
import { ElMessage } from 'element-plus'
import { computed, reactive, ref } from 'vue'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  studentId: {
    type: [Number, null],
    default: null
  },
  schoolTree: {
    type: Array,
    default: () => []
  },
  subjectList: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['update:modelValue', 'success'])

const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

const isEdit = computed(() => !!props.studentId)

const formRef = ref(null)
const submitLoading = ref(false)

const initialForm = {
  id: null,
  name: '',
  studentNo: '',
  gender: '1',
  birthday: '',
  schoolPath: [],
  subject: '',
  userId: null,
  userNickname: ''
}

const form = reactive({ ...initialForm })

const rules = {
  name: [
    { required: true, message: '请输入学生姓名', trigger: 'blur' }
  ],
  schoolPath: [
    { required: true, message: '请选择学校/年级/班级', trigger: 'change' }
  ]
}

// 弹窗打开时
const handleOpen = async () => {
  Object.assign(form, initialForm)
  formRef.value?.clearValidate()

  if (props.studentId) {
    try {
      const res = await getStudent(props.studentId)
      if (res.data) {
        const data = res.data
        form.id = data.id
        form.name = data.name
        form.studentNo = data.studentNo
        form.gender = data.gender
        form.birthday = data.birthday
        form.subject = data.subject
        form.userId = data.userId
        form.userNickname = data.userNickname
        // 需要根据实际数据结构构建 schoolPath
        form.schoolPath = [data.schoolId]
      }
    } catch (e) {
      console.error('获取学生详情失败:', e)
    }
  }
}

// 选择用户
const handleSelectUser = () => {
  // 简化处理，实际应该弹出用户选择器
  ElMessage.info('用户选择功能需要对接会员管理模块')
}

// 提交
const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
  } catch (e) {
    return
  }

  submitLoading.value = true
  try {
    const submitData = {
      ...form,
      schoolId: form.schoolPath[0],
      gradeId: form.schoolPath[1],
      classId: form.schoolPath[2]
    }
    delete submitData.schoolPath

    if (isEdit.value) {
      await updateStudent(submitData)
      ElMessage.success('修改成功')
    } else {
      await addStudent(submitData)
      ElMessage.success('新增成功')
    }
    visible.value = false
    emit('success')
  } catch (e) {
    // 错误在拦截器中已处理
  } finally {
    submitLoading.value = false
  }
}
</script>
