<template>
  <el-dialog
    :title="studentDialogTitle"
    v-model="showDialog"
    :modal-append-to-body="false"
    append-to-body
    center
    class="page_dialog"
    width="480px"
  >
    <div class="dialog_center">
      <el-form
        :model="addStudentData"
        ref="addStudentFormRef"
        :rules="addStudentDataRules"
        label-width="120px"
      >
        <el-form-item
          label="学校："
          prop="schoolId"
          v-if="schoolType == 1 && studentDialogTitle == '新增学生'"
        >
          <el-select
            v-model="addStudentData.schoolId"
            style="margin-right: 10px"
            placeholder="选择学校"
            :disabled="selectSchoolId != '-1'"
            class="select_width"
            v-if="schoolType == 1"
            @change="AddChangeSchool"
          >
            <el-option
              v-for="item in schoolList"
              :key="item.schoolCode"
              :label="item.schoolNickName || item.schoolName"
              :value="item.schoolId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学号：" prop="studentCode">
          <el-input
            v-model="addStudentData.studentCode"
            placeholder=""
            @change="GetSchoolUserInfos"
            :disabled="studentDialogTitle == '编辑学生'"
          ></el-input>
        </el-form-item>
        <el-form-item label="姓名：" prop="studentName">
          <el-input v-model="addStudentData.studentName" placeholder=""></el-input>
        </el-form-item>
        <el-form-item label="考号：" prop="exCode">
          <el-input v-model="addStudentData.examCode" placeholder=""></el-input>
        </el-form-item>
        <el-form-item label="考场：" prop="examRoomCode">
          <el-select  v-model="addStudentData.examRoomCode"  placeholder="请选择">
            <el-option  v-for="(item, index) in examRoomList"  :key="'exam_room_' + index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="行政班：" prop="adminClassIdCode">
          <el-select
            v-model="addStudentData.adminClassIdCode"
            @change="ChangeAdminClass"
            placeholder="请选择">
            <el-option
              v-for="(item, index) in adminClassList"
              :key="'admin_class_' + index"
              :label="item.className"
              :value="item.classIdCode"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item
          label="教学班："
          v-if="teachingClassList.length > 0"
          prop="teachingClassIdCode"
        >
          <el-select
            v-model="addStudentData.teachingClassIdCode"
            @change="ChangeTeachingClass"
            placeholder="请选择"
          >
            <el-option
              v-for="(item, index) in teachingClassList"
              :key="'teaching_class_' + index"
              :label="item.className"
              :value="item.classIdCode"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="学生类型："
          v-if="studentTypeList.length > 0"
          prop="registrationTypeCode"
        >
          <el-select
            v-model="addStudentData.registrationTypeCode"
            @change="ChangeStudentType"
            placeholder="请选择"
          >
            <el-option
              v-for="(item, index) in studentTypeList"
              :key="'teaching_class_' + index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="showDialog = false">取 消</el-button>
        <el-button type="primary" @click="EnterStudent()" :loading="loadingSubmit"
          >确 定</el-button
        >
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { useExamStore } from '@/store/exam'
import { useUserStore } from '@/store/user'
import { ref, reactive, computed, watch, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
// 假设你有这些 API 导入，请根据实际路径调整
import { getExamStudentInfo, getClassListData, updateExamStudentInfo } from '@/api/exam'
// 假设你使用 Pinia 或 Vuex，这里需要引入对应的 store
// import { useMakeTemplateStore } from '@/store/makeTemplate'
// import { useUserStore } from '@/store/user'
// 实例化 Store
const examStore = useExamStore()
// 定义 Props
const props = defineProps<{
  modelValue: boolean
  selectSchoolId: string | number
}>()

// 定义 Emits
const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'SaveSuccess'): void
}>()

// 双向绑定 showDialog
const showDialog = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val),
})

// --- Store 数据模拟 (请根据你的实际 Store 实现替换) ---
// const makeTemplateStore = useMakeTemplateStore()
// const userStore = useUserStore()

// 临时模拟 store 数据，实际使用时请取消注释上面的 store 并使用下面的计算属性
const mockSchoolList = ref([]) 
const mockExamTempDetail = ref({
  examId: '',
  id: '',
  courseName: '',
  courseCode: ''
})

const mockUserSchoolType = ref(0)

const schoolList = computed(() => mockSchoolList.value) // 实际: makeTemplateStore.schoolList
const examId = computed(()=>{
  return examStore.currentExam?.id
}) // 实际: makeTemplateStore.examTempDetail.examId
// 考试科目 ID
const examSubjectId = computed(() => {
  return examStore.currentExam?.id
})//计算属性

const schoolYearCode = computed(() => {
  return examStore.currentExam?.schoolYearCode
})//计算属性

// 学校 ID
const schoolId= computed(() => {
  return examStore.currentExam?.schoolInfoId
})


const schoolType = computed(() => mockUserSchoolType.value) // 实际: userStore.schoolType
const currentCourseCode = computed(() => mockExamTempDetail.value.courseCode) // 实际: makeTemplateStore.examTempDetail.courseCode

// --- 响应式数据 ---
const studentDialogTitle = ref('新增学生')
const loadingSubmit = ref(false)
const addStudentFormRef = ref<any>(null)

const addStudentData = reactive({
  id: '',
  schoolId: '',
  studentName: '',
  studentRegistrationCode: '',
  studentCode: '',
  examCode: '',
  examRoomCode: '',
  adminClassIdCode: '',
  adminClassName: '',
  adminClassSort: '',
  teachingClassIdCode: '',
  teachingClassName: '',
  teachingClassSort: '',
  registrationTypeCode: '',
  registrationTypeName: '',
})

const addStudentDataRules = {
  studentCode: [{ required: true, message: '请输入学号', trigger: 'change' }],
  examCode: [{ required: true, message: '请输入考号', trigger: 'change' }],
  studentName: [{ required: true, message: '请输入姓名', trigger: 'change' }],
  adminClassIdCode: [{ required: true, message: '请选择行政班', trigger: 'change' }],
  teachingClassIdCode: [{ required: true, message: '请选择教学班', trigger: 'change' }],
}

const studentTypeList = ref<any[]>([])
const examRoomList = ref<any[]>([])
const adminClassList = ref<any[]>([])
const teachingClassList = ref<any[]>([])

// --- Watch ---
watch(
  () => props.modelValue,
  (newVal) => {
    if (newVal) {
      if (props.selectSchoolId != -1) {
        addStudentData.schoolId = props.selectSchoolId as any 
        GetClassListData()
      }
    }
  }
)

// --- Methods ---

const AddChangeSchool = () => {
  if (props.selectSchoolId != -1) {
    addStudentData.schoolId = props.selectSchoolId as any
  }
  let schoolId = addStudentData.schoolId
  GetClassListData()
}

const AddStudent = () => {
  studentDialogTitle.value = '新增学生'
  resetFormData()
  showDialog.value = true
}

//编辑学生
const EditorStudent = (studentData: any) => {
  console.log('打印传过来的编辑的学生信息', studentData)
  studentDialogTitle.value = '编辑学生'
  
  Object.assign(addStudentData, {
    id: studentData.id || '',
    schoolId: studentData.schoolId || '',
    studentName: studentData.studentName || '',
    studentRegistrationCode: studentData.studentRegistrationCode || '',
    studentCode: studentData.studentCode || '',
    examCode: studentData.examCode || '',
    examRoomCode: studentData.examRoomCode || '',
    adminClassIdCode: studentData.adminClassIdCode || '',
    adminClassName: studentData.adminClassName || '',
    adminClassSort: studentData.adminClassSort,
    teachingClassIdCode: studentData.teachingClassIdCode || '',
    teachingClassName: studentData.teachingClassName || '',
    teachingClassSort: studentData.teachingClassSort || '',
    registrationTypeCode: studentData.registrationTypeCode || '',
    registrationTypeName: studentData.registrationTypeName || '',
  })
  
  showDialog.value = true
}

const resetFormData = () => {
  Object.assign(addStudentData, {
    id: '',
    schoolId: '',
    studentName: '',
    studentRegistrationCode: '',
    studentCode: '',
    exCode: '',
    examRoomCode: '',
    adminClassIdCode: '',
    adminClassName: '',
    adminClassSort: '',
    teachingClassIdCode: '',
    teachingClassName: '',
    teachingClassSort: '',
    registrationTypeCode: '',
    registrationTypeName: '',
  })
}

const ChangeAdminClass = () => {
  const classItem = adminClassList.value.find(
    (item) => item.classIdCode === addStudentData.adminClassIdCode
  )
  if (classItem) {
    addStudentData.adminClassName = classItem.className
    addStudentData.adminClassSort = classItem.classCode
  }
}

const ChangeTeachingClass = () => {
  const classItem = teachingClassList.value.find(
    (item) => item.classIdCode === addStudentData.teachingClassIdCode
  )
  if (classItem) {
    addStudentData.teachingClassName = classItem.className
    addStudentData.teachingClassSort = classItem.classCode
  }
}

const ChangeStudentType = () => {
  const classItem = studentTypeList.value.find(
    (item) => item.value === addStudentData.registrationTypeCode
  )
  if (classItem) {
    addStudentData.registrationTypeName = classItem.label
  }
}

//获取考试学生信息
const GetSchoolUserInfos = () => {
  let params = {
    studentCode: addStudentData.studentCode,
    schoolYearCode: schoolYearCode.value,
    schoolId: schoolId.value,
  }
  
  getExamStudentInfo(params).then((res: any) => {
    if (res.code == 200 && res.data) {
      let teachingClassIdCode = ''
      if (res.data.classTblVOS && res.data.classTblVOS.length > 0) {
        const foundItem = res.data.classTblVOS.find(
          (item: any) => item.courseCode == currentCourseCode.value
        )
        if (foundItem) {
          teachingClassIdCode = foundItem.classIdCode
        }
      }

      const teachingclassItem = teachingClassList.value.find(
        (classItem) => classItem.classIdCode == teachingClassIdCode
      )
      const adminClassItem = adminClassList.value.find(
        (classItem) => classItem.classIdCode == res.data.adminClassIdCode
      )

      Object.assign(addStudentData, {
        id: '',
        schoolId: res.data.schoolId,
        studentName: res.data.studentName || '',
        studentRegistrationCode: res.data.registrationCode,
        studentCode: res.data.studentCode,
        exCode: res.data.examCode,
        examRoomCode: '',
        adminClassIdCode: res.data.adminClassIdCode,
        adminClassName: adminClassItem?.className,
        adminClassSort: adminClassItem?.classCode,
        teachingClassIdCode: teachingClassIdCode || '',
        teachingClassName: teachingclassItem?.className || '',
        teachingClassSort: teachingclassItem?.classCode || '',
        registrationTypeCode: res.data.registrationTypeCode,
        registrationTypeName: res.data.registrationTypeName,
      })
    } else {
      addStudentData.studentCode = ''
      ElMessage.error('没有查询到相关数据,请先去个人中心维护!')
    }
  })
}

//获取考试班级列表
const GetClassListData = () => {
  let param = {
    examSubjectId: examSubjectId.value,
    schoolId: schoolId.value,
  }
  
  getClassListData(param).then((res: any) => {
    if (res.code == 200) {
      adminClassList.value = res.data.adminClassSelect || []
      teachingClassList.value = res.data.teachClassSelect || []
      studentTypeList.value = res.data?.studentType || []
      examRoomList.value = res.data.examRoomSelect || []
    }
  })
}

const EnterStudent = () => {
  // 表单验证
  if (!addStudentFormRef.value) return
  
  addStudentFormRef.value.validate((valid: boolean) => {
    if (!valid) return

    if (addStudentData.studentRegistrationCode == '') {
      ElMessage.error('该学生基础数据不存在，请到个人中心添加!')
      return
    }

    let param = {
      id: addStudentData.id,
      schoolId: schoolId.value,
      examId: examId.value,
      examSubjectId: examSubjectId.value,
      studentName: addStudentData.studentName,
      studentRegistrationCode: addStudentData.studentRegistrationCode,
      studentCode: addStudentData.studentCode,
      examRoomCode: addStudentData.examRoomCode,
      examCode: addStudentData.examCode,
      adminClassIdCode: addStudentData.adminClassIdCode,
      adminClassName: addStudentData.adminClassName,
      adminClassSort: addStudentData.adminClassSort,
      teachingClassIdCode: addStudentData.teachingClassIdCode,
      teachingClassName: addStudentData.teachingClassName,
      teachingClassSort: addStudentData.teachingClassSort,
      registrationTypeCode: addStudentData.registrationTypeCode,
      registrationTypeName: addStudentData.registrationTypeName,
    }
    
    loadingSubmit.value = true
    updateExamStudentInfo(param).then((res: any) => {
      loadingSubmit.value = false
      if (res.code == 200) {
        emit('SaveSuccess')
        ElMessage.success('保存成功')
        showDialog.value = false
      } else {
        ElMessage.error('保存失败!' + res.msg)
      }
    })
  })
}

// 暴露方法给父组件（如果需要）
defineExpose({
  AddStudent,
  EditorStudent,
})

onMounted(() => {
  if (props.selectSchoolId) {
    GetClassListData()
  } else {
    GetClassListData(0)
  }
})
</script>

<style lang="scss" scoped>
/* 保持原有样式 */
</style>