<template>
  <div>
    <div class="basic-info-title">
      <img src="@/assets/enterpriseLibrary/basic-info.png" alt="合同信息">
      <span>合同信息</span>
    </div>

    <el-form
      :model="formData"
      :rules="rules"
      ref="contractForm"
      label-width="110px"
      label-position="top"
    >
      <!-- 合同附件：单组件处理显示+上传+删除 -->
      <el-form-item label="合同附件" prop="fileList">
        <UploadFile
        :fileList="formatFileList()"
        :fileUploadRule="contractUploadRule"
        @file-change="(files, type) => handleFileChange(files, type)"
        @del-file="handleDelFile"
        :uploadType="uploadType"
        :maxFileTips="maxFileTips"
        type="contract"
        :limitUploadNum="1"
        :show-file-list="true"
        />
      </el-form-item>

      <!-- 项目名称 -->
      <el-form-item label="项目名称" prop="proName">
        <el-input
          v-model="formData.proName"
          placeholder="请输入项目名称"
          class="form-control"
          maxlength="100"
        ></el-input>
      </el-form-item>

      <!-- 合同签订时间 -->
      <el-form-item label="合同签订时间" prop="contractSigningTime">
        <el-date-picker
          v-model="formData.contractSigningTime"
          type="date"
          placeholder="请选择合同签订时间"
          value-format="yyyy-MM-dd"
          class="form-control"
          :disabled-date="disabledFutureDate"
        ></el-date-picker>
      </el-form-item>

      <!-- 合同金额 -->
      <el-form-item label="合同金额" prop="contractAmount">
        <el-input
          v-model="formData.contractAmount"
          placeholder="请输入合同金额"
          type="number"
          class="form-control"
          min="0"
          step="1"
        ></el-input>
      </el-form-item>

      <!-- 建设地点 -->
      <el-form-item label="建设地点" prop="constructionSite">
        <el-input
          v-model="formData.constructionSite"
          placeholder="请输入建设地点"
          class="form-control"
          maxlength="100"
        ></el-input>
      </el-form-item>

      <!-- 建设单位 -->
      <el-form-item label="建设单位" prop="constructionUnit">
        <el-input
          v-model="formData.constructionUnit"
          placeholder="请输入建设单位"
          class="form-control"
          maxlength="100"
        ></el-input>
      </el-form-item>

      <!-- 建设单位联系方式 -->
      <el-form-item label="建设单位联系方式" prop="constructionPhone">
        <el-input
          v-model="formData.constructionPhone"
          placeholder="请输入建设单位联系方式"
          class="form-control"
          maxlength="20"
          type="tel"
        ></el-input>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import UploadFile from '@/views/common/UploadFile.vue'
export default {
  name: 'ContractInfoEdit',
  components: { UploadFile },
  dicts: ['identification_tag'],
  data() {
    return {
      uploadType: 'pdf',
      maxFileTips: '20MB',
      ocrRuleList: ['contract'],
      fileUploadList: [],
      ocrResultParams: {
        "项目名称": "proName",
        "合同签订时间": "contractSigningTime",
        "合同金额": "contractAmount",
        "建设地点": "constructionSite",
        "建设单位": "constructionUnit",
        "建设单位联系方式": "constructionPhone"
      },
      formData: {
        fileList: [], // 合同文件列表（直接绑定组件）
        proName: '',
        contractSigningTime: '',
        contractAmount: '',
        constructionSite: '',
        constructionUnit: '',
        constructionPhone: '',
        delFileList: [] // 记录删除的文件路径
      },
      rules: {
        proName: [
          { required: true, message: '请输入项目名称', trigger: 'blur' }
        ],
        fileList: [
          { required: true, message: '请上传合同附件', trigger: 'change' }
        ],
        contractSigningTime: [
          { required: true, message: '请选择合同签订时间', trigger: 'blur' }
        ],
        contractAmount: [
          { required: true, message: '请输入合同金额', trigger: 'blur' },
        ],
        constructionSite: [
          { required: true, message: '请输入建设地点', trigger: 'blur' }
        ],
        constructionUnit: [
          { required: true, message: '请输入建设单位', trigger: 'blur' }
        ],
        constructionPhone: [
          { required: true, message: '请输入建设单位联系方式', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    contractUploadRule() {
      return this.fileUploadList[0]
    }
  },
  watch: {
    'dict.type.identification_tag': {
      handler(newVal) {
        if (newVal && newVal.length > 0) {
          this.addOcrRule()
        }
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    // 接收父组件数据并回显
    setFormData(data) {
      // 筛选出合同类型的文件
      const contractFiles = Array.isArray(data.fileList)
        ? data.fileList.filter(file => file && file.businessType === 'contract')
        : []

      this.formData = {
        fileList: contractFiles,
        proName: data.proName || '',
        contractSigningTime: data.contractSigningTime || '',
        contractAmount: data.contractAmount || '',
        constructionSite: data.constructionSite || '',
        constructionUnit: data.constructionUnit || '',
        constructionPhone: data.constructionPhone || '',
        delFileList: []
      }
    },

    // 格式化文件列表，确保适配UploadFile组件
    formatFileList() {
      return this.formData.fileList.map((file, index) => {
        const fileExt = file.fileName ? file.fileName.split('.').pop().toLowerCase() : ''
        return {
          ...file,
          uid: file.uid || file.filePath || `${Date.now()}-${index}`, // 唯一标识
          name: file.name || file.fileName || `未命名合同.${fileExt}`, // 确保文件名存在
          status: file.status || 'success', // 默认为已上传状态
          percentage: file.percentage || 100, // 进度100%
          fileType: file.fileType || '2' // 文档类型
        }
      })
    },

    // 处理文件上传/变更
    handleFileChange(files, type) {
      if (type === 'contract') {
        // 标记文件类型为合同，并确保name字段存在
        const formattedFiles = files.map(file => ({
          ...file,
          businessType: 'contract',
          name: file.name || file.fileName || '未知合同文件'
        }))
        // 直接更新表单文件列表（实现回显）
        this.formData.fileList = formattedFiles
        // 触发OCR识别
        this.handleOcrResult(formattedFiles)
      }
    },

    // 处理文件删除
    handleDelFile(file) {
      // 记录删除的文件路径
      const filePath = file.filePath || file.response?.fileRes?.uploadPath
      if (filePath && !this.formData.delFileList.includes(filePath)) {
        this.formData.delFileList.push(filePath)
      }
      // 从表单中移除文件（允许重新上传）
      this.formData.fileList = this.formData.fileList.filter(item =>
        item.filePath !== filePath
      )
    },

    // 处理OCR识别结果
    handleOcrResult(files) {
      if (files.length > 0 && files[0].response) {
        const response = files[0].response
        if (response.ocrResult && response.ocrResult.status_code === 200) {
          const chat_res = response.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]) {
                let value = chat_res[key]
                // 清洗合同金额中的非数字字符
                if (formField === 'contractAmount') {
                  value = value.replace(/[^\d.]/g, '')
                }
                this.formData[formField] = value
              }
            })
            this.$message.success('OCR识别成功，已自动填充合同信息')
            this.$refs.contractForm.validate()
          }
        } else if (response.ocrResult) {
          this.$message.error(`OCR识别失败: ${response.ocrResult.status_msg || '未知错误'}`)
        }
      }
    },

    // 禁止选择未来日期
    disabledFutureDate(date) {
      return date > new Date()
    },

    // 表单验证
    validate() {
      return new Promise((resolve, reject) => {
        this.$refs.contractForm.validate((valid) => {
          if (valid) {
            resolve(this.formData)
          } else {
            reject(new Error('合同信息填写不完整'))
          }
        })
      })
    },

    // 重置表单
    resetForm() {
      if (this.$refs.contractForm) {
        this.$refs.contractForm.resetFields()
      }
      this.formData = {
        fileList: [],
        proName: '',
        contractSigningTime: '',
        contractAmount: '',
        constructionSite: '',
        constructionUnit: '',
        constructionPhone: '',
        delFileList: []
      }
    },

    // 初始化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)
    }
  }
}
</script>

<style scoped lang="scss">
.basic-info-title {
  display: flex;
  align-items: center;
  margin: 10px 0;
  span {
    margin: 0 5px;
    font-size: 20px;
  }
  img {
    width: 24px;
    height: 24px;
    object-fit: contain;
  }
}

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

.form-control {
  width: 100%;
}

// 适配UploadFile组件样式
::v-deep .upload-container {
  margin-bottom: 10px;

  // 上传区域样式
  ::v-deep .el-upload-dragger {
    height: 180px;
    transition: border-color 0.3s;

    &:hover {
      border-color: #409eff;
    }
  }

  // 文件名显示样式（与原el-link风格保持一致）
  ::v-deep .file-name {
    display: block !important;
    color: #1890ff;
    font-size: 14px;
    text-decoration: underline;
    margin-top: 8px;
    cursor: pointer;
  }

  // 删除按钮样式（与原按钮风格一致）
  ::v-deep .el-upload-list__item-delete {
    color: #f56c6c;
    margin-left: 8px;

    &:hover {
      color: #ff4d4f;
    }
  }

  // 文档图标样式
  ::v-deep .file-icon {
    color: #1890ff;
    font-size: 24px;
  }
}
</style>
