<template>
  <el-dialog v-model="dialogVisible" title="编辑教师资格证" width="800px" append-to-body :close-on-click-modal="false" destroy-on-close>
    <div v-if="showForm">
      <el-form
        ref="formRef"
        :model="dataForm"
        :rules="formRules"
        label-width="120px"
      >
        <el-form-item label="类型" prop="certificateConfId">
          <el-select
            v-model="dataForm.certificateConfId"
            filterable
            clearable
            placeholder="请选择类型"
            style="width: 100%"
          >
            <el-option
              v-for="item in teacherCertificateList"
              :key="item.id"
              :label="item.cretificateName || item.certificateName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="取证时间" prop="certificateTime">
          <el-date-picker
            v-model="dataForm.certificateTime"
            type="date"
            placeholder="请选择取证时间"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>

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

        <el-form-item label="材料1" prop="materialA">
          <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 label="材料2" prop="materialB">
          <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 } from 'vue'
import { Session } from '/@/utils/storage'
import { useMessage } from '/@/hooks/message'
import { getMyTeacherNo, updateOtherInfo } from '/@/api/professional/professionaluser/teacherbase'
import { putObj } from '/@/api/professional/professionaluser/professionalteachercertificaterelation'
import { getTeacherCertificateList } from '/@/api/professional/rsbase/professionalteachercertificateconf'
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({
  certificateConfId: '',
  certificateTime: '',
  certificateNumber: '',
  materialA: '',
  materialB: '',
  evidenceA: '',
  evidenceB: '',
  state: '',
  teacherNo: '',
  id: ''
})

// 表单验证规则
const formRules = {
  certificateConfId: [
    { required: true, message: '请选择类型', trigger: 'change' }
  ],
  certificateTime: [
    { required: true, message: '请选择取证时间', trigger: 'change' }
  ],
  certificateNumber: [
    { required: true, message: '请输入证书编号', trigger: 'blur' },
    { pattern: /^[A-Za-z0-9]+$/, message: '证书编号只能包含英文和数字', trigger: 'blur' }
  ]
}

// 教师资格证列表
const teacherCertificateList = 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 certResponse = await getTeacherCertificateList()
    
    // 获取教师资格证列表
    if (certResponse && certResponse.data) {
      teacherCertificateList.value = Array.isArray(certResponse.data) 
        ? certResponse.data 
        : (certResponse.data.records || certResponse.data.list || [])
    }
  } catch (error) {
    // 获取字典数据失败
  }
}

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

// 文件上传成功 - 材料A
const materiaUploadSuccess = (response: any) => {
  if (response.data && response.data.code === "-1") {
    message.error("当前不允许上传文件")
    return
  }
  dataForm.evidenceA = response.data.url
}

// 文件上传成功 - 材料B
const materiaUploadSuccessB = (response: any) => {
  if (response.data && response.data.code === "-1") {
    message.error("当前不允许上传文件")
    return
  }
  dataForm.evidenceB = response.data.url
}

// 打开对话框
const openDialog = async (row?: any) => {
  if (row && row.id) {
    // 编辑模式
    url.value = `/professional/file/teacherAboutInfoUpload?teacherNo=${row.teacherNo}&type=0`
    fileList.value = []
    fileListB.value = []
    Object.assign(dataForm, {
      certificateConfId: row.certificateConfId || '',
      certificateTime: row.certificateTime || '',
      certificateNumber: row.certificateNumber || '',
      materialA: row.materialA || '',
      materialB: row.materialB || '',
      evidenceA: row.evidenceA || '',
      evidenceB: row.evidenceB || '',
      state: row.state || '',
      teacherNo: row.teacherNo || '',
      id: row.id || ''
    })
    showForm.value = true
    await initDicData()
    dialogVisible.value = true
  } else {
    // 新增模式：先检查是否锁定，再获取当前用户的 teacherNo
    try {
      const lockResponse = await checkLocked('teacherTitle')
      if (lockResponse.data) {
        // 已锁定
        message.warning("新增功能已锁定，暂不允许操作")
        return
      }
      
      // 未锁定，继续获取 teacherNo
      const response = await getMyTeacherNo()
      const teacherNo = response.data
      url.value = `/professional/file/teacherAboutInfoUpload?teacherNo=${teacherNo}&type=0`
      Object.assign(dataForm, {
        certificateConfId: '',
        certificateTime: '',
        certificateNumber: '',
        materialA: '',
        materialB: '',
        evidenceA: '',
        evidenceB: '',
        state: '',
        teacherNo: teacherNo,
        id: ''
      })
      fileList.value = []
      fileListB.value = []
      // 先加载字典数据，再显示表单
      await initDicData()
      showForm.value = true
      dialogVisible.value = true
    } catch (error) {
      message.error('获取教师编号失败')
      return
    }
  }
}

// 提交表单
const dialogSubmit = async () => {
  if (!formRef.value) return
  
  // 验证证明材料是否上传（与 MultiDialog 保持一致）
  if (!dataForm.evidenceA && !dataForm.materialA) {
    message.warning("请上传证明材料")
    return
  }
  
  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      submitLoading.value = true
      try {
        if (dataForm.id) {
          // 编辑：使用 putObj 接口（管理员编辑）
          dataForm.state = '0'
          await putObj(dataForm)
          message.success("修改成功")
        } else {
          // 新增：使用 updateOtherInfo 接口（与 MultiDialog 保持一致）
          // 注意：MultiDialog 的 type=0 表单只有 certificateConfId 和 certificateNumber，没有 certificateTime
          const submitData: any = {
            type: 0, // 教师资格证类型
            teacherNo: dataForm.teacherNo,
            certificateConfId: dataForm.certificateConfId,
            certificateNumber: dataForm.certificateNumber,
            mateA: dataForm.evidenceA || dataForm.materialA // 使用 mateA 字段（与 MultiDialog 一致）
          }
          
          const res = await updateOtherInfo(submitData)
          if (res.data == '-1') {
            message.warning("当前不允许提交")
          } else {
            message.success("提交成功")
          }
        }
        dialogVisible.value = false
        emit('refreshData')
      } catch (error: any) {
        message.error(error?.msg || '操作失败')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

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

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

<style scoped>
</style>
