<!-- 去重合并标签页：检测重复实体并支持合并操作 -->
<template>
  <a-space style="margin-bottom: 12px">
    <a-select
      v-model:value="dedupFilter.label"
      placeholder="实体类型"
      allowClear
      style="width: 150px"
    >
      <a-select-option v-for="t in entityTypeNames" :key="t" :value="t">{{ t }}</a-select-option>
    </a-select>
    <span>阈值:</span>
    <a-slider
      v-model:value="dedupFilter.threshold"
      :min="0.5"
      :max="1"
      :step="0.05"
      style="width: 200px"
    />
    <span>{{ dedupFilter.threshold }}</span>
    <a-button type="primary" :loading="dedupLoading" @click="loadDuplicates">检测</a-button>
  </a-space>

  <a-list
    :dataSource="duplicates"
    :loading="dedupLoading"
    :locale="{ emptyText: '点击检测按钮开始去重分析' }"
  >
    <template #renderItem="{ item }">
      <a-list-item>
        <a-list-item-meta>
          <template #title>
            <a-tag :color="getNodeColor(item.label)">{{ item.label }}</a-tag>
            <strong>{{ item.entity_a_name }}</strong>
            <a-tag color="orange" style="margin: 0 8px">
              {{ (item.similarity * 100).toFixed(0) }}%
              · {{ item.match_type === 'alias_match' ? '别名匹配' : '编辑距离' }}
            </a-tag>
            <strong>{{ item.entity_b_name }}</strong>
          </template>
        </a-list-item-meta>
        <template #actions>
          <a-button
            size="small"
            type="primary"
            @click="handleMerge(item.entity_a_id, item.entity_b_id)"
          >
            合并到 A
          </a-button>
          <a-button
            size="small"
            @click="handleMerge(item.entity_b_id, item.entity_a_id)"
          >
            合并到 B
          </a-button>
        </template>
      </a-list-item>
    </template>
  </a-list>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { message } from 'ant-design-vue'
import { detectDuplicates, mergeEntities } from '@/api/admin-graph'
import type { DuplicateCandidate } from '@/types/admin-graph'
import { getNodeColor } from '@/utils/graphLabels'

// ── Props ──
const props = defineProps<{
  /** 可选实体类型名称列表 */
  entityTypeNames: string[]
}>()

// ── 事件：合并后通知父组件刷新实体列表 ──
const emit = defineEmits<{
  (e: 'merged'): void
}>()

// ── 状态 ──
const dedupLoading = ref(false)
const dedupFilter = reactive({ label: undefined as string | undefined, threshold: 0.85 })
const duplicates = ref<DuplicateCandidate[]>([])

// ── 数据加载 ──
async function loadDuplicates() {
  dedupLoading.value = true
  try {
    const resp = await detectDuplicates({
      label: dedupFilter.label,
      threshold: dedupFilter.threshold,
    })
    duplicates.value = resp.candidates
  } catch {
    message.error('检测失败')
  } finally {
    dedupLoading.value = false
  }
}

// ── 合并操作 ──
async function handleMerge(primaryId: string, secondaryId: string) {
  try {
    const result = await mergeEntities({
      primary_id: primaryId,
      secondary_id: secondaryId,
      add_alias: true,
    })
    message.success(`合并成功，迁移了 ${result.migrated_relationships} 条关系`)
    loadDuplicates()
    emit('merged')
  } catch (e: unknown) {
    const err = e as { response?: { data?: { detail?: string } } }
    message.error(err.response?.data?.detail || '合并失败')
  }
}
</script>
