<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="100px">
      <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-form-item label="学校代码" prop="schoolCode">
        <el-input v-model="dataForm.schoolCode" placeholder="学校代码"></el-input>
      </el-form-item>
      <el-form-item label="学校名称" prop="schoolName">
        <el-input v-model="dataForm.schoolName" placeholder="学校名称"></el-input>
      </el-form-item>
      <el-form-item label="对接学院" prop="deptCode">
        <el-select v-model="dataForm.deptCode" filterable clearable placeholder="请选择对接学院">
          <el-option
            v-for="item in deptList"
            :key="item.deptCode"
            :label="item.deptName"
            :value="item.deptCode">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="地区" prop="area">
        <el-select v-model="dataForm.area" filterable placeholder="请选择地区">
          <el-option
            v-for="item in areaListData"
            :key="item.code"
            :label="item.name"
            :value="item.code">
          </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 { addObj, areaList, getObj, putObj } from '/@/api/recruit/recruitstudentschool'
import { getDeptList } from '/@/api/basic/basicclass'
import { getList } from '/@/api/recruit/recruitstudentplangroup'

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

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

// 响应式数据
const visible = ref(false)
const canSubmit = ref(false)
const planList = ref<any[]>([])
const areaListData = ref<any[]>([])
const deptList = ref<any[]>([])

const dataForm = reactive({
  id: "",
  groupId: "",
  area: "",
  deptCode: "",
  schoolName: ""
})

const dataRule = {
  groupId: [
    { required: true, message: '招生计划不能为空', trigger: 'blur' },
  ],
  schoolName: [
    { required: true, message: '学校名称不能为空', trigger: 'blur' },
    { min: 1, max: 20, message: '学校名称长度不大于20个字符', trigger: 'blur' }
  ],
  schoolCode:[
    { required: true, message: '学校代码不能为空', trigger: 'blur' },
    { min: 1, max: 20, message: '学校代码长度不大于20个字符', trigger: 'blur' }
  ],
  area: [
    { required: true, message: '地区不能为空', trigger: 'blur' },
  ],
}

// 初始化数据
const initData = () => {
  // 查询二级学院信息
  getDeptList().then((data: any) => {
    deptList.value = data.data
    deptList.value.push({ deptCode: "190", deptName: "招生就业处" })
  })
  getList().then((data: any) => {
    planList.value = data.data
  })
  // 获取所有省
  areaList({ type: "0", parentId: 112 }).then((res: any) => {
    areaListData.value = res.data
  })
}

// 表单提交
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 {
        addObj(dataForm).then(() => {
          ElNotification.success({
            title: '成功',
            message: '添加成功'
          })
          visible.value = false
          emit('refreshDataList')
        }).catch(() => {
          canSubmit.value = true
        })
      }
    }
  })
}

// 初始化方法
const init = (id: string | null) => {
  visible.value = true
  canSubmit.value = true
  dataForm.id = ""
  
  // 重置表单数据
  nextTick(() => {
    dataFormRef.value?.resetFields()
  })
  
  initData()
  
  // 获取详情数据
  if (id) {
    dataForm.id = id
    getObj(id).then((response: any) => {
      if (response && response.data) {
        Object.assign(dataForm, response.data)
        if (dataForm.area) {
          dataForm.area = String(dataForm.area)
        }
        // 确保 deptCode 正确映射（如果 API 返回的是 xy 字段）
        if (response.data.xy && !response.data.deptCode) {
          dataForm.deptCode = response.data.xy
        }
      }
    }).catch(() => {
      // 错误处理
    })
  } else {
    // 新增模式：设置默认招生计划
    getList().then((data: any) => {
      if (data.data && data.data.length > 0) {
        dataForm.groupId = data.data[0]?.id || ""
    }
  })
  }
}

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

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