<template>
  <el-dialog
    v-model="dialogVisible"
    title="新增考试"
    width="480px"
    class="page_dialog"
    :before-close="handleClose"
  >
    <el-form ref="formRef"   :model="formData"  :rules="rules"  label-width="100px">
      <el-form-item label="考试名称:" prop="examSubjectName">
        <el-input v-model="formData.examSubjectName" placeholder="请输入考试名称" style="width: 300px;"/>
      </el-form-item>
      
      <el-form-item label="考试年级:" prop="gradeCode">
        <el-radio-group v-model="formData.gradeCode" @change="HandleGradeChange">
          <el-radio :value="grade.gradeCode"  v-for="grade in gradeList">{{grade.gradeName}}</el-radio>

        </el-radio-group>
      </el-form-item>
      <el-form-item label="考试科目:" prop="courseCode">
        <el-radio-group v-model="formData.courseCode" @change="HandleCourseChange">
          <el-radio :value="subject.courseCode"  v-for="subject in subjectList">{{subject.courseName}}</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="HandleCancel">取消</el-button>
        <el-button type="primary" :loading="loading" @click="HandleSubmit">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, watch } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
// 1. 确保导入接口函数，请根据实际路径调整
import { getExamTypeData,createExamSubject } from '@/api/exam' 
// 定义 Props 和 Emits
const props = defineProps<{
  modelValue: boolean,
  editData: Record<string, any> | null ,
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'success'): void
}>()

// 弹窗显示状态的双向绑定
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

// 表单引用
const formRef = ref<FormInstance>()

//定义用于存储下拉菜单选项的响应式数据
const gradeList=ref<any[]>([]);
const subjectList=ref<any[]>([]);
// 表单数据
const formData = reactive({
    id:'',//考试科目列表id 不为空表示修改
    schoolYearId:'',//学年id
    schoolYearGradeId:'',//学年表id
    schoolYearCode:'',//学年code
    levelCode:'',//学段code
    levelName:'',//学段名称
    graduates:'',//毕业年份
    gradeCode:'',//年级code
    gradeName:'',//年级名称
    examSubjectName:'',//考试科目名称
    courseCode:'',//科目code
    courseName:'',//科目名称
})
// 重置表单
const ResetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(formData, {
    id:'',//考试科目列表id 不为空表示修改
    schoolYearId:'',//学年id
    schoolYearGradeId:'',//学年表id
    schoolYearCode:'',//学年code
    levelCode:'',//学段code
    levelName:'',//学段名称
    graduates:'',//毕业年份
    gradeCode:'',//年级code
    gradeName:'',//年级名称
    examSubjectName:'',//考试科目名称
    courseCode:'',//科目code
    courseName:'',//科目名称
  })
}
//监听数据变化
watch(() => props.editData, (newData) => { 
  if (newData) 
  {
    // --- 编辑模式：回填数据 ---
    console.log('编辑模式，回填数据:', newData);
    //编辑模式 回填数据
    Object.assign(formData, newData)
    console.log('回填数据:', formData)
    // 2. 关键：根据回填的 gradeCode，手动更新 subjectList 和其他关联字段
      // 因为 HandleGradeChange 是用户交互触发的，程序赋值不会触发它，
      // 所以我们需要手动执行一次类似的逻辑，确保科目列表正确显示，且隐藏字段完整
      if (formData.gradeCode && gradeList.value.length > 0) {
        const selectedGrade = gradeList.value.find((item: any) => item.gradeCode === formData.gradeCode);
        if (selectedGrade) {
          subjectList.value = selectedGrade.gradeCourseVOS || [];
          
          // 补全隐藏字段（确保提交时数据完整）
          formData.schoolYearId = selectedGrade.schoolYearId;
          formData.schoolYearGradeId = selectedGrade.id;
          formData.schoolYearCode = selectedGrade.schoolYearCode;
          formData.levelCode = selectedGrade.levelCode;
          const code = String(selectedGrade.levelCode);
          formData.levelName = LEVEL_NAME_MAP[code] || '';
          formData.graduates = selectedGrade.graduates;
          formData.gradeName = selectedGrade.gradeName;

          // 补全 courseName (防止后端没传或数据不一致)
          if (formData.courseCode) {
            const selectedCourse = subjectList.value.find((item: any) => item.courseCode === formData.courseCode);
            if (selectedCourse) {
              formData.courseName = selectedCourse.courseName;
            }
          }
        }
      }
  }
  else
  {
    //新增模式 清空表单数据
    ResetForm()
  }
},{ immediate: true } // 【关键】立即执行，确保组件挂载时就能处理初始 prop
)

