<!-- EnhancedTable.vue -->
<template>
  <div class="enhanced-table-container">
    <!-- 列控制按钮 -->
    <div class="column-control">
      <el-tooltip content="列配置" placement="left">
        <el-button circle size="small" class="control-btn" @click="showConfigDialog = true">
          <el-icon>
            <Operation />
          </el-icon>
        </el-button>
      </el-tooltip>
    </div>

    <!-- 列配置弹窗 -->
    <el-dialog v-model="showConfigDialog" title="列显示配置" width="500px">
      <el-checkbox-group v-model="visibleKeys">
        <el-row :gutter="20">
          <el-col v-for="col in configurableColumns" :key="col.uniqueKey" :span="8">
            <el-checkbox :value="col.uniqueKey" :disabled="col.fixed">
              {{ col.displayLabel }}
            </el-checkbox>
          </el-col>
        </el-row>
      </el-checkbox-group>
    </el-dialog>

    <!-- 动态渲染表格 -->
    <el-table ref="tableRef" v-bind="$attrs" :data="tableData" v-loading="loading" @current-change="handleCurrentChange" highlight-current-row>
      <template v-for="col in visibleColumns" :key="col.uniqueKey">
        <component :is="col.component" v-bind="col.props">
          <template v-for="(slot, name) in col.slots" #[name]="scope">
            <slot :name="name" v-bind="scope" />
          </template>
        </component>
      </template>
    </el-table>
  </div>
</template>

<script setup>
import { ref, computed, watch, useSlots, onMounted } from 'vue';

// 生成稳定唯一键（核心修复）
const generateStableKey = (node) => {
  // 特殊列处理（如展开列）
  if (node.props?.type) {
    return `special_${node.props.type}`;
  }

  // 有prop的列：prop+label双校验
  if (node.props?.prop) {
    return `prop_${node.props.prop}_${node.props.label || 'nolabel'}`;
  }

  // 无prop但有label的列：label+组件名哈希
  if (node.props?.label) {
    return `label_${node.props.label.replace(/\W/g, '_')}_${hashCode(node.type?.name)}`;
  }

  // 最终回退方案（使用slot哈希）
  return `slot_${hashCode(JSON.stringify(node.children))}`;
};

// 哈希函数（生成8位标识）
const hashCode = (str) => {
  let hash = 0;
  for (let i = 0; i < (str || '').length; i++) {
    hash = (hash << 5) - hash + str.charCodeAt(i);
    hash |= 0;
  }
  return Math.abs(hash).toString(16).padStart(8, '0');
};

// 解析列配置（带缓存）
const parsedColumns = ref([]);
const parseColumns = () => {
  const slots = useSlots().default?.();
  parsedColumns.value = (slots || [])
    .filter((node) => !node.type?.toString().includes('Comment'))
    .map((node) => ({
      uniqueKey: generateStableKey(node),
      label: node.props?.label,
      component: node.type,
      props: node.props,
      slots: node.children,
      fixed: !!node.props?.type
    }));
};

// 初始化列配置
onMounted(parseColumns);
watch(useSlots(), parseColumns, { deep: true });
</script>

<style scoped>
/* 保持原有样式不变 */
</style>
