<template>
  <div class="region-viewer" style="padding: 20px;">
    <el-card shadow="never">
      <template #header>
        <div style="display: flex; justify-content: space-between; align-items: center;">
          <span style="font-weight: bold;">地区数据</span>
          <el-tag type="info">总数据量: {{ rawListCount }} 条</el-tag>
        </div>
      </template>

      <!-- 树形表格 -->
      <el-table
        v-if="treeData.length > 0"
        :data="treeData"
        style="width: 100%; max-height: 600px; overflow: auto;"
        row-key="id"
        border
        :tree-props="{ children: 'children' }"
      >
        <el-table-column prop="id" label="编号 (邮编)" width="220" />
        <el-table-column prop="name" label="地名" />
      </el-table>

      <el-empty v-else :description="loadingStatus" />
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, computed } from 'vue';
import { useRegionCache } from '@/composables/useRegionCache';

const rawList = ref<any[]>([]);
const treeData = ref<any[]>([]);
const loadingStatus = ref('正在解析数据...');

const rawListCount = computed(() => rawList.value.length);

// 从 parentMap 递归构建树
const buildTreeFromCache = (parentMap: Map<number, any[]>, pId: number): any[] => {
  const children = parentMap.get(pId) || [];
  return children.map((child) => {
    const node = { ...child };
    const sub = buildTreeFromCache(parentMap, child.id);
    if (sub.length > 0) node.children = sub;
    return node;
  });
};

const initRegionTree = async () => {
  try {
    const cache = await useRegionCache();
    rawList.value = cache.list;

    // 自动探测根节点（最小 parentId）
    const rootParentId = Math.min(...cache.list.map((r) => r.parentId));
    const tree = buildTreeFromCache(cache.parentMap, rootParentId);

    if (tree.length === 0) {
      loadingStatus.value = '构建失败：根节点下无数据';
    } else {
      treeData.value = tree;
      loadingStatus.value = '加载完成';
    }
  } catch (error: any) {
    loadingStatus.value = `错误: ${error.message}`;
    console.error(error);
  }
};

onMounted(initRegionTree);
</script>

<style scoped>
.region-viewer .el-table {
  /* 虚拟滚动样式 */
  max-height: 600px;
  overflow-y: auto;
}
</style>
