<template>
  <el-dialog 
    :title="form.id ? '编辑' : '新增'" 
    v-model="visible"
    :close-on-click-modal="false" 
    draggable
    width="900px">
    <el-form 
      ref="dataFormRef" 
      :model="form" 
      :rules="dataRules" 
      label-width="140px" 
      :validate-on-rule-change="false"
      v-loading="loading">
      <el-row :gutter="24">
        <el-col :span="12" class="mb20">
          <el-form-item label="姓名" prop="realName">
            <el-input 
              v-model="form.realName" 
              placeholder="请输入姓名" 
              clearable />
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="身份证" prop="idCard">
            <el-input 
              v-model="form.idCard" 
              placeholder="请输入身份证号" 
              clearable />
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="性别" prop="sex">
            <el-select 
              v-model="form.sex" 
              placeholder="请选择" 
              clearable
              style="width: 100%">
              <el-option label="男" value="1" />
              <el-option label="女" value="0" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="出生日期" prop="birthday">
            <el-date-picker
              v-model="form.birthday"
              type="date"
              placeholder="选择日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 100%" />
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="户口所在地" prop="householdAddress">
            <el-input 
              v-model="form.householdAddress" 
              placeholder="请输入户口所在地" 
              clearable />
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="班级" prop="classCode">
            <el-select 
              v-model="form.classCode" 
              placeholder="请选择班级" 
              clearable
              filterable
              style="width: 100%">
              <el-option
                v-for="item in classList"
                :key="item.classCode"
                :label="item.classNo"
                :value="item.classCode">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="学号" prop="stuNo">
            <el-input 
              v-model="form.stuNo" 
              placeholder="请输入学号" 
              clearable />
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="辩色力" prop="colourSense">
            <el-select 
              v-model="form.colourSense" 
              placeholder="请选择辩色力" 
              clearable
              filterable
              style="width: 100%">
              <el-option
                v-for="item in eyeStatusList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="退伍军人" prop="veteran">
            <el-select 
              v-model="form.veteran" 
              placeholder="请选择" 
              clearable
              filterable
              style="width: 100%">
              <el-option
                v-for="item in veteranStatusList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="政治面貌" prop="politicsStatus">
            <el-select 
              v-model="form.politicsStatus" 
              placeholder="请选择政治面貌" 
              clearable
              filterable
              style="width: 100%">
              <el-option
                v-for="item in politicsStatusList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="民族" prop="national">
            <el-select 
              v-model="form.national" 
              placeholder="请选择民族" 
              clearable
              filterable
              style="width: 100%">
              <el-option
                v-for="item in nationalList"
                :key="item.nationCode"
                :label="item.nationName"
                :value="item.nationCode">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="是否10万以下民族" prop="isLowPopulation">
            <el-select 
              v-model="form.isLowPopulation" 
              placeholder="请选择" 
              clearable
              style="width: 100%">
              <el-option label="是" value="1" />
              <el-option label="否" value="0" />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="既往病史" prop="medicalHistory">
            <el-input 
              v-model="form.medicalHistory" 
              placeholder="请输入既往病史" 
              clearable />
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="入学前文化程度" prop="beforeEducation">
            <el-select 
              v-model="form.beforeEducation" 
              placeholder="请选择入学前文化程度" 
              clearable
              filterable
              style="width: 100%">
              <el-option
                v-for="item in preSchoolEducationList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="入学前毕业学校" prop="beforeSchool">
            <el-input 
              v-model="form.beforeSchool" 
              placeholder="请输入入学前毕业学校" 
              clearable />
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="毕业学校省市" prop="schoolProvince">
            <el-select 
              v-model="form.schoolProvince" 
              placeholder="请选择毕业学校省市" 
              clearable
              filterable
              style="width: 100%">
              <el-option
                v-for="item in schoolProvinceList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit" :disabled="loading">确 认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="BasicStudentDialog">
