<template>
	<div class="ontology-page">
		<!-- 顶部工具栏 -->
		<div class="toolbar">
			<span class="toolbar-title">本体模型编辑器</span>
			<div class="toolbar-actions">
				<el-button :icon="Refresh" @click="refreshTree">刷新</el-button>
				<el-button :icon="Check" @click="validateAll">校验</el-button>
			</div>
		</div>

		<!-- 主体区域 -->
		<div class="main-content">
			<!-- 左侧模型树 -->
			<div class="left-panel">
				<div class="tree-container">
					<el-input v-model="treeFilter" placeholder="搜索模型..." clearable size="small" class="tree-search" />
					<el-tree
						ref="treeRef"
						:data="treeData"
						:props="{ label: 'label', children: 'children' }"
						node-key="name"
						:filter-node-method="filterNode"
						highlight-current
						@node-click="onNodeClick"
					>
						<template #default="{ node, data }">
							<span class="tree-node">
								<el-icon v-if="data.nodeType === 'category'" class="node-icon category">
									<Folder />
								</el-icon>
								<el-icon v-else-if="data.nodeType === 'group'" class="node-icon group">
									<Folder />
								</el-icon>
								<el-icon v-else-if="data.nodeType === 'leaf'" class="node-icon leaf">
									<Document />
								</el-icon>
								<el-icon v-else-if="data.kind === 'object'" class="node-icon object">
									<Box />
								</el-icon>
								<el-icon v-else-if="data.kind === 'behavior'" class="node-icon behavior">
									<Operation />
								</el-icon>
								<el-icon v-else-if="data.kind === 'rule'" class="node-icon rule">
									<Setting />
								</el-icon>
								<el-icon v-else-if="data.kind === 'event'" class="node-icon event">
									<Bell />
								</el-icon>
								<el-icon v-else-if="data.kind === 'scenario'" class="node-icon scenario">
									<VideoPlay />
								</el-icon>
								<el-icon v-else class="node-icon leaf">
									<Document />
								</el-icon>
								<span>{{ node.label }}</span>
							</span>
						</template>
					</el-tree>
				</div>

				<!-- 底部新增按钮 -->
				<div class="add-buttons">
					<el-button size="small" @click="openAddDialog('object')">+ 对象</el-button>
					<el-button size="small" @click="openAddDialog('behavior')">+ 行为</el-button>
					<el-button size="small" @click="openAddDialog('rule')">+ 规则</el-button>
					<el-button size="small" @click="openAddDialog('event')">+ 事件</el-button>
					<el-button size="small" @click="openAddDialog('scenario')">+ 场景</el-button>
				</div>
			</div>
			<!-- 右侧编辑区 -->
			<div class="right-panel">
				<!-- Tabs -->
				<el-tabs v-model="activeTab" type="card" closable @tab-remove="removeTab">
					<el-tab-pane
						v-for="tab in openTabs"
						:key="tab.name"
						:label="tab.label"
						:name="tab.name"
					/>
					<el-tab-pane label="知识图谱" name="__graph__" :closable="false" />
				</el-tabs>

				<!-- 模型编辑内容 -->
				<div v-if="activeTab && activeTab !== '__graph__'" class="editor-area">
					<div class="editor-toolbar">
						<el-radio-group v-model="editMode" size="small">
							<el-radio-button value="form">表单模式</el-radio-button>
							<el-radio-button value="yaml">YAML模式</el-radio-button>
						</el-radio-group>
						<div class="editor-actions">
							<el-button type="primary" size="small" @click="saveCurrentModel">保存</el-button>
							<el-button type="danger" size="small" @click="deleteCurrentModel">删除</el-button>
						</div>
					</div>

					<!-- 表单模式 -->
					<div v-if="editMode === 'form'" class="form-editor">

						<!-- ===== 规则模型 ===== -->
						<template v-if="currentModel.kind === 'rule'">
							<h3 class="detail-title">规则详情: {{ currentModel.label }}</h3>
							<el-descriptions :column="2" border size="small" class="info-card">
								<el-descriptions-item label="规则ID">{{ currentModel.name }}</el-descriptions-item>
								<el-descriptions-item label="规则类型">
									<el-tag size="small">{{ (currentModel.ruleType || 'validation').toUpperCase() }}</el-tag>
								</el-descriptions-item>
								<el-descriptions-item label="版本">{{ currentModel.version || '1.0' }}</el-descriptions-item>
								<el-descriptions-item label="输出类型">Boolean</el-descriptions-item>
							</el-descriptions>
							<el-form :model="currentModel" label-position="top" class="detail-form">
								<el-form-item label="规则名称" required>
									<el-input v-model="currentModel.label" />
								</el-form-item>
								<el-form-item label="规则类型">
									<el-select v-model="currentModel.ruleType" style="width: 100%">
										<el-option value="validation" label="VALIDATION（验证规则）" />
										<el-option value="computation" label="COMPUTATION（计算规则）" />
										<el-option value="constraint" label="CONSTRAINT（约束规则）" />
										<el-option value="derivation" label="DERIVATION（推导规则）" />
									</el-select>
								</el-form-item>
								<el-form-item label="描述">
									<el-input v-model="currentModel.description" type="textarea" :rows="3" />
								</el-form-item>
								<el-divider content-position="left">参数</el-divider>
								<el-table :data="currentModel.params || []" border size="small">
									<el-table-column prop="name" label="参数名" width="140" />
									<el-table-column prop="label" label="显示名" width="140" />
									<el-table-column prop="type" label="类型" width="100" />
									<el-table-column prop="required" label="必填" width="60">
										<template #default="{ row }">{{ row.required ? '是' : '' }}</template>
									</el-table-column>
								</el-table>
								<el-form-item label="规则表达式">
									<el-input v-model="currentModel.expression" type="textarea" :rows="6" placeholder="JavaScript 表达式" />
								</el-form-item>
								<el-form-item label="违规提示消息">
									<el-input v-model="currentModel.violationMessage" />
								</el-form-item>
								<el-form-item label="输出类型">
									<el-input model-value="Boolean" disabled />
								</el-form-item>
							</el-form>
						</template>

						<!-- ===== 行为模型 ===== -->
						<template v-else-if="currentModel.kind === 'behavior'">
							<h3 class="detail-title">行为详情: {{ currentModel.label }}</h3>
							<el-descriptions :column="2" border size="small" class="info-card">
								<el-descriptions-item label="行为ID">{{ currentModel.name }}</el-descriptions-item>
								<el-descriptions-item label="操作对象">{{ currentModel.objectRef || '-' }}</el-descriptions-item>
								<el-descriptions-item label="版本">{{ currentModel.version || '1.0' }}</el-descriptions-item>
								<el-descriptions-item label="触发方式">{{ currentModel.trigger?.type || 'manual' }}</el-descriptions-item>
							</el-descriptions>
							<el-form :model="currentModel" label-position="top" class="detail-form">
								<el-form-item label="行为名称" required>
									<el-input v-model="currentModel.label" />
								</el-form-item>
								<el-form-item label="操作对象">
									<el-input v-model="currentModel.objectRef" placeholder="关联的对象模型标识" />
								</el-form-item>
								<el-form-item label="描述">
									<el-input v-model="currentModel.description" type="textarea" :rows="3" />
								</el-form-item>
								<el-divider content-position="left">应用规则</el-divider>
								<el-table :data="currentModel.rules || []" border size="small">
									<el-table-column prop="ref" label="规则引用" width="200" />
									<el-table-column prop="phase" label="阶段" width="100" />
								</el-table>
								<el-divider content-position="left">触发事件</el-divider>
								<el-table :data="currentModel.emitEvents || []" border size="small">
									<el-table-column prop="ref" label="事件引用" width="200" />
									<el-table-column prop="on" label="触发时机" width="100" />
								</el-table>
							</el-form>
						</template>

						<!-- ===== 事件模型 ===== -->
						<template v-else-if="currentModel.kind === 'event'">
							<h3 class="detail-title">事件详情: {{ currentModel.label }}</h3>
							<el-descriptions :column="2" border size="small" class="info-card">
								<el-descriptions-item label="事件ID">{{ currentModel.name }}</el-descriptions-item>
								<el-descriptions-item label="版本">{{ currentModel.version || '1.0' }}</el-descriptions-item>
								<el-descriptions-item label="触发行为">{{ currentModel.triggerBy?.behavior || '-' }}</el-descriptions-item>
								<el-descriptions-item label="触发对象">{{ currentModel.triggerBy?.object || '-' }}</el-descriptions-item>
							</el-descriptions>
							<el-form :model="currentModel" label-position="top" class="detail-form">
								<el-form-item label="事件名称" required>
									<el-input v-model="currentModel.label" />
								</el-form-item>
								<el-form-item label="描述">
									<el-input v-model="currentModel.description" type="textarea" :rows="3" />
								</el-form-item>

								<el-divider content-position="left">触发来源（谁产生了这个事件）</el-divider>
								<el-form :model="currentModel.triggerBy || {}" label-width="100px" size="small" class="nested-form">
									<el-form-item label="触发行为">
										<el-input v-model="currentModel.triggerBy.behavior" placeholder="行为模型标识" />
									</el-form-item>
									<el-form-item label="触发对象">
										<el-input v-model="currentModel.triggerBy.object" placeholder="对象模型标识" />
									</el-form-item>
									<el-form-item label="说明">
										<el-input v-model="currentModel.triggerBy.description" />
									</el-form-item>
								</el-form>

								<el-divider content-position="left">订阅消费者（谁消费这个事件）</el-divider>
								<el-table :data="currentModel.subscribeBy || []" border size="small">
									<el-table-column prop="object" label="订阅对象" width="140" />
									<el-table-column prop="behavior" label="触发行为" width="140" />
									<el-table-column prop="description" label="说明" />
								</el-table>

								<el-divider content-position="left">载荷字段</el-divider>
								<el-table :data="currentModel.payload || []" border size="small">
									<el-table-column prop="name" label="字段名" width="140" />
									<el-table-column prop="type" label="类型" width="100" />
									<el-table-column prop="required" label="必填" width="60">
										<template #default="{ row }">{{ row.required ? '是' : '' }}</template>
									</el-table-column>
								</el-table>
							</el-form>
						</template>

						<!-- ===== 场景模型 ===== -->
						<template v-else-if="currentModel.kind === 'scenario'">
							<h3 class="detail-title">场景详情: {{ currentModel.label }}</h3>
							<el-descriptions :column="2" border size="small" class="info-card">
								<el-descriptions-item label="场景ID">{{ currentModel.name }}</el-descriptions-item>
								<el-descriptions-item label="版本">{{ currentModel.version || '1.0' }}</el-descriptions-item>
								<el-descriptions-item label="主体对象">{{ currentModel.actor || '-' }}</el-descriptions-item>
								<el-descriptions-item label="步骤数">{{ (currentModel.steps || []).length }}</el-descriptions-item>
							</el-descriptions>
							<el-form :model="currentModel" label-position="top" class="detail-form">
								<el-form-item label="场景名称" required>
									<el-input v-model="currentModel.label" />
								</el-form-item>
								<el-form-item label="主体对象">
									<el-input v-model="currentModel.actor" placeholder="场景的核心操作对象标识" />
								</el-form-item>
								<el-form-item label="描述">
									<el-input v-model="currentModel.description" type="textarea" :rows="3" />
								</el-form-item>
								<el-divider content-position="left">流程步骤</el-divider>
								<el-table :data="currentModel.steps || []" border size="small">
									<el-table-column prop="order" label="序号" width="60" />
									<el-table-column prop="type" label="类型" width="90">
										<template #default="{ row }">
											<el-tag :type="row.type === 'behavior' ? 'warning' : 'success'" size="small">
												{{ row.type === 'behavior' ? '行为' : '事件' }}
											</el-tag>
										</template>
									</el-table-column>
									<el-table-column prop="ref" label="引用模型" width="160" />
									<el-table-column prop="label" label="步骤名称" width="180" />
									<el-table-column prop="description" label="说明" />
								</el-table>
							</el-form>
						</template>

						<!-- ===== 对象模型 ===== -->
						<template v-else-if="currentModel.kind === 'object'">
							<h3 class="detail-title">对象详情: {{ currentModel.label }}</h3>
							<el-descriptions :column="2" border size="small" class="info-card">
								<el-descriptions-item label="对象ID">{{ currentModel.name }}</el-descriptions-item>
								<el-descriptions-item label="数据表">{{ currentModel.sourceTable || '-' }}</el-descriptions-item>
								<el-descriptions-item label="版本">{{ currentModel.version || '1.0' }}</el-descriptions-item>
								<el-descriptions-item label="属性数">{{ (currentModel.properties || []).length }}</el-descriptions-item>
							</el-descriptions>
							<el-form :model="currentModel" label-position="top" class="detail-form">
								<el-form-item label="对象名称" required>
									<el-input v-model="currentModel.label" />
								</el-form-item>
								<el-form-item label="描述">
									<el-input v-model="currentModel.description" type="textarea" :rows="2" />
								</el-form-item>
								<el-divider content-position="left">属性</el-divider>
								<el-table :data="currentModel.properties || []" border size="small">
									<el-table-column prop="name" label="字段名" width="120" />
									<el-table-column prop="label" label="显示名" width="120" />
									<el-table-column prop="type" label="类型" width="80" />
									<el-table-column prop="required" label="必填" width="60">
										<template #default="{ row }">{{ row.required ? '是' : '' }}</template>
									</el-table-column>
									<el-table-column prop="description" label="说明" />
								</el-table>
								<el-divider content-position="left">关联</el-divider>
								<el-table :data="currentModel.relations || []" border size="small">
									<el-table-column prop="name" label="关联名" width="120" />
									<el-table-column prop="label" label="显示名" width="120" />
									<el-table-column prop="target" label="目标对象" width="100" />
									<el-table-column prop="type" label="关联类型" width="120" />
									<el-table-column prop="through" label="中间表" />
								</el-table>
							</el-form>
						</template>

						<!-- ===== 兜底 ===== -->
						<template v-else>
							<el-form :model="currentModel" label-width="100px" size="small">
								<el-form-item label="标识"><el-input v-model="currentModel.name" disabled /></el-form-item>
								<el-form-item label="名称"><el-input v-model="currentModel.label" /></el-form-item>
								<el-form-item label="描述"><el-input v-model="currentModel.description" type="textarea" :rows="2" /></el-form-item>
							</el-form>
						</template>

					</div>

					<!-- YAML模式 -->
					<div v-if="editMode === 'yaml'" class="yaml-editor">
						<cl-editor-monaco
							v-model="currentYaml"
							language="yaml"
							:height="500"
						/>
					</div>
				</div>
				<!-- 知识图谱 -->
				<div v-if="activeTab === '__graph__'" class="graph-area">
					<div class="graph-toolbar">
						<el-radio-group v-model="graphFilter" size="small" @change="updateGraph">
							<el-radio-button value="all">全部</el-radio-button>
							<el-radio-button value="object">对象</el-radio-button>
							<el-radio-button value="behavior">行为</el-radio-button>
							<el-radio-button value="rule">规则</el-radio-button>
							<el-radio-button value="event">事件</el-radio-button>
							<el-radio-button value="scenario">场景</el-radio-button>
						</el-radio-group>
					</div>
					<div ref="graphRef" class="graph-container" />
				</div>

				<!-- 空状态 -->
				<div v-if="!activeTab" class="empty-state">
					<el-empty description="点击左侧模型节点开始编辑，或切换到知识图谱查看全局关系" />
				</div>
			</div>
		</div>

		<!-- 新增模型对话框 -->
		<el-dialog v-model="addDialogVisible" title="新增模型" width="400px">
			<el-form :model="addForm" label-width="80px">
				<el-form-item label="类型">
					<el-tag>{{ kindLabels[addForm.kind] }}</el-tag>
				</el-form-item>
				<el-form-item label="标识" required>
					<el-input v-model="addForm.name" placeholder="英文标识，如 user_profile" />
				</el-form-item>
				<el-form-item label="名称" required>
					<el-input v-model="addForm.label" placeholder="中文名称" />
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button @click="addDialogVisible = false">取消</el-button>
				<el-button type="primary" @click="confirmAdd">确定</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts" name="ontology-model-tree">
import { ref, watch, nextTick, onMounted, onBeforeUnmount } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Folder, Box, Operation, Bell, Document, Refresh, Check, Setting, VideoPlay } from '@element-plus/icons-vue';
import { useCool } from '/@/cool';
import * as echarts from 'echarts';

const { service } = useCool();

// ===== 常量 =====
const kindLabels: Record<string, string> = {
	object: '对象模型',
	behavior: '行为模型',
	rule: '规则模型',
	event: '事件模型',
	scenario: '场景模型'
};

// ===== 模型树 =====
const treeRef = ref();
const treeData = ref<any[]>([]);
const treeFilter = ref('');

watch(treeFilter, (val) => {
	treeRef.value?.filter(val);
});

function filterNode(value: string, data: any) {
	if (!value) return true;
	return data.label?.includes(value) || data.name?.includes(value);
}

async function refreshTree() {
	try {
		const res = await service.request({
			url: '/admin/ontology/model/tree',
			method: 'POST'
		});
		treeData.value = res || [];
	} catch (e: any) {
		ElMessage.error('加载模型树失败: ' + e.message);
	}
}

// ===== Tabs =====
const activeTab = ref('__graph__');
const openTabs = ref<{ name: string; label: string }[]>([]);
const editMode = ref<'form' | 'yaml'>('form');
const currentModel = ref<any>({});
const currentYaml = ref('');

function onNodeClick(data: any) {
	// 只处理模型节点（后端标记 isModel: true）
	if (!data.isModel) return;

	// 引用节点用 refName 指向真实模型，否则用 name
	const modelName = data.refName || data.name;

	// 打开 Tab
	const existing = openTabs.value.find(t => t.name === modelName);
	if (!existing) {
		openTabs.value.push({ name: modelName, label: data.label });
	}
	activeTab.value = modelName;
	loadModelDetail(modelName);
}

function removeTab(name: string | number) {
	const idx = openTabs.value.findIndex(t => t.name === String(name));
	if (idx >= 0) {
		openTabs.value.splice(idx, 1);
		if (activeTab.value === String(name)) {
			activeTab.value = openTabs.value.length > 0 ? openTabs.value[openTabs.value.length - 1].name : '__graph__';
		}
	}
}

async function loadModelDetail(name: string) {
	try {
		const res = await service.request({
			url: '/admin/ontology/model/detail',
			method: 'POST',
			data: { name }
		});
		currentModel.value = res.content || {};
		currentYaml.value = res.yaml || '';
	} catch (e: any) {
		ElMessage.error('加载模型详情失败: ' + e.message);
	}
}

// ===== 保存/删除 =====
async function saveCurrentModel() {
	const name = activeTab.value;
	if (!name || name === '__graph__') return;

	let yamlToSave = currentYaml.value;
	// 如果在表单模式，暂时只支持 YAML 模式保存
	if (editMode.value === 'form') {
		ElMessage.info('请切换到 YAML 模式进行保存');
		return;
	}

	try {
		await service.request({
			url: '/admin/ontology/model/save',
			method: 'POST',
			data: { name, yaml: yamlToSave }
		});
		ElMessage.success('保存成功');
		refreshTree();
	} catch (e: any) {
		ElMessage.error('保存失败: ' + e.message);
	}
}

async function deleteCurrentModel() {
	const name = activeTab.value;
	if (!name || name === '__graph__') return;

	await ElMessageBox.confirm(`确定删除模型 "${name}" 吗？此操作将同时删除 YAML 文件和数据库记录。`, '确认删除', {
		type: 'warning'
	});

	try {
		await service.request({
			url: '/admin/ontology/model/remove',
			method: 'POST',
			data: { name }
		});
		ElMessage.success('删除成功');
		removeTab(name);
		refreshTree();
	} catch (e: any) {
		ElMessage.error('删除失败: ' + e.message);
	}
}

// ===== 校验 =====
async function validateAll() {
	try {
		const res = await service.request({
			url: '/admin/ontology/model/validate',
			method: 'POST'
		});
		if (res.valid) {
			ElMessage.success('所有模型引用校验通过');
		} else {
			ElMessage.warning(`发现 ${res.errors.length} 个问题:\n${res.errors.join('\n')}`);
		}
	} catch (e: any) {
		ElMessage.error('校验失败: ' + e.message);
	}
}

// ===== 新增模型 =====
const addDialogVisible = ref(false);
const addForm = ref({ kind: '', name: '', label: '' });

function openAddDialog(kind: string) {
	addForm.value = { kind, name: '', label: '' };
	addDialogVisible.value = true;
}

async function confirmAdd() {
	if (!addForm.value.name || !addForm.value.label) {
		ElMessage.warning('请填写标识和名称');
		return;
	}
	try {
		await service.request({
			url: '/admin/ontology/model/create',
			method: 'POST',
			data: addForm.value
		});
		ElMessage.success('创建成功');
		addDialogVisible.value = false;
		refreshTree();
	} catch (e: any) {
		ElMessage.error('创建失败: ' + e.message);
	}
}

// ===== 知识图谱 =====
const graphRef = ref<HTMLElement>();
const graphFilter = ref('all');
let chartInstance: echarts.ECharts | null = null;
let graphData: { nodes: any[]; edges: any[] } = { nodes: [], edges: [] };

const categories = [
	{ name: '核心对象', itemStyle: { color: '#4A7BF7' } },
	{ name: '支撑域对象', itemStyle: { color: '#52C41A' } },
	{ name: '行为', itemStyle: { color: '#FA8C16' } },
	{ name: '规则', itemStyle: { color: '#FAAD14' } },
	{ name: '事件', itemStyle: { color: '#13C2C2' } },
	{ name: '场景', itemStyle: { color: '#722ED1' } }
];

function getCategoryIndex(category: string): number {
	const idx = categories.findIndex(c => c.name === category);
	return idx >= 0 ? idx : 0;
}

async function loadGraphData() {
	try {
		const res = await service.request({
			url: '/admin/ontology/model/graph',
			method: 'POST'
		});
		graphData = res || { nodes: [], edges: [] };
	} catch (e: any) {
		ElMessage.error('加载图谱数据失败: ' + e.message);
	}
}

function renderGraph() {
	if (!graphRef.value) return;

	if (!chartInstance) {
		chartInstance = echarts.init(graphRef.value);
		chartInstance.on('click', (params: any) => {
			if (params.dataType === 'node' && params.data?.modelName) {
				const name = params.data.modelName;
				// 在树中定位并打开
				treeRef.value?.setCurrentKey(name);
				const nodeData = findNodeInTree(name);
				if (nodeData) onNodeClick(nodeData);
			}
		});
	}

	// 过滤
	let filteredNodes = graphData.nodes;
	let filteredEdges = graphData.edges;
	if (graphFilter.value !== 'all') {
		const kindFilter = graphFilter.value;
		filteredNodes = graphData.nodes.filter(n => n.kind === kindFilter);
		const nodeIds = new Set(filteredNodes.map(n => n.id));
		filteredEdges = graphData.edges.filter(e => nodeIds.has(e.source) && nodeIds.has(e.target));
	}

	const option: echarts.EChartsOption = {
		tooltip: { trigger: 'item' },
		legend: {
			data: categories.map(c => c.name),
			top: 10
		},
		series: [{
			type: 'graph',
			layout: 'force',
			roam: true,
			draggable: true,
			force: { repulsion: 300, edgeLength: [100, 200], gravity: 0.1 },
			categories,
			label: { show: true, position: 'bottom', fontSize: 12 },
			edgeLabel: { show: true, fontSize: 10, formatter: (p: any) => p.data?.edgeLabel || '' },
			lineStyle: { color: '#aaa', curveness: 0.1 },
			data: filteredNodes.map(n => ({
				name: n.label,
				id: n.id,
				modelName: n.id,
				category: getCategoryIndex(n.category),
				symbolSize: n.kind === 'object' ? 50 : n.kind === 'scenario' ? 55 : 35
			})),
			edges: filteredEdges.map(e => ({
				source: e.source,
				target: e.target,
				edgeLabel: e.label
			}))
		}]
	};

	chartInstance.setOption(option, true);
}

function findNodeInTree(name: string): any {
	for (const group of treeData.value) {
		if (group.children) {
			const found = group.children.find((c: any) => c.name === name);
			if (found) return found;
		}
	}
	return null;
}

function updateGraph() {
	renderGraph();
}

// 监听 Tab 切换到图谱时渲染
watch(activeTab, async (val, oldVal) => {
	// 离开图谱 Tab 时销毁 chart（因为 v-if 会销毁 DOM）
	if (oldVal === '__graph__' && chartInstance) {
		chartInstance.dispose();
		chartInstance = null;
	}
	// 进入图谱 Tab 时重新加载并渲染
	if (val === '__graph__') {
		await loadGraphData();
		await nextTick();
		renderGraph();
	}
});

// 窗口 resize
function handleResize() {
	chartInstance?.resize();
}

onMounted(async () => {
	refreshTree();
	window.addEventListener('resize', handleResize);
	// 默认 Tab 是知识图谱，初始加载
	await loadGraphData();
	await nextTick();
	renderGraph();
});

onBeforeUnmount(() => {
	window.removeEventListener('resize', handleResize);
	chartInstance?.dispose();
});
</script>

<style scoped lang="scss">
.ontology-page {
	display: flex;
	flex-direction: column;
	height: 100%;
	background: var(--el-bg-color);
}

.toolbar {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 10px 16px;
	border-bottom: 1px solid var(--el-border-color-lighter);
	background: var(--el-bg-color);
}

.toolbar-title {
	font-size: 16px;
	font-weight: 600;
}

.main-content {
	display: flex;
	flex: 1;
	overflow: hidden;
}

.left-panel {
	width: 260px;
	min-width: 260px;
	display: flex;
	flex-direction: column;
	border-right: 1px solid var(--el-border-color-lighter);
	background: var(--el-bg-color);
}

.tree-container {
	flex: 1;
	overflow: auto;
	padding: 8px;
}

.tree-search {
	margin-bottom: 8px;
}

.tree-node {
	display: flex;
	align-items: center;
	gap: 4px;
	font-size: 13px;
}

.node-icon {
	font-size: 14px;
	&.category { color: #909399; }
	&.group { color: #c0c4cc; }
	&.object { color: #4A7BF7; }
	&.behavior { color: #FA8C16; }
	&.rule { color: #FAAD14; }
	&.event { color: #13C2C2; }
	&.scenario { color: #722ED1; }
	&.leaf { color: #c0c4cc; }
}

.add-buttons {
	display: flex;
	gap: 4px;
	padding: 8px;
	border-top: 1px solid var(--el-border-color-lighter);
	flex-wrap: wrap;
}

.right-panel {
	flex: 1;
	display: flex;
	flex-direction: column;
	overflow: hidden;
	padding: 8px 16px;
}

.editor-area {
	flex: 1;
	overflow: auto;
}

.editor-toolbar {
	display: flex;
	align-items: center;
	justify-content: space-between;
	margin-bottom: 12px;
}

.form-editor {
	padding: 8px 0;
	overflow: auto;
}

.detail-title {
	font-size: 18px;
	font-weight: 600;
	margin: 0 0 16px 0;
}

.info-card {
	margin-bottom: 20px;
}

.detail-form {
	margin-top: 16px;
}

.nested-form {
	background: var(--el-fill-color-lighter);
	padding: 12px;
	border-radius: 4px;
}

.yaml-editor {
	height: 500px;
}

.graph-area {
	flex: 1;
	display: flex;
	flex-direction: column;
}

.graph-toolbar {
	margin-bottom: 8px;
}

.graph-container {
	flex: 1;
	min-height: 500px;
}

.empty-state {
	flex: 1;
	display: flex;
	align-items: center;
	justify-content: center;
}
</style>
