<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';

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

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

// 优化后的构建树函数
const buildTreeMap = (list: any[]) => {
  const map = new Map<number, any[]>();

  // 构建 parentId -> children 的 Map
  list.forEach(item => {
    const pid = item.parentid;
    if (!map.has(pid)) map.set(pid, []);
    map.get(pid)!.push({ ...item });
  });

  // 递归构建树
  const createTree = (pId: number): any[] => {
    const children = map.get(pId) || [];
    children.forEach(child => {
      const sub = createTree(child.id);
      if (sub.length > 0) child.children = sub;
    });
    return children;
  };

  // 自动探测根节点
  const rootParentId = Math.min(...list.map(r => r.parentid));
  return createTree(rootParentId);
};

const initRegionTree = async () => {
  try {
    const res = await fetch("/region.csv");
    if (!res.ok) throw new Error("无法读取数据，请检查文件");

    const text = await res.text();
    const lines = text.split("\n").map(l => l.trim()).filter(l => l);
    if (lines.length < 2) throw new Error("内容为空或格式错误");

    const headers = lines[0].split(",").map(h => h.trim().toLowerCase());

    rawList.value = lines.slice(1).map(line => {
      const cols = line.split(",").map(c => c.trim());
      const obj: any = {};
      headers.forEach((h, i) => {
        obj[h] = h === 'name' ? cols[i] : Number(cols[i]);
      });
      return obj;
    });

    // 构建树
    const tree = buildTreeMap(rawList.value);
    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>
