<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-form-item label="竣工报告附件" prop="completionReportFileList">
        <UploadFile
        :fileList="formatFileList('completion')"
        :fileUploadRule="completionReportUploadRule"
        @file-change="(files, type) => handleFileChange(files, type, 'completion')"
        @del-file="(file) => handleDelFile(file, 'completionReportFileList')"
        :uploadType="uploadType"
        :maxFileTips="maxFileTips"
        :limitUploadNum="1"
        type="completion_report"
        :show-file-list="true"
        />
      </el-form-item>

      <!-- 开工时间 -->
      <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-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>

      <div class="basic-info-title">
        <img src="@/assets/enterpriseLibrary/basic-info.png" alt="中标通知书">
        <span>中标通知书</span>
      </div>

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

<script>
import UploadFile from '@/views/common/UploadFile.vue'
export default {
  name: 'CompletionAndBidInfoEdit',
  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' }
        ]
      }
    }
  },
  computed: {
    completionReportUploadRule() {
      return this.fileUploadList[0]
    },
    bidNoticeUploadRule() {
      return {
        fileUploadType: 'bid_notice',
        suffix: 'mainDatabase'
      }
    }
  },
  watch: {
    'dict.type.identification_tag': {
      handler(newVal) {
        if (newVal && newVal.length > 0) {
          this.addOcrRule()
        }
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    // 接收父组件数据并回显
    setFormData(data) {
      // 筛选并格式化竣工报告文件（确保包含name字段）
      const completionFiles = Array.isArray(data.fileList)
        ? data.fileList.filter(file => file && file.businessType === 'completion_report')
        : []

      // 筛选并格式化中标通知书文件
      const bidFiles = Array.isArray(data.fileList)
        ? data.fileList.filter(file => file && file.businessType === 'bid_notice')
        : []

      this.formData = {
        completionReportFileList: completionFiles,
        bidNoticeFileList: bidFiles,
        startTime: data.startTime || '',
        completionTime: data.completionTime || '',
        delFileList: []
      }
    },

    // 核心：格式化文件列表，确保适配UploadFile组件（补充name等字段）
    formatFileList(type) {
      const sourceFiles = type === 'completion'
        ? this.formData.completionReportFileList
        : this.formData.bidNoticeFileList

      return sourceFiles.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, fileType) {
      // 给文件标记业务类型，并确保name字段存在
      const formattedFiles = files.map(file => ({
        ...file,
        businessType: fileType === 'completion' ? 'completion_report' : 'bid_notice',
        name: file.name || file.fileName || '未知文件' // 强制补充name
      }))

      // 直接更新表单对应的文件列表（实现回显）
      if (fileType === 'completion') {
        this.formData.completionReportFileList = formattedFiles
        // 触发OCR识别（仅竣工报告需要）
        this.handleOcrResult(formattedFiles)
      } else if (fileType === 'bid') {
        this.formData.bidNoticeFileList = formattedFiles
      }
    },

    // 处理文件删除（删除后允许重新上传）
    handleDelFile(file, field) {
      // 记录删除的文件路径（用于后端删除）
      const filePath = file.filePath || file.response?.fileRes?.uploadPath
      if (filePath && !this.formData.delFileList.includes(filePath)) {
        this.formData.delFileList.push(filePath)
      }
      // 清空表单文件列表（触发组件显示上传区域，允许重新上传）
      this.formData[field] = []
    },

    // 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]) {
                this.formData[formField] = chat_res[key]
              }
            })
            this.$message.success('OCR识别成功，已自动填充信息')
            this.$refs.completionForm.validate()
          }
        } else if (response.ocrResult) {
          this.$message.error(`OCR识别失败: ${response.ocrResult.status_msg || '未知错误'}`)
        }
      }
    },

    // 禁止选择未来日期
    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) => {
        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.formData)
            }
          } else {
            reject(new Error('竣工报告与中标通知书信息填写不完整'))
          }
        })
      })
    },

    // 重置表单
    resetForm() {
      if (this.$refs.completionForm) {
        this.$refs.completionForm.resetFields()
      }
      this.formData = {
        completionReportFileList: [],
        bidNoticeFileList: [],
        startTime: '',
        completionTime: '',
        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: all 0.3s;

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

  // 文件名显示样式
  ::v-deep .file-name {
    display: block !important; // 强制显示文件名
    color: #606266;
    font-size: 14px;
    margin-top: 8px;
  }

  // 删除按钮样式
  ::v-deep .el-upload-list__item-delete {
    color: #f56c6c;
    &:hover {
      color: #ff4d4f;
    }
  }
}
</style>
