<!-- 类型定义管理标签页：只读展示 schema 定义的实体类型和关系类型 -->
<!-- 类型定义由 graph_schema.yaml 统一管控，不允许通过管理界面新建/重命名/删除 -->
<template>
  <a-alert
    type="info"
    show-icon
    style="margin-bottom: 16px"
    message="类型定义由 graph_schema.yaml 统一管控，仅支持编辑显示名称、图标和颜色。"
  />

  <a-row :gutter="16">
    <a-col :span="12">
      <a-card title="实体类型" size="small">
        <a-table
          :dataSource="entityTypes"
          :columns="entityTypeCols"
          :loading="typesLoading"
          :pagination="false"
          size="small"
          row-key="name"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'color'">
              <span
                :style="{
                  display: 'inline-block',
                  width: '16px',
                  height: '16px',
                  borderRadius: '4px',
                  backgroundColor: record.color || '#ccc',
                }"
              />
            </template>
            <template v-else-if="column.key === 'actions'">
              <a-button size="small" @click="openEditEntityType(record)">编辑显示</a-button>
            </template>
          </template>
        </a-table>
      </a-card>
    </a-col>

    <a-col :span="12">
      <a-card title="关系类型" size="small">
        <a-table
          :dataSource="relTypes"
          :columns="relTypeCols"
          :loading="typesLoading"
          :pagination="false"
          size="small"
          row-key="name"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'actions'">
              <a-button size="small" @click="openEditRelType(record)">编辑显示</a-button>
            </template>
          </template>
        </a-table>
      </a-card>
    </a-col>
  </a-row>

  <!-- 编辑实体类型显示属性弹窗 -->
  <a-modal v-model:open="showEditEntityType" title="编辑实体类型显示" @ok="handleEditEntityType">
    <a-form layout="vertical">
      <a-form-item label="类型名称">
        <a-input :value="editEntityType.name" disabled />
      </a-form-item>
      <a-form-item label="中文名称">
        <a-input v-model:value="editEntityType.zh_name" placeholder="如 机构" />
      </a-form-item>
      <a-form-item label="颜色">
        <a-input v-model:value="editEntityType.color" placeholder="#52c41a" />
      </a-form-item>
      <a-form-item label="图标">
        <a-input v-model:value="editEntityType.icon" placeholder="book" />
      </a-form-item>
    </a-form>
  </a-modal>

  <!-- 编辑关系类型显示属性弹窗 -->
  <a-modal v-model:open="showEditRelType" title="编辑关系类型显示" @ok="handleEditRelType">
    <a-form layout="vertical">
      <a-form-item label="类型名称">
        <a-input :value="editRelType.name" disabled />
      </a-form-item>
      <a-form-item label="中文名称">
        <a-input v-model:value="editRelType.zh_name" placeholder="如 发布机构" />
      </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 {
  listEntityTypes,
  updateEntityType,
  listRelTypes,
  updateRelType,
} from '@/api/admin-graph'
import type { EntityTypeItem, RelTypeItem } from '@/types/admin-graph'

// ── 事件 ──
const emit = defineEmits<{
  /** 类型变更后通知父组件刷新相关数据 */
  (e: 'types-changed', entityTypeNames: string[], relTypeNames: string[]): void
}>()

// ── 状态 ──
const typesLoading = ref(false)
const entityTypes = ref<EntityTypeItem[]>([])
const relTypes = ref<RelTypeItem[]>([])

const showEditEntityType = ref(false)
const editEntityType = reactive({ name: '', zh_name: '', color: '', icon: '' })

const showEditRelType = ref(false)
const editRelType = reactive({ name: '', zh_name: '' })

// ── 表格列 ──
const entityTypeCols = [
  { title: '名称', dataIndex: 'name', key: 'name' },
  { title: '中文名', dataIndex: 'zh_name', key: 'zh_name' },
  { title: '描述', dataIndex: 'description', key: 'description', ellipsis: true },
  { title: '颜色', key: 'color', width: 60 },
  { title: '主键', dataIndex: 'key_property', key: 'key_property', width: 100 },
  { title: '实例数', dataIndex: 'instance_count', key: 'instance_count', width: 80 },
  { title: '操作', key: 'actions', width: 100 },
]
const relTypeCols = [
  { title: '名称', dataIndex: 'name', key: 'name' },
  { title: '中文名', dataIndex: 'zh_name', key: 'zh_name' },
  { title: '描述', dataIndex: 'description', key: 'description', ellipsis: true },
  { title: '实例数', dataIndex: 'instance_count', key: 'instance_count', width: 80 },
  { title: '操作', key: 'actions', width: 100 },
]

// ── 数据加载 ──
async function loadTypes() {
  typesLoading.value = true
  try {
    const [et, rt] = await Promise.all([listEntityTypes(), listRelTypes()])
    entityTypes.value = et.items
    relTypes.value = rt.items
    emitTypesChanged()
  } catch {
    message.error('加载类型失败')
  } finally {
    typesLoading.value = false
  }
}

function emitTypesChanged() {
  emit(
    'types-changed',
    entityTypes.value.map((t) => t.name),
    relTypes.value.map((t) => t.name),
  )
}

// ── 编辑实体类型显示属性 ──
function openEditEntityType(record: EntityTypeItem) {
  editEntityType.name = record.name
  editEntityType.zh_name = record.zh_name || ''
  editEntityType.color = record.color || ''
  editEntityType.icon = record.icon || ''
  showEditEntityType.value = true
}

async function handleEditEntityType() {
  try {
    await updateEntityType(editEntityType.name, {
      zh_name: editEntityType.zh_name || undefined,
      color: editEntityType.color || undefined,
      icon: editEntityType.icon || undefined,
    })
    message.success('更新成功')
    showEditEntityType.value = false
    loadTypes()
  } catch (e: unknown) {
    const err = e as { response?: { data?: { detail?: string } } }
    message.error(err.response?.data?.detail || '更新失败')
  }
}

// ── 编辑关系类型显示属性 ──
function openEditRelType(record: RelTypeItem) {
  editRelType.name = record.name
  editRelType.zh_name = record.zh_name || ''
  showEditRelType.value = true
}

async function handleEditRelType() {
  try {
    await updateRelType(editRelType.name, {
      zh_name: editRelType.zh_name || undefined,
    })
    message.success('更新成功')
    showEditRelType.value = false
    loadTypes()
  } catch (e: unknown) {
    const err = e as { response?: { data?: { detail?: string } } }
    message.error(err.response?.data?.detail || '更新失败')
  }
}

defineExpose({ loadTypes })

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