<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-for="group in timeColumnGroups" :key="`time-group-${group.key}`">
        <!-- 有一级分组标题 -->
        <el-table-column
          v-if="!group.isSingle && group.label"
          :label="group.label"
          align="right"
        >
          <!-- 遍历一级分组的子项 -->
          <template v-for="child in group.children" :key="`child-${child.key || child.prop}`">
            <!-- 如果是二级分组 -->
            <el-table-column
              v-if="child.isSubGroup"
              :label="child.label"
              align="center"
            >
              <el-table-column
                v-for="timeItem in child.children"
                :key="`time-col-${timeItem.prop}`"
                :label="timeItem.label"
                min-width="140"
                align="center"
              >
                <template #default="{ row }">
                  <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>
            <!-- 如果是直接列（没有二级分组） -->
            <el-table-column
              v-else
              :key="`time-col-${child.prop}`"
              :label="child.label"
              min-width="140"
              align="center"
            >
              <template #default="{ row }">
                <el-input
                  v-if="child.isTextRow || row.isTextRow"
                  v-model="row[child.prop]"
                  type="textarea"
                  :rows="2"
                  :disabled="isPreview"
                  placeholder="请输入说明"
                  style="width: 100%"
                  @input="() => handleTextInput(row)"
                />
                <el-input
                  v-else
                  v-model="row[child.prop]"
                  :precision="2"
                  controls-position="right"
                  :disabled="isPreview"
                  placeholder="请输入金额"
                  style="width: 100%"
                  @change="() => handleFinancialChange(row)"
                />
              </template>
            </el-table-column>
          </template>
        </el-table-column>
        <!-- 单列（没有分组标题，label 为空） -->
        <el-table-column
          v-else
          v-for="timeItem in group.children"
          :key="`time-col-${timeItem.prop}`"
          :label="timeItem.label"
          min-width="140"
          align="center"
        >
          <template #default="{ row }">
            <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>
      </template>
    </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: "",
          subGroup: "", // 支持三级分组
          isTextRow: false, // 字符串格式默认数字列
        };
      }
      return {
        label: item.label?.trim() || "",
        prop: item.prop?.trim() || item.label?.trim() || "",
        headerGroup: item.headerGroup?.trim() || "",
        subGroup: item.subGroup?.trim() || "", // 支持三级分组
        isTextRow: item.isTextRow === true, // 显式转换为布尔值，默认false
      };
    })
    .filter((item) => !!item.prop);
});

// 时间列分组计算（支持三级分组：headerGroup -> subGroup -> 列）
const timeColumnGroups = computed(() => {
  const timeConfig = validDynamicTimeConfig.value;
  if (!timeConfig.length) return [];

  const groupMap = {}; // 一级分组：headerGroup
  const singleColumns = []; // 没有分组的单列

  timeConfig.forEach((item) => {
    const headerGroup = item.headerGroup?.trim();
    const subGroup = item.subGroup?.trim();

    // 如果有有效的 headerGroup，则创建分组
    if (headerGroup && headerGroup.length > 0) {
      if (!groupMap[headerGroup]) {
        groupMap[headerGroup] = {
          label: headerGroup,
          key: headerGroup,
          children: [],
        };
      }

      // 如果有 subGroup，在一级分组下创建二级分组
      if (subGroup && subGroup.length > 0) {
        let subGroupItem = groupMap[headerGroup].children.find(
          (child) => child.label === subGroup
        );
        if (!subGroupItem) {
          subGroupItem = {
            label: subGroup,
            key: `${headerGroup}_${subGroup}`,
            isSubGroup: true, // 标记为二级分组
            children: [],
          };
          groupMap[headerGroup].children.push(subGroupItem);
        }
        subGroupItem.children.push(item);
      } else {
        // 没有 subGroup，直接挂在一级分组下
        groupMap[headerGroup].children.push(item);
      }
    } else {
      // 没有 headerGroup 的作为单列处理（不显示一级标题）
      singleColumns.push({
        label: "", // 空标题，不显示一级分组
        key: `single_${item.prop}`,
        isSingle: true, // 标记为单列
        children: [item],
      });
    }
  });

  // 合并分组和单列，保持原始顺序
  const result = [];
  const addedKeys = new Set();

  timeConfig.forEach((item) => {
    const headerGroup = item.headerGroup?.trim();

    // 有分组的
    if (headerGroup && headerGroup.length > 0) {
      if (!addedKeys.has(headerGroup)) {
        result.push(groupMap[headerGroup]);
        addedKeys.add(headerGroup);
      }
    } else {
      // 单列
      const singleKey = `single_${item.prop}`;
      if (!addedKeys.has(singleKey)) {
        const singleColumn = singleColumns.find((sc) => sc.key === singleKey);
        if (singleColumn) {
          result.push(singleColumn);
          addedKeys.add(singleKey);
        }
      }
    }
  });

  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;
  margin-bottom: 0;
}

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