<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="financialStatementForm"
      label-width="110px"
      label-position="top"
    >
      <el-row :gutter="24" class="data-row">
        <el-col :span="8" class="data-col">
          <el-form-item label="财务报表附件" prop="fileList" class="data-item">
            <UploadFile
              :fileList="formData.fileList"
              :fileUploadRule="financialStatementUploadRule"
              @file-change="(files, type) => handleFileChange(files, type)"
              @del-file="handleDelFile"
              :uploadType="uploadType"
              :maxFileTips="maxFileTips"
              :limitUploadNum="1"
              type="financial_statement"
              @xlsx-content="handleXlsxContent"
              :show-file-list="true"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24" class="data-row">
        <el-col :span="8" class="data-col">
          <el-form-item label="营业收入" prop="operatingIncome" class="data-item">
            <el-input
              v-model="formData.operatingIncome"
              placeholder="自动提取"
              class="form-control auto-input"
              show-word-limit
              maxlength="16"
              @input="handleNumberInput('operatingIncome', 2)"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8" class="data-col">
          <el-form-item label="流动资产" prop="currentAssets" class="data-item">
            <el-input
              v-model="formData.currentAssets"
              placeholder="自动提取"
              class="form-control auto-input"
              show-word-limit
              maxlength="16"
              @input="handleNumberInput('currentAssets', 2)"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8" class="data-col">
          <el-form-item label="流动负债" prop="currentLiabilities" class="data-item">
            <el-input
              v-model="formData.currentLiabilities"
              placeholder="自动提取"
              class="form-control auto-input"
              show-word-limit
              maxlength="16"
              @input="handleNumberInput('currentLiabilities', 2)"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24" class="data-row">
        <el-col :span="8" class="data-col">
          <el-form-item label="流动比率" prop="currentRatio" class="data-item">
            <el-input
              v-model="formData.currentRatio"
              placeholder="自动提取"
              class="form-control auto-input"
              show-word-limit
              maxlength="16"
              @input="handleNumberInput('currentRatio', 2)"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8" class="data-col">
          <el-form-item label="净利润" prop="netProfit" class="data-item">
            <el-input
              v-model="formData.netProfit"
              placeholder="自动提取"
              class="form-control auto-input"
              show-word-limit
              maxlength="16"
              @input="handleNumberInput('netProfit', 2)"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8" class="data-col">
          <el-form-item label="股东权益" prop="shareholdersEquity" class="data-item">
            <el-input
              v-model="formData.shareholdersEquity"
              placeholder="自动提取"
              class="form-control auto-input"
              show-word-limit
              maxlength="16"
              @input="handleNumberInput('shareholdersEquity', 2)"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24" class="data-row">
        <el-col :span="8" class="data-col">
          <el-form-item label="净资产收益率" prop="returnOnNetAssets" class="data-item">
            <el-input
              v-model="formData.returnOnNetAssets"
              placeholder="自动提取"
              class="form-control auto-input"
              show-word-limit
              maxlength="16"
              @input="handleNumberInput('returnOnNetAssets', 2)"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8" class="data-col">
          <el-form-item label="负债总额" prop="totalLiabilities" class="data-item">
            <el-input
              v-model="formData.totalLiabilities"
              placeholder="自动提取"
              class="form-control auto-input"
              show-word-limit
              maxlength="16"
              @input="handleNumberInput('totalLiabilities', 2)"

            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8" class="data-col">
          <el-form-item label="资产总额" prop="totalAssets" class="data-item">
            <el-input
              v-model="formData.totalAssets"
              placeholder="自动提取"
              class="form-control auto-input"
              show-word-limit
              maxlength="16"
              @input="handleNumberInput('totalAssets', 2)"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="24" class="data-row">
        <el-col :span="8" class="data-col">
          <el-form-item label="资产负债率" prop="assetLiabilityRatio" class="data-item">
            <el-input
              v-model="formData.assetLiabilityRatio"
              placeholder="自动提取"
              class="form-control auto-input"
              show-word-limit
              maxlength="16"
              @input="handleNumberInput('assetLiabilityRatio', 2)"

            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

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

export default {
  name: 'FinancialStatement',
  components: { UploadFile },
  dicts: ['identification_tag'],
  data() {
    return {
      uploadType: 'xlsx、xls',
      maxFileTips: '100MB',
      ocrRuleList: ['financial_statement'],
      fileUploadList: [],
      ocrResultParams: {
        "营业收入": "operatingIncome",
        "流动资产": "currentAssets",
        "流动负债": "currentLiabilities",
        "流动比率": "currentRatio",
        "净利润": "netProfit",
        "股东权益": "shareholdersEquity",
        "净资产收益率": "returnOnNetAssets",
        "负债总额": "totalLiabilities",
        "资产总额": "totalAssets",
        "资产负债率": "assetLiabilityRatio"
      },
      formData: {
        fileList: [],
        operatingIncome: '',
        currentAssets: '',
        currentLiabilities: '',
        currentRatio: '',
        netProfit: '',
        shareholdersEquity: '',
        returnOnNetAssets: '',
        totalLiabilities: '',
        totalAssets: '',
        assetLiabilityRatio: '',
        delFileList: []
      },
      rules: {
        fileList: [
          { required: true, message: '请上传财务报表附件', trigger: 'change' }
        ],
        operatingIncome: [
          { required: true, message: '营业收入为必填项', trigger: 'change' },
          { type: 'string', max: 16, message: '长度不能超过16个字符', trigger: 'blur' },
        ],
        netProfit: [
          { required: true, message: '净利润为必填项', trigger: 'change' },
          { type: 'string', max: 16, message: '长度不能超过16个字符', trigger: 'blur' },
        ],
        returnOnNetAssets: [
          { required: true, message: '净资产收益率为必填项', trigger: 'change' },
          { pattern: /^\d+(\.\d+)?%?$/, message: '请输入有效的净资产收益率（如1或1%）', trigger: 'blur' },
          { type: 'string', max: 16, message: '长度不能超过16个字符', trigger: 'blur' },
        ],
        currentAssets: [
          { required: true, message: '流动资产为必填项', trigger: 'blur' },
          { type: 'string', max: 16, message: '长度不能超过16个字符', trigger: 'blur' },
        ],
        currentLiabilities: [
          { required: true, message: '流动负债为必填项', trigger: 'blur' },
          { type: 'string', max: 16, message: '长度不能超过16个字符', trigger: 'blur' },
        ],
        currentRatio: [
          { required: true, message: '流动比率为必填项', trigger: 'blur' },
          { pattern: /^\d+(\.\d+)?%?$/, message: '请输入有效的流动比率（如1或1%）', trigger: 'blur' },
          { type: 'string', max: 16, message: '长度不能超过16个字符', trigger: 'blur' },
        ],
        shareholdersEquity: [
          { required: true, message: '股东权益为必填项', trigger: 'blur' },
          { type: 'string', max: 16, message: '长度不能超过16个字符', trigger: 'blur' },
        ],
        totalLiabilities: [
          { required: true, message: '负债总额为必填项', trigger: 'blur' },
          { type: 'string', max: 16, message: '长度不能超过16个字符', trigger: 'blur' },
        ],
        totalAssets: [
          { required: true, message: '资产总额为必填项', trigger: 'blur' },
          { type: 'string', max: 16, message: '长度不能超过16个字符', trigger: 'blur' },
        ],
        assetLiabilityRatio: [
          { required: true, message: '资产负债率为必填项', trigger: 'blur' },
          { pattern: /^\d+(\.\d+)?%?$/, message: '请输入有效的资产负债率（如1或1%）', trigger: 'blur' },
          { type: 'string', max: 16, message: '长度不能超过16个字符', trigger: 'blur' },
        ]
      },
      isReplacingFile: false // 新增：标记是否正在替换文件
    }
  },
  computed: {
    financialStatementUploadRule() {
      return this.fileUploadList[0]
    }
  },
  watch: {
    'dict.type.identification_tag': {
      handler(newVal) {
        if (newVal && newVal.length > 0) {
          this.addOcrRule()
        }
      },
      immediate: true
    }
  },
  methods: {

    handleXlsxContent(text) {
      this.$bus.$emit('startUpload', '正在解析Excel财务数据')

      try {
        // 从Excel文本中提取财务数据
        const financialData = this.extractFinancialDataFromText(text);
        // 填充到表单
        this.fillFormWithFinancialData(financialData);
        this.$message.success('Excel解析成功，已自动填充财务数据');
      } catch (error) {
        this.$message.error(`Excel解析失败: ${error.message}`);
      } finally {
        this.$bus.$emit('endUpload');
      }
    },

    // 从文本中提取财务数据（核心逻辑）
    extractFinancialDataFromText(text) {
      const data = {};
      const keywords = Object.keys(this.ocrResultParams); // 获取所有财务指标关键词

      // 遍历每个关键词，在文本中匹配对应值
      keywords.forEach(keyword => {
        // 正则：匹配"关键词: 值"或"关键词  值"（支持中英文标点、空格）
        const regex = new RegExp(`${keyword}\\s*[:：]?\\s*([\\d,.%]+)`, 'i');
        const match = text.match(regex);

        if (match && match[1]) {
          // 提取数值（去除千分位逗号等干扰符）
          data[keyword] = match[1].replace(/,/g, '').trim();
        }
      });

      return data;
    },

    // 将提取的财务数据填充到表单
    fillFormWithFinancialData(financialData) {
      Object.keys(financialData).forEach(keyword => {
        const formField = this.ocrResultParams[keyword];
        if (formField) {
          // 保留数字、小数点和百分号（清除其他字符）
          const cleanedValue = financialData[keyword].replace(/[^\d.%]/g, '');

          // 对特定字段进行两位小数格式化
          if (formField === 'netProfit' || formField === 'totalAssets') {
            this.formData[formField] = this.formatToTwoDecimalPlaces(cleanedValue);
          } else {
            this.formData[formField] = cleanedValue;
          }
        }
      });
      // 触发表单验证
      this.$refs.financialStatementForm.validate();
    },

    setFormData(data) {
      // 财务报表文件：不手动生成uid
      const financialFiles = Array.isArray(data.fileList)
        ? data.fileList.filter(file => file && file.businessType === 'financial_statement')
          .map(file => ({
            name: file.name || file.fileName || '未知文件',
            filePath: file.filePath,
            lsFilePath: file.lsFilePath,
            fileType: file.fileType || '2',
            businessType: 'financial_statement'
          }))
        : [];

      this.formData = {
        operatingIncome: data.operatingIncome,
        currentAssets: data.currentAssets,
        currentLiabilities: data.currentLiabilities,
        currentRatio: data.currentRatio,
        netProfit: data.netProfit,
        shareholdersEquity: data.shareholdersEquity,
        returnOnNetAssets: data.returnOnNetAssets,
        totalLiabilities: data.totalLiabilities,
        totalAssets: data.totalAssets,
        assetLiabilityRatio: data.assetLiabilityRatio,
        fileList: financialFiles,
        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 === 'financial_statement' && files instanceof Array) {
        // 处理文件替换逻辑
        if (files.length > 0 && files[0].response) { // 验证上传成功
          // 标记为已完成替换
          this.isReplacingFile = false;

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

          const markedFiles = files.map(file => ({
            ...file,
            businessType: 'financial_statement'
          })).slice(-1);

          this.formData.fileList = markedFiles;
          const fileExt = this.getFileExt(markedFiles[0]);
          if (['xls', 'xlsx'].includes(fileExt)) {
            // 已通过@xlsx-content处理，此处无需额外操作
          } else {
            // 非Excel文件走原有OCR逻辑
            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) {
          const ocrResult = firstFile.response.ocrResult
          if (ocrResult.status_code === 200) {
            const chat_res = ocrResult.data
            if (chat_res && typeof chat_res === 'object') {
              Object.keys(chat_res).forEach(key => {
                const formField = this.ocrResultParams[key]
                if (formField && chat_res[key]) {
                  let processedValue = chat_res[key].replace(/[^\d.]/g, '')

                  // 对特定字段进行两位小数格式化
                  if (formField === 'netProfit' || formField === 'totalAssets') {
                    processedValue = this.formatToTwoDecimalPlaces(processedValue)
                  }

                  this.formData[formField] = processedValue
                }
              })
              this.$message.success('OCR识别成功，已自动填充财务数据')
              this.$refs.financialStatementForm.validate()
            }
          } else {
            this.$message.error(`OCR识别失败: ${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);
      }
    },

    validate() {
      return new Promise((resolve, reject) => {
        this.$refs.financialStatementForm.validate((valid) => {
          if (valid) {
            resolve(this.formData)
          } else {
            // 前端验证失败，不继续提交到后端
            reject(new Error('请完善表单信息'))
          }
        })
      })
    },

    resetForm() {
      if (this.$refs.financialStatementForm) {
        this.$refs.financialStatementForm.resetFields()
      }
      this.formData = {
        fileList: [],
        operatingIncome: '',
        currentAssets: '',
        currentLiabilities: '',
        currentRatio: '',
        netProfit: '',
        shareholdersEquity: '',
        returnOnNetAssets: '',
        totalLiabilities: '',
        totalAssets: '',
        assetLiabilityRatio: '',
        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)
    },

    /**
     * 将数值格式化为最多保留两位小数的字符串
     * @param {string|number} value - 需要格式化的数值
     * @returns {string} 格式化后的字符串
     */
    formatToTwoDecimalPlaces(value) {
      if (value === null || value === undefined || value === '') {
        return '';
      }
      // 尝试将输入值转换为数字
      const num = Number(value);
      // 检查转换是否成功
      if (isNaN(num)) {
        return value; // 如果无法转换，返回原始值
      }
      // 使用 toFixed(2) 进行四舍五入并保留两位小数
      // 注意：toFixed会返回一个字符串
      return num.toFixed(2);
    },

    /**
     * 处理数字输入框的change事件，确保格式正确
     * @param {string} fieldName - 表单字段名
     */
    handleNumberInput(fieldName, decimalPlaces) {
      let value = this.formData[fieldName];

      if (value === null || value === undefined) {
        value = '';
      }

      // 1. 转为字符串并清除所有非数字和非小数点的字符
      // 对于允许输入百分比的字段，可以加上 %，如 /[^\d.%]/g
      value = value.toString().replace(/[^\d.]/g, '');

      // 2. 只保留第一个小数点
      const parts = value.split('.');
      if (parts.length > 2) {
        value = parts[0] + '.' + parts.slice(1).join('');
      }

      // 3. 限制小数点后的位数
      if (decimalPlaces > 0 && parts.length === 2) {
        value = parts[0] + '.' + parts[1].substring(0, decimalPlaces);
      } else if (decimalPlaces === 0) {
        // 如果不允许小数，则取整数部分
        value = parts[0];
      }

      // 4. 严格控制总长度不超过 maxlength (16)
      if (value.length > 16) {
        value = value.substring(0, 16);
      }

      // 5. 将处理后的值赋回给 v-model
      this.formData[fieldName] = value;
    },
  }
}
</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%;
}

.auto-input {
  background-color: #f7f8fa;
  color: #1d2129;
}

.data-row {
  margin-bottom: 10px;
}

.data-col {
  padding: 0 10px;
}

.data-item {
  margin-bottom: 16px;

  &.required ::v-deep .el-form-item__label::after {
    content: '*';
    color: #ff4d4f;
    margin-left: 4px;
  }
}

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

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

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