<!--
  学生编辑弹窗
  @author pangu
-->
<template>
  <el-dialog
    v-model="dialogVisible"
    :title="form.studentId ? '编辑学生' : '新增学生'"
    width="800px"
    :close-on-click-modal="false"
    @open="handleOpen"
    @close="handleClose"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="学生姓名" prop="studentName">
            <el-input v-model="form.studentName" placeholder="请输入学生姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="学号" prop="studentNo">
            <el-input v-model="form.studentNo" placeholder="请输入学号" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="性别" prop="gender">
            <el-select v-model="form.gender" placeholder="请选择性别">
              <el-option label="男" value="1" />
              <el-option label="女" value="2" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <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-col>
        <el-col :span="24">
          <el-form-item label="所属区域" prop="regionId">
            <el-cascader
              v-model="form.regionId"
              :options="regionTree"
              :props="{ value: 'id', label: 'label', children: 'children', emitPath: false }"
              placeholder="请选择区域"
              clearable
              style="width: 100%;"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="所属学校" prop="schoolId">
            <el-select v-model="form.schoolId" placeholder="请选择学校" @change="handleSchoolChange">
              <el-option v-for="item in schoolList" :key="item.schoolId" :label="item.schoolName" :value="item.schoolId" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="年级" prop="schoolGradeId">
            <el-select v-model="form.schoolGradeId" placeholder="请选择年级" @change="handleGradeChange">
              <el-option v-for="item in gradeList" :key="item.id" :label="item.gradeName" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="班级" prop="schoolClassId">
            <el-select v-model="form.schoolClassId" placeholder="请选择班级">
              <el-option v-for="item in classList" :key="item.id" :label="item.className" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="归属会员" prop="memberId">
            <el-select v-model="form.memberId" placeholder="请选择归属会员" filterable>
              <el-option v-for="item in memberList" :key="item.memberId" :label="`${item.nickname} (${item.phone})`" :value="item.memberId" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注">
            <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { getStudent, addStudent, updateStudent } from '@/api/student'
import { getRegionTree } from '@/api/region'
import { getSchoolListByRegion, getGradeListBySchool, getClassListByGrade } from '@/api/school'
import { getMemberList } from '@/api/student'

const props = defineProps({
  visible: Boolean,
  studentId: Number
})

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

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

const formRef = ref(null)
const form = reactive({
  studentId: null,
  studentName: '',
  studentNo: '',
  gender: '',
  birthday: null,
  regionId: null,
  schoolId: null,
  schoolGradeId: null,
  schoolClassId: null,
  memberId: null,
  remark: ''
})

const rules = {
  studentName: [{ required: true, message: '请输入学生姓名', trigger: 'blur' }],
  regionId: [{ required: true, message: '请选择所属区域', trigger: 'change' }],
  schoolId: [{ required: true, message: '请选择所属学校', trigger: 'change' }],
  schoolGradeId: [{ required: true, message: '请选择年级', trigger: 'change' }],
  schoolClassId: [{ required: true, message: '请选择班级', trigger: 'change' }],
  memberId: [{ required: true, message: '请选择归属会员', trigger: 'change' }]
}

const regionTree = ref([])
const schoolList = ref([])
const gradeList = ref([])
const classList = ref([])
const memberList = ref([])

async function handleOpen() {
  await loadRegionTree()
  await loadMemberList()
  
  if (props.studentId) {
    const res = await getStudent(props.studentId)
    if (res.code === 200) {
      Object.assign(form, res.data)
      await loadSchoolList()
      await loadGradeList()
      await loadClassList()
    }
  }
}

function handleClose() {
  formRef.value?.resetFields()
  Object.assign(form, {
    studentId: null,
    studentName: '',
    studentNo: '',
    gender: '',
    birthday: null,
    regionId: null,
    schoolId: null,
    schoolGradeId: null,
    schoolClassId: null,
    memberId: null,
    remark: ''
  })
}

async function loadRegionTree() {
  const res = await getRegionTree()
  if (res.code === 200) {
    regionTree.value = res.data || []
  }
}

async function loadSchoolList() {
  if (!form.regionId) return
  const res = await getSchoolListByRegion(form.regionId)
  if (res.code === 200) {
    schoolList.value = res.data || []
  }
}

async function loadGradeList() {
  if (!form.schoolId) return
  const res = await getGradeListBySchool(form.schoolId)
  if (res.code === 200) {
    gradeList.value = res.data || []
  }
}

async function loadClassList() {
  if (!form.schoolGradeId) return
  const res = await getClassListByGrade(form.schoolGradeId)
  if (res.code === 200) {
    classList.value = res.data || []
  }
}

async function loadMemberList() {
  const res = await getMemberList({ pageNum: 1, pageSize: 100 })
  if (res.code === 200) {
    memberList.value = res.rows || []
  }
}

function handleSchoolChange() {
  form.schoolGradeId = null
  form.schoolClassId = null
  gradeList.value = []
  classList.value = []
  loadGradeList()
}

function handleGradeChange() {
  form.schoolClassId = null
  classList.value = []
  loadClassList()
}

async function handleSubmit() {
  await formRef.value?.validate()
  
  const api = form.studentId ? updateStudent : addStudent
  const res = await api(form)
  
  if (res.code === 200) {
    ElMessage.success(form.studentId ? '修改成功' : '新增成功')
    dialogVisible.value = false
    emit('success')
  } else {
    ElMessage.error(res.msg || '操作失败')
  }
}
</script>
