<!-- 关系管理标签页：列表查询、新建、删除关系 -->
<template>
  <a-space style="margin-bottom: 12px">
    <a-select
      v-model:value="relFilter.type"
      placeholder="关系类型"
      allowClear
      style="width: 180px"
      @change="loadRelationships"
    >
      <a-select-option v-for="t in relTypeNames" :key="t" :value="t">{{ t }}</a-select-option>
    </a-select>
    <a-button type="primary" @click="showCreateRel = true">新建关系</a-button>
  </a-space>

  <a-table
    :dataSource="relationships.items"
    :columns="relCols"
    :loading="relsLoading"
    :pagination="{
      current: relationships.page,
      pageSize: relationships.page_size,
      total: relationships.total,
    }"
    size="small"
    row-key="id"
    @change="onRelTableChange"
  >
    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'type'">
        <a-tag color="blue">{{ record.type }}</a-tag>
      </template>
      <template v-else-if="column.key === 'actions'">
        <a-popconfirm title="确认删除此关系？" @confirm="handleDeleteRel(record.id)">
          <a-button size="small" danger>删除</a-button>
        </a-popconfirm>
      </template>
    </template>
  </a-table>

  <!-- 新建关系弹窗 -->
  <a-modal v-model:open="showCreateRel" title="新建关系" @ok="handleCreateRel">
    <a-form layout="vertical">
      <a-form-item label="来源实体 ID">
        <a-input v-model:value="newRel.source_id" />
      </a-form-item>
      <a-form-item label="目标实体 ID">
        <a-input v-model:value="newRel.target_id" />
      </a-form-item>
      <a-form-item label="关系类型">
        <a-select v-model:value="newRel.type">
          <a-select-option v-for="t in relTypeNames" :key="t" :value="t">{{ t }}</a-select-option>
        </a-select>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import {
  listRelationships,
  createRelationship,
  deleteRelationship,
} from '@/api/admin-graph'
import type { RelationshipListResponse } from '@/types/admin-graph'

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

// ── 状态 ──
const relsLoading = ref(false)
const relationships = ref<RelationshipListResponse>({ items: [], total: 0, page: 1, page_size: 20 })
const relFilter = reactive({ type: undefined as string | undefined })
const showCreateRel = ref(false)
const newRel = reactive({ source_id: '', target_id: '', type: '' })

// ── 表格列 ──
const relCols = [
  { title: '来源', dataIndex: 'source_name', key: 'source_name' },
  { title: '关系', key: 'type', width: 140 },
  { title: '目标', dataIndex: 'target_name', key: 'target_name' },
  { title: '操作', key: 'actions', width: 80 },
]

// ── 数据加载 ──
async function loadRelationships() {
  relsLoading.value = true
  try {
    relationships.value = await listRelationships({
      type: relFilter.type,
      page: relationships.value.page,
      page_size: relationships.value.page_size,
    })
  } catch {
    message.error('加载关系失败')
  } finally {
    relsLoading.value = false
  }
}

// ── 分页变更 ──
function onRelTableChange(pagination: { current: number; pageSize: number }) {
  relationships.value.page = pagination.current
  relationships.value.page_size = pagination.pageSize
  loadRelationships()
}

// ── 新建关系 ──
async function handleCreateRel() {
  try {
    await createRelationship({
      source_id: newRel.source_id,
      target_id: newRel.target_id,
      type: newRel.type,
    })
    message.success('创建成功')
    showCreateRel.value = false
    Object.assign(newRel, { source_id: '', target_id: '', type: '' })
    loadRelationships()
  } catch (e: unknown) {
    const err = e as { response?: { data?: { detail?: string } } }
    message.error(err.response?.data?.detail || '创建失败')
  }
}

// ── 删除关系 ──
async function handleDeleteRel(id: string) {
  try {
    await deleteRelationship(id)
    message.success('删除成功')
    loadRelationships()
  } catch {
    message.error('删除失败')
  }
}

defineExpose({ loadRelationships })

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