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

      <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-form-item label="姓名" prop="name">
        <el-input v-model="dataForm.name" placeholder="姓名"></el-input>
      </el-form-item>
      <el-form-item label="电话" prop="phone">
        <el-input v-model="dataForm.phone" placeholder="电话"></el-input>
      </el-form-item>
      <el-form-item label="身份证" prop="idCard">
        <el-input v-model="dataForm.idCard" placeholder="身份证"></el-input>
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-select v-model="dataForm.gender">
          <el-option
            v-for="item in sexyList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="准考证" prop="admission">
        <el-input v-model="dataForm.admission" placeholder="准考证"></el-input>
      </el-form-item>
      <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-form-item label="对接人" prop="djUser" v-if="permissions.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-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-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-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-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-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-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-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-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-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-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-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-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-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-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, computed, nextTick } from 'vue'
import { storeToRefs } from 'pinia'
import { useUserInfo } from '/@/stores/userInfo'
import { ElNotification } from 'element-plus'
import { getObj, addObjStu, putObj } from '/@/api/recruit/recruitprestudent'
import { queryTeacherBaseByNoByAssets } from '/@/api/professional/professionaluser/teacherbase'
import { list } from '/@/api/recruit/recruitstudentplangroup'
import { getDicts } from '/@/api/admin/dict'

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

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

// 使用 Pinia store
const userInfoStore = useUserInfo()
const { userInfos } = storeToRefs(userInfoStore)

// 创建权限对象
const permissions = computed(() => {
  const perms: Record<string, boolean> = {}
  userInfos.value.authBtnList.forEach((perm: string) => {
    perms[perm] = true
  })
  return perms
})

// 表单引用
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' },
    { min: 11, max: 11, message: "电话号码长度为11位", 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 || null
  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 || []
    })
    // 这里如果需要教师列表，可以改用新的教师接口；当前项目中常用的是 queryTeacherBaseByNoByAssets
    if (dataForm.id) {
      getObj(dataForm.id).then((response: any) => {
        Object.assign(dataForm, response.data)
        if (dataForm.year) {
          dataForm.year = String(dataForm.year)
        }
      })
    } else {
      list().then((data: any) => {
        planListLocal.value = data.data
        if (planListLocal.value.length > 0) {
          dataForm.groupId = planListLocal.value[0].id
        }
      })
    }
  })
}

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

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