<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="financeReportForm"
      label-width="110px"
      label-position="top"
    >
      <!-- 财务报告上传 -->
      <el-row :gutter="24">
        <el-col :span="8">
          <el-form-item label="财务报告附件" prop="fileList">
            <UploadFile
              :fileList="formatFileList()"
              :fileUploadRule="financeReportUploadRule"
              @file-change="(files, type) => handleFileChange(files, type)"
              @del-file="handleDelFile"
              :uploadType="uploadType"
              :maxFileTips="maxFileTips"
              :limitUploadNum="1"
              type="finance_report"
              :show-file-list="true"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 文件名 -->
      <el-row :gutter="24" class="info-row">
        <el-col :span="8" class="info-col">
          <el-form-item label="文件名" prop="fileName">
            <el-input
              v-model="formData.fileName"
              placeholder="文件上传后自动提取"
              class="form-control"
              maxlength="100"
              readonly
            ></el-input>
          </el-form-item>
        </el-col>

        <!-- 报告年份 -->
        <el-col :span="8" class="info-col">
          <el-form-item label="报告年份" prop="reportYear">
            <el-date-picker
              v-model="formData.reportYear"
              type="year"
              placeholder="选择年份"
              class="form-control"
              value-format="yyyy"
              :disabled-date="disabledFutureYear"
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

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

export default {
  name: 'FinanceReportUpload',
  components: { UploadFile },
  dicts: ['identification_tag'],
  data() {
    return {
      uploadType: 'pdf、doc、docx',
      maxFileTips: '100MB',
      ocrRuleList: ['finance_report'],
      fileUploadList: [],
      ocrResultParams: {
        "报告年份": "reportYear"
      },
      formData: {
        fileList: [],  // 存储原始文件数据
        fileName: '',
        reportYear: '', // 存储年份字符串（如"2023"）
        delFileList: []  // 记录删除的文件路径
      },
      rules: {
        fileList: [
          { required: true, message: '请上传财务报告附件', trigger: 'change' }
        ],
        fileName: [
          { required: true, message: '文件名需等待文件上传后自动提取', trigger: 'blur' }
        ],
        reportYear: [
          { required: true, message: '请选择报告年份', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    financeReportUploadRule() {
      return this.fileUploadList[0]
    }
  },
  watch: {
    'dict.type.identification_tag': {
      handler(newVal) {
        if (newVal && newVal.length > 0) {
          this.addOcrRule()
        }
      },
      immediate: true
    }
  },
  methods: {
    // 接收父组件数据并回显
    setFormData(data) {
      const financeFiles = Array.isArray(data.fileList)
        ? data.fileList.filter(file => file && file.businessType === 'finance_report')
        : []

      this.formData = {
        ...data,
        fileList: financeFiles,
        fileName: financeFiles.length > 0 ? this.getFileName(financeFiles[0]) : '',
        delFileList: []
      }
    },

    // 格式化文件列表，适配UploadFile组件
    formatFileList() {
      return this.formData.fileList.map((file, index) => {
        const fileExt = this.getFileExt(file)
        return {
          ...file,
          uid: file.uid || file.filePath || `${Date.now()}-${index}`,
          name: this.getFileName(file),  // 这里会使用去掉后缀的文件名
          status: file.status || 'success',
          percentage: file.percentage || 100,
          fileType: file.fileType || '2'
        }
      })
    },

    // 核心修改：提取文件名并去掉后缀
    getFileName(file) {
      // 先获取原始文件名（包含后缀）
      const fullName = file.name || file.fileName || `未命名文件.${this.getFileExt(file)}`

      // 查找最后一个点的位置，用于分割文件名和后缀
      const lastDotIndex = fullName.lastIndexOf('.')

      // 如果存在后缀（且点不是文件名的第一个字符），则去掉后缀；否则返回原文件名
      if (lastDotIndex > 0) {
        return fullName.substring(0, lastDotIndex)
      }
      return fullName
    },

    // 提取文件后缀（保持不变）
    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 === 'finance_report') {
        const markedFiles = files.map(file => ({
          ...file,
          businessType: 'finance_report',
          name: file.name || file.fileName || '未知文件'
        }))
        this.formData.fileList = markedFiles

        if (markedFiles.length > 0) {
          const originalFileName = this.getFileName(markedFiles[0])  // 这里会使用去掉后缀的文件名
          const safeFileName = originalFileName.replace(/--+/g, '-')
          this.formData.fileName = safeFileName
          this.$refs.financeReportForm.validateField('fileName')
          this.$message.success(`文件名已自动提取：${safeFileName}`)
        }

        this.handleOcrResult(markedFiles)
      }
    },

    // 其他方法保持不变
    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.fileName = ''
      this.formData.reportYear = ''
    },

    handleOcrResult(files) {
      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 === 'reportYear' && chat_res[key]) {
                  const year = chat_res[key].replace(/[^\d]/g, '')
                  this.formData[formField] = year.length === 4 ? year : ''
                }
              })
              this.$message.success('OCR识别成功，已自动填充报告年份')
              this.$refs.financeReportForm.validateField('reportYear')
            }
          } else {
            this.$message.error(`年份识别失败: ${ocrResult.status_msg || '未知错误'}`)
          }
        }
      } catch (error) {
        this.$message.error(`处理年份结果失败: ${error.message}`)
      } finally {
        this.$bus.$emit('endUpload')
      }
    },

    disabledFutureYear(date) {
      return date > new Date(new Date().getFullYear(), 11, 31)
    },

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

        this.$refs.financeReportForm.validate((valid) => {
          if (valid) {
            resolve(this.formData)
          } else {
            reject(new Error('财务报告信息填写不完整'))
          }
        })
      })
    },

    resetForm() {
      if (this.$refs.financeReportForm) {
        this.$refs.financeReportForm.resetFields()
      }
      this.formData = {
        fileList: [],
        fileName: '',
        reportYear: '',
        delFileList: []
      }
    },

    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;
  padding: 0 15px;
}

.form-control {
  width: 100%;
}

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

.upload-tip {
  color: #909399;
  font-size: 12px;
  margin-top: 5px;
  line-height: 1.5;
}

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

::v-deep .el-input.is-readonly .el-input__inner {
  background-color: #f5f7fa;
  cursor: default;
}

::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;
  }

  ::v-deep .el-upload-list__item-name {
    display: inline-block;
    max-width: 80%;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}
</style>
