<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)"
            />
            <!-- 计算字段 -->
            <span v-else class="calculated-value">
              {{ formatCalculatedValue(row[col.prop]) }}
            </span>
          </template>
        </el-table-column>
      </template>

      <!-- 月度更新表格的列 -->
      <template v-else>
        <!-- 1-12月 -->
        <el-table-column
          v-for="month in 12"
          :key="`month-${month}`"
          :label="`${month}月`"
          :prop="`m${month}`"
          min-width="180"
          align="center"
        >
          <template #default="{ row }">
            <el-input
              v-model="row[`m${month}`]"
              type="number"
              :disabled="isPreview || row.noEdit"
              placeholder="请输入"
              @input="handleMonthInput(row)"
            />
          </template>
        </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>
        </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, "%") }}
              </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, "%") }}
              </span>
            </template>
          </el-table-column>
        </el-table-column>

        <!-- 截至本年完成（开累） -->
        <el-table-column
          label="截至本年完成（开累）"
          prop="invoiceCompleted"
          min-width="200"
          align="center"
        >
          <template #default="{ row }">
            <el-input
              v-model="row.invoiceCompleted"
              type="number"
              :disabled="isPreview || row.noEdit"
              placeholder="请输入"
              @input="handleInvoiceInput(row)"
            />
          </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, "%")
                }}
              </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, "%") }}
              </span>
            </template>
          </el-table-column>
        </el-table-column>

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

        <!-- 计划差额 -->
        <el-table-column
          label="计划差额"
          prop="planDifference"
          min-width="120"
          align="center"
        >
          <template #default="{ row }">
            <span class="calculated-value">
              {{ formatCalculatedValue(row.planDifference) }}
            </span>
          </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'
    validator: (val) => ["year", "month"].includes(val),
  },
  tableTitle: {
    type: String,
    default: "",
  },
  // 投资回收计划数据（用于自动填充本年计划、开累计划）
  planData: {
    type: Object,
    default: () => ({}),
  },
  // 投资回收决策数据（用于自动填充本年决策、开累决策）
  decisionData: {
    type: Object,
    default: () => ({}),
  },
  // 去年投资回收计划数据（用于获取前年数据）
  lastYearPlanData: {
    type: Object,
    default: () => ({}),
  },
  // 当前年份
  currentYear: {
    type: [String, Number],
    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: "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 "-";
  if (suffix === "%") {
    return `${Number(value).toFixed(2)}%`;
  }
  return Number(value).toFixed(2);
};

// 初始化行数据
const initRowData = (indicator, index, sourceRow = {}) => {
  const baseRow = {
    serialNumber: 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 || "",
    };
  } else {
    // 月度表格
    const monthData = {};
    for (let i = 1; i <= 12; i++) {
      monthData[`m${i}`] = sourceRow[`m${i}`] || 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 || null,
      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 },
  { name: "建设期", noEdit: false },
  { name: "运营期", noEdit: false },
  { name: "使用者付费", noEdit: false },
  { name: "投资价款", noEdit: false },
  { name: "参股项目投资回收", noEdit: false },
  { name: "代建工程款", noEdit: false },
  { name: "其他", noEdit: false },
  { name: "合计", isTotalRow: true, noEdit: true },
];

// 从计划数据和决策数据中获取对应指标的值
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",
      );
    }
  });

  // 重新计算完成率
  tableDataRef.value.forEach((row) => {
    calculateMonthRow(row);
  });
};

// 年度表格计算
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}`]) || 0;
    }
    row.yearTotal = monthSum;
  }

  // 本年完成率/本年决策 = 本年累计 / 本年决策 * 100
  const yearDecision = parseFloat(row.yearDecision) || 0;
  const yearTotal = parseFloat(row.yearTotal) || 0;
  if (yearDecision > 0) {
    row.yearCompletionRateDecision = (yearTotal / yearDecision) * 100;
  } else {
    row.yearCompletionRateDecision = 0;
  }

  // 本年完成率/本年计划 = 本年累计 / 本年计划 * 100
  const yearPlan = parseFloat(row.yearPlan) || 0;
  if (yearPlan > 0) {
    row.yearCompletionRatePlan = (yearTotal / yearPlan) * 100;
  } else {
    row.yearCompletionRatePlan = 0;
  }

  // 开累完成率/开累决策 = 开累完成 / 开累决策 * 100
  const invoiceDecision = parseFloat(row.invoiceDecision) || 0;
  const invoiceCompleted = parseFloat(row.invoiceCompleted) || 0;
  if (invoiceDecision > 0) {
    row.invoiceCompletionRateDecision =
      (invoiceCompleted / invoiceDecision) * 100;
  } else {
    row.invoiceCompletionRateDecision = 0;
  }

  // 开累完成率/本年计划 = 开累完成 / 开累计划 * 100
  const invoicePlan = parseFloat(row.invoicePlan) || 0;
  if (invoicePlan > 0) {
    row.invoiceCompletionRatePlan = (invoiceCompleted / invoicePlan) * 100;
  } else {
    row.invoiceCompletionRatePlan = 0;
  }

  // 欠收金额 = 本年决策 - 本年累计
  row.shortfallAmount = yearDecision - yearTotal;

  // 计划差额 = 合同总金额 - 本年计划
  const contractTotal = parseFloat(row.contractTotalAmount) || 0;
  row.planDifference = contractTotal - yearPlan;
};

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

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

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

    totalRow.decisionReceivable = totalDecision;
    totalRow.actualReceived = totalActual;
    totalRow.shortfall = totalDecision - totalActual;
    if (totalDecision > 0) {
      totalRow.completionRate = (totalActual / totalDecision) * 100;
    } else {
      totalRow.completionRate = 0;
    }
  } else {
    // 月度表格合计
    for (let i = 1; i <= 12; i++) {
      let monthSum = 0;
      tableDataRef.value.forEach((row) => {
        if (!row.isTotalRow && !row.noEdit) {
          monthSum += parseFloat(row[`m${i}`]) || 0;
        }
      });
      totalRow[`m${i}`] = monthSum;
    }

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

// 处理输入事件
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 handleInvoiceInput = (row) => {
  calculateMonthRow(row);
  calculateTotalRow();
  emitChange();
};

const handleContractAmountInput = (row) => {
  calculateMonthRow(row);
  calculateTotalRow();
  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 },
);
</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>
