<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="completionForm"
      label-width="110px"
      label-position="top"
    >
      <el-row :gutter="24">
        <el-col :span="8">
          <el-form-item label="竣工报告附件" prop="completionReportFileList">
            <UploadFile
              :fileList="formData.completionReportFileList"
              :fileUploadRule="completionReportUploadRule"
              @file-change="(files, type) => handleFileChange('completionReportFileList', files, type)"
              @del-file="(file) => handleDelFile('completionReportFileList', file)"
              :uploadType="uploadType"
              :maxFileTips="maxFileTips"
              :limitUploadNum="1"
              type="completion_report"
              :show-file-list="true"
            />
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="中标通知书附件" prop="bidNoticeFileList">
            <UploadFile
              :fileList="formData.bidNoticeFileList"
              :fileUploadRule="bidNoticeUploadRule"
              @file-change="(files, type) => handleFileChange('bidNoticeFileList', files, type)"
              @del-file="(file) => handleDelFile('bidNoticeFileList', file)"
              :uploadType="uploadType"
              :maxFileTips="maxFileTips"
              :limitUploadNum="1"
              type="bid_notice"
              :show-file-list="true"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24">
        <el-col :span="8">
          <el-form-item label="开工时间" prop="startTime">
            <el-date-picker
              v-model="formData.startTime"
              type="date"
              placeholder="自动提取"
              value-format="yyyy-MM-dd"
              class="form-control"
              :disabled-date="disabledFutureDate"
              @change="validateDateOrder"
            ></el-date-picker>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="竣工时间" prop="completionTime">
            <el-date-picker
              v-model="formData.completionTime"
              type="date"
              placeholder="自动提取"
              value-format="yyyy-MM-dd"
              class="form-control"
              :disabled-date="(date) => disabledCompletionDate(date)"
              @change="validateDateOrder"
            ></el-date-picker>
          </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: 'CompletionAndBidInfo',
  components: { UploadFile },
  dicts: ['identification_tag'],
  data() {
    return {
      uploadType: 'pdf',
      maxFileTips: '20MB',
      ocrRuleList: ['completion_report'],
      fileUploadList: [],
      ocrResultParams: {
        "开工时间": "startTime",
        "竣工时间": "completionTime"
      },
      formData: {
        completionReportFileList: [],
        bidNoticeFileList: [],
        startTime: '',
        completionTime: '',
        delFileList: []
      },
      rules: {
        completionReportFileList: [
          { required: true, message: '请上传竣工报告附件', trigger: 'change' }
        ],
        startTime: [
          { required: true, message: '请选择开工时间', trigger: 'blur' }
        ],
        completionTime: [
          { required: true, message: '请选择竣工时间', trigger: 'blur' }
        ],
        bidNoticeFileList: [
          { required: true, message: '请上传中标通知书附件', trigger: 'change' }
        ]
      },
      replacingFiles: {
        completionReportFileList: false,
        bidNoticeFileList: false
      }
    }
  },
  computed: {
    completionReportUploadRule() {
      return this.fileUploadList[0]
    },
    bidNoticeUploadRule() {
      return {
        fileUploadType: 'bid_notice',
        suffix: 'mainDatabase'
      }
    }
  },
  watch: {
    'dict.type.identification_tag': {
      handler(newVal) {
        if (newVal?.length) this.addOcrRule()
      },
      immediate: true
    }
  },
  methods: {
    setFormData(data) {
      // 竣工报告文件：不手动生成uid
      const completionFiles = Array.isArray(data.fileList)
        ? data.fileList.filter(file => file && file.businessType === 'completion_report')
          .map(file => ({
            name: file.name || file.fileName || '未知文件',
            filePath: file.filePath,
            lsFilePath: file.lsFilePath,
            fileType: file.fileType || '2',
            businessType: 'completion_report'
          }))
        : [];

      // 中标通知书文件：不手动生成uid
      const bidFiles = Array.isArray(data.fileList)
        ? data.fileList.filter(file => file && file.businessType === 'bid_notice')
          .map(file => ({
            name: file.name || file.fileName || '未知文件',
            filePath: file.filePath,
            lsFilePath: file.lsFilePath,
            fileType: file.fileType || '2',
            businessType: 'bid_notice'
          }))
        : [];

      this.formData = {
        startTime:data.startTime,
        completionTime:data.completionTime,
        completionReportFileList: completionFiles,
        bidNoticeFileList: bidFiles,
        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(field, files, type) {
      if (files instanceof Array) {
        // 处理新文件上传
        if (files.length > 0) {
          // 标记为已完成替换
          this.replacingFiles[field] = false;

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

          // 处理旧文件删除
          if (this.formData[field].length > 0) {
            const oldFile = this.formData[field][0];
            const delPath = oldFile?.response?.fileRes?.filePath || oldFile?.filePath || null;
            if (delPath && !this.formData.delFileList.includes(delPath)) {
              this.formData.delFileList.push(delPath);
            }
          }

          // 更新为新文件
          this.formData[field] = markedFiles;

          // 处理OCR识别（仅竣工报告）
          if (field === 'completionReportFileList' && type === 'completion_report' && markedFiles[0].response) {
            this.handleOcrResult(markedFiles)
          }
        } else if (!this.replacingFiles[field]) {
          // 只有非替换操作才清空文件列表
          this.formData[field] = [];
        }
      }
    },

    handleOcrResult(files) {
      if (!files?.length) 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) {
            Object.keys(chatRes).forEach(key => {
              const field = this.ocrResultParams[key]
              if (field && chatRes[key]) {
                if (field === 'completionTime' || field === 'startTime') {
                  this.formData[field] = convertChineseDate(chatRes[key]);
                } else {
                  this.formData[field] = chatRes[key];
                }
              }
            })
            this.$message.success('竣工信息识别成功，已自动填充')
            this.$refs.completionForm.validate()
          }
        } else {
          this.$message.error(`识别失败: ${firstFile.response?.ocrResult?.status_msg || '未知错误'}`)
        }
      } catch (error) {
        this.$message.error(`处理识别结果失败: ${error.message}`)
      } finally {
        this.$bus.$emit('endUpload')
      }
    },

    handleDelFile(field, file) {
      // 标记为替换操作，保留文件列表结构
      this.replacingFiles[field] = 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()
    },

    disabledCompletionDate(date) {
      const startDate = this.formData.startTime ? new Date(this.formData.startTime) : null
      return date > new Date() || (startDate && date < startDate)
    },

    validateDateOrder() {
      if (this.formData.startTime && this.formData.completionTime) {
        const start = new Date(this.formData.startTime)
        const completion = new Date(this.formData.completionTime)
        if (start > completion) {
          this.$message.warning('开工时间不能晚于竣工时间')
        }
      }
    },

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

        this.$refs.completionForm.validate(valid => {
          if (valid) {
            if (this.formData.startTime && this.formData.completionTime &&
              new Date(this.formData.startTime) > new Date(this.formData.completionTime)) {
              reject(new Error('开工时间不能晚于竣工时间'))
            } else {
              resolve(this.$refs.completionForm.model)
            }
          } else {
            reject(new Error('竣工报告与中标通知书信息填写不完整'))
          }
        })
      })
    },

    resetForm() {
      if (this.$refs.completionForm) {
        this.$refs.completionForm.resetFields()
      }
      this.formData = {
        completionReportFileList: [],
        bidNoticeFileList: [],
        startTime: '',
        completionTime: '',
        delFileList: []
      }
      this.replacingFiles = {
        completionReportFileList: false,
        bidNoticeFileList: 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
      }
      this.fileUploadList.push({
        fileUploadType: foundItem.value,
        fields_json: foundItem.raw?.remark,
        suffix: 'mainDatabase'
      })
    }
  }
}
</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;
  padding: 0 15px;
}

.form-control {
  width: 100%;
}

.el-form-item {
  margin-bottom: 20px;
}
</style>
