<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    v-model="visible"
    width="800px"
  >
    <el-form :model="dataForm" :rules="dataRule" ref="dataFormRef" @keyup.enter="dataFormSubmit" label-width="100px">
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="招生计划" prop="groupId">
            <el-select v-model="dataForm.groupId" filterable placeholder="请选择招生计划" :disabled="!!dataForm.id">
              <el-option
                v-for="item in planListLocal"
                :key="item.id"
                :label="item.groupName"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="dataForm.name" placeholder="姓名"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="电话" prop="phone">
            <el-input 
              v-model="dataForm.phone" 
              placeholder="电话" 
              type="tel" 
              maxlength="11"
              v-input-filter="'number'">
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="dataForm.gender">
              <el-radio v-for="item in sexyList" :key="item.value" :label="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="身份证" prop="idCard">
            <el-input 
              v-model="dataForm.idCard" 
              placeholder="身份证号" 
              maxlength="20"
              v-input-filter="'idcard'">
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="准考证" prop="admission">
            <el-input 
              v-model="dataForm.admission" 
              placeholder="准考证" 
              maxlength="20"
              v-input-filter="'alphanumeric'">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="中考成绩" prop="achievement">
            <el-input-number v-model="dataForm.achievement" :min="0" :max="700" placeholder="中考成绩" ></el-input-number>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="对接人" prop="djUser" v-if="hasAuth('recruit_recruitprestudent_dj_sure')">
            <el-select v-model="dataForm.djUser" filterable clearable placeholder="" >
              <el-option
                v-for="item in contactNameList"
                :key="item.teacherNo"
                :label="item.realName+'-'+item.deptCode"
                :value="item.teacherNo">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="学校" prop="schoolId">
            <el-select v-model="dataForm.schoolId" filterable placeholder="请选择学校" >
              <el-option
                v-for="item in schoolList"
                :key="item.id"
                :label="item.schoolName"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="拟报专业1" prop="planMajorOne">
            <el-select v-model="dataForm.planMajorOne" filterable  placeholder="请选择拟报专业1" >
              <el-option
                v-for="item in planMajorList"
                :key="item.id"
                :label="item.majorName"
                :value="item.id"
                :disabled="isDisable(item.id)"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="拟报专业2" prop="planMajorTwo">
            <el-select v-model="dataForm.planMajorTwo" filterable clearable placeholder="请选择拟报专业2" >
              <el-option
                v-for="item in planMajorList"
                :key="item.id"
                :label="item.majorName"
                :value="item.id"
                :disabled="isDisable(item.id)"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="拟报专业3" prop="planMajorThree">
            <el-select v-model="dataForm.planMajorThree" filterable clearable placeholder="请选择拟报专业3" >
              <el-option
                v-for="item in planMajorList"
                :key="item.id"
                :label="item.majorName"
                :value="item.id"
                :disabled="isDisable(item.id)"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="拟报专业4" prop="planMajorFour">
            <el-select v-model="dataForm.planMajorFour" filterable clearable placeholder="请选择拟报专业4" >
              <el-option
                v-for="item in planMajorList"
                :key="item.id"
                :label="item.majorName"
                :value="item.id"
                :disabled="isDisable(item.id)"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="拟报专业5" prop="planMajorFive">
            <el-select v-model="dataForm.planMajorFive" filterable clearable placeholder="请选择拟报专业5" >
              <el-option
                v-for="item in planMajorList"
                :key="item.id"
                :label="item.majorName"
                :value="item.id"
                :disabled="isDisable(item.id)"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="拟报专业6" prop="planMajorSix">
            <el-select v-model="dataForm.planMajorSix" filterable clearable placeholder="请选择拟报专业6" >
              <el-option
                v-for="item in planMajorList"
                :key="item.id"
                :label="item.majorName"
                :value="item.id"
                :disabled="isDisable(item.id)"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="拟报专业7" prop="planMajorSeven">
            <el-select v-model="dataForm.planMajorSeven" filterable clearable placeholder="请选择拟报专业7" >
              <el-option
                v-for="item in planMajorList"
                :key="item.id"
                :label="item.majorName"
                :value="item.id"
                :disabled="isDisable(item.id)"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="拟报专业8" prop="planMajorEight">
            <el-select v-model="dataForm.planMajorEight" filterable clearable placeholder="请选择拟报专业8" >
              <el-option
                v-for="item in planMajorList"
                :key="item.id"
                :label="item.majorName"
                :value="item.id"
                :disabled="isDisable(item.id)"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="拟报专业9" prop="planMajorNine">
            <el-select v-model="dataForm.planMajorNine" filterable clearable placeholder="请选择拟报专业9" >
              <el-option
                v-for="item in planMajorList"
                :key="item.id"
                :label="item.majorName"
                :value="item.id"
                :disabled="isDisable(item.id)"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="拟报专业10" prop="planMajorTen">
            <el-select v-model="dataForm.planMajorTen" filterable clearable placeholder="请选择拟报专业10" >
              <el-option
                v-for="item in planMajorList"
                :key="item.id"
                :label="item.majorName"
                :value="item.id"
                :disabled="isDisable(item.id)"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="拟报专业11" prop="planMajorEleven">
            <el-select v-model="dataForm.planMajorEleven" filterable clearable placeholder="请选择拟报专业11" >
              <el-option
                v-for="item in planMajorList"
                :key="item.id"
                :label="item.majorName"
                :value="item.id"
                :disabled="isDisable(item.id)"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="拟报专业12" prop="planMajorTwelve">
            <el-select v-model="dataForm.planMajorTwelve" filterable clearable placeholder="请选择拟报专业12" >
              <el-option
                v-for="item in planMajorList"
                :key="item.id"
                :label="item.majorName"
                :value="item.id"
                :disabled="isDisable(item.id)"
              >
              </el-option>
            </el-select>
          </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" 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 { useAuth } from '/@/hooks/auth'
