<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 label="截至年底应收" align="center">
          <el-table-column
            label="决策应收"
            prop="decisionReceivable"
            min-width="150"
            align="center"
          >
            <template #default="{ row }">
              <span
                v-if="row.isTotalRow || row.isParentRow"
                class="calculated-value"
              >
                {{ formatCalculatedValue(row.decisionReceivable) }}
              </span>
              <el-input
                v-else
                v-model="row.decisionReceivable"
                type="number"
                :disabled="isPreview || row.noEdit"
                placeholder="请输入"
                @input="handleNumberInput(row)"
              >
                <template #suffix>
                  <span>{{ moneyUnit }}</span>
                </template>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column
            label="计划应收"
            prop="actualReceived"
            min-width="150"
            align="center"
          >
            <template #default="{ row }">
              <span
                v-if="row.isTotalRow || row.isParentRow"
                class="calculated-value"
              >
                {{ formatCalculatedValue(row.actualReceived) }}
              </span>
              <el-input
                v-else
                v-model="row.actualReceived"
                type="number"
                :disabled="isPreview || row.noEdit"
                placeholder="请输入"
                @input="handleNumberInput(row)"
              >
                <template #suffix>
                  <span>{{ moneyUnit }}</span>
                </template>
              </el-input>
            </template>
          </el-table-column>
        </el-table-column>

        <!-- 截至年底实收 -->
        <el-table-column
          label="截至年底实收"
          prop="jzss"
          min-width="150"
          align="center"
        >
          <template #default="{ row }">
            <span
              v-if="row.isTotalRow || row.isParentRow"
              class="calculated-value"
            >
              {{ formatCalculatedValue(row.jzss) }}
            </span>
            <el-input
              v-else
              v-model="row.jzss"
              type="number"
              :disabled="isPreview || row.noEdit"
              placeholder="请输入"
              @input="handleNumberInput(row)"
            >
              <template #suffix>
                <span>{{ moneyUnit }}</span>
              </template>
            </el-input>
          </template>
        </el-table-column>

        <!-- 截至年底欠收 -->
        <el-table-column label="截至年底欠收" align="center">
          <el-table-column
            label="决策应收-实收"
            prop="shortfallDecision"
            min-width="150"
            align="center"
          >
            <template #default="{ row }">
              <span class="calculated-value">
                {{ formatCalculatedValue(row.shortfallDecision) }}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            label="计划应收-实收"
            prop="shortfallPlan"
            min-width="150"
            align="center"
          >
            <template #default="{ row }">
              <span class="calculated-value">
                {{ formatCalculatedValue(row.shortfallPlan) }}
              </span>
            </template>
          </el-table-column>
        </el-table-column>

        <!-- 完成率 -->
        <el-table-column label="完成率" align="center">
          <el-table-column
            label="实收/决策应收"
            prop="completionRateDecision"
            min-width="150"
            align="center"
          >
            <template #default="{ row }">
              <span class="calculated-value">
                {{
                  formatCalculatedValue(row.completionRateDecision, rateUnit)
                }}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            label="实收/计划应收"
            prop="completionRatePlan"
            min-width="150"
            align="center"
          >
            <template #default="{ row }">
              <span class="calculated-value">
                {{ formatCalculatedValue(row.completionRatePlan, rateUnit) }}
              </span>
            </template>
          </el-table-column>
        </el-table-column>

        <!-- 存在主要问题 -->
        <el-table-column
          label="存在主要问题"
          prop="problems"
          min-width="200"
          align="center"
        >
          <template #default="{ row }">
            <el-input
              v-model="row.problems"
              type="textarea"
              :rows="2"
              :disabled="isPreview || row.noEdit"
              placeholder="请输入"
              @input="handleTextInput"
            />
          </template>
        </el-table-column>

        <!-- 采取措施情况 -->
        <el-table-column
          label="采取措施情况"
          prop="measures"
          min-width="200"
          align="center"
        >
          <template #default="{ row }">
            <el-input
              v-model="row.measures"
              type="textarea"
              :rows="2"
              :disabled="isPreview || row.noEdit"
              placeholder="请输入"
              @input="handleTextInput"
            />
          </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}Received`"
            min-width="150"
            align="center"
          >
            <template #default="{ row }">
              <span
                v-if="row.isTotalRow || row.isParentRow"
                class="calculated-value"
              >
                {{ formatCalculatedValue(row[`m${month}Received`]) }}
              </span>
              <el-input
                v-else
                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
            :label="`应收`"
            :prop="`m${month}Receivable`"
            min-width="150"
            align="center"
          >
            <template #default="{ row }">
              <span
                v-if="row.isTotalRow || row.isParentRow"
                class="calculated-value"
              >
                {{ formatCalculatedValue(row[`m${month}Receivable`]) }}
              </span>
              <el-input
                v-else
                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>

        <!-- 本年累计 -->
        <el-table-column label="本年累计" align="center">
          <el-table-column
            label="实收"
            prop="yearTotal"
            min-width="150"
            align="center"
          >
            <template #default="{ row }">
              <span class="calculated-value">
                {{ formatCalculatedValue(row.yearTotal) }}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            label="应收"
            prop="yearTotalReceivable"
            min-width="150"
            align="center"
          >
            <template #default="{ row }">
              <span class="calculated-value">
                {{ formatCalculatedValue(row.yearTotalReceivable) }}
              </span>
            </template>
          </el-table-column>
        </el-table-column>

        <!-- 本年完成率 -->
        <el-table-column label="本年完成率" align="center">
          <el-table-column
            label="累计实收/累计应收"
            prop="yearCompletionRateReceivable"
            min-width="180"
            align="center"
          >
            <template #default="{ row }">
              <span class="calculated-value">
                {{
                  formatCalculatedValue(
                    row.yearCompletionRateReceivable,
                    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 class="calculated-value">
              {{ formatCalculatedValue(row.invoiceCompleted) }}
            </span>
          </template>
        </el-table-column>

        <!-- 开累完成率 -->
        <el-table-column
          label="开累完成率"
          prop="invoiceCompletionRate"
          min-width="180"
          align="center"
        >
          <template #default="{ row }">
            <span class="calculated-value">
              {{ formatCalculatedValue(row.invoiceCompletionRate, rateUnit) }}
            </span>
          </template>
        </el-table-column>

        <!-- 欠收金额 -->
        <el-table-column
          label="欠收金额"
          prop="shortfallAmount"
          min-width="150"
          align="center"
        >
          <template #default="{ row }">
            <span class="calculated-value">
              {{ formatCalculatedValue(row.shortfallAmount) }}
            </span>
          </template>
        </el-table-column>

        <!-- 合同总金额 -->
        <el-table-column
          label="合同总金额"
          prop="contractTotalAmount"
          min-width="150"
          align="center"
        >
          <template #default="{ row }">
            <span
              v-if="row.isTotalRow || row.isParentRow"
              class="calculated-value"
            >
              {{ formatCalculatedValue(row.contractTotalAmount) }}
            </span>
            <el-input
              v-else
              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 }">
              <span
                v-if="row.isTotalRow || row.isParentRow"
                class="calculated-value"
              >
                {{ formatCalculatedValue(row[`m${month}Decision`]) }}
              </span>
              <el-input
                v-else
                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 }">
              <span
                v-if="row.isTotalRow || row.isParentRow"
                class="calculated-value"
              >
                {{ formatCalculatedValue(row[`m${month}Plan`]) }}
              </span>
              <el-input
                v-else
                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",
    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 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,
    isParentRow: indicator.isParentRow || false,
    isChild: indicator.isChild || false,
  };

  if (props.tableType === "year") {
    return {
      ...baseRow,
      decisionReceivable: sourceRow.decisionReceivable || null,
      actualReceived: sourceRow.actualReceived || null,
      jzss: sourceRow.jzss || null,
      shortfallDecision: sourceRow.shortfallDecision || null,
      shortfallPlan: sourceRow.shortfallPlan || null,
      completionRateDecision: sourceRow.completionRateDecision || null,
      completionRatePlan: sourceRow.completionRatePlan || null,
      // backward compat
      shortfall: sourceRow.shortfall || null,
      completionRate: sourceRow.completionRate || null,
      problems: sourceRow.problems || "",
      measures: sourceRow.measures || "",
    };
  } 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,
      yearTotalReceivable: sourceRow.yearTotalReceivable || null,
      yearCompletionRateReceivable:
        sourceRow.yearCompletionRateReceivable || null,
      yearCompletionRatePlan: sourceRow.yearCompletionRatePlan || null,
      invoiceCompleted: sourceRow.invoiceCompleted || null,
      invoiceCompletionRate: sourceRow.invoiceCompletionRate || null,
      shortfallAmount: sourceRow.shortfallAmount || null,
      contractTotalAmount: sourceRow.contractTotalAmount || null,
      planDifference: sourceRow.planDifference || "",
    };
  }
};

const indicators = [
  {
    name: "政府付费",
    noEdit: false,
    xh: "1",
    isParentRow: true,
    childNames: ["建设期", "运营期"],
  },
  { name: "建设期", noEdit: false, xh: "1.1", isChild: true },
  { name: "运营期", noEdit: false, xh: "1.2", isChild: true },
  { 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 calculateParentRows = () => {
  const parentRows = tableDataRef.value.filter((row) => row.isParentRow);
  parentRows.forEach((parentRow) => {
    const indicator = indicators.find(
      (i) => i.name === parentRow.indicatorName,
    );
    if (!indicator || !indicator.childNames) return;

    const childRows = tableDataRef.value.filter((r) =>
      indicator.childNames.includes(r.indicatorName),
    );

    if (props.tableType === "year") {
      parentRow.decisionReceivable = childRows.reduce(
        (sum, r) => sum + (parseFloat(r.decisionReceivable) || 0),
        0,
      );
      parentRow.actualReceived = childRows.reduce(
        (sum, r) => sum + (parseFloat(r.actualReceived) || 0),
        0,
      );
      parentRow.jzss = childRows.reduce(
        (sum, r) => sum + (parseFloat(r.jzss) || 0),
        0,
      );
      const dr = parentRow.decisionReceivable;
      const pr = parentRow.actualReceived;
      const jz = parentRow.jzss;
      parentRow.shortfallDecision = dr - jz;
      parentRow.shortfallPlan = pr - jz;
      parentRow.completionRateDecision = dr > 0 ? (jz / dr) * 100 : 0;
      parentRow.completionRatePlan = pr > 0 ? (jz / pr) * 100 : 0;
    } else if (props.tableType === "plan") {
      for (let i = 1; i <= 12; i++) {
        parentRow[`m${i}Decision`] = childRows.reduce(
          (sum, r) => sum + (parseFloat(r[`m${i}Decision`]) || 0),
          0,
        );
        parentRow[`m${i}Plan`] = childRows.reduce(
          (sum, r) => sum + (parseFloat(r[`m${i}Plan`]) || 0),
          0,
        );
      }
      let totalDecision = 0,
        totalPlan = 0;
      for (let i = 1; i <= 12; i++) {
        totalDecision += parseFloat(parentRow[`m${i}Decision`]) || 0;
        totalPlan += parseFloat(parentRow[`m${i}Plan`]) || 0;
      }
      parentRow.totalDecision = totalDecision;
      parentRow.totalPlan = totalPlan;
    } else if (props.tableType === "month") {
      for (let i = 1; i <= 12; i++) {
        parentRow[`m${i}Received`] = childRows.reduce(
          (sum, r) => sum + (parseFloat(r[`m${i}Received`]) || 0),
          0,
        );
        parentRow[`m${i}Receivable`] = childRows.reduce(
          (sum, r) => sum + (parseFloat(r[`m${i}Receivable`]) || 0),
          0,
        );
      }
      parentRow.contractTotalAmount = childRows.reduce(
        (sum, r) => sum + (parseFloat(r.contractTotalAmount) || 0),
        0,
      );
      calculateMonthRowInternal(parentRow);
    }
  });
};

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

  const decisionReceivable = parseFloat(row.decisionReceivable) || 0;
  const planReceivable = parseFloat(row.actualReceived) || 0;
  const jzss = parseFloat(row.jzss) || 0;

  // 欠收（决策应收-实收）
  row.shortfallDecision = decisionReceivable - jzss;
  // 欠收（计划应收-实收）
  row.shortfallPlan = planReceivable - jzss;
  // 完成率（实收/决策应收）
  row.completionRateDecision =
    decisionReceivable > 0 ? (jzss / decisionReceivable) * 100 : 0;
  // 完成率（实收/计划应收）
  row.completionRatePlan =
    planReceivable > 0 ? (jzss / planReceivable) * 100 : 0;
};

// 月度表格计算（内部，不检查 isParentRow）
const calculateMonthRowInternal = (row) => {
  // 本年累计实收
  let monthReceivedSum = 0;
  for (let i = 1; i <= 12; i++) {
    monthReceivedSum += parseFloat(row[`m${i}Received`]) || 0;
  }
  row.yearTotal = monthReceivedSum;

  // 本年累计应收
  let monthReceivableSum = 0;
  for (let i = 1; i <= 12; i++) {
    monthReceivableSum += parseFloat(row[`m${i}Receivable`]) || 0;
  }
  row.yearTotalReceivable = monthReceivableSum;

  const yearTotal = row.yearTotal || 0;
  const yearTotalReceivable = row.yearTotalReceivable || 0;

  // 本年完成率: 累计实收/累计应收
  row.yearCompletionRateReceivable =
    yearTotalReceivable > 0 ? (yearTotal / yearTotalReceivable) * 100 : 0;

  // 本年完成率: 累计实收/本年计划（从计划表获取该行的计划合计）
  const getPlanTotalPlan = () => {
    if (!props.yearlyPlanData || !props.yearlyPlanData.tableData) return 0;
    const planRow = props.yearlyPlanData.tableData.find(
      (r) => r.indicatorName === row.indicatorName,
    );
    return planRow ? parseFloat(planRow.totalPlan) || 0 : 0;
  };
  const planTotalPlan = getPlanTotalPlan();
  row.yearCompletionRatePlan =
    planTotalPlan > 0 ? (yearTotal / planTotalPlan) * 100 : 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;
  };
  const yearlyJzss = getYearlyJzss();
  row.invoiceCompleted = yearTotal + yearlyJzss;

  // 开累完成率 = 截至本年完成 / 合同总金额
  const contractTotal = parseFloat(row.contractTotalAmount) || 0;
  row.invoiceCompletionRate =
    contractTotal > 0 ? (row.invoiceCompleted / contractTotal) * 100 : 0;

  // 欠收金额 = 累计应收 - 累计实收
  row.shortfallAmount = yearTotalReceivable - yearTotal;
};

// 月度表格计算（对外，检查 isParentRow）
const calculateMonthRow = (row) => {
  if (row.noEdit || row.isTotalRow || row.isParentRow) return;
  calculateMonthRowInternal(row);
};

// 计算合计行（仅汇总非子行）
const calculateTotalRow = () => {
  const totalRow = tableDataRef.value.find((row) => row.isTotalRow);
  if (!totalRow) return;

  // 获取参与合计的行（排除子行、合计行、noEdit 行）
  const sumRows = tableDataRef.value.filter(
    (row) => !row.isTotalRow && !row.noEdit && !row.isChild,
  );

  if (props.tableType === "year") {
    let totalDecisionReceivable = 0;
    let totalPlanReceivable = 0;
    let totalJzss = 0;

    sumRows.forEach((row) => {
      totalDecisionReceivable += parseFloat(row.decisionReceivable) || 0;
      totalPlanReceivable += parseFloat(row.actualReceived) || 0;
      totalJzss += parseFloat(row.jzss) || 0;
    });

    totalRow.decisionReceivable = totalDecisionReceivable;
    totalRow.actualReceived = totalPlanReceivable;
    totalRow.jzss = totalJzss;
    totalRow.shortfallDecision = totalDecisionReceivable - totalJzss;
    totalRow.shortfallPlan = totalPlanReceivable - totalJzss;
    totalRow.completionRateDecision =
      totalDecisionReceivable > 0
        ? (totalJzss / totalDecisionReceivable) * 100
        : 0;
    totalRow.completionRatePlan =
      totalPlanReceivable > 0
        ? (totalJzss / totalPlanReceivable) * 100
        : 0;
  } else if (props.tableType === "plan") {
    // 每行先算自己的合计
    tableDataRef.value.forEach((row) => {
      if (!row.isTotalRow && !row.noEdit && !row.isParentRow) {
        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;
      }
    });

    // 合计行汇总
    for (let i = 1; i <= 12; i++) {
      let decisionSum = 0;
      let planSum = 0;
      sumRows.forEach((row) => {
        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;
  } else {
    // 月度表格合计
    for (let i = 1; i <= 12; i++) {
      let receivedSum = 0;
      let receivableSum = 0;
      sumRows.forEach((row) => {
        receivedSum += parseFloat(row[`m${i}Received`]) || 0;
        receivableSum += parseFloat(row[`m${i}Receivable`]) || 0;
      });
      totalRow[`m${i}Received`] = receivedSum;
      totalRow[`m${i}Receivable`] = receivableSum;
    }

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

    // 本年累计应收
    let yearTotalReceivableSum = 0;
    for (let i = 1; i <= 12; i++) {
      yearTotalReceivableSum += parseFloat(totalRow[`m${i}Receivable`]) || 0;
    }
    totalRow.yearTotalReceivable = yearTotalReceivableSum;

    // 本年完成率: 累计实收/累计应收
    totalRow.yearCompletionRateReceivable =
      yearTotalReceivableSum > 0
        ? (yearTotalSum / yearTotalReceivableSum) * 100
        : 0;

    // 本年完成率: 累计实收/本年计划
    const getPlanTotalPlan = () => {
      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 planTotalPlan = getPlanTotalPlan();
    totalRow.yearCompletionRatePlan =
      planTotalPlan > 0 ? (yearTotalSum / planTotalPlan) * 100 : 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 contractTotalAmountSum = 0;
    sumRows.forEach((row) => {
      contractTotalAmountSum += parseFloat(row.contractTotalAmount) || 0;
    });
    totalRow.contractTotalAmount = contractTotalAmountSum;

    // 开累完成率 = 截至本年完成 / 合同总金额
    totalRow.invoiceCompletionRate =
      contractTotalAmountSum > 0
        ? (totalRow.invoiceCompleted / contractTotalAmountSum) * 100
        : 0;

    // 欠收金额 = 累计应收 - 累计实收
    totalRow.shortfallAmount = yearTotalReceivableSum - yearTotalSum;
  }
};

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

  tableDataRef.value.forEach((row) => {
    calculateMonthRow(row);
  });

  calculateParentRows();
  calculateTotalRow();
};

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

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

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

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

const handleShortfallAmountInput = (row) => {
  calculateMonthRow(row);
  calculateParentRows();
  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" };
  }
  if (row.isParentRow) {
    return { background: "#fafafa", fontWeight: "500", 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;

      // 重新计算
      tableDataRef.value.forEach((row) => {
        if (props.tableType === "year") {
          calculateYearRow(row);
        } else if (props.tableType === "month") {
          calculateMonthRow(row);
        }
      });
      calculateParentRows();
      calculateTotalRow();

      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);
        });
        calculateParentRows();
        calculateTotalRow();
      }
    });
  },
  { deep: true },
);

// 监听年度更新数据变化，重新计算截至本年完成
watch(
  () => props.yearlyCompletionData,
  () => {
    nextTick(() => {
      if (props.tableType === "month") {
        tableDataRef.value.forEach((row) => {
          calculateMonthRow(row);
        });
        calculateParentRows();
        calculateTotalRow();
      }
    });
  },
  { 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>