// 表单验证规则
const rules = reactive<FormRules>({
  examSubjectName: [
    { required: true, message: '请输入考试名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  gradeCode: [
    { required: true, message: '请选择考试年级', trigger: 'change' }
  ],
  courseCode: [
    { required: true, message: '请选择考试科目', trigger: 'change' }
  ]
})

const loading=ref(false);//加载状态

// 关闭弹窗前的处理
const handleClose = (done: () => void) => {
  // 可以在这里添加确认关闭的逻辑
  done()
}

// 获取下拉菜单选项
const GetExamType=async()=>{
  const res:any = await getExamTypeData({});
  console.log("打印获取的结果",res)
  if(res.code==200 && res.data)
  {
    gradeList.value=res.data.schoolGrade;
    console.log("打印formData",formData)
    // if(props.editData==null)
    // {
    //   formData.gradeCode=res.data.schoolGrade[0].gradeCode;
    //   subjectList.value=res.data.schoolGrade[0].gradeCourseVOS || [];
    //   formData.courseCode=res.data.schoolGrade[0].gradeCourseVOS[0].courseCode;
    // }

    // 如果当前是编辑模式，且已经回填了 formData，但 subjectList 还没更新
    // 说明 watch(editData) 先于 GetExamType 执行了，这里需要手动补救一下
    if (props.editData && formData.gradeCode) {
       const selectedGrade = gradeList.value.find((item: any) => item.gradeCode === formData.gradeCode);
       if (selectedGrade) {
          subjectList.value = selectedGrade.gradeCourseVOS || [];
          // 再次补全隐藏字段，确保万无一失
          formData.schoolYearId = selectedGrade.schoolYearId;
          formData.schoolYearGradeId = selectedGrade.id;
          formData.schoolYearCode = selectedGrade.schoolYearCode;
          formData.levelCode = selectedGrade.levelCode;
          const code = String(selectedGrade.levelCode);
          formData.levelName = LEVEL_NAME_MAP[code] || '';
          formData.graduates = selectedGrade.graduates;
          formData.gradeName = selectedGrade.gradeName;
          
          if (formData.courseCode) {
            const selectedCourse = subjectList.value.find((item: any) => item.courseCode === formData.courseCode);
            if (selectedCourse) {
              formData.courseName = selectedCourse.courseName;
            }
          }
       }
    } 
    // 如果是新增模式，自动选中第一个
    else if (!props.editData && !formData.gradeCode && gradeList.value.length > 0) {
       const firstGrade = gradeList.value[0];
       subjectList.value = firstGrade.gradeCourseVOS || [];
       formData.gradeCode = firstGrade.gradeCode;
       formData.schoolYearId = firstGrade.schoolYearId;
       formData.schoolYearGradeId = firstGrade.id;
       formData.schoolYearCode = firstGrade.schoolYearCode;
       formData.levelCode = firstGrade.levelCode;
       const code = String(firstGrade.levelCode);
       formData.levelName = LEVEL_NAME_MAP[code] || '';
       formData.graduates = firstGrade.graduates;
       formData.gradeName = firstGrade.gradeName;
       if (subjectList.value.length > 0) {
         formData.courseCode = subjectList.value[0].courseCode;
         formData.courseName = subjectList.value[0].courseName;
       }
    }
   
  }
}
//监听弹窗打开，调用接口
watch(dialogVisible, (val) => { 
  if (val) 
  {
    //弹窗打开时获取数据
    GetExamType()
  }
})
// 学段名称映射表
const LEVEL_NAME_MAP: Record<string, string> = {
  '1': '小学',
  '2': '初中',
  '3': '高中'
}

//切换年级改变事件
const HandleGradeChange=()=>{
  // 在 gradeList 中找到当前选中的年级对象
  const selectedGrade = gradeList.value.find((item: any) => item.gradeCode === formData.gradeCode);
  console.log('选中的年级对象:', selectedGrade);
  if (selectedGrade) {
    // 更新科目列表
    subjectList.value = selectedGrade.gradeCourseVOS || [];
    formData.schoolYearId=selectedGrade.schoolYearId;//年级id
    formData.schoolYearGradeId=selectedGrade.id;//年级表id
    formData.schoolYearCode=selectedGrade.schoolYearCode;//年级code
    formData.levelCode=selectedGrade.levelCode;//学段code
    const code = String(selectedGrade.levelCode); 
    formData.levelName = LEVEL_NAME_MAP[code] || ''; // 如果找不到对应代码，则设为空字符串
    formData.graduates=selectedGrade.graduates;//毕业年份
    formData.gradeName=selectedGrade.gradeName;//年级名称
    
    // 切换年级后，自动选中该年级的第一个科目（或者清空，视需求而定）
    if (subjectList.value.length > 0) {
      formData.courseCode = subjectList.value[0].courseCode;
      formData.courseName=subjectList.value[0].courseName;
    } else {
      formData.courseCode = '';
    }
  }
}

//切换科目改变事件
const HandleCourseChange=()=>{
  //在gradeList 中找到当前选中的年级对象
  const selectedCourse = subjectList.value.find((item: any) => item.courseCode === formData.courseCode);
  console.log('选中的科目对象:', selectedCourse);
  if(selectedCourse) 
  {
    // 更新科目列表
    formData.courseName=selectedCourse.courseName;
  }
}

// 取消按钮
const HandleCancel = () => {
  dialogVisible.value = false
  ResetForm()
}

// 提交按钮
const HandleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate()
  console.log('提交数据:', formData)
  // TODO: 调用接口提交数据
  let params={
    id:formData.id || '',//考试科目列表id 不为空表示修改
    examType:1,//考试类型
    schoolYearId:formData.schoolYearId,//学年id
    schoolYearGradeId:formData.schoolYearGradeId,//学年表id
    schoolYearCode:formData.schoolYearCode,//学年code
    levelCode:formData.levelCode,//学段code
    levelName:formData.levelName,//学段名称
    graduates:formData.graduates,//毕业年份
    gradeCode:formData.gradeCode,//年级code
    gradeName:formData.gradeName,//年级名称
    examSubjectName:formData.examSubjectName,//考试科目名称
    courseCode:formData.courseCode,//科目code
    courseName:formData.courseName,//科目名称
  };
  loading.value=true;
  const res:any=await createExamSubject(params);
  console.log("打印提交的结果",res)
  if(res.code==200)
  {
    loading.value=false;
    ElMessage.success('新增考试成功')
    dialogVisible.value = false
    emit('success')
    ResetForm()
  }
  // ElMessage.success('新增考试成功')
  // dialogVisible.value = false
  // emit('success')
  // 
}


</script>

<style lang="scss" scoped>
.exam-form {
  padding-right: 20px;
}
</style>