<template>
  <div class="mixed-table-wrap">
    <!-- 总标题（可配置） -->
    <div
      v-if="tableTitle"
      class="table-main-title"
      :style="{
        paddingLeft:
          !showSerialColumn && !showNameColumn && !showTotalColumn
            ? '0'
            : '80px',
      }"
    >
      {{ tableTitle }}
    </div>

    <el-table
      :data="tableDataRef"
      style="width: 100%"
      border
      :cell-style="tableCellStyle"
      row-key="serialNumber"
      v-if="validConfig"
    >
      <!-- 序号列：控制参数 showSerialColumn -->
      <el-table-column
        v-if="showSerialColumn"
        prop="serialNumber"
        label="序号"
        width="80"
        fixed="left"
        align="center"
      />
      <!-- 指标项列：控制参数 showNameColumn -->
      <el-table-column
        v-if="showNameColumn"
        prop="indicatorName"
        label="名称"
        fixed="left"
        align="left"
        min-width="260"
      >
        <template #default="{ row }">
          <div
            class="indicatorName"
            :style="{
              textIndent: row.level ? `${row.level * 20}px` : '0px',
              textAlign: 'left',
            }"
          >
            {{ row.indicatorName }}
          </div>
        </template>
      </el-table-column>
      <!-- 合计列：控制参数 showTotalColumn -->
      <el-table-column
        v-if="showTotalColumn"
        fixed="left"
        label="合计"
        width="140"
        align="right"
      >
        <template #default="{ row }">
          <span v-if="!row.noTotal">
            {{ row.total ? Number(row.total).toFixed(2) : "0.00" }}万元
          </span>
          <span v-else>&nbsp;</span>
        </template>
      </el-table-column>

      <!-- 多级时间列表头渲染逻辑 -->
      <template v-if="hasTimeHeaderGroup">
        <el-table-column
          v-for="group in timeColumnGroups"
          :key="`time-group-${group.key}`"
          :label="group.label"
          align="right"
        >
          <el-table-column
            v-for="timeItem in group.children"
            :key="`time-col-${timeItem.prop}`"
            :label="timeItem.label"
            min-width="140"
            align="center"
          >
            <template #default="{ row }">
              <!-- 🌟 核心修改：优先使用列级isTextRow配置，其次行级 -->
              <el-input
                v-if="timeItem.isTextRow || row.isTextRow"
                v-model="row[timeItem.prop]"
                type="textarea"
                :rows="2"
                :disabled="isPreview"
                placeholder="请输入说明"
                style="width: 100%"
                @input="() => handleTextInput(row)"
              />
              <!-- 数字行：金额输入框 -->
              <el-input
                v-else
                v-model="row[timeItem.prop]"
                :precision="2"
                controls-position="right"
                :disabled="isPreview"
                placeholder="请输入金额"
                style="width: 100%"
                @change="() => handleFinancialChange(row)"
              />
            </template>
          </el-table-column>
        </el-table-column>
      </template>

      <!-- 无时间列分组 → 单级表头逻辑 -->
      <el-table-column
        v-else
        v-for="time in validDynamicTimeConfig"
        :key="`time-col-${time.prop || time}`"
        :label="time.label || time"
        min-width="140"
        align="center"
      >
        <template #default="{ row }">
          <!-- 🌟 核心修改：优先使用列级isTextRow配置，其次行级 -->
          <el-input
            v-if="time.isTextRow || row.isTextRow"
            v-model="row[time.prop || time]"
            type="textarea"
            :rows="2"
            :disabled="isPreview"
            placeholder="请输入说明"
            style="width: 100%"
            @input="() => handleTextInput(row)"
          />
          <!-- 数字行：金额输入框 -->
          <el-input
            v-else
            v-model="row[time.prop || time]"
            :precision="2"
            controls-position="right"
            :disabled="isPreview"
            placeholder="请输入金额"
            style="width: 100%"
            @change="() => handleFinancialChange(row)"
          />
        </template>
      </el-table-column>
    </el-table>
    <div v-else style="text-align: center; padding: 20px; color: #909399">
      请传入合法的表格配置（包含indicatorList、dynamicTimeList）
    </div>
  </div>
</template>

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

// 1. 新增总标题Props参数
const props = defineProps({
  modelValue: {
    type: Object,
    default: () => ({ indicatorList: [], dynamicTimeList: [], tableData: [] }),
    validator: (val) =>
      val &&
      Array.isArray(val.indicatorList) &&
      Array.isArray(val.dynamicTimeList),
  },
  isPreview: {
    type: Boolean,
    default: false,
  },
  // 控制序号列显示（默认显示）
  showSerialColumn: {
    type: Boolean,
    default: true,
  },
  // 控制名称列显示（默认显示）
  showNameColumn: {
    type: Boolean,
    default: true,
  },
  // 控制合计列显示（默认显示）
  showTotalColumn: {
    type: Boolean,
    default: true,
  },
  // 表格总标题（不传则不显示）
  tableTitle: {
    type: String,
    default: "",
  },
});

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

const tableDataRef = ref([]);

// 处理动态时间列表（兼容单级/多级配置，新增isTextRow字段处理）
const validDynamicTimeConfig = computed(() => {
  const rawTimeList = props.modelValue.dynamicTimeList || [];
  if (!Array.isArray(rawTimeList) || rawTimeList.length === 0) {
    return [
      { label: "2025", prop: "2025", headerGroup: "", isTextRow: false },
      { label: "2026", prop: "2026", headerGroup: "", isTextRow: false },
      { label: "2027", prop: "2027", headerGroup: "", isTextRow: false },
    ];
  }

  return rawTimeList
    .map((item) => {
      if (typeof item === "string") {
        return {
          label: item.trim(),
          prop: item.trim(),
          headerGroup: "",
          isTextRow: false, // 字符串格式默认数字列
        };
      }
      return {
        label: item.label?.trim() || "",
        prop: item.prop?.trim() || item.label?.trim() || "",
        headerGroup: item.headerGroup?.trim() || "",
        isTextRow: item.isTextRow === true, // 显式转换为布尔值，默认false
      };
    })
    .filter((item) => !!item.prop);
});

// 判断是否有时间列分组
const hasTimeHeaderGroup = computed(() => {
  return validDynamicTimeConfig.value.some((item) => !!item.headerGroup);
});

// 时间列分组计算
const timeColumnGroups = computed(() => {
  const timeConfig = validDynamicTimeConfig.value;
  if (!timeConfig.length) return [];

  const groupMap = {};
  timeConfig.forEach((item) => {
    const groupKey = item.headerGroup || `single_${item.prop}`;
    if (!groupMap[groupKey]) {
      groupMap[groupKey] = {
        label: item.headerGroup || item.label,
        key: groupKey,
        children: [],
      };
    }
    groupMap[groupKey].children.push(item);
  });

  const result = [];
  const addedKeys = new Set();
  timeConfig.forEach((item) => {
    const groupKey = item.headerGroup || `single_${item.prop}`;
    if (!addedKeys.has(groupKey)) {
      result.push(groupMap[groupKey]);
      addedKeys.add(groupKey);
    }
  });

  return result;
});

// 提取纯时间prop列表（用于数据初始化/计算合计）
const validDynamicTimeList = computed(() => {
  return validDynamicTimeConfig.value.map((item) => item.prop);
});

// 配置合法性校验
const validConfig = computed(() => {
  const { indicatorList } = props.modelValue;
  return (
    Array.isArray(indicatorList) &&
    indicatorList.length > 0 &&
    validDynamicTimeList.value.length > 0
  );
});

// 🌟 核心修改：初始化行的时间字段时，适配列级isTextRow配置
const initRowTimeField = (row) => {
  if (!row || typeof row !== "object") return;
  validDynamicTimeConfig.value.forEach((timeConfig) => {
    const timeProp = timeConfig.prop;
    // 列级配置为文本 → 按文本初始化；否则按行级配置
    const isColumnTextRow = timeConfig.isTextRow;
    if (isColumnTextRow) {
      // 列级文本：置空字符串
      row[timeProp] =
        row[timeProp] === undefined || row[timeProp] === null
          ? ""
          : String(row[timeProp]);
    } else if (row.isTextRow) {
      // 行级文本：置空字符串
      row[timeProp] =
        row[timeProp] === undefined || row[timeProp] === null
          ? ""
          : String(row[timeProp]);
    } else {
      // 数字列：置0
      row[timeProp] =
        row[timeProp] === undefined ||
        row[timeProp] === null ||
        isNaN(Number(row[timeProp]))
          ? null
          : Number(row[timeProp]);
    }
  });
};

// 计算单行合计（排除文本列）
const calculateRowTotal = (row) => {
  if (!row || typeof row !== "object" || row.noTotal || row.isTextRow) return 0;
  const total = validDynamicTimeConfig.value
    .filter((timeConfig) => !timeConfig.isTextRow) // 🌟 过滤文本列，不参与合计
    .reduce((sum, timeConfig) => {
      const timeProp = timeConfig.prop;
      return sum + (Number(row[timeProp]) || 0);
    }, 0);
  return Number(total.toFixed(2));
};

// 核心工具方法：深拷贝+数据处理
const handleTableData = (sourceIndicatorList, sourceTableData) => {
  if (!validConfig.value) return [];
  const newData = [];
  sourceIndicatorList.forEach((item, index) => {
    const { name, isTextRow = false, noTotal = false } = item;
    const level = item?.level || 0;
    const serialNumber = item?.serialNumber || index + 1;
    const originRow =
      sourceTableData.find((row) => row.indicatorName === name) || {};
    const rowData = JSON.parse(
      JSON.stringify({
        serialNumber,
        level,
        indicatorName: name,
        isTextRow,
        noTotal,
        total: 0,
        ...originRow,
      }),
    );
    initRowTimeField(rowData);
    rowData.total = calculateRowTotal(rowData);
    newData.push(rowData);
  });
  return newData;
};

// 数据变化后统一发射
const emitDataChange = (newInnerData) => {
  if (props.isPreview) return;
  const emitData = JSON.parse(JSON.stringify(newInnerData));
  const newModelValue = {
    ...props.modelValue,
    tableData: emitData,
  };
  emit("update:modelValue", newModelValue);
  emit("handleTableChange", newModelValue);
};

// 监听Props变化
watch(
  () => props.modelValue,
  async (newVal) => {
    if (!validConfig.value) return;
    await nextTick();
    const newTableData = handleTableData(
      newVal.indicatorList,
      newVal.tableData,
    );
    tableDataRef.value = newTableData;
  },
  { deep: true, immediate: true },
);

// 数字行输入回调
const handleFinancialChange = (currentRow) => {
  if (props.isPreview || !currentRow || currentRow.noTotal) return;
  currentRow.total = calculateRowTotal(currentRow);
  emitDataChange(tableDataRef.value);
};

// 文本行输入回调
const handleTextInput = (currentRow) => {
  if (props.isPreview || !currentRow) return;
  emitDataChange(tableDataRef.value);
};

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

<style scoped lang="scss">
.mixed-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;
}

:deep(.el-input-number) {
  width: 100%;
}
:deep(.el-input-number__input) {
  text-align: right;
  padding-right: 25px;
  width: 100% !important;
}

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

:deep(.el-table__header-cell) {
  text-align: right !important;
  &.el-table__header-cell--align-center {
    text-align: center !important;
  }
}

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

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