<template>
  <div class="investment-recovery-table-wrap">
    <!-- 总标题 -->
    <div v-if="tableTitle" class="table-main-title">
      {{ tableTitle }}
    </div>

    <el-table
      :data="tableDataRef"
      style="width: 100%"
      border
      :cell-style="tableCellStyle"
      row-key="serialNumber"
    >
      <!-- 序号列 -->
      <el-table-column
        prop="serialNumber"
        label="序号"
        width="80"
        fixed="left"
        align="center"
      />

      <!-- 指标名称列 -->
      <el-table-column
        prop="indicatorName"
        label="指标名称"
        fixed="left"
        align="left"
        min-width="180"
      />

      <!-- 年度更新表格的列 -->
      <template v-if="tableType === 'year'">
        <el-table-column
          v-for="col in yearColumns"
          :key="col.prop"
          :label="col.label"
          min-width="180"
          align="center"
        >
          <template #default="{ row }">
            <!-- 文本输入 -->
            <el-input
              v-if="col.isText"
              v-model="row[col.prop]"
              type="textarea"
              :rows="2"
              :disabled="isPreview || row.noEdit"
              placeholder="请输入"
              style="width: 100%"
              @input="handleTextInput"
            />
            <!-- 数字输入 -->
            <el-input
              v-else-if="!col.isCalculated"
              v-model="row[col.prop]"
              type="number"
              :disabled="isPreview || row.noEdit"
              placeholder="请输入"
              @input="handleNumberInput(row)"
            >
              <template #suffix>
                <span>{{ moneyUnit }}</span>
              </template>
            </el-input>
            <!-- 计算字段 -->
            <span v-else class="calculated-value">
              {{ formatCalculatedValue(row[col.prop], rateUnit) }}
            </span>
          </template>
        </el-table-column>
      </template>

      <!-- 月度更新表格的列 -->
      <template v-else-if="tableType === 'month'">
        <!-- 1-12月 -->
        <el-table-column
          v-for="month in 12"
          :key="`month-${month}`"
          :label="`${month}月`"
          align="center"
        >
          <!-- 应收 -->
          <el-table-column
            :label="`应收`"
            :prop="`m${month}Receivable`"
            min-width="150"
            align="center"
          >
            <template #default="{ row }">
              <el-input
                v-model="row[`m${month}Receivable`]"
                type="number"
                :disabled="isPreview || row.noEdit"
                placeholder="请输入"
                @input="handleMonthInput(row)"
              >
                <template #suffix>
                  <span>{{ moneyUnit }}</span>
                </template>
              </el-input>
            </template>
          </el-table-column>
          <!-- 实收 -->
          <el-table-column
            :label="`实收`"
            :prop="`m${month}Received`"
            min-width="150"
            align="center"
          >
            <template #default="{ row }">
              <el-input
                v-model="row[`m${month}Received`]"
                type="number"
                :disabled="isPreview || row.noEdit"
                placeholder="请输入"
                @input="handleMonthInput(row)"
              >
                <template #suffix>
                  <span>{{ moneyUnit }}</span>
                </template>
              </el-input>
            </template>
          </el-table-column>
        </el-table-column>

        <!-- 本年累计 -->
        <el-table-column
          label="本年累计（实收）"
          prop="yearTotal"
          min-width="180"
          align="center"
        >
          <template #default="{ row }">
            <span v-if="row.isTotalRow" class="calculated-value">
              {{ formatCalculatedValue(row.yearTotal) }}
            </span>
            <el-input
              v-else
              v-model="row.yearTotal"
              type="number"
              :disabled="isPreview || row.noEdit || row.autoCalcYearTotal"
              placeholder="自动计算"
              @input="handleYearTotalInput(row)"
            >
              <template #suffix>
                <span>{{ moneyUnit }}</span>
              </template>
            </el-input>
          </template>
        </el-table-column>

        <!-- 本年完成率（分组） -->
        <el-table-column label="本年完成率" align="center">
          <el-table-column
            label="本年累计/本年决策"
            prop="yearCompletionRateDecision"
            min-width="180"
            align="center"
          >
            <template #default="{ row }">
              <span class="calculated-value">
                {{
                  formatCalculatedValue(
                    row.yearCompletionRateDecision,
                    rateUnit,
                  )
                }}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            label="本年累计/本年计划"
            prop="yearCompletionRatePlan"
            min-width="180"
            align="center"
          >
            <template #default="{ row }">
              <span class="calculated-value">
                {{
                  formatCalculatedValue(row.yearCompletionRatePlan, rateUnit)
                }}
              </span>
            </template>
          </el-table-column>
        </el-table-column>

        <!-- 截至本年完成（开累） -->
        <el-table-column
          label="截至本年完成（开累）"
          prop="invoiceCompleted"
          min-width="200"
          align="center"
        >
          <template #default="{ row }">
            <span v-if="row.isTotalRow" class="calculated-value">
              {{ formatCalculatedValue(row.invoiceCompleted) }}
            </span>
            <span v-else class="calculated-value">
              {{ formatCalculatedValue(row.invoiceCompleted) }}
            </span>
          </template>
        </el-table-column>

        <!-- 开累完成率（分组） -->
        <el-table-column label="开累完成率" min-width="180" align="center">
          <el-table-column
            label="开累完成/开累决策"
            prop="invoiceCompletionRateDecision"
            min-width="180"
            align="center"
          >
            <template #default="{ row }">
              <span class="calculated-value">
                {{
                  formatCalculatedValue(
                    row.invoiceCompletionRateDecision,
                    rateUnit,
                  )
                }}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            label="开累完成/开累计划"
            prop="invoiceCompletionRatePlan"
            min-width="180"
            align="center"
          >
            <template #default="{ row }">
              <span class="calculated-value">
                {{
                  formatCalculatedValue(row.invoiceCompletionRatePlan, rateUnit)
                }}
              </span>
            </template>
          </el-table-column>
        </el-table-column>

        <!-- 欠收金额 -->
        <el-table-column
          label="欠收金额"
          prop="shortfallAmount"
          min-width="180"
          align="center"
        >
          <template #default="{ row }">
            <el-input
              v-model="row.shortfallAmount"
              type="number"
              :disabled="isPreview || row.noEdit"
              placeholder="请输入"
              @input="handleShortfallAmountInput(row)"
            >
              <template #suffix>
                <span>{{ moneyUnit }}</span>
              </template>
            </el-input>
          </template>
        </el-table-column>

        <!-- 合同总金额 -->
        <el-table-column
          label="合同总金额"
          prop="contractTotalAmount"
          min-width="150"
          align="center"
        >
          <template #default="{ row }">
            <el-input
              v-model="row.contractTotalAmount"
              type="number"
              :disabled="isPreview || row.noEdit"
              placeholder="请输入"
              @input="handleContractAmountInput(row)"
            >
              <template #suffix>
                <span>{{ moneyUnit }}</span>
              </template>
            </el-input>
          </template>
        </el-table-column>

        <!-- 实际与计划差异说明 -->
        <el-table-column
          label="实际与计划差异说明"
          prop="planDifference"
          min-width="200"
          align="center"
        >
          <template #default="{ row }">
            <el-input
              v-model="row.planDifference"
              type="textarea"
              :rows="2"
              :disabled="isPreview || row.noEdit"
              placeholder="请输入"
              @input="handlePlanDifferenceInput"
            />
          </template>
        </el-table-column>
      </template>

      <!-- 计划表格的列 -->
      <template v-else-if="tableType === 'plan'">
        <!-- 1-12月 -->
        <el-table-column
          v-for="month in 12"
          :key="`month-${month}`"
          :label="`${month}月`"
          align="center"
        >
          <!-- 决策 -->
          <el-table-column
            :label="`决策`"
            :prop="`m${month}Decision`"
            min-width="150"
            align="center"
          >
            <template #default="{ row }">
              <el-input
                v-model="row[`m${month}Decision`]"
                type="number"
                :disabled="isPreview || row.noEdit"
                placeholder="请输入"
                @input="handleMonthInput(row)"
              >
                <template #suffix>
                  <span>{{ moneyUnit }}</span>
                </template>
              </el-input>
            </template>
          </el-table-column>
          <!-- 计划 -->
          <el-table-column
            :label="`计划`"
            :prop="`m${month}Plan`"
            min-width="150"
            align="center"
          >
            <template #default="{ row }">
              <el-input
                v-model="row[`m${month}Plan`]"
                type="number"
                :disabled="isPreview || row.noEdit"
                placeholder="请输入"
                @input="handleMonthInput(row)"
              >
                <template #suffix>
                  <span>{{ moneyUnit }}</span>
                </template>
              </el-input>
            </template>
          </el-table-column>
        </el-table-column>

        <!-- 合计 -->
        <el-table-column label="合计" align="center">
          <!-- 决策 -->
          <el-table-column
            label="决策"
            prop="totalDecision"
            min-width="180"
            align="center"
          >
            <template #default="{ row }">
              <span class="calculated-value">
                {{ formatCalculatedValue(row.totalDecision) }}
              </span>
            </template>
          </el-table-column>
          <!-- 计划 -->
          <el-table-column
            label="计划"
            prop="totalPlan"
            min-width="180"
            align="center"
          >
            <template #default="{ row }">
              <span class="calculated-value">
                {{ formatCalculatedValue(row.totalPlan) }}
              </span>
            </template>
          </el-table-column>
        </el-table-column>

        <!-- 目标（决策）与计划差异说明 -->
        <el-table-column
          label="目标（决策）与计划差异说明"
          prop="differenceExplanation"
          min-width="200"
          align="center"
        >
          <template #default="{ row }">
            <el-input
              v-model="row.differenceExplanation"
              type="textarea"
              :rows="2"
              :disabled="isPreview || row.noEdit"
              placeholder="请输入"
              @input="handleTextInput"
            />
          </template>
        </el-table-column>
      </template>
    </el-table>
  </div>
</template>

<script setup>
import { ref, computed, watch, nextTick } from "vue";

const props = defineProps({
  modelValue: {
    type: Object,
    default: () => ({ tableData: [] }),
  },
  isPreview: {
    type: Boolean,
    default: false,
  },
  tableType: {
    type: String,
    default: "year", // 'year' 或 'month' 或 'plan'
    validator: (val) => ["year", "month", "plan"].includes(val),
  },
  tableTitle: {
    type: String,
    default: "",
  },
  // 投资回收计划数据（用于自动填充本年计划、开累计划）
  planData: {
    type: Object,
    default: () => ({}),
  },
  // 投资回收决策数据（用于自动填充本年决策、开累决策）
  decisionData: {
    type: Object,
    default: () => ({}),
  },
  // 去年投资回收计划数据（用于获取前年数据）
  lastYearPlanData: {
    type: Object,
    default: () => ({}),
  },
  // 当前年份
  currentYear: {
    type: [String, Number],
    default: "",
  },
  // 投资回收完成情况年度计划数据（用于获取年度计划的合计决策值）
  yearlyPlanData: {
    type: Object,
    default: () => ({}),
  },
  // 投资回收完成情况年度更新数据（用于获取截至年底实收值）
  yearlyCompletionData: {
    type: Object,
    default: () => ({}),
  },
  // 金额单位（默认万元）
  moneyUnit: {
    type: String,
    default: "万元",
  },
  // 利率单位（默认%）
  rateUnit: {
    type: String,
    default: "%",
  },
});

const emit = defineEmits(["update:modelValue"]);

const tableDataRef = ref([]);

// 年度表格列配置
const yearColumns = computed(() => [
  {
    prop: "decisionReceivable",
    label: "截至年底应收决策应收",
    width: 160,
    isText: false,
    isCalculated: false,
  },
  {
    prop: "actualReceived",
    label: "截至年底计划应收",
    width: 140,
    isText: false,
    isCalculated: false,
  },
  {
    prop: "jzss",
    label: "截至（具体年份）年底实收",
    width: 180,
    isText: false,
    isCalculated: false,
  },
  {
    prop: "shortfall",
    label: "欠收（决策应收-实收）",
    width: 180,
    isText: false,
    isCalculated: true,
  },
  {
    prop: "completionRate",
    label: "完成率",
    width: 120,
    isText: false,
    isCalculated: true,
  },
  {
    prop: "problems",
    label: "存在主要问题",
    width: 200,
    isText: true,
    isCalculated: false,
  },
  {
    prop: "measures",
    label: "采取措施情况",
    width: 200,
    isText: true,
    isCalculated: false,
  },
]);

// 格式化计算值
const formatCalculatedValue = (value, suffix = "") => {
  if (value === null || value === undefined || isNaN(value)) return "-";
  return `${Number(value).toFixed(2)}${suffix}`;
};

// 初始化行数据
const initRowData = (indicator, index, sourceRow = {}) => {
  const baseRow = {
    serialNumber: indicator.xh || index + 1,
    indicatorName: indicator.name,
    noEdit: indicator.noEdit || false,
    isTotalRow: indicator.isTotalRow || false,
  };

  if (props.tableType === "year") {
    return {
      ...baseRow,
      decisionReceivable: sourceRow.decisionReceivable || null,
      actualReceived: sourceRow.actualReceived || null,
      shortfall: sourceRow.shortfall || null,
      completionRate: sourceRow.completionRate || null,
      problems: sourceRow.problems || "",
      measures: sourceRow.measures || "",
      jzss: sourceRow.jzss || null,
    };
  } else if (props.tableType === "plan") {
    // 计划表格
    const monthData = {};
    for (let i = 1; i <= 12; i++) {
      monthData[`m${i}Decision`] = sourceRow[`m${i}Decision`] || null;
      monthData[`m${i}Plan`] = sourceRow[`m${i}Plan`] || null;
    }
    return {
      ...baseRow,
      ...monthData,
      totalDecision: sourceRow.totalDecision || null,
      totalPlan: sourceRow.totalPlan || null,
      differenceExplanation: sourceRow.differenceExplanation || "",
    };
  } else {
    // 月度表格
    const monthData = {};
    for (let i = 1; i <= 12; i++) {
      monthData[`m${i}Receivable`] = sourceRow[`m${i}Receivable`] || null;
      monthData[`m${i}Received`] = sourceRow[`m${i}Received`] || null;
    }
    return {
      ...baseRow,
      ...monthData,
      yearTotal: sourceRow.yearTotal || null,
      yearCompletionRateDecision: sourceRow.yearCompletionRateDecision || null,
      yearCompletionRatePlan: sourceRow.yearCompletionRatePlan || null,
      invoiceCompleted: sourceRow.invoiceCompleted || null,
      invoiceCompletionRateDecision:
        sourceRow.invoiceCompletionRateDecision || null,
      invoiceCompletionRatePlan: sourceRow.invoiceCompletionRatePlan || null,
      shortfallAmount: sourceRow.shortfallAmount || null,
      contractTotalAmount: sourceRow.contractTotalAmount || null,
      planDifference: sourceRow.planDifference || "",
      yearDecision: sourceRow.yearDecision || null, // 本年决策目标
      yearPlan: sourceRow.yearPlan || null, // 本年计划目标
      invoiceDecision: sourceRow.invoiceDecision || null, // 开累决策目标
      invoicePlan: sourceRow.invoicePlan || null, // 开累计划目标
      autoCalcYearTotal: indicator.autoCalcYearTotal !== false, // 默认自动计算本年累计
    };
  }
};

// 指标列表
const indicators = [
  { name: "政府付费", noEdit: false, xh: "1" },
  { name: "建设期", noEdit: false, xh: "1.1" },
  { name: "运营期", noEdit: false, xh: "1.2" },
  { name: "使用者付费", noEdit: false, xh: "2" },
  { name: "投资价款", noEdit: false, xh: "3" },
  { name: "参股项目投资回收", noEdit: false, xh: "4" },
  { name: "代建工程款", noEdit: false, xh: "5" },
  { name: "其他", noEdit: false, xh: "6" },
  { name: "合计", isTotalRow: true, noEdit: true, xh: "7" },
];

// 从计划数据和决策数据中获取对应指标的值
const getIndicatorValue = (indicatorName, dataSource, type) => {
  if (!dataSource || !dataSource.tableData) return 0;

  const row = dataSource.tableData.find(
    (r) => r.indicatorName === indicatorName,
  );
  if (!row) return 0;

  // 根据类型返回对应字段的值
  if (type === "yearDecision") {
    // 本年决策：从决策数据中获取当前年度的合计
    // 决策数据的时间列表是 ["一季度", "二季度", "三季度", "四季度"]
    // 合计 = 一季度 + 二季度 + 三季度 + 四季度
    const q1 = parseFloat(row["一季度"]) || 0;
    const q2 = parseFloat(row["二季度"]) || 0;
    const q3 = parseFloat(row["三季度"]) || 0;
    const q4 = parseFloat(row["四季度"]) || 0;
    return q1 + q2 + q3 + q4;
  } else if (type === "yearPlan") {
    // 本年计划：从去年投资回收计划数据中获取合计值
    return parseFloat(row.a1) || 0;
  } else if (type === "invoiceDecision") {
    // 开累决策：从决策数据中获取开累值
    // 这里可能是累计值，需要根据实际业务逻辑确定
    const q1 = parseFloat(row["一季度"]) || 0;
    const q2 = parseFloat(row["二季度"]) || 0;
    const q3 = parseFloat(row["三季度"]) || 0;
    const q4 = parseFloat(row["四季度"]) || 0;
    return q1 + q2 + q3 + q4; // 暂时用年度合计
  } else if (type === "invoicePlan") {
    // 开累计划：从计划数据中获取开累值
    return parseFloat(row.a1) || 0; // 暂时用年度合计
  }

  return 0;
};

// 自动填充决策和计划数据
const autoFillDecisionAndPlan = () => {
  if (props.tableType !== "month") return;

  tableDataRef.value.forEach((row) => {
    if (row.isTotalRow || row.noEdit) return;

    // 自动填充本年决策（从决策数据获取）
    if (props.decisionData && Object.keys(props.decisionData).length > 0) {
      row.yearDecision = getIndicatorValue(
        row.indicatorName,
        props.decisionData,
        "yearDecision",
      );
    }

    // 自动填充本年计划（从去年投资回收计划数据获取）
    if (
      props.lastYearPlanData &&
      Object.keys(props.lastYearPlanData).length > 0
    ) {
      row.yearPlan = getIndicatorValue(
        row.indicatorName,
        props.lastYearPlanData,
        "yearPlan",
      );
    } else if (props.planData && Object.keys(props.planData).length > 0) {
      // 如果没有去年数据，则使用当前年计划数据作为后备
      row.yearPlan = getIndicatorValue(
        row.indicatorName,
        props.planData,
        "yearPlan",
      );
    }

    // 自动填充开累决策（从决策数据获取）
    if (props.decisionData && Object.keys(props.decisionData).length > 0) {
      row.invoiceDecision = getIndicatorValue(
        row.indicatorName,
        props.decisionData,
        "invoiceDecision",
      );
    }

    // 自动填充开累计划（从计划数据获取）
    if (props.planData && Object.keys(props.planData).length > 0) {
      row.invoicePlan = getIndicatorValue(
        row.indicatorName,
        props.planData,
        "invoicePlan",
      );
    }
  });

  // 重新计算完成率（不触发 emitChange，避免循环）
  tableDataRef.value.forEach((row) => {
    calculateMonthRow(row);
  });

  // 计算合计行（不触发 emitChange，避免循环）
  calculateTotalRow();
};

// 年度表格计算
const calculateYearRow = (row) => {
  if (row.noEdit || row.isTotalRow) return;

  // 欠收 = 决策应收 - 实收
  const decision = parseFloat(row.decisionReceivable) || 0;
  const actual = parseFloat(row.actualReceived) || 0;
  row.shortfall = decision - actual;

  // 完成率 = 实收 / 决策应收 * 100
  if (decision > 0) {
    row.completionRate = (actual / decision) * 100;
  } else {
    row.completionRate = 0;
  }
};

// 月度表格计算
const calculateMonthRow = (row) => {
  if (row.noEdit || row.isTotalRow) return;

  // 本年累计 = 1-12月实收之和
  if (row.autoCalcYearTotal) {
    let monthSum = 0;
    for (let i = 1; i <= 12; i++) {
      monthSum += parseFloat(row[`m${i}Received`]) || 0;
    }
    row.yearTotal = monthSum;
  }

  // 从年度计划数据中获取合计计划值
  const getYearlyPlanTotalPlan = () => {
    if (!props.yearlyPlanData || !props.yearlyPlanData.tableData) return 0;
    const totalRow = props.yearlyPlanData.tableData.find((r) => r.isTotalRow);
    return totalRow ? parseFloat(totalRow.totalPlan) || 0 : 0;
  };

  // 从年度更新数据中获取截至年底实收值
  const getYearlyJzss = () => {
    if (!props.yearlyCompletionData || !props.yearlyCompletionData.tableData)
      return 0;
    const targetRow = props.yearlyCompletionData.tableData.find(
      (r) => r.indicatorName === row.indicatorName,
    );
    return targetRow ? parseFloat(targetRow.jzss) || 0 : 0;
  };

  // 本年完成率/本年决策 = 本年累计 / 年度计划的合计计划值 * 100
  const yearlyPlanTotalPlan = getYearlyPlanTotalPlan();
  const yearTotal = parseFloat(row.yearTotal) || 0;
  if (yearlyPlanTotalPlan > 0) {
    row.yearCompletionRateDecision = (yearTotal / yearlyPlanTotalPlan) * 100;
  } else {
    row.yearCompletionRateDecision = 0;
  }

  // 自动计算截至本年完成（开累）= 本年累计 + 年度更新的截至年底实收
  const yearlyJzss = getYearlyJzss();
  row.invoiceCompleted = yearTotal + yearlyJzss;

  // 从年度更新数据中获取决策应收和计划应收值
  const getYearlyDecisionReceivable = () => {
    if (!props.yearlyCompletionData || !props.yearlyCompletionData.tableData)
      return 0;
    const targetRow = props.yearlyCompletionData.tableData.find(
      (r) => r.indicatorName === row.indicatorName,
    );
    return targetRow ? parseFloat(targetRow.decisionReceivable) || 0 : 0;
  };

  const getYearlyActualReceived = () => {
    if (!props.yearlyCompletionData || !props.yearlyCompletionData.tableData)
      return 0;
    const targetRow = props.yearlyCompletionData.tableData.find(
      (r) => r.indicatorName === row.indicatorName,
    );
    return targetRow ? parseFloat(targetRow.actualReceived) || 0 : 0;
  };

  // 本年完成率/本年计划 = 本年累计 / 年度更新的计划应收值 * 100
  const yearlyActualReceived = getYearlyActualReceived();
  if (yearlyActualReceived > 0) {
    row.yearCompletionRatePlan = (yearTotal / yearlyActualReceived) * 100;
  } else {
    row.yearCompletionRatePlan = 0;
  }

  // 开累完成率/开累决策 = 截至本年完成（开累） / (year的决策应收 + plan的合计决策值) * 100
  const yearlyDecisionReceivable = getYearlyDecisionReceivable();
  const invoiceCompleted = parseFloat(row.invoiceCompleted) || 0;
  const totalInvoiceDecision = yearlyDecisionReceivable + yearlyPlanTotalPlan;
  if (totalInvoiceDecision > 0) {
    row.invoiceCompletionRateDecision =
      (invoiceCompleted / totalInvoiceDecision) * 100;
  } else {
    row.invoiceCompletionRateDecision = 0;
  }

  // 开累完成率/开累计划 = 截至本年完成（开累） / (year的计划应收 + plan的合计计划值) * 100
  const totalInvoicePlan = yearlyActualReceived + yearlyPlanTotalPlan;
  if (totalInvoicePlan > 0) {
    row.invoiceCompletionRatePlan = (invoiceCompleted / totalInvoicePlan) * 100;
  } else {
    row.invoiceCompletionRatePlan = 0;
  }

  // 欠收金额不再自动计算，由用户手动输入
  // row.shortfallAmount = yearDecision - yearTotal;
};

// 计算合计行
const calculateTotalRow = () => {
  const totalRow = tableDataRef.value.find((row) => row.isTotalRow);
  if (!totalRow) return;

  if (props.tableType === "year") {
    // 年度表格合计
    let totalDecision = 0;
    let totalActual = 0;
    let totalJzss = 0;

    tableDataRef.value.forEach((row) => {
      if (!row.isTotalRow && !row.noEdit) {
        totalDecision += parseFloat(row.decisionReceivable) || 0;
        totalActual += parseFloat(row.actualReceived) || 0;
        totalJzss += parseFloat(row.jzss) || 0;
      }
    });

    totalRow.decisionReceivable = totalDecision;
    totalRow.actualReceived = totalActual;
    totalRow.jzss = totalJzss;
    totalRow.shortfall = totalDecision - totalActual;
    if (totalDecision > 0) {
      totalRow.completionRate = (totalActual / totalDecision) * 100;
    } else {
      totalRow.completionRate = 0;
    }
  } else if (props.tableType === "plan") {
    // 计划表格合计
    for (let i = 1; i <= 12; i++) {
      let decisionSum = 0;
      let planSum = 0;
      tableDataRef.value.forEach((row) => {
        if (!row.isTotalRow && !row.noEdit) {
          decisionSum += parseFloat(row[`m${i}Decision`]) || 0;
          planSum += parseFloat(row[`m${i}Plan`]) || 0;
        }
      });
      totalRow[`m${i}Decision`] = decisionSum;
      totalRow[`m${i}Plan`] = planSum;
    }

    // 计算合计列
    let totalDecisionSum = 0;
    let totalPlanSum = 0;
    for (let i = 1; i <= 12; i++) {
      totalDecisionSum += parseFloat(totalRow[`m${i}Decision`]) || 0;
      totalPlanSum += parseFloat(totalRow[`m${i}Plan`]) || 0;
    }
    totalRow.totalDecision = totalDecisionSum;
    totalRow.totalPlan = totalPlanSum;

    // 计算每行的合计值（1-12月总和）
    tableDataRef.value.forEach((row) => {
      if (!row.isTotalRow && !row.noEdit) {
        let decisionSum = 0;
        let planSum = 0;
        for (let i = 1; i <= 12; i++) {
          decisionSum += parseFloat(row[`m${i}Decision`]) || 0;
          planSum += parseFloat(row[`m${i}Plan`]) || 0;
        }
        row.totalDecision = decisionSum;
        row.totalPlan = planSum;
      }
    });
  } else {
    // 月度表格合计
    for (let i = 1; i <= 12; i++) {
      let receivableSum = 0;
      let receivedSum = 0;
      tableDataRef.value.forEach((row) => {
        if (!row.isTotalRow && !row.noEdit) {
          receivableSum += parseFloat(row[`m${i}Receivable`]) || 0;
          receivedSum += parseFloat(row[`m${i}Received`]) || 0;
        }
      });
      totalRow[`m${i}Receivable`] = receivableSum;
      totalRow[`m${i}Received`] = receivedSum;
    }

    // 本年累计（实收合计）
    let yearTotalSum = 0;
    for (let i = 1; i <= 12; i++) {
      yearTotalSum += parseFloat(totalRow[`m${i}Received`]) || 0;
    }
    totalRow.yearTotal = yearTotalSum;

    // 计算合计行的完成率
    // 从年度计划数据中获取合计计划值
    const getYearlyPlanTotalPlan = () => {
      if (!props.yearlyPlanData || !props.yearlyPlanData.tableData) return 0;
      const yearlyTotalRow = props.yearlyPlanData.tableData.find(
        (r) => r.isTotalRow,
      );
      return yearlyTotalRow ? parseFloat(yearlyTotalRow.totalPlan) || 0 : 0;
    };

    const yearlyPlanTotalPlan = getYearlyPlanTotalPlan();

    // 本年完成率/本年决策 = 本年累计 / 年度计划的合计计划值 * 100
    if (yearlyPlanTotalPlan > 0) {
      totalRow.yearCompletionRateDecision =
        (yearTotalSum / yearlyPlanTotalPlan) * 100;
    } else {
      totalRow.yearCompletionRateDecision = 0;
    }

    // 本年完成率/本年计划 = 本年累计 / 本年计划 * 100（合计行暂不计算此值）
    totalRow.yearCompletionRatePlan = 0;

    // 计算合计行的截至本年完成（开累）
    // 从年度更新数据中获取截至年底实收值
    const getYearlyJzss = () => {
      if (!props.yearlyCompletionData || !props.yearlyCompletionData.tableData)
        return 0;
      const yearlyTotalRow = props.yearlyCompletionData.tableData.find(
        (r) => r.isTotalRow,
      );
      return yearlyTotalRow ? parseFloat(yearlyTotalRow.jzss) || 0 : 0;
    };

    const yearlyJzss = getYearlyJzss();
    totalRow.invoiceCompleted = yearTotalSum + yearlyJzss;

    // 计算合计行的欠收金额
    let shortfallAmountSum = 0;
    tableDataRef.value.forEach((row) => {
      if (!row.isTotalRow && !row.noEdit) {
        shortfallAmountSum += parseFloat(row.shortfallAmount) || 0;
      }
    });
    totalRow.shortfallAmount = shortfallAmountSum;

    // 计算合计行的合同总金额
    let contractTotalAmountSum = 0;
    tableDataRef.value.forEach((row) => {
      if (!row.isTotalRow && !row.noEdit) {
        contractTotalAmountSum += parseFloat(row.contractTotalAmount) || 0;
      }
    });
    totalRow.contractTotalAmount = contractTotalAmountSum;

    // 计算合计行的开累完成率
    // 从年度更新数据中获取合计的决策应收和计划应收值
    const getYearlyDecisionReceivable = () => {
      if (!props.yearlyCompletionData || !props.yearlyCompletionData.tableData)
        return 0;
      const yearlyTotalRow = props.yearlyCompletionData.tableData.find(
        (r) => r.isTotalRow,
      );
      return yearlyTotalRow
        ? parseFloat(yearlyTotalRow.decisionReceivable) || 0
        : 0;
    };

    const getYearlyActualReceived = () => {
      if (!props.yearlyCompletionData || !props.yearlyCompletionData.tableData)
        return 0;
      const yearlyTotalRow = props.yearlyCompletionData.tableData.find(
        (r) => r.isTotalRow,
      );
      return yearlyTotalRow
        ? parseFloat(yearlyTotalRow.actualReceived) || 0
        : 0;
    };

    const yearlyDecisionReceivable = getYearlyDecisionReceivable();
    const yearlyActualReceived = getYearlyActualReceived();
    const invoiceCompleted = parseFloat(totalRow.invoiceCompleted) || 0;
    const totalInvoiceDecision = yearlyDecisionReceivable + yearlyPlanTotalPlan;
    const totalInvoicePlan = yearlyActualReceived + yearlyPlanTotalPlan;

    // 开累完成率/开累决策
    if (totalInvoiceDecision > 0) {
      totalRow.invoiceCompletionRateDecision =
        (invoiceCompleted / totalInvoiceDecision) * 100;
    } else {
      totalRow.invoiceCompletionRateDecision = 0;
    }

    // 开累完成率/开累计划
    if (totalInvoicePlan > 0) {
      totalRow.invoiceCompletionRatePlan =
        (invoiceCompleted / totalInvoicePlan) * 100;
    } else {
      totalRow.invoiceCompletionRatePlan = 0;
    }
  }
};

// 处理输入事件
const handleNumberInput = (row) => {
  calculateYearRow(row);
  calculateTotalRow();
  emitChange();
};

const handleTextInput = () => {
  emitChange();
};

const handleMonthInput = (row) => {
  calculateMonthRow(row);
  calculateTotalRow();
  emitChange();
};

const handleYearTotalInput = (row) => {
  calculateMonthRow(row);
  calculateTotalRow();
  emitChange();
};

const handleContractAmountInput = (row) => {
  calculateMonthRow(row);
  calculateTotalRow();
  emitChange();
};

const handleShortfallAmountInput = (row) => {
  calculateMonthRow(row);
  calculateTotalRow();
  emitChange();
};

const handlePlanDifferenceInput = () => {
  emitChange();
};

const emitChange = () => {
  if (props.isPreview) return;
  const newModelValue = {
    ...props.modelValue,
    tableData: JSON.parse(JSON.stringify(tableDataRef.value)),
  };
  emit("update:modelValue", newModelValue);
};

// 表格单元格样式
const tableCellStyle = ({ row }) => {
  if (row.isTotalRow) {
    return { background: "#f5f7fa", fontWeight: "bold", textAlign: "center" };
  }
  return { textAlign: "center" };
};

// 监听数据变化
watch(
  () => props.modelValue,
  (newVal) => {
    nextTick(() => {
      const sourceData = newVal.tableData || [];
      const newData = indicators.map((indicator, index) => {
        const sourceRow =
          sourceData.find((r) => r.indicatorName === indicator.name) || {};
        return initRowData(indicator, index, sourceRow);
      });
      tableDataRef.value = newData;
      // 自动填充决策和计划数据
      autoFillDecisionAndPlan();
    });
  },
  { deep: true, immediate: true },
);

// 监听计划数据和决策数据变化
watch(
  [
    () => props.planData,
    () => props.decisionData,
    () => props.lastYearPlanData,
  ],
  () => {
    nextTick(() => {
      autoFillDecisionAndPlan();
    });
  },
  { deep: true },
);

// 监听年度计划数据变化，重新计算完成率
watch(
  () => props.yearlyPlanData,
  () => {
    nextTick(() => {
      if (props.tableType === "month") {
        tableDataRef.value.forEach((row) => {
          calculateMonthRow(row);
        });
        calculateTotalRow();
        // 不调用 emitChange，避免无限循环
      }
    });
  },
  { deep: true },
);

// 监听年度更新数据变化，重新计算截至本年完成
watch(
  () => props.yearlyCompletionData,
  () => {
    nextTick(() => {
      if (props.tableType === "month") {
        tableDataRef.value.forEach((row) => {
          calculateMonthRow(row);
        });
        calculateTotalRow();
        // 不调用 emitChange，避免无限循环
      }
    });
  },
  { deep: true },
);
</script>

<style scoped lang="scss">
.investment-recovery-table-wrap {
  width: 100%;
  box-sizing: border-box;
  overflow-x: auto;
}

.table-main-title {
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
  border-bottom: 1px solid #ebeef5;
  height: 48px;
  line-height: 48px;
  background: #f5f7fa;
  text-align: center;
}

.calculated-value {
  color: #409eff;
  font-weight: 500;
}

:deep(.el-input__wrapper) {
  width: 100%;
}

:deep(.el-input__inner) {
  text-align: center;
}

:deep(.el-textarea__inner) {
  text-align: left;
  min-height: 40px !important;
}

:deep(.el-table__cell) {
  padding: 4px 8px !important;
  height: 48px !important;
  vertical-align: middle !important;
}

:deep(.el-table__row) {
  height: 48px !important;
}
</style>
