<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    v-model="visible"
    append-to-body
    width="600px"
  >
    <el-form :model="dataForm" :rules="dataRule" ref="dataFormRef" @keyup.enter="dataFormSubmit" label-width="120px">

      <el-form-item label="模拟学生" prop="serialNumber">
        <el-select
          v-model="dataForm.serialNumber"
          @change="changeStu"
          filterable
          remote
          clearable
          reserve-keyword
          :disabled="!!dataForm.id" placeholder="请选择唯一号"
          :remote-method="remoteTeacherByQuery"
        >
          <el-option
            v-for="item in serialNumberList"
            :key="item.serialNumber"
            :label="item.name+'('+item.serialNumber+')'"
            :value="item.serialNumber">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="来源" prop="isOut">
        <el-select v-model="dataForm.isOut" filterable disabled placeholder="请选择来源" >
          <el-option
            v-for="item in isOutList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="拟报专业1" prop="wishMajorOne">
        <el-select v-model="dataForm.wishMajorOne" filterable placeholder="请选择拟报专业1" >
          <el-option
            v-for="item in planMajorList"
            :key="item.majorCode"
            :label="item.majorName+' | '+item.learnYear+'年 | '+item.majorCode"
            :value="item.majorCode"
            :disabled="isDisable(item.majorCode)"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="拟报专业2" prop="wishMajorTwo">
        <el-select v-model="dataForm.wishMajorTwo" filterable placeholder="请选择拟报专业2" >
          <el-option
            v-for="item in planMajorList"
            :key="item.majorCode"
            :label="item.majorName+' | '+item.learnYear+'年 | '+item.majorCode"
            :value="item.majorCode"
            :disabled="isDisable(item.majorCode)"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="拟报专业3" prop="wishMajorThree">
        <el-select v-model="dataForm.wishMajorThree" filterable placeholder="请选择拟报专业3" >
          <el-option
            v-for="item in planMajorList"
            :key="item.majorCode"
            :label="item.majorName+' | '+item.learnYear+'年 | '+item.majorCode"
            :value="item.majorCode"
            :disabled="isDisable(item.majorCode)"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="录取专业" prop="confirmedMajor">
        <el-select v-model="dataForm.confirmedMajor" filterable placeholder="请选择录取专业" >
          <el-option
            v-for="item in planMajorEduList"
            :key="item.majorCode"
            :label="item.majorName+' | '+item.learnYear+'年 | '+item.majorCode"
            :value="item.majorCode">
          </el-option>
        </el-select>
      </el-form-item>

    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @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 { addMNObj, getMNObj, putMNObj } from '/@/api/recruit/recruitImitateAdjustBatch'
import { getList } from '/@/api/recruit/recruitstudentsignup'
import { listPlanByCondition as planMajor, listByEdu } from '/@/api/recruit/recruitstudentplan'

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

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

// 响应式数据
const visible = ref(false)
const canSubmit = ref(false)
const disabled = ref(false)
const serialNumberList = ref<any[]>([])
const planMajorEduList = ref<any[]>([])
const planMajorList = ref<any[]>([])

const isOutList = [
  { label: "学校", value: "0" },
  { label: "市平台", value: "1" }
]

const dataForm = reactive({
  id: "",
  serialNumber: "",
  groupId: "",
  batchNo: "",
  wishMajorOne: '',
  wishMajorTwo: '',
  wishMajorThree: '',
  confirmedMajor: '',
  isOut: '',
  degreeOfEducation: "",
  name: "",
  gender: "",
  idNumber: "",
  oldConfirmedMajor: ""
})

const dataRule = {
  serialNumber: [
    { required: true, message: '模拟学生不能为空', trigger: 'blur' },
  ],
  confirmedMajor: [
    { required: true, message: '录取专业不能为空', trigger: 'blur' },
  ],
}

/**
 * 判断拟报专业是否已经占用,占用不可选
 */
const isDisable = (majorCode: string) => {
  if (majorCode == dataForm.wishMajorOne
    || majorCode == dataForm.wishMajorTwo
    || majorCode == dataForm.wishMajorThree
  ) {
    return true
  } else {
    return false
  }
}

// 初始化数据
const initData = () => {
  planMajorList.value = []
  serialNumberList.value = []
  planMajor({ groupId: dataForm.groupId }).then((data: any) => {
    planMajorList.value = data.data
  })
}

// 远程搜索学生
const remoteTeacherByQuery = (query: string) => {
  serialNumberList.value = []
  if (query !== '') {
    setTimeout(() => {
      getList({ groupId: dataForm.groupId, serialNumber: query }).then((response: any) => {
        serialNumberList.value = response.data
      })
    }, 200)
  }
}

// 学生选择变化
const changeStu = () => {
  planMajorEduList.value = []
  dataForm.wishMajorOne = ''
  dataForm.wishMajorTwo = ''
  dataForm.wishMajorThree = ''
  dataForm.degreeOfEducation = ""
  dataForm.oldConfirmedMajor = ""
  dataForm.name = ""
  dataForm.idNumber = ""
  dataForm.confirmedMajor = ""
  dataForm.gender = ""
  dataForm.isOut = ""
  serialNumberList.value.forEach(e => {
    if (e.serialNumber == dataForm.serialNumber) {
      dataForm.wishMajorOne = e.wishMajorOne
      dataForm.wishMajorTwo = e.wishMajorTwo
      dataForm.wishMajorThree = e.wishMajorThree
      dataForm.degreeOfEducation = e.degreeOfEducation
      dataForm.name = e.name
      dataForm.idNumber = e.idNumber
      dataForm.gender = e.gender
      dataForm.isOut = e.isOut
      dataForm.confirmedMajor = e.confirmedMajor
      dataForm.oldConfirmedMajor = e.confirmedMajor
      getMajorListByEdu()
    }
  })
}

// 根据学历获取专业列表
const getMajorListByEdu = () => {
  planMajorEduList.value = []
  listByEdu({ groupId: dataForm.groupId, degreeOfEducation: dataForm.degreeOfEducation }).then((res: any) => {
    planMajorEduList.value = res.data
  })
}

// 表单提交
const dataFormSubmit = () => {
  dataFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      if (dataForm.oldConfirmedMajor == dataForm.confirmedMajor) {
        ElNotification.error({
          title: '错误',
          message: '模拟调整的专业不能和原录取专业相同,请检查'
        })
        return
      }
      canSubmit.value = false
      if (dataForm.id) {
        putMNObj(dataForm).then(() => {
          ElNotification.success({
            title: '成功',
            message: '修改成功'
          })
          visible.value = false
          emit('refreshDataList')
        }).catch(() => {
          canSubmit.value = true
        })
      } else {
        addMNObj(dataForm).then(() => {
          ElNotification.success({
            title: '成功',
            message: '添加成功'
          })
          visible.value = false
          emit('refreshDataList')
        }).catch(() => {
          canSubmit.value = true
        })
      }
    }
  })
}

// 初始化方法
const init = (id: string | null, groupId: string, batchNo: string) => {
  dataForm.id = id || null
  dataForm.batchNo = batchNo
  dataForm.groupId = groupId
  visible.value = true
  canSubmit.value = true
  planMajorEduList.value = []
  initData()
  nextTick(() => {
    dataFormRef.value?.resetFields()
    if (dataForm.id) {
      getMNObj(dataForm.id).then((response: any) => {
        Object.assign(dataForm, response.data)
        getMajorListByEdu()
      })
    } else {
      disabled.value = true
    }
  })
}

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

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