<!-- 重建与占位符管理标签页：图谱重建任务、占位符文档关联和删除 -->
<template>
  <a-card title="图谱重建" size="small">
    <a-space>
      <a-button type="primary" @click="showRebuildModal = true">重建选定文档</a-button>
      <a-popconfirm title="确认全量重建？这将重建库中所有文档的图谱。" @confirm="handleRebuildAll">
        <a-button danger>重建全部图谱</a-button>
      </a-popconfirm>
    </a-space>

    <template v-if="rebuildTask.task_id">
      <a-card size="small" style="margin-top: 12px">
        <a-descriptions :column="2" size="small">
          <a-descriptions-item label="任务ID">{{ rebuildTask.task_id }}</a-descriptions-item>
          <a-descriptions-item label="状态">
            <a-tag :color="rebuildTask.status === 'COMPLETED' ? 'green' : rebuildTask.status === 'FAILED' ? 'red' : 'blue'">
              {{ rebuildTask.status }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="进度">
            {{ rebuildTask.current }} / {{ rebuildTask.total }}
          </a-descriptions-item>
          <a-descriptions-item label="当前文档">{{ rebuildTask.current_doc_id }}</a-descriptions-item>
        </a-descriptions>
        <a-progress
          :percent="Math.round(rebuildTask.progress * 100)"
          :status="rebuildTask.status === 'FAILED' ? 'exception' : rebuildTask.status === 'COMPLETED' ? 'success' : 'active'"
        />
        <div v-if="rebuildTask.error" style="color: red; margin-top: 8px">{{ rebuildTask.error }}</div>
      </a-card>
    </template>
  </a-card>

  <!-- 重建弹窗 -->
  <a-modal v-model:open="showRebuildModal" title="选择文档重建" @ok="handleRebuild">
    <a-form layout="vertical">
      <a-form-item label="文档 ID（每行一个）">
        <a-textarea v-model:value="rebuildDocIds" :rows="6" placeholder="doc_id_1&#10;doc_id_2" />
      </a-form-item>
    </a-form>
  </a-modal>

  <a-card title="占位符文档" size="small" style="margin-top: 16px">
    <a-table
      :dataSource="placeholders"
      :columns="placeholderCols"
      :loading="placeholdersLoading"
      :pagination="false"
      size="small"
      row-key="id"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'referencers'">
          <a-tag v-for="r in record.referencers" :key="r.doc_id">{{ r.title || r.doc_id }}</a-tag>
        </template>
        <template v-else-if="column.key === 'actions'">
          <a-space>
            <a-button size="small" @click="openLinkPlaceholder(record)">关联文档</a-button>
            <a-popconfirm title="确认删除此占位符？" @confirm="handleDeletePlaceholder(record.id)">
              <a-button size="small" danger>删除</a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </template>
    </a-table>
  </a-card>

  <!-- 关联占位符弹窗 -->
  <a-modal v-model:open="showLinkPlaceholder" title="关联真实文档" @ok="handleLinkPlaceholder">
    <a-form layout="vertical">
      <a-form-item label="真实文档 ID">
        <a-input v-model:value="linkRealDocId" placeholder="输入文档 ID" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import {
  rebuildDocGraphs,
  rebuildAllGraphs,
  listPlaceholders,
  linkPlaceholder,
  deletePlaceholder,
} from '@/api/admin-graph'
import type { PlaceholderItem } from '@/types/admin-graph'
import { useRebuildPolling } from '@/composables/useRebuildPolling'

// ── 事件：重建完成后通知父组件刷新统计 ──
const emit = defineEmits<{
  (e: 'rebuild-completed'): void
}>()

// ── 重建轮询 ──
const { rebuildTask, startPolling } = useRebuildPolling(() => {
  emit('rebuild-completed')
})

// ── 重建状态 ──
const showRebuildModal = ref(false)
const rebuildDocIds = ref('')

// ── 占位符状态 ──
const placeholdersLoading = ref(false)
const placeholders = ref<PlaceholderItem[]>([])
const showLinkPlaceholder = ref(false)
const linkPlaceholderId = ref('')
const linkRealDocId = ref('')

// ── 表格列 ──
const placeholderCols = [
  { title: '文号', dataIndex: 'doc_number', key: 'doc_number' },
  { title: '引用方', key: 'referencers' },
  { title: '操作', key: 'actions', width: 180 },
]

// ── 数据加载 ──
async function loadPlaceholders() {
  placeholdersLoading.value = true
  try {
    const resp = await listPlaceholders()
    placeholders.value = resp.items
  } catch {
    message.error('加载占位符失败')
  } finally {
    placeholdersLoading.value = false
  }
}

// ── 重建操作 ──
async function handleRebuild() {
  const ids = rebuildDocIds.value
    .split('\n')
    .map((s) => s.trim())
    .filter(Boolean)
  if (!ids.length) {
    message.warning('请输入至少一个文档 ID')
    return
  }
  try {
    const resp = await rebuildDocGraphs(ids)
    rebuildTask.value = {
      task_id: resp.task_id,
      status: 'PENDING',
      progress: 0,
      current: 0,
      total: resp.doc_count,
      current_doc_id: '',
    }
    showRebuildModal.value = false
    startPolling()
    message.success(`已提交重建任务，共 ${resp.doc_count} 个文档`)
  } catch {
    message.error('提交失败')
  }
}

async function handleRebuildAll() {
  try {
    const resp = await rebuildAllGraphs()
    rebuildTask.value = {
      task_id: resp.task_id,
      status: 'PENDING',
      progress: 0,
      current: 0,
      total: resp.total_docs,
      current_doc_id: '',
    }
    startPolling()
    message.success(`已提交全量重建任务，共 ${resp.total_docs} 个文档`)
  } catch {
    message.error('提交失败')
  }
}

// ── 占位符操作 ──
function openLinkPlaceholder(record: PlaceholderItem) {
  linkPlaceholderId.value = record.id
  linkRealDocId.value = ''
  showLinkPlaceholder.value = true
}

async function handleLinkPlaceholder() {
  try {
    const result = await linkPlaceholder(linkPlaceholderId.value, linkRealDocId.value)
    message.success(`关联成功，迁移了 ${result.migrated_relationships} 条引用关系`)
    showLinkPlaceholder.value = false
    loadPlaceholders()
  } catch (e: unknown) {
    const err = e as { response?: { data?: { detail?: string } } }
    message.error(err.response?.data?.detail || '关联失败')
  }
}

async function handleDeletePlaceholder(id: string) {
  try {
    await deletePlaceholder(id)
    message.success('删除成功')
    loadPlaceholders()
  } catch {
    message.error('删除失败')
  }
}

onMounted(() => {
  loadPlaceholders()
})
</script>
