<template>
  <el-dialog v-model="dialogVisible" title="修改学历学位" width="600px" append-to-body :close-on-click-modal="false" destroy-on-close>
    <div v-if="showForm">
      <el-form
        ref="formRef"
        :model="dataForm"
        :rules="formRules"
        :validate-on-rule-change="false"
        label-width="120px"
      >
        <el-form-item label="毕业时间" prop="graduateTime">
          <el-date-picker
            v-model="dataForm.graduateTime"
            type="date"
            placeholder="请选择毕业时间"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>

        <el-form-item label="教育类型" prop="type">
          <el-select
            v-model="dataForm.type"
            filterable
            clearable
            placeholder="请选择教育类型"
          >
            <el-option
              v-for="item in educationTypeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="学历" prop="qualificationConfigId">
          <el-select
            v-model="dataForm.qualificationConfigId"
            filterable
            clearable
            placeholder="请选择学历"
            @change="handleQualificationChange"
          >
            <el-option
              v-for="item in qualificationList"
              :key="item.id"
              :label="item.qualificationName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="学位" prop="degreeConfigId">
          <el-select
            v-model="dataForm.degreeConfigId"
            filterable
            clearable
            placeholder="请选择学位"
            @change="handleDegreeChange"
          >
            <el-option
              v-for="item in degreeList"
              :key="item.id"
              :label="item.degreeName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="毕业学校" prop="graduateSchool">
          <el-input
            v-model="dataForm.graduateSchool"
            placeholder="请输入毕业学校"
            clearable
          />
        </el-form-item>

        <el-form-item label="所学专业" prop="major">
          <el-input
            v-model="dataForm.major"
            placeholder="请输入所学专业"
            clearable
          />
        </el-form-item>

        <el-form-item label="证书编号" prop="certificateNumber">
          <el-input
            v-model="dataForm.certificateNumber"
            placeholder="请输入证书编号（仅支持英文和数字）"
            clearable
            show-word-limit
            maxlength="100"
            @input="handleCertificateNumberInput"
          />
        </el-form-item>

        <el-form-item v-if="needQualificationImg" label="学历证书" prop="qualificationImg" required>
          <el-upload
            :headers="headers"
            :limit="1"
            :action="url"
            :file-list="fileList"
            :on-success="materiaUploadSuccess"
            :accept="'.jpg,.jpeg,.png,.pdf'"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <template #tip>
              <div style="margin-top: 8px;">
                <el-tag>仅支持jpg,jpeg,png,pdf后缀的文件上传</el-tag>
              </div>
            </template>
          </el-upload>
        </el-form-item>

        <el-form-item v-if="needDegreeImg" label="学位证书" prop="degreeImg" required>
          <el-upload
            :headers="headers"
            :limit="1"
            :action="url"
            :file-list="fileListB"
            :on-success="materiaUploadSuccessB"
            :accept="'.jpg,.jpeg,.png,.pdf'"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <template #tip>
              <div style="margin-top: 8px;">
                <el-tag>仅支持jpg,jpeg,png,pdf后缀的文件上传</el-tag>
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogSubmit" :loading="submitLoading">确定</el-button>
      </div>
      </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, nextTick } from 'vue'
import { Session } from '/@/utils/storage'
import { useMessage } from '/@/hooks/message'
import { addObj } from '/@/api/professional/professionaluser/professionalteacheracademicrelation'
import { getAllTypeList } from '/@/api/professional/rsbase/professionalacademiceducationtypeconfig'
import { getQualificationList } from '/@/api/professional/rsbase/academicqualificationsconfig'
import { getDegreeList } from '/@/api/professional/rsbase/professionalacademicdegreeconfig'
import { checkLocked } from '/@/api/professional/professionalstatuslock'

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

// 消息提示
const message = useMessage()

// 表单引用
const formRef = ref()
const submitLoading = ref(false)

// 对话框显示状态（内部管理）
const dialogVisible = ref(false)

// 表单数据
const dataForm = reactive({
  graduateTime: '',
  type: '',
  qualificationConfigId: '',
  degreeConfigId: '',
  graduateSchool: '',
  major: '',
  certificateNumber: '',
  qualificationImg: '',
  degreeImg: '',
  state: '',
  id: ''
})

// 计算属性：是否需要学历证书（选择了学历）
const needQualificationImg = computed(() => {
  return !!dataForm.qualificationConfigId
})

// 计算属性：是否需要学位证书（选择了学位且不等于 -1 或"无"）
const needDegreeImg = computed(() => {
  if (!dataForm.degreeConfigId) return false
  // 检查是否为 -1 或"无"（处理类型转换）
  const degreeId = String(dataForm.degreeConfigId)
  if (degreeId === '-1') return false
  // 检查学位列表中是否有名称为"无"的选项
  const degreeItem = degreeList.value.find(item => String(item.id) === degreeId)
  if (degreeItem && degreeItem.degreeName === '无') return false
  return true
})

// 验证规则
const formRules = computed(() => {
  const rules: any = {
    graduateTime: [
      { required: true, message: '请选择毕业时间', trigger: 'blur' }
    ],
    type: [
      { required: true, message: '请选择教育类型', trigger: 'blur' }
    ],
    graduateSchool: [
      { required: true, message: '请输入毕业学校', trigger: 'blur' }
    ],
    major: [
      { required: true, message: '请输入所学专业', trigger: 'blur' }
    ],
    certificateNumber: [
      { required: true, message: '请输入证书编号', trigger: 'blur' },
      { pattern: /^[A-Za-z0-9]+$/, message: '证书编号只能包含英文和数字', trigger: 'blur' }
    ]
  }
  
  // 只有当需要学历证书时才添加验证规则
  if (needQualificationImg.value) {
    rules.qualificationImg = [
      { required: true, message: '请上传学历证书', trigger: 'blur' }
    ]
  }
  
  // 只有当需要学位证书时才添加验证规则
  if (needDegreeImg.value) {
    rules.degreeImg = [
      { required: true, message: '请上传学位证书', trigger: 'blur' }
    ]
  }
  
  return rules
})

// 下拉列表数据
const educationTypeList = ref<any[]>([])
const qualificationList = ref<any[]>([])
const degreeList = ref<any[]>([])

// 基础信息（简化，只保留需要的）

// 上传相关
const url = ref('')
const fileList = ref<any[]>([])
const fileListB = ref<any[]>([])

// 请求头
const headers = computed(() => {
      return {
    "Authorization": 'Bearer ' + Session.getToken()
  }
})

// 显示表单标志
const showForm = ref(false)

// 初始化字典数据
const initDicData = async () => {
  try {
    // 使用专门的 API 获取数据（与 index.vue 保持一致）
    const [eduRes, quaRes, degRes] = await Promise.all([
      getAllTypeList(),
      getQualificationList(),
      getDegreeList()
    ])
    
    // 获取教育类型列表
    if (eduRes && eduRes.data) {
      educationTypeList.value = eduRes.data
    }
    
    // 获取学历列表
    if (quaRes && quaRes.data) {
      qualificationList.value = quaRes.data
    }
    
    // 获取学位列表
    if (degRes && degRes.data) {
      degreeList.value = degRes.data
    }
  } catch (error) {
    // 获取字典数据失败
  }
}

// 证书编号输入处理（只允许英文和数字）
const handleCertificateNumberInput = (value: string) => {
  dataForm.certificateNumber = value.replace(/[^A-Za-z0-9]/g, '')
}

// 学历改变时的处理
const handleQualificationChange = () => {
  // 如果不需要学历证书，清除学历证书字段、文件列表和验证错误
  if (!needQualificationImg.value) {
    dataForm.qualificationImg = ''
    fileList.value = []
    formRef.value?.clearValidate('qualificationImg')
  } else {
    // 如果需要学历证书，延迟清除验证（等字段显示后）
    nextTick(() => {
      formRef.value?.clearValidate('qualificationImg')
    })
  }
}

// 学位改变时的处理
const handleDegreeChange = () => {
  // 如果不需要学位证书，清除学位证书字段、文件列表和验证错误
  if (!needDegreeImg.value) {
    dataForm.degreeImg = ''
    fileListB.value = []
    formRef.value?.clearValidate('degreeImg')
  } else {
    // 如果需要学位证书，延迟清除验证（等字段显示后）
    nextTick(() => {
      formRef.value?.clearValidate('degreeImg')
    })
  }
}

// 文件上传成功 - 学历证书
const materiaUploadSuccess = (response: any) => {
  if (response.data && response.data.code === "-1") {
    message.error("当前不允许上传文件")
    return
  }
  dataForm.qualificationImg = response.data.url
  // 清除验证错误
  formRef.value?.clearValidate('qualificationImg')
}

// 文件上传成功 - 学位证书
const materiaUploadSuccessB = (response: any) => {
  if (response.data && response.data.code === "-1") {
    message.error("当前不允许上传文件")
    return
  }
  dataForm.degreeImg = response.data.url
  // 清除验证错误
  formRef.value?.clearValidate('degreeImg')
}

// 打开对话框
const openDialog = async (row?: any) => {
  // 新增模式：先检查是否锁定
  if (!row || !row.id) {
    try {
      const lockResponse = await checkLocked('acade')
      if (lockResponse.data) {
        message.warning("新增功能已锁定，暂不允许操作")
        return
      }
    } catch (error) {
      // 错误处理已在数据请求层统一处理，此处不需要提示
      return
    }
  }
  
  // 公共设置
  url.value = `/professional/file/teacherAboutInfoUpload?type=1`
  fileList.value = []
  fileListB.value = []
  
  // 根据是否有 row 设置不同的表单数据
  if (row && row.id) {
    // 编辑模式：使用传入的数据
    // 确保类型匹配（将 id 转换为字符串或数字，与选项列表保持一致）
    Object.assign(dataForm, {
      graduateTime: row.graduateTime || '',
      type: row.type !== null && row.type !== undefined ? String(row.type) : '',
      qualificationConfigId: row.qualificationConfigId !== null && row.qualificationConfigId !== undefined ? String(row.qualificationConfigId) : '',
      degreeConfigId: row.degreeConfigId !== null && row.degreeConfigId !== undefined ? String(row.degreeConfigId) : '',
      graduateSchool: row.graduateSchool || '',
      major: row.major || '',
      certificateNumber: row.certificateNumber || '',
      qualificationImg: row.qualificationImg || '',
      degreeImg: row.degreeImg || '',
      state: row.state || '',
      id: row.id || ''
    })
  } else {
    // 新增模式：重置为空
    Object.assign(dataForm, {
      graduateTime: '',
      type: '',
      qualificationConfigId: '',
      degreeConfigId: '',
      graduateSchool: '',
      major: '',
      certificateNumber: '',
      qualificationImg: '',
      degreeImg: '',
      state: '',
      id: ''
    })
  }
  
  // 公共操作：先加载字典数据，再显示对话框
  await initDicData()
  // 等待字典数据加载完成后再显示表单，确保选项列表已准备好
  await nextTick()
  showForm.value = true
  dialogVisible.value = true
  // 对话框打开后，清除所有验证错误，避免立即显示验证提示
  await nextTick()
  formRef.value?.clearValidate()
}

// 提交表单
const dialogSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      submitLoading.value = true
      try {
        // 统一使用 addObj 接口（新增和编辑都使用）
        const submitData: any = {
          graduateTime: dataForm.graduateTime,
          type: dataForm.type,
          qualificationConfigId: dataForm.qualificationConfigId,
          degreeConfigId: dataForm.degreeConfigId,
          graduateSchool: dataForm.graduateSchool,
          major: dataForm.major,
          certificateNumber: dataForm.certificateNumber,
          qualificationImg: dataForm.qualificationImg,
          degreeImg: dataForm.degreeImg,
          state: '' // 待审核
        }
        
        // 编辑时需要传递 id
        if (dataForm.id) {
          submitData.id = dataForm.id
        }
        
        await addObj(submitData)
        message.success(dataForm.id ? "修改成功" : "提交成功")
        dialogVisible.value = false
        emit('refreshData')
      } catch (error: any) {
        // 错误处理已在数据请求层统一处理，此处不需要提示
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 初始化方法（保持兼容性）
const init = () => {
  // 新版本不再需要初始化配置
}

// 暴露方法
defineExpose({
  openDialog,
  init
})
</script>

<style scoped>
</style>
