<template>
  <IeModal :title="modalTitle" ref="modalRef" width="700px" @beforeClose="handleBeforeClose" @confirm="handleConfirm">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="学生姓名" prop="nickName" :required="true">
            <el-input v-model="form.nickName" placeholder="请输入学生姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号" prop="mobile" :required="true">
            <el-input v-model="form.mobile" maxlength="11" placeholder="请输入手机号" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="省份" prop="provinceId">
            <ie-select v-model="area.selected" v-model:selectedItem="area.selectedItem" :options="area.list" label-key="areaName" value-key="areaId" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="考生类型" prop="examType">
            <ie-select v-model="selectedExamType" :options="examTypeList" label-key="dictLabel" value-key="dictValue" />
          </el-form-item>
        </el-col>
        <el-col :span="12" prop="examMajor"  v-if="selectedExamType === 'VHS'">
          <el-form-item label="专业类别" prop="examMajor">
            <ie-select v-model="selectedExamMajor" :options="examMajorList" label-key="dictLabel" value-key="dictValue" placeholder="请选择专业类别" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="注册学校" prop="schoolId">
            <ie-select v-model="selectedSchool" :options="schoolList" label-key="name" value-key="id" filterable />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="注册班级" prop="classId">
            <ie-select v-model="selectedClass" :options="classList" label-key="name" value-key="classId" filterable />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="培训学校" prop="campusSchoolId">
            <ie-select v-model="selectedCampus" :options="campusList" label-key="name" value-key="id" filterable />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="培训班级" prop="campusClassId">
            <ie-select v-model="selectedCampusClass" :options="campusClassList" label-key="name" value-key="classId"
              filterable />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="语文成绩" prop="scores.chinese">
            <el-input v-model.number="form.scores.chinese" v-number placeholder="请输入语文成绩" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="数学成绩" prop="scores.mathematics">
            <el-input v-model.number="form.scores.mathematics" v-number placeholder="请输入数学成绩" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="外语成绩" prop="scores.foreign">
            <el-input v-model.number="form.scores.foreign" v-number placeholder="请输入外语成绩" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="政治成绩" prop="scores.political">
            <el-input v-model.number="form.scores.political" v-number placeholder="请输入政治成绩" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="物理成绩" prop="scores.physics">
            <el-input v-model.number="form.scores.physics" v-number placeholder="请输入物理成绩" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="到期时间" prop="outDate">
            <el-date-picker v-model="form.outDate" placeholder="请选择到期时间" value-format="YYYY-MM-DD"
                            class="w-full!" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="目标院校" prop="targetCollege">
            <div class="w-full flex items-center gap-x-2 ">
              <div class="flex-1 flex flex-col gap-2">
                <draggable v-model="form.directionStudy" item-key="id" handle=".drag-handle" animation="200"
                  class="flex flex-col gap-2" ghost-class="ghost-class" chosen-class="chosen-class">
                  <template #item="{ element, index }">
                    <div
                      class="flex items-center gap-x-2 border-1 border-solid border-[#e5e5e5] rounded-[4px] px-2 py-2 relative bg-white">
                      <el-icon class="cursor-move drag-handle mr-1" color="#909399">
                        <Rank />
                      </el-icon>
                      <div class="text-[13px] leading-[13px] font-bold">{{ element.universityName }}</div>
                      <div
                        class="text-[11px] text-[#5692fa] leading-[11px] border-1 border-solid border-[#5692fa] rounded-[4px] px-1 py-1">
                        {{ element.majorName }}</div>
                      <div class="text-[11px] text-[#999] leading-[11px]">{{ element.majorAncestors }}</div>
                      <div class="absolute top-1/2 right-2 -translate-y-1/2 cursor-pointer">
                        <el-icon @click="handleRemoveTargetCollege(index)" color="#ff4949">
                          <Close />
                        </el-icon>
                      </div>
                    </div>
                  </template>
                </draggable>
              </div>
              <el-button type="primary" :disabled="form.directionStudy.length >= 3" icon="plus" plain
                @click="handleAddTargetCollege">添加</el-button>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </IeModal>
  <DirectionDialog ref="directionDialogRef" @confirm="handleDirectionConfirm" />
</template>
<script setup>
import useSchool from '@/hooks/useSchool';
import IeModal from '@/components/IeModal/index.vue';
import IeSelect from '@/components/IeSelect/index.vue';
import IeUniversitySelect from '@/components/IeUniversitySelect/index.vue';
import DirectionDialog from './DirectionDialog.vue';
import { updateCardUser, getUserByCardId } from '@/api/dz/cards';
import { getCurrentInstance, nextTick, watch, watchEffect } from 'vue';
import draggable from 'vuedraggable';
import { Rank, Close } from '@element-plus/icons-vue';
import useProvinceExamTypeSubject from '@/views/dz/hooks/useProvinceExamTypeSubject.js';

const { proxy } = getCurrentInstance();

const modalRef = ref(null);
const formRef = ref(null);
const modalTitle = ref('修改用户');
const form = ref({
  scores: {},
  directionStudy: []
})

// 使用通用的省份-考生类型-科目联动 hook（专业类别即科目，只在VHS时显示）
const {
  area,
  getAreaList,
  selectedExamType,
  examTypeList,
  selectedSubjectId,
  subjectList,
  reset: resetProvinceExamTypeSubject,
  initData: initProvinceExamTypeSubject
} = useProvinceExamTypeSubject({
  autoLoadArea: false,
  loadExamType: true,
  onlyVHS: true  // 只在考生类型为 VHS 时加载科目
})

// 专业类别相关（使用 selectedSubjectId 和 subjectList）
const examMajorList = computed(() => {
  // 转换数据格式，dictValue 对应 subject_id，dictLabel 对应 subject_name
  return subjectList.value.map(item => ({
    dictValue: Number(item.subjectId),
    dictLabel: item.subjectName
  }))
})

const selectedExamMajor = computed({
  get: () => selectedSubjectId.value ? Number(selectedSubjectId.value) : null,
  set: (val) => {
    selectedSubjectId.value = val ? Number(val) : null
  }
})

const {
  area: schoolArea,
  schoolList,
  selectedSchool,
  classList,
  selectedClass,
  campusList,
  selectedCampus,
  campusClassList,
  selectedCampusClass,
  getAreaList: getSchoolAreaList,
  getSchoolList,
  getCampusList,
  reset: resetSchool
} = useSchool({ autoLoad: false, loadClass: true, loadCampus: true, loadCampusClass: true });

watchEffect(() => {
  form.value.examType = selectedExamType.value;
  form.value.schoolId = selectedSchool.value;
  form.value.classId = selectedClass.value;
  form.value.campusSchoolId = selectedCampus.value;
  form.value.campusClassId = selectedCampusClass.value;
  form.value.examMajor = selectedExamMajor.value;
  // 同步 examMajorName：从 examMajorList 中找到对应的 dictLabel
  if (selectedExamMajor.value != null) {
    const selectedMajor = examMajorList.value.find(item => item.dictValue === selectedExamMajor.value);
    form.value.examMajorName = selectedMajor ? selectedMajor.dictLabel : null;
  } else {
    form.value.examMajorName = null;
  }
  // 同步 location
  form.value.location = area.selectedItem?.shortName || area.selectedItem?.areaName?.replace('省', '') || null;
});



const rules = ref({
  nickName: [
    { required: true, message: '请输入学生姓名', trigger: ['blur', 'change'] }
  ],
  mobile: [
    { required: true, message: '请输入手机号', trigger: ['blur', 'change'] },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入正确的手机号',
      trigger: ['blur', 'change']
    }
  ],
})

const handleBeforeClose = () => {
  resetSchool();
  resetProvinceExamTypeSubject();
  form.value = {
    scores: {},
    directionStudy: []
  };
}

const open = (cardInfo) => {
  // 设置弹窗标题，显示卡号
  if (cardInfo.cardNo) {
    modalTitle.value = `修改用户 - 卡号：${cardInfo.cardNo}`;
  } else {
    modalTitle.value = '修改用户';
  }
  getUserInfo(cardInfo);
  modalRef.value.open()
}
const close = () => {
  modalRef.value.close()
}

const getUserInfo = (cardInfo) => {
  const { cardId, location, nickName, outDate } = cardInfo;
  getUserByCardId(cardId).then(async res => {
    form.value = {
      ...res.data,
      location,
      nickName,
      outDate,
      directionStudy: res.data.directionStudy || []
    };
    
    // 使用通用 hook 的 initData 方法初始化省份、考生类型、科目
    await initProvinceExamTypeSubject({
      location: location,
      examType: res.data.examType,
      subjectId: res.data.examMajor
    })
    
    // 加载学校相关的省份列表，并设置省份选择
    await getSchoolAreaList()
    // 根据 location 找到对应的 areaId
    if (area.selectedItem && area.selectedItem.areaId) {
      schoolArea.selected = area.selectedItem.areaId
    } else if (area.selected) {
      schoolArea.selected = Array.isArray(area.selected) ? area.selected[area.selected.length - 1] : area.selected
    }
    
    // 加载学校列表和培训学校列表
    if (schoolArea.selected) {
      await getSchoolList()
      await getCampusList()
    }
    
    // 设置其他字段（在加载完列表后再设置，确保下拉框有数据）
    selectedCampus.value = res.data.campusSchoolId;
    selectedCampusClass.value = res.data.campusClassId;
    selectedSchool.value = res.data.schoolId;
    selectedClass.value = res.data.classId;
  })
}

const directionDialogRef = ref(null);
const handleAddTargetCollege = () => {
  directionDialogRef.value.open(form.value.directionStudy);
}
const handleDirectionConfirm = (selectedList) => {
  form.value.directionStudy = selectedList;
  console.log(form.value.directionStudy, 'form.value.directionStudy')
}

const handleRemoveTargetCollege = (index) => {
  form.value.directionStudy.splice(index, 1);
}

const emit = defineEmits(['refresh'])
const handleConfirm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      modalRef.value.showLoading()
      // 准备提交的数据
      const submitData = { ...form.value };
      // 如果考生类型不是 VHS，则不传递 examMajor 和 examMajorName
      if (selectedExamType.value !== 'VHS') {
        delete submitData.examMajor;
        delete submitData.examMajorName;
      }
      updateCardUser(submitData).then(res => {
        proxy.$modal.msgSuccess('修改成功')
        close();
        emit('refresh')
      }).finally(() => {
        modalRef.value.hideLoading()
      })
    }
  })
}
defineExpose({
  open,
  close
})
</script>
<style lang="scss" scoped>
:deep(.ghost-class) {
  opacity: 1 !important;
  background: #fff !important;
  border: 1px solid #e5e5e5 !important;
}

:deep(.chosen-class) {
  background: #fff !important;
  border: 1px solid var(--el-color-primary) !important;
}
</style>