<template>
  <el-dialog
    :title="title"
    :close-on-click-modal="false"
    v-model="visible"
    append-to-body
    width="90%">
    <el-form :model="dataForm" :rules="dataRule" ref="dataFormRef" @keyup.enter="dataFormSubmit"
             label-width="170px" size="small">
      <el-row>
        <el-col :span="24">
          <el-form-item label="招生计划" prop="groupId">
            <el-select v-model="dataForm.groupId" filterable :disabled="!!dataForm.id"
                       placeholder="请选择招生计划" size="small" style="width: 100%">
              <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="type != 1"></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="type != 2"></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" style="width: 100%;"></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="" size="small" style="width: 100%" :disabled="type != 1" @change="changeM(dataForm.confirmedMajor)">
              <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="" size="small" style="width: 100%" @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="6">
          <el-form-item label="学费" prop="feeTuition">
            <el-input-number v-model="dataForm.feeTuition" controls-position="right" :min="0" :max="999999" :step-strictly="true" style="width:100%;" :disabled="type == 2"></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="代办费" prop="feeAgency">
            <el-input-number v-model="dataForm.feeAgency" controls-position="right" :min="0" :max="999999" :step-strictly="true" style="width:100%;" :disabled="type == 2"></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="总费用" prop="allMoney">
            <span style="color: red">{{ dataForm.feeTuition + 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="success" @click="dataFormSubmit" v-if="canSubmit">确认修改</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick } from 'vue'
import { ElNotification } from 'element-plus'
import { useMessageBox } from '/@/hooks/message'
import { getObj, changeMajor } from '@/api/recruit/recruitstudentsignup'
import { getList } from "@/api/recruit/recruitstudentplangroup"
import { listByEdu } from "@/api/recruit/recruitstudentplan"
import { getDictByType } from "@/api/contract/contract"
import { list as scoreList } from "@/api/recruit/recruitstudentplancorrectscoreconfig"

// 消息提示 hooks
const messageBox = useMessageBox()

// Emits
const emit = defineEmits<{
  (e: 'refreshDataList'): void
}>()

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

// 响应式数据
const visible = ref(false)
const canSubmit = ref(false)
const title = ref("")
const type = ref<number | null>(null)
const planList = ref<any[]>([])
const planMajorList = ref<any[]>([])
const agencyFeeList = ref<any[]>([])
const tuitionFeeList = 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 = {
  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 changeCM = (id: string) => {
  if (id) {
    let flag = false
    planMajorList.value.forEach((e: any) => {
      if (dataForm.newConfirmedMajor == e.majorCode && e.isZd == "1" && String(dataForm.degreeOfEducation) == "1") {
        flag = true
      }
    })
    if (String(dataForm.degreeOfEducation) == "1") {
      dataForm.feeTuition = 0
      tuitionFeeList.value.forEach((e: any) => {
        if (e.label == "0" && flag) {
          dataForm.feeTuition = e.value
        }
      })
    }
  }
}

// 改变原专业
const changeM = (id: string) => {
  if (id) {
    dataForm.confirmedMajor = id
    // 是初中生并且是中德班
    let flag = false
    planMajorList.value.forEach((e: any) => {
      if (dataForm.confirmedMajor == e.majorCode && e.isZd == "1" && String(dataForm.degreeOfEducation) == "1") {
        flag = true
      }
    })
    if (String(dataForm.degreeOfEducation) == "1") {
      dataForm.feeTuition = 0
      tuitionFeeList.value.forEach((e: any) => {
        if (e.label == "0" && flag) {
          dataForm.feeTuition = e.value
        }
      })
    }
  }
}

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

// 初始化方法
const init = (id: string | null) => {
  dataForm.id = id || null
  visible.value = true
  canSubmit.value = true
  initData()
  nextTick(() => {
    dataFormRef.value?.resetFields()
    if (dataForm.id) {
      // 获取数据字典代办费
      getDictByType("agency_fee").then((res: any) => {
        agencyFeeList.value = res.data
        // 获取数据字典学费
        getDictByType("tuition_fee").then((res: any) => {
          tuitionFeeList.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
              }
            })
            tuitionFeeList.value.forEach((e: any) => {
              if (String(dataForm.degreeOfEducation) == String(e.label) && (String(dataForm.degreeOfEducation) != "1")) {
                dataForm.feeTuition = e.value
              }
            })
            listByEdu({ groupId: dataForm.groupId, degreeOfEducation: dataForm.degreeOfEducation }).then((e: any) => {
              planMajorList.value = e.data
            })
            // 获取招生计划下的学校和分数线
            scoreList({ groupId: dataForm.groupId }).then((data: any) => {
              schoolCodeList.value = data.data
            })

            if ("1" == dataForm.degreeOfEducation) {
              title.value = "C" + title.value
            } else if ("2" == dataForm.degreeOfEducation) {
              title.value = "G" + title.value
            } else if ("3" == dataForm.degreeOfEducation) {
              title.value = "J" + title.value
            }

            if ("-20" == dataForm.auditStatus) {
              title.value = "未录取 " + title.value
            } else if ("0" == dataForm.auditStatus) {
              title.value = "待审核 " + title.value
            } else if ("20" == dataForm.auditStatus) {
              title.value = "已录取 " + title.value
            }
          })
        })
      })
    }
  })
}

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

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>