import { getObj, addObjStu, putObj } from '/@/api/recruit/recruitprestudent'
import { getList } from '/@/api/recruit/recruitstudentplangroup'
import { getDicts } from '/@/api/admin/dict'
import { queryAllTeacherByRecruit } from '/@/api/professional/professionaluser/teacherbase'
import { verifyPhone, verifyAdmissionNumber } from '/@/utils/toolsValidate'

const { hasAuth } = useAuth()
// Props
const props = defineProps<{
  planList?: any[]
  planMajorList?: any[]
  schoolList?: any[]
}>()

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

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

// 响应式数据
const visible = ref(false)
const canSubmit = ref(false)
const contactNameList = ref<any[]>([])
const planListLocal = ref<any[]>([])
const sexyList = ref<any[]>([])

const dataForm = reactive({
  id: "",
  groupId: "",
  name: "",
  gender: "",
  phone: "",
  idCard: "",
  schoolId: "",
  planMajorOne: "",
  planMajorTwo: "",
  planMajorThree: "",
  planMajorFour: "",
  planMajorFive: "",
  planMajorSix: "",
  planMajorSeven: "",
  planMajorEight: "",
  planMajorNine: "",
  planMajorTen: "",
  planMajorEleven: "",
  planMajorTwelve: "",
  admission: "",
  achievement: null as number | null,
  contactsNo: "",
  djUser: null as string | null,
  djTime: null as string | null,
  djName: null as string | null,
  djDept: null as string | null,
  isDj: "0",
  year: ""
})

const dataRule = {
  planMajorOne: [
    { required: true, message: '拟报专业1不能为空', trigger: 'blur' }
  ],
  groupId: [
    { required: true, message: '招生计划不能为空', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '姓名不能为空', trigger: 'blur' },
    { min: 1, max: 20, message: "姓名长度最多20位", trigger: "blur" }
  ],
  phone: [
    { required: true, message: '电话不能为空', trigger: 'blur' },
    {
      validator: (rule: any, value: any, callback: any) => {
        if (value && !verifyPhone(value)) {
          callback(new Error('请输入正确的手机号码'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  idCard: [
    { required: true, message: '身份证不能为空', trigger: 'blur' }
  ],
  admission: [
    { required: true, message: '准考证不能为空', trigger: 'blur' },
    {
      validator: (rule: any, value: any, callback: any) => {
        if (value && !verifyAdmissionNumber(value)) {
          callback(new Error('请输入正确的准考证号'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  gender: [
    { required: true, message: '性别不能为空', trigger: 'blur' }
  ],
  schoolId: [
    { required: true, message: '学校不能为空', trigger: 'blur' }
  ],
}

/**
 * 判断拟报专业是否已经占用,占用不可选
 */
const isDisable = (id: string) => {
  if (id == dataForm.planMajorOne
    || id == dataForm.planMajorTwo
    || id == dataForm.planMajorThree
    || id == dataForm.planMajorFour
    || id == dataForm.planMajorFive
    || id == dataForm.planMajorSix
    || id == dataForm.planMajorSeven
    || id == dataForm.planMajorEight
    || id == dataForm.planMajorNine
    || id == dataForm.planMajorTen
    || id == dataForm.planMajorEleven
    || id == dataForm.planMajorTwelve
  ) {
    return true
  } else {
    return false
  }
}

// 表单提交
const dataFormSubmit = () => {
  dataFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      canSubmit.value = false
      if (dataForm.id) {
        putObj(dataForm).then(() => {
          ElNotification.success({
            title: '成功',
            message: '修改成功'
          })
          visible.value = false
          emit('refreshDataList')
        }).catch(() => {
          canSubmit.value = true
        })
      } else {
        dataForm.djUser = null
        dataForm.djTime = null
        dataForm.djName = null
        dataForm.djDept = null
        dataForm.isDj = "0"
        addObjStu(dataForm).then(() => {
          ElNotification.success({
            title: '成功',
            message: '添加成功'
          })
          visible.value = false
          emit('refreshDataList')
        }).catch(() => {
          canSubmit.value = true
        })
      }
    }
  })
}

// 初始化方法
const init = (id: string | null) => {
  dataForm.id = id || ""
  visible.value = true
  canSubmit.value = true
  
  // 初始化 planListLocal，优先使用 props，如果没有则使用空数组
  planListLocal.value = props.planList ? [...props.planList] : []
  
  nextTick(() => {
    dataFormRef.value?.resetFields()
    // 获取性别字典
    getDicts('sexy').then((res: any) => {
      sexyList.value = res.data || []
    })
    // 获取教师列表（对接人）
    queryAllTeacherByRecruit().then((res: any) => {
      contactNameList.value = res.data || []
    }).catch(() => {
      contactNameList.value = []
    })
    if (dataForm.id) {
      getObj(dataForm.id).then((response: any) => {
        Object.assign(dataForm, response.data)
        if (dataForm.year) {
          dataForm.year = String(dataForm.year)
        }
      })
    } else {
      getList().then((data: any) => {
        planListLocal.value = data.data
        if (planListLocal.value.length > 0) {
          dataForm.groupId = planListLocal.value[0].id
        }
      })
    }
  })
}

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

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