<!-- 图谱管理页面：以标签页形式组织统计概览、实体管理、类型定义、去重合并、关系管理和重建功能 -->
<template>
  <div style="padding: 24px">
    <a-tabs v-model:activeKey="activeTab">
      <a-tab-pane key="stats" tab="统计概览">
        <GraphStatsTab ref="statsRef" />
      </a-tab-pane>

      <a-tab-pane key="entities" tab="实体管理">
        <EntityManageTab ref="entityRef" :entity-type-names="entityTypeNames" />
      </a-tab-pane>

      <a-tab-pane key="types" tab="类型定义">
        <TypeManageTab ref="typeRef" @types-changed="onTypesChanged" />
      </a-tab-pane>

      <a-tab-pane key="dedup" tab="去重合并">
        <DedupTab :entity-type-names="entityTypeNames" @merged="onMerged" />
      </a-tab-pane>

      <a-tab-pane key="relationships" tab="关系管理">
        <RelationshipTab ref="relRef" :rel-type-names="relTypeNames" />
      </a-tab-pane>

      <a-tab-pane key="rebuild" tab="重建 & 占位符">
        <GraphRebuildTab @rebuild-completed="onRebuildCompleted" />
      </a-tab-pane>
    </a-tabs>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { listEntityTypes, listRelTypes } from '@/api/admin-graph'
import GraphStatsTab from './graph/GraphStatsTab.vue'
import EntityManageTab from './graph/EntityManageTab.vue'
import TypeManageTab from './graph/TypeManageTab.vue'
import DedupTab from './graph/DedupTab.vue'
import RelationshipTab from './graph/RelationshipTab.vue'
import GraphRebuildTab from './graph/GraphRebuildTab.vue'

// ── 当前标签页 ──
const activeTab = ref('stats')

// ── 子组件 ref ──
const statsRef = ref<InstanceType<typeof GraphStatsTab>>()
const entityRef = ref<InstanceType<typeof EntityManageTab>>()
const typeRef = ref<InstanceType<typeof TypeManageTab>>()
const relRef = ref<InstanceType<typeof RelationshipTab>>()

// ── 类型名称列表，由 TypeManageTab 通过事件同步 ──
const entityTypeNames = ref<string[]>([])
const relTypeNames = ref<string[]>([])

/** 类型变更回调：同步类型名称列表，并刷新实体和关系列表 */
function onTypesChanged(nextEntityTypes: string[], nextRelTypes: string[]) {
  entityTypeNames.value = nextEntityTypes
  relTypeNames.value = nextRelTypes
  entityRef.value?.loadEntities()
  relRef.value?.loadRelationships()
}

/** 合并完成后刷新实体列表 */
function onMerged() {
  entityRef.value?.loadEntities()
}

/** 重建完成后刷新统计 */
function onRebuildCompleted() {
  statsRef.value?.loadStats()
}

// ── 页面挂载时立即加载类型列表，避免惰性渲染 Tab 导致下拉为空 ──
onMounted(async () => {
  try {
    const [et, rt] = await Promise.all([listEntityTypes(), listRelTypes()])
    entityTypeNames.value = et.items.map((t) => t.name)
    relTypeNames.value = rt.items.map((t) => t.name)
  } catch {
    // TypeManageTab 渲染时会重试，此处静默
  }
})
</script>
