<!-- 实体管理标签页：列表查询、新建、编辑、删除实体及查看实体详情 -->
<template>
  <a-space style="margin-bottom: 12px">
    <a-select
      v-model:value="entityFilter.label"
      placeholder="实体类型"
      allowClear
      style="width: 150px"
      @change="loadEntities"
    >
      <a-select-option v-for="t in entityTypeNames" :key="t" :value="t">{{ t }}</a-select-option>
    </a-select>
    <a-input-search
      v-model:value="entityFilter.name"
      placeholder="搜索名称"
      style="width: 200px"
      @search="loadEntities"
    />
    <a-button type="primary" @click="showCreateEntity = true">新建实体</a-button>
  </a-space>

  <a-table
    :dataSource="entities.items"
    :columns="entityCols"
    :loading="entitiesLoading"
    :pagination="{
      current: entities.page,
      pageSize: entities.page_size,
      total: entities.total,
      showSizeChanger: true,
    }"
    row-key="id"
    size="small"
    @change="onEntityTableChange"
  >
    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'labels'">
        <a-tag v-for="l in record.labels" :key="l" :color="getNodeColor(l)">{{ l }}</a-tag>
      </template>
      <template v-else-if="column.key === 'actions'">
        <a-space>
          <a-button size="small" @click="openEntityDetail(record)">详情</a-button>
          <a-button size="small" @click="openEditEntity(record)">编辑</a-button>
          <a-popconfirm title="确认删除此实体？" @confirm="handleDeleteEntity(record.id)">
            <a-button size="small" danger>删除</a-button>
          </a-popconfirm>
        </a-space>
      </template>
    </template>
  </a-table>

  <!-- 新建实体弹窗 -->
  <a-modal v-model:open="showCreateEntity" title="新建实体" @ok="handleCreateEntity">
    <a-form layout="vertical">
      <a-form-item label="实体类型">
        <a-select v-model:value="newEntity.label" placeholder="选择类型">
          <a-select-option v-for="t in entityTypeNames" :key="t" :value="t">{{ t }}</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="名称">
        <a-input v-model:value="newEntity.name" placeholder="实体名称" />
      </a-form-item>
    </a-form>
  </a-modal>

  <!-- 编辑实体弹窗 -->
  <a-modal v-model:open="showEditEntity" title="编辑实体" @ok="handleUpdateEntity">
    <a-form layout="vertical">
      <a-form-item label="名称">
        <a-input v-model:value="editEntity.name" />
      </a-form-item>
      <a-form-item label="别名（逗号分隔）">
        <a-input v-model:value="editEntity.aliases" />
      </a-form-item>
    </a-form>
  </a-modal>

  <!-- 实体详情抽屉 -->
  <a-drawer
    v-model:open="showEntityDetail"
    title="实体详情"
    width="500"
  >
    <template v-if="entityDetail">
      <a-descriptions :column="1" bordered size="small">
        <a-descriptions-item label="ID">{{ entityDetail.id }}</a-descriptions-item>
        <a-descriptions-item label="类型">
          <a-tag v-for="l in entityDetail.labels" :key="l" :color="getNodeColor(l)">{{ l }}</a-tag>
        </a-descriptions-item>
        <a-descriptions-item
          v-for="(val, key) in entityDetail.properties"
          :key="key"
          :label="String(key)"
        >
          {{ Array.isArray(val) ? val.join(', ') : val }}
        </a-descriptions-item>
      </a-descriptions>

      <a-divider>关联文档</a-divider>
      <a-list
        size="small"
        :dataSource="entityDetail.related_docs"
        :locale="{ emptyText: '无关联文档' }"
      >
        <template #renderItem="{ item }">
          <a-list-item>
            <a-list-item-meta
              :title="item.title || item.doc_id"
              :description="`${item.rel_type} · ${item.doc_number || ''}`"
            />
          </a-list-item>
        </template>
      </a-list>

      <a-divider>邻域实体</a-divider>
      <a-list
        size="small"
        :dataSource="entityDetail.neighbors"
        :locale="{ emptyText: '无邻域实体' }"
      >
        <template #renderItem="{ item }">
          <a-list-item>
            <a-tag :color="getNodeColor(item.labels[0])">{{ item.labels[0] }}</a-tag>
            {{ item.name }}
            <template #extra>
              <a-tag>{{ item.direction === 'out' ? '\u2192' : '\u2190' }} {{ item.rel_type }}</a-tag>
            </template>
          </a-list-item>
        </template>
      </a-list>
    </template>
  </a-drawer>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import {
  listEntities,
  getEntityDetail as fetchEntityDetail,
  createEntity,
  updateEntity,
  deleteEntity,
} from '@/api/admin-graph'
import type { EntityListResponse, EntityDetailResponse, EntityListItem } from '@/types/admin-graph'
import { getNodeColor } from '@/utils/graphLabels'

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

// ── 状态 ──
const entitiesLoading = ref(false)
const entities = ref<EntityListResponse>({ items: [], total: 0, page: 1, page_size: 20 })
const entityFilter = reactive({ label: undefined as string | undefined, name: '' })
const showCreateEntity = ref(false)
const newEntity = reactive({ label: '', name: '' })
const showEditEntity = ref(false)
const editEntity = reactive({ id: '', name: '', aliases: '' })
const showEntityDetail = ref(false)
const entityDetail = ref<EntityDetailResponse | null>(null)

// ── 表格列 ──
const entityCols = [
  { title: '名称', dataIndex: 'name', key: 'name' },
  { title: '类型', key: 'labels', width: 120 },
  { title: '关联数', dataIndex: 'connection_count', key: 'connection_count', width: 80 },
  { title: '操作', key: 'actions', width: 220 },
]

// ── 数据加载 ──
async function loadEntities() {
  entitiesLoading.value = true
  try {
    entities.value = await listEntities({
      label: entityFilter.label,
      name: entityFilter.name || undefined,
      page: entities.value.page,
      page_size: entities.value.page_size,
    })
  } catch {
    message.error('加载实体失败')
  } finally {
    entitiesLoading.value = false
  }
}

// ── 分页变更 ──
function onEntityTableChange(pagination: { current: number; pageSize: number }) {
  entities.value.page = pagination.current
  entities.value.page_size = pagination.pageSize
  loadEntities()
}

// ── 查看详情 ──
async function openEntityDetail(record: EntityListItem) {
  showEntityDetail.value = true
  try {
    entityDetail.value = await fetchEntityDetail(record.id)
  } catch {
    message.error('加载详情失败')
  }
}

// ── 编辑实体 ──
function openEditEntity(record: EntityListItem) {
  editEntity.id = record.id
  editEntity.name = record.properties?.name || record.name
  editEntity.aliases = (record.properties?.aliases || []).join(', ')
  showEditEntity.value = true
}

// ── 新建实体 ──
async function handleCreateEntity() {
  try {
    await createEntity({
      label: newEntity.label,
      properties: { name: newEntity.name },
    })
    message.success('创建成功')
    showCreateEntity.value = false
    newEntity.label = ''
    newEntity.name = ''
    loadEntities()
  } catch (e: unknown) {
    const err = e as { response?: { data?: { detail?: string } } }
    message.error(err.response?.data?.detail || '创建失败')
  }
}

// ── 更新实体 ──
async function handleUpdateEntity() {
  try {
    const aliases = editEntity.aliases
      ? editEntity.aliases.split(',').map((s: string) => s.trim()).filter(Boolean)
      : []
    await updateEntity(editEntity.id, {
      properties: { name: editEntity.name, aliases },
    })
    message.success('更新成功')
    showEditEntity.value = false
    loadEntities()
  } catch (e: unknown) {
    const err = e as { response?: { data?: { detail?: string } } }
    message.error(err.response?.data?.detail || '更新失败')
  }
}

// ── 删除实体 ──
async function handleDeleteEntity(id: string) {
  try {
    await deleteEntity(id)
    message.success('删除成功')
    loadEntities()
  } catch {
    message.error('删除失败')
  }
}

defineExpose({ loadEntities })

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