<template>
  <div class="qualification-form">
    <el-form
      :model="formData"
      :rules="rules"
      ref="qualificationForm"
      label-width="110px"
      label-position="top"
      class="form-wrapper"
      :disabled="isDetail"
    >
      <!-- 资质证书附件：根据是否为详情模式切换组件 -->
      <el-form-item label="资质证书附件" prop="files">
        <template v-if="isDetail">
          <!-- 详情模式：使用FileOrImageDisplay组件 -->
          <FileOrImageDisplay
            :label="''"
            :file="form.fileList[0]"
            :image-url="form.url"
            without-modal="true"
          />
          <span v-if="form.fileList.length === 0" class="no-file-tip">无附件</span>
        </template>
        <template v-else>
          <!-- 编辑模式：保留UploadFile组件 -->
          <UploadFile
            ref="uploadFileComp"
            :fileList="formatFileList()"
            :fileUploadRule="qualificationUploadRule"
            @file-change="(files, type) => handleFileChange(files, type)"
            @del-file="handleDelFile"
            :uploadType="uploadType"
            :maxFileTips="maxFileTips"
            type="qualification_certificate"
            :auto-upload="true"
          />
        </template>
      </el-form-item>

      <el-form-item label="证书名称" prop="certificateName">
        <el-input
          v-model="formData.certificateName"
          placeholder="文件上传后自动提取"
          class="form-control"
          maxlength="50"
          :readonly="isDetail"
        ></el-input>
      </el-form-item>

      <el-form-item label="证书编号" prop="certificateCode">
        <el-input
          v-model="formData.certificateCode"
          placeholder="文件上传后自动提取"
          class="form-control"
          maxlength="32"
          :readonly="isDetail"
        ></el-input>
      </el-form-item>

      <el-form-item label="发证日期" prop="certificateDate">
        <el-date-picker
          v-model="formData.certificateDate"
          type="date"
          placeholder="文件上传后自动提取"
          value-format="yyyy-MM-dd"
          class="form-control"
          :disabled="isDetail"
        />
      </el-form-item>

      <el-form-item label="证书有效截止日期" prop="certificateEndDate">
        <el-date-picker
          v-model="formData.certificateEndDate"
          type="date"
          placeholder="文件上传后自动提取"
          value-format="yyyy-MM-dd"
          class="form-control"
          :disabled="isDetail"
        />
      </el-form-item>

      <el-form-item label="发证机构" prop="certificateInstitution">
        <el-input
          v-model="formData.certificateInstitution"
          placeholder="文件上传后自动提取"
          class="form-control"
          maxlength="64"
          :readonly="isDetail"
        ></el-input>
      </el-form-item>

      <el-form-item label="资质类型" prop="qualificationType">
        <el-select
          v-model="formData.qualificationType"
          placeholder="请选择资质类型"
          clearable
          class="form-control"
          :disabled="isDetail"
        >
          <el-option
            v-for="item in qualificationTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import UploadFile from '@/views/common/UploadFile.vue'
import FileOrImageDisplay from '@/views/common/FileOrImageDisplay.vue'

export default {
  name: 'QualificationFormDetail',
  components: { UploadFile, FileOrImageDisplay },
  dicts: ['identification_tag'],
  props: {
    isDetail: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      uploadType: 'docx',
      maxFileTips: '100MB',
      ocrRuleList: ['qualification_certificate'],
      fileUploadList: [],
      ocrResultParams: {
        "证书名称": "certificateName",
        "证书编号": "certificateCode",
        "发证日期": "certificateDate",
        "证书有效截止日期": "certificateEndDate",
        "发证机构": "certificateInstitution"
      },
      // 表单数据
      formData: {
        files: [], // 编辑模式文件列表
        certificateName: '',
        certificateCode: '',
        certificateDate: '',
        certificateEndDate: '',
        certificateInstitution: '',
        qualificationType: '',
        delFileList: []
      },
      // 详情模式文件数据
      form: {
        fileList: [],
        url: ''
      },
      qualificationTypeOptions: []
    };
  },
  computed: {
    qualificationUploadRule() {
      return this.fileUploadList[0]
    }
  },
  watch: {
    'dict.type.identification_tag': {
      handler(newVal) {
        if (newVal && newVal.length > 0) {
          this.addOcrRule()
        }
      },
      immediate: true
    },
    // 监听数据变化，同步更新详情页文件回显
    formData: {
      handler(newVal) {
        if (this.isDetail) {
          this.setFileData(newVal)
        }
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    // 加载资质类型字典
    loadQualificationTypeDict() {
      this.getDicts('qualification_type').then(response => {
        this.qualificationTypeOptions = response.data.map(item => ({
          label: item.dictLabel,
          value: item.dictValue
        }))
      }).catch(error => {
        console.error('加载资质类型字典失败：', error)
      })
    },

    // 接收父组件数据并回显
    setFormData(data) {
      // 筛选资质证书类型文件
      const qualificationFiles = Array.isArray(data.fileList)
        ? data.fileList.filter(file => file && file.businessType === 'qualification_certificate')
        : []

      // 编辑模式数据
      this.formData = {
        ...data,
        files: qualificationFiles,
        delFileList: []
      }

      // 详情模式文件数据处理
      if (this.isDetail) {
        this.setFileData(data)
      }
    },

    // 格式化详情页文件数据
    setFileData(data) {
      const rawFileList = Array.isArray(data.fileList) ? data.fileList : []
      const targetFiles = rawFileList.filter(file => file && file.businessType === 'qualification_certificate')

      const formattedFiles = targetFiles.map(item => ({
        name: item.fileName || item.name || '未知文件',
        filePath: item.filePath || '',
        lsFilePath: item.lsFilePath || item.fileUrl || '',
        fileType: item.fileType || '2',
        id: item.sourceId + ''
      }))

      this.form = {
        fileList: formattedFiles,
        url: formattedFiles.length > 0 ? formattedFiles[0].lsFilePath : ''
      }
    },

    // 编辑模式：格式化文件列表
    formatFileList() {
      return this.formData.files.map((file, index) => ({
        ...file,
        uid: file.uid || file.filePath || `${Date.now()}-${index}`,
        name: file.name || file.fileName || '未知文件',
        status: file.status || 'success',
        percentage: file.percentage || 100,
        fileType: file.fileType || '2'
      }))
    },

    // 处理文件变更（编辑模式）
    handleFileChange(files, type) {
      if (!this.isDetail && type === 'qualification_certificate') {
        const markedFiles = files.map(file => ({
          ...file,
          businessType: 'qualification_certificate',
          name: file.name || file.fileName || '未知文件'
        }))
        this.formData.files = markedFiles
        this.handleOcrResult(markedFiles)
      }
    },

    // 处理OCR识别结果
    handleOcrResult(files) {
      if (this.isDetail) return;
      if (!files || !Array.isArray(files) || files.length === 0) return

      this.$bus.$emit('startUpload', '正在识别证书信息')

      try {
        const firstFile = files[0]
        if (firstFile.response?.ocrResult) {
          const ocrResult = firstFile.response.ocrResult
          if (ocrResult.status_code === 200) {
            const chat_res = ocrResult.data?.chat_res
            if (chat_res && typeof chat_res === 'object') {
              Object.keys(chat_res).forEach(key => {
                const formField = this.ocrResultParams[key]
                if (formField && chat_res[key]) {
                  if (['certificateDate', 'certificateEndDate'].includes(formField)) {
                    const dateStr = chat_res[key].replace(/[^\d-]/g, '')
                    this.formData[formField] = dateStr || ''
                  } else {
                    this.formData[formField] = chat_res[key] || ''
                  }
                }
              })
              this.$message.success('OCR识别成功，已自动填充证书信息')
              Object.keys(this.ocrResultParams).forEach(key => {
                const formField = this.ocrResultParams[key]
                this.$refs.qualificationForm.validateField(formField)
              })
            }
          } else {
            this.$message.error(`识别失败: ${ocrResult.status_msg || '未知错误'}`)
          }
        }
      } catch (error) {
        this.$message.error(`处理识别结果失败: ${error.message}`)
      } finally {
        this.$bus.$emit('endUpload')
      }
    },

    // 处理文件删除（编辑模式）
    handleDelFile(file) {
      if (this.isDetail) return;

      const filePath = file.response?.fileRes?.uploadPath || file.filePath
      if (filePath && !this.formData.delFileList.includes(filePath)) {
        this.formData.delFileList.push(filePath)
      }
      if (this.formData.files.length === 0) {
        this.formData.certificateName = ''
        this.formData.certificateCode = ''
        this.formData.certificateDate = ''
        this.formData.certificateEndDate = ''
        this.formData.certificateInstitution = ''
      }
    },

    // 表单验证
    validate() {
      return new Promise((resolve, reject) => {
        if (!this.$refs.qualificationForm) {
          reject(new Error('表单实例未加载完成'))
          return
        }

        this.$refs.qualificationForm.validate((valid) => {
          if (valid) {
            resolve(this.formData)
          } else {
            reject(new Error('资质证书信息填写不完整'))
          }
        })
      })
    },

    // 重置表单
    resetForm() {
      const oldFileList = [...this.formData.files];

      this.$nextTick(async () => {
        this.formData.files = oldFileList;

        await this.$nextTick();
        if (oldFileList.length > 0 && this.$refs.uploadFileComp) {
          const uploadInnerFiles = this.$refs.uploadFileComp.files;
          uploadInnerFiles.forEach(file => {
            this.$refs.uploadFileComp.handleRemove(file, []);
          });
        }

        this.formData.files = [];

        if (this.$refs.qualificationForm) {
          this.$refs.qualificationForm.resetFields();
        }

        this.formData = {
          ...this.formData,
          certificateName: '',
          certificateCode: '',
          certificateDate: '',
          certificateEndDate: '',
          certificateInstitution: '',
          qualificationType: '',
          delFileList: []
        };

        // 重置详情页文件数据
        if (this.isDetail) {
          this.form = {
            fileList: [],
            url: ''
          }
        }
      });
    },

    // 初始化OCR识别规则
    addOcrRule() {
      this.ocrRuleList.forEach(item => {
        this.ocrRule(item)
      })
    },

    // 获取OCR识别规则
    ocrRule(type) {
      const foundItem = this.dict.type.identification_tag?.find(item => item.value === type)
      if (!foundItem) {
        this.$message.warning(`未找到${type}的识别规则配置`)
        return
      }

      const item = {
        fileUploadType: foundItem.value,
        fields_json: foundItem.raw?.remark,
        suffix: 'mainDatabase'
      }

      this.fileUploadList.push(item)
    }
  },
  created() {
    this.loadQualificationTypeDict();
  }
};
</script>

<style scoped lang="scss">
.qualification-form {
  padding: 0;
}

.el-form {
  margin-top: 15px;
}

.form-control {
  width: 100%;
}

.el-form-item {
  margin-bottom: 20px;
}

::v-deep .el-form-item__label {
  color: #4e5969;
  font-weight: 500;
}

.form-wrapper {
  padding: 24px;
  background: #fff;
}

/* 详情模式样式 */
::v-deep .is-detail .el-input__inner:read-only,
::v-deep .is-detail .el-select-disabled .el-select__inner {
  color: #333;
  background-color: #fafafa;
  cursor: default;
}

/* 无附件提示样式 */
.no-file-tip {
  color: #909399;
  font-size: 14px;
  display: inline-block;
  margin-top: 10px;
}

/* 编辑模式上传组件样式 */
::v-deep .upload-container {
  ::v-deep .el-upload-dragger {
    height: 180px;
    transition: border-color 0.3s;
  }

  ::v-deep .el-upload-list__item {
    margin-top: 10px;
  }
}
</style>
