<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-row :gutter="24">
        <el-col :span="8">
          <el-form-item label="合同附件" prop="fileList">
            <UploadFile
              :fileList="formData.fileList"
              :fileUploadRule="contractUploadRule"
              @file-change="(files, type) => handleFileChange(files, type)"
              @del-file="handleDelFile"
              :uploadType="uploadType"
              :maxFileTips="maxFileTips"
              type="contract"
              :show-file-list="true"
              :limitUploadNum="1"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24">
        <el-col :span="8">
          <el-form-item label="项目名称" prop="proName">
            <el-input
              v-model="formData.proName"
              placeholder="请输入项目名称"
              class="form-control"
              show-word-limit
              maxlength="64"
              @input="handleInputTest"
            ></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <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-col>

        <el-col :span="8">
          <el-form-item label="合同金额" prop="contractAmount">
            <el-input
              v-model="formData.contractAmount"
              placeholder="请输入合同金额"
              class="form-control"
              min="0"
              step="1"
              show-word-limit
              maxlength="32"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24">
        <el-col :span="8">
          <el-form-item label="建设地点" prop="constructionSite">
            <el-input
              v-model="formData.constructionSite"
              placeholder="请输入建设地点"
              class="form-control"
              show-word-limit
              maxlength="32"
            ></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="建设单位" prop="constructionUnit">
            <el-input
              v-model="formData.constructionUnit"
              placeholder="请输入建设单位"
              class="form-control"
              show-word-limit
              maxlength="32"
            ></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="建设单位联系方式" prop="constructionPhone">
            <el-input
              v-model="formData.constructionPhone"
              placeholder="请输入建设单位联系方式"
              class="form-control"
              show-word-limit
              maxlength="11"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import UploadFile from '@/views/common/UploadFile.vue'
import {convertChineseDate} from '@/utils/bonus'
export default {
  name: 'ContractInfo',
  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' }
        ]
      },
      isReplacingFile: false // 标记是否正在替换文件
    }
  },
  computed: {
    contractUploadRule() {
      return this.fileUploadList[0]
    }
  },
  watch: {
    'dict.type.identification_tag': {
      handler(newVal) {
        if (newVal && newVal.length > 0) {
          this.addOcrRule()
        }
      },
      immediate: true
    }
  },

  mounted() {
    // 使用 $nextTick 确保 el-form 已经完全初始化
    this.$nextTick(() => {
      if (this.$refs.contractForm) {
        console.log('el-form 内部的 model 对象:', this.$refs.contractForm.model);
        console.log('el-form 的 model 是否与组件的 formData 是同一个对象?', this.$refs.contractForm.model === this.formData);
      }
    });
  },

  methods: {

    handleInputTest() {
      // 在输入时立即打印 formData 的值
      console.log('formData.proName 在输入时的值:', this.formData.proName);
      console.log('完整的 formData 对象:', this.formData);
    },

    setFormData(data) {
      // 回显文件：不手动生成uid，仅传递基础字段
      const contractFiles = Array.isArray(data.fileList)
        ? data.fileList.filter(file => file && file.businessType === 'contract')
          .map(file => ({
            name: file.name || file.fileName || '未知文件',
            filePath: file.filePath,
            lsFilePath: file.lsFilePath,
            fileType: file.fileType || '2',
            businessType: 'contract'
          }))
        : [];

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

    getFileName(file) {
      return file.name || file.fileName || '未知文件'
    },

    getFileExt(file) {
      if (!file) return ''
      const fileName = file.name || file.fileName || ''
      const extMatch = fileName.match(/\.([a-zA-Z0-9]+)$/)
      return extMatch ? extMatch[1].toLowerCase() : ''
    },

    handleFileChange(files, type) {
      if (type === 'contract' && files instanceof Array) {
        // 处理文件替换逻辑
        if (files.length > 0) {
          // 标记为已完成替换
          this.isReplacingFile = false;

          const markedFiles = files.map(file => ({
            ...file,
            businessType: 'contract'
          })).slice(-1); // 限制1个文件

          this.formData.fileList = markedFiles;

          // 只有当文件有response时才进行OCR识别
          if (markedFiles.length > 0 && markedFiles[0].response) {
            this.handleOcrResult(markedFiles);
          }
        } else if (!this.isReplacingFile) {
          // 只有非替换操作才清空文件列表
          this.formData.fileList = [];
        }
      }
    },

    handleOcrResult(files) {
      if (!files || !Array.isArray(files) || files.length === 0) return

      this.$bus.$emit('startUpload', '正在识别合同信息')
      try {
        const firstFile = files[0]
        if (firstFile.response?.ocrResult?.status_code === 200) {
          const chatRes = firstFile.response.ocrResult.data
          if (chatRes && typeof chatRes === 'object') {
            Object.keys(chatRes).forEach(key => {
              const formField = this.ocrResultParams[key]
              if (formField && chatRes[key]) {
                let value = chatRes[key]
                if (formField === 'contractAmount') {
                  value = value.replace(/[^\d.]/g, '')
                }
                if (formField === 'contractSigningTime') {
                  value = convertChineseDate(value);
                }
                this.formData[formField] = value
              }
            })
            this.$message.success('OCR识别成功，已自动填充合同信息')
            this.$refs.contractForm.validate()
          }
        } else {
          this.$message.error(`识别失败: ${firstFile.response?.ocrResult?.status_msg || '未知错误'}`)
        }
      } catch (error) {
        this.$message.error(`处理识别结果失败: ${error.message}`)
      } finally {
        this.$bus.$emit('endUpload')
      }
    },

    handleDelFile(file) {
      // 标记为替换操作，保留文件列表结构等待新文件
      this.isReplacingFile = true;

      const delPath = file?.response?.fileRes?.filePath || file?.filePath || null;
      if (delPath && !this.formData.delFileList.includes(delPath)) {
        this.formData.delFileList.push(delPath);
      }
    },

    disabledFutureDate(date) {
      return date > new Date()
    },

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

        this.$refs.contractForm.validate((valid) => {
          if (valid) {
            console.log('validate',this.formData)
            resolve(this.formData)
          } else {
            reject(new Error('合同信息填写不完整'))
          }
        })
      })
    },

    resetForm() {
      if (this.$refs.contractForm) {
        this.$refs.contractForm.resetFields()
      }
      this.formData.proName = '';
      this.formData.contractSigningTime = '';
      this.formData.contractAmount = '';
      this.formData.constructionSite = '';
      this.formData.constructionUnit = '';
      this.formData.constructionPhone = '';
      this.formData.fileList = [];
      this.formData.delFileList = [];

      this.isReplacingFile = false;
    },

    addOcrRule() {
      this.ocrRuleList.forEach(item => {
        this.ocrRule(item)
      })
    },

    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%;
}
</style>