import { ref, reactive, nextTick, onMounted } from 'vue'
import { useMessage } from "/@/hooks/message";
import { getObj, addObj, putObj } from '/@/api/basic/basicstudent'
import { getClassListByRole } from '/@/api/basic/basicclass'
import { getNationalList } from '/@/api/basic/basicnation'
import { getPoliticsStatusDict } from '/@/api/basic/basicpoliticsstatusbase'
import { queryDictByTypeList } from '/@/api/admin/dict'

const emit = defineEmits(['refresh']);

// 定义变量内容
const dataFormRef = ref();
const visible = ref(false)
const loading = ref(false)
const classList = ref<any[]>([])
const nationalList = ref<any[]>([])
const politicsStatusList = ref<any[]>([])
const eyeStatusList = ref<any[]>([])
const veteranStatusList = ref<any[]>([])
const preSchoolEducationList = ref<any[]>([])
const schoolProvinceList = ref<any[]>([])

// 提交表单数据
const form = reactive({
  id: '',
  realName: '',
  idCard: '',
  sex: '',
  birthday: '',
  householdAddress: '',
  classCode: '',
  stuNo: '',
  colourSense: '',
  veteran: '',
  politicsStatus: '',
  national: '',
  isLowPopulation: '',
  medicalHistory: '',
  beforeEducation: '',
  beforeSchool: '',
  schoolProvince: ''
});

// 定义校验规则 - 除了"是否10万以下民族"外，其他字段都是必填
const dataRules = ref({
  realName: [
    { required: true, message: '姓名不能为空', trigger: 'blur' }
  ],
  idCard: [
    { required: true, message: '身份证不能为空', trigger: 'blur' },
    { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号', trigger: 'blur' }
  ],
  sex: [
    { required: true, message: '性别不能为空', trigger: 'change' }
  ],
  birthday: [
    { required: true, message: '出生日期不能为空', trigger: 'change' }
  ],
  householdAddress: [
    { required: true, message: '户口所在地不能为空', trigger: 'blur' }
  ],
  classCode: [
    { required: true, message: '班级不能为空', trigger: 'change' }
  ],
  stuNo: [
    { required: true, message: '学号不能为空', trigger: 'blur' }
  ],
  colourSense: [
    { required: true, message: '辩色力不能为空', trigger: 'blur' }
  ],
  veteran: [
    { required: true, message: '退伍军人不能为空', trigger: 'change' }
  ],
  politicsStatus: [
    { required: true, message: '政治面貌不能为空', trigger: 'change' }
  ],
  national: [
    { required: true, message: '民族不能为空', trigger: 'change' }
  ],
  medicalHistory: [
    { required: true, message: '既往病史不能为空', trigger: 'blur' }
  ],
  beforeEducation: [
    { required: true, message: '入学前文化程度不能为空', trigger: 'blur' }
  ],
  beforeSchool: [
    { required: true, message: '入学前毕业学校不能为空', trigger: 'blur' }
  ],
  schoolProvince: [
    { required: true, message: '毕业学校省市不能为空', trigger: 'blur' }
  ]
  // isLowPopulation 不需要必填验证
})

// 打开弹窗
const openDialog = (id?: string) => {
  visible.value = true
  
  // 重置表单数据
  Object.assign(form, {
    id: '',
    realName: '',
    idCard: '',
    sex: '',
    birthday: '',
    householdAddress: '',
    classCode: '',
    stuNo: '',
    colourSense: '',
    veteran: '',
    politicsStatus: '',
    national: '',
    isLowPopulation: '',
    medicalHistory: '',
    beforeEducation: '',
    beforeSchool: '',
    schoolProvince: ''
  })

  // 清除表单验证状态，不触发验证
  nextTick(() => {
    dataFormRef.value?.clearValidate();
    dataFormRef.value?.resetFields();
  });

  // 获取详情
  if (id) {
    form.id = id
    getStudentData(id)
  } else {
    // 新增时，确保验证状态已清除
    nextTick(() => {
      dataFormRef.value?.clearValidate();
    });
  }
};

// 提交
const onSubmit = async () => {
  const valid = await dataFormRef.value.validate().catch(() => {});
  if (!valid) return false;

  try {
    loading.value = true;
    if (form.id) {
      await putObj(form);
      useMessage().success('编辑成功');
    } else {
      await addObj(form);
      useMessage().success('新增成功');
    }
    visible.value = false;
    emit('refresh');
  } catch (err: any) {
    useMessage().error(err.msg || (form.id ? '编辑失败' : '新增失败'));
  } finally {
    loading.value = false;
  }
};

// 获取详情
const getStudentData = (id: string) => {
  loading.value = true
  getObj(id).then((res: any) => {
    if (res.data) {
      Object.assign(form, {
        id: res.data.id || '',
        realName: res.data.realName || '',
        idCard: res.data.idCard || '',
        sex: res.data.sex || '',
        birthday: res.data.birthday || '',
        householdAddress: res.data.householdAddress || '',
        classCode: res.data.classCode || '',
        stuNo: res.data.stuNo || '',
        colourSense: res.data.colourSense || '',
        veteran: res.data.veteran || '',
        politicsStatus: res.data.politicsStatus || '',
        national: res.data.national || '',
        isLowPopulation: res.data.isLowPopulation || '',
        medicalHistory: res.data.medicalHistory || '',
        beforeEducation: res.data.beforeEducation || '',
        beforeSchool: res.data.beforeSchool || '',
        schoolProvince: res.data.schoolProvince || ''
      })
    }
  }).catch((err: any) => {
    console.error('获取详情失败', err)
    useMessage().error('获取详情失败')
  }).finally(() => {
    loading.value = false
    // 数据加载完成后，清除验证状态，避免触发验证
    nextTick(() => {
      dataFormRef.value?.clearValidate();
    });
  })
}

// 获取班级列表
const getClassListData = async () => {
  try {
    const res = await getClassListByRole()
    if (res.data) {
      classList.value = Array.isArray(res.data) ? res.data : []
    }
  } catch (err) {
    console.error('获取班级列表失败', err)
    classList.value = []
  }
}

// 获取民族列表
const getNationalListData = async () => {
  try {
    const res = await getNationalList()
    if (res.data) {
      nationalList.value = Array.isArray(res.data) ? res.data : []
    }
  } catch (err) {
    console.error('获取民族列表失败', err)
    nationalList.value = []
  }
}

// 获取政治面貌列表
const getPoliticsStatusListData = async () => {
  try {
    const res = await getPoliticsStatusDict()
    if (res.data) {
      politicsStatusList.value = Array.isArray(res.data) ? res.data : []
    }
  } catch (err) {
    console.error('获取政治面貌列表失败', err)
    politicsStatusList.value = []
  }
}

// 获取字典数据
const getDictData = async () => {
  try {
    const dictTypes = ['eye_status', 'veteran_status', 'pre_school_education', 'school_province']
    const res = await queryDictByTypeList(dictTypes)
    if (res.data && typeof res.data === 'object') {
      // 解析返回的字典数据，统一转换为 {label, value} 格式
      const parseDictList = (dictData: any) => {
        if (!Array.isArray(dictData)) return []
        return dictData.map((item: any) => ({
          label: item.label || item.name || item.dictLabel || '',
          value: item.value || item.code || item.dictValue || ''
        })).filter((item: any) => item.label && item.value !== undefined && item.value !== null && item.value !== '')
      }
      
      if (res.data.eye_status) {
        eyeStatusList.value = parseDictList(res.data.eye_status)
      }
      if (res.data.veteran_status) {
        veteranStatusList.value = parseDictList(res.data.veteran_status)
      }
      if (res.data.pre_school_education) {
        preSchoolEducationList.value = parseDictList(res.data.pre_school_education)
      }
      if (res.data.school_province) {
        schoolProvinceList.value = parseDictList(res.data.school_province)
      }
    }
  } catch (err) {
    console.error('获取字典数据失败', err)
    eyeStatusList.value = []
    veteranStatusList.value = []
    preSchoolEducationList.value = []
    schoolProvinceList.value = []
  }
}

// 初始化
onMounted(() => {
  getClassListData()
  getNationalListData()
  getPoliticsStatusListData()
  getDictData()
})

// 暴露变量
defineExpose({
  openDialog
});
</script>

<style lang="scss" scoped>
.mb20 {
  margin-bottom: 20px;
}
</style>
