<template>
  <el-dialog
    :title="title"
    :close-on-click-modal="false"
    v-model="visible"
    append-to-body
    width="600">
    <el-form :model="dataForm" :rules="dataRule" ref="dataFormRef" @keyup.enter="dataFormSubmit"
             label-width="100px">
      <el-row>
        <el-col :span="24">
          <el-form-item label="招生计划" prop="groupId">
            <el-select v-model="dataForm.groupId" filterable :disabled="!!dataForm.id"
                       placeholder="请选择招生计划">
              <el-option
                v-for="item in planList"
                :key="item.id"
                :label="item.groupName"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="姓名" prop="name">
            <el-input type="text" v-model="dataForm.name" disabled></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="身份证号" prop="idNumber">
            <el-input type="text" v-model="dataForm.idNumber" disabled></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="成绩折算分" prop="correctedScore">
            <el-input-number v-model="dataForm.correctedScore" controls-position="right" :min="0" :max="999" :step-strictly="true"></el-input-number>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="原录取专业" prop="confirmedMajor">
            <el-select v-model="dataForm.confirmedMajor" filterable clearable placeholder="" disabled>
              <el-option
                v-for="item in planMajorList"
                :key="item.majorCode"
                :label="item.majorName"
                :value="item.majorCode">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="新录取专业" prop="newConfirmedMajor">
            <el-select v-model="dataForm.newConfirmedMajor" filterable placeholder="" @change="changeCM(dataForm.newConfirmedMajor)">
              <el-option
                v-for="item in planMajorList"
                :key="item.majorCode"
                :label="item.majorName+' || '+item.xyNum"
                :value="item.majorCode">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="学费" prop="feeTuition">
            <el-input-number v-model="dataForm.feeTuition" controls-position="right" :min="0" :max="999999" :step-strictly="true" disabled></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="代办费" prop="feeAgency">
            <el-input-number v-model="dataForm.feeAgency" controls-position="right" :min="0" :max="999999" :step-strictly="true" disabled></el-input-number>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="总费用" prop="allMoney">
            <span style="color: red">{{ Number(dataForm.feeTuition) + Number(dataForm.feeAgency) }}</span>
          </el-form-item>
        </el-col>
      </el-row>     
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注" prop="auditRemarks">
            <el-input type="textarea" v-model="dataForm.auditRemarks" placeholder="备注" :rows="2"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="dataFormSubmit(false)" v-if="canSubmit">确认修改</el-button>
        <el-button type="warning" @click="dataFormSubmit(true)" v-if="canSubmit" v-auth="'recruit_signup_change_force'">强制修改</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick } from 'vue'
import { useMessageBox, useMessage } from '/@/hooks/message'
import { getObj, changeMajor } from '/@/api/recruit/recruitstudentsignup'
import { getList } from "/@/api/recruit/recruitstudentplangroup"
import { listByEdu } from "/@/api/recruit/recruitstudentplan"
import { getDicts } from "/@/api/admin/dict"
import { list as scoreList } from "/@/api/recruit/recruitstudentplancorrectscoreconfig"
import { getStatusConfig, AUDIT_STATUS_LIST } from '/@/config/global'

const auditStatusList = AUDIT_STATUS_LIST
// 消息提示 hooks
const messageBox = useMessageBox()
const message = useMessage()
// Emits
const emit = defineEmits<{
  (e: 'refreshDataList'): void
}>()

// 表单引用
const dataFormRef = ref()

// 响应式数据
const visible = ref(false)
const canSubmit = ref(false)
const title = ref("")
const planList = ref<any[]>([])
const planMajorList = ref<any[]>([])
const agencyFeeList = ref<any[]>([])
const schoolCodeList = ref<any[]>([])

const dataForm = reactive({
  id: "",
  groupId: "",
  name: "",
  oldName: "",
  gender: "",
  nationality: "",
  degreeOfEducation: "",
  isLeagueMember: "",
  schoolOfGraduation: "",
  isAccommodation: "",
  examRegistrationNumbers: "",
  isMinimumLivingSecurity: "",
  score: "",
  postcode: "",
  residenceType: "",
  correctedScore: null as number | null,
  placeScore: "",
  schoolFrom: "",
  idNumber: "",
  residenceProvince: "",
  residenceCity: "",
  residenceArea: "",
  residenceDetail: "",
  homeAddressProvince: "",
  homeAddressCity: "",
  homeAddressArea: "",
  homeAddressDetail: "",
  parentName: "",
  parentTelOne: "",
  parentTelTwo: "",
  selfTel: "",
  wishMajorOne: "",
  wishMajorTwo: "",
  wishMajorThree: "",
  confirmedMajor: "",
  sevenMajor: "",
  sixMajor: "",
  fiveMajor: "",
  fourMajor: "",
  threeMajor: "",
  twoMajor: "",
  feeContribute: 0,
  scorePhoto: "",
  graPic: "",
  yyPic: "",
  housePic: "",
  sbPic: "",
  contactName: "",
  oldSerialNumber: "",
  colorDiscrimination: "",
  nutrition: "",
  height: "",
  weight: "",
  pastMedicalHistory: "",
  eyesightLeft: "",
  eyesightRight: "",
  correctEyesightLeft: "",
  correctEyesightRight: "",
  remarks: "",
  auditRemarks: "",
  serialNumber: "",
  auditStatus: "",
  schoolCode: "",
  newConfirmedMajor: "",
  householdPic: "",
  feeTuition: 0,
  feeAgency: 0
})

const dataRule = reactive({
  groupId: [
    { required: true, message: '招生计划不能为空', trigger: 'change' }
  ],
  name: [
    { required: true, message: '姓名不能为空', trigger: 'change' }
  ],
  idNumber: [
    { required: true, message: '身份证不能为空', trigger: 'change' }
  ],
  correctedScore: [
    { required: true, message: '成绩折算分不能为空', trigger: 'change' }
  ],
  confirmedMajor: [
    { required: true, message: '原录取专业不能为空', trigger: 'change' }
  ],
  newConfirmedMajor: [
    { required: true, message: '新录取专业不能为空', trigger: 'change' }
  ]
})

// 初始化数据
const initData = () => {
  getList().then((data: any) => {
    planList.value = data.data
  })
}

// 根据新专业和文化程度更新学费
const updateTuitionByNewMajorAndEducation = () => {
  if (!dataForm.newConfirmedMajor || !dataForm.degreeOfEducation) {
    return
  }
  
  // 查找选中的新专业
  const selectedMajor = planMajorList.value.find((major: any) => major.majorCode === dataForm.newConfirmedMajor)
  if (!selectedMajor) {
    return
  }
  
  // 根据文化程度选择对应的学费字段
  // '1' = 初中 -> czFee
  // '2' = 高中 -> gzFee
  // '3' = 技职校 -> jzxFee
  if (dataForm.degreeOfEducation === '1' && selectedMajor.czFee !== undefined && selectedMajor.czFee !== null) {
    dataForm.feeTuition = selectedMajor.czFee
  } else if (dataForm.degreeOfEducation === '2' && selectedMajor.gzFee !== undefined && selectedMajor.gzFee !== null) {
    dataForm.feeTuition = selectedMajor.gzFee
  } else if (dataForm.degreeOfEducation === '3' && selectedMajor.jzxFee !== undefined && selectedMajor.jzxFee !== null) {
    dataForm.feeTuition = selectedMajor.jzxFee
  }
}

// 改变新专业
const changeCM = (id: string) => {
  if (id) {
    // 从新专业中获取学费
    updateTuitionByNewMajorAndEducation()
  }
}


// 表单提交
const dataFormSubmit = async (force:any) => {
  const titleText = "确认调整录取专业么?"
  if (dataForm.confirmedMajor == dataForm.newConfirmedMajor) {
    message.error('新专业不能和原专业相同')
    return
  }
  dataForm.force=force
  try {
    await messageBox.confirm(titleText)
    dataFormRef.value?.validate((valid: boolean) => {
      if (valid) {
        canSubmit.value = false
        if (dataForm.id) {
          changeMajor(dataForm).then(() => {
            message.success('操作成功')
            visible.value = false
            emit('refreshDataList')
          }).catch(() => {
            canSubmit.value = true
          })
        }
      }
    })
  } catch {
    // 用户取消
  }
}

// 初始化方法
const init = (id: string | null) => {
  dataForm.id = id || ""
  visible.value = true
  canSubmit.value = true
  initData()
  nextTick(() => {
    dataFormRef.value?.resetFields()
    if (dataForm.id) {
      // 获取数据字典代办费
      getDicts('recruit_agency_fee').then((res: any) => {
        agencyFeeList.value = res.data
        getObj(dataForm.id).then((response: any) => {
          Object.assign(dataForm, response.data)
          title.value = dataForm.serialNumber
          // 获取文化程度对应的专业
          planMajorList.value = []

          agencyFeeList.value.forEach((e: any) => {
            if (String(dataForm.degreeOfEducation) == String(e.label)) {
              dataForm.feeAgency = e.value
            }
          })
          listByEdu({ groupId: dataForm.groupId, degreeOfEducation: dataForm.degreeOfEducation }).then((e: any) => {
            planMajorList.value = e.data
            // 加载专业列表后，如果已有新专业，更新学费
            if (dataForm.newConfirmedMajor) {
              updateTuitionByNewMajorAndEducation()
            }
            // 获取招生计划下的学校和分数线
            scoreList({ groupId: dataForm.groupId }).then((data: any) => {
              schoolCodeList.value = data.data
            })

            const educationPrefixMap: Record<string, string> = {
              '1': 'C',  // 初中
              '2': 'G',  // 高中
              '3': 'J'   // 技职校
            }
            const prefix = educationPrefixMap[String(dataForm.degreeOfEducation)]
            if (prefix) {
              title.value = prefix + title.value
            }
            // 从字典数据获取录取状态标签
            const auditStatusConfig = getStatusConfig(auditStatusList, dataForm.auditStatus)
            if (auditStatusConfig && auditStatusConfig.label) {
              title.value = auditStatusConfig.label + " " + title.value
            }

          })
        })
      })
    }
  })
}

// 暴露方法给父组件
defineExpose({
  init
})
</script>

<style lang="scss" scoped>
.el-form {
  .el-row:not(:last-of-type) {
    margin-bottom: 18px !important;
  }
}
.dialog-footer {
  text-align: right;
}
</style>
