Files
auto-solution/modeler/src/views/decision/communication/communication.vue

763 lines
29 KiB
Vue
Raw Normal View History

2026-02-08 15:59:14 +08:00
<template>
<Wrapper>
<a-layout class="bg-transparent" style="background: transparent">
<Header />
<a-layout class="ks-layout-body">
<div class="ks-model-builder-body">
<div class="ks-model-builder-left">
2026-03-14 21:37:07 +08:00
<PlatformCard
2026-03-15 19:32:20 +08:00
ref="scenariosCardRef"
2026-03-15 16:15:23 +08:00
@create="handleCreate"
@select="handleSelect"
2026-02-08 15:59:14 +08:00
/>
<NodesCard
2026-03-15 20:20:56 +08:00
v-if="currentScenario && currentScenario.id >0"
:scenario="currentScenario"
2026-02-08 15:59:14 +08:00
@drag-item-start="handleDragStart"
@drag-item-end="handleDragEnd"
/>
</div>
2026-03-14 21:37:07 +08:00
<div class="ks-model-builder-content" style="width: calc(100% - 250px);">
2026-02-08 15:59:14 +08:00
<div class="ks-model-builder-actions">
<a-space>
<a-button v-if="graph && currentScenario" class="ks-model-builder-save" style="width: auto;" size="small" @click="handleGenerateRandom">
<ThunderboltOutlined />
<span>随机生成</span>
</a-button>
<a-button v-if="graph && currentScenario && currentScenario.id > 0" class="ks-model-builder-save" style="width: auto;" size="small" @click="handleLoadFromBackend">
<DatabaseOutlined />
<span>从后端加载</span>
</a-button>
2026-03-14 22:35:21 +08:00
<a-button v-if="graph && currentScenario" class="ks-model-builder-save" size="small" @click="handleSave">
2026-02-09 15:06:04 +08:00
<CheckOutlined />
<span>保存</span>
</a-button>
2026-02-08 15:59:14 +08:00
</a-space>
</div>
<!-- 画布容器,添加拖放事件 -->
<div
ref="canvas"
class="ks-model-builder-canvas"
@dragenter="handleDragEnter"
@dragleave="handleDragLeave"
@drop="handleDrop"
@dragover.prevent
></div>
<TeleportContainer />
</div>
</div>
</a-layout>
</a-layout>
</Wrapper>
</template>
<script lang="ts">
import { defineComponent, nextTick, onBeforeUnmount, onMounted, ref } from 'vue';
2026-03-31 11:10:43 +08:00
import { useRoute, useRouter } from 'vue-router';
2026-02-08 15:59:14 +08:00
import { message } from 'ant-design-vue';
import { getTeleport } from '@antv/x6-vue-shape';
2026-02-08 17:11:03 +08:00
import { Graph, Node, type NodeProperties } from '@antv/x6';
import { CheckCircleOutlined, CheckOutlined, DatabaseOutlined, RollbackOutlined, SaveOutlined, ThunderboltOutlined } from '@ant-design/icons-vue';
2026-02-08 15:59:14 +08:00
import { Wrapper } from '@/components/wrapper';
import { safePreventDefault, safeStopPropagation } from '@/utils/event';
2026-03-14 21:37:07 +08:00
import Header from '../header.vue';
2026-03-14 22:35:21 +08:00
2026-03-26 22:05:31 +08:00
import type { Scenario } from './types';
import type { PlatformWithComponents } from '../types';
import { createLineOptions, type GraphContainer, type GraphEdgeElement, type GraphTaskElement, resolveGraph, useGraphCanvas } from '../graph';
2026-03-15 19:32:20 +08:00
import { registerScenarioElement } from './register';
2026-03-15 20:20:56 +08:00
import { createGraphScenarioElement, createGraphTaskElementFromScenario } from './utils';
2026-03-14 22:35:21 +08:00
2026-03-14 21:37:07 +08:00
import PlatformCard from './platform-card.vue';
2026-02-08 15:59:14 +08:00
import NodesCard from './nodes-card.vue';
2026-04-15 10:50:02 +08:00
import { findOneScenarioById, saveScenario, findRelations, getAllBehaviorTreesBySceneId, findPlatformWithComponents } from './api';
2026-03-26 22:05:31 +08:00
import { resolveConnectionRelation } from './relation';
2026-04-15 13:42:07 +08:00
import { generateRandomCommunicationData } from '../graph/random-data-generator';
import { convertRecordsToGraphContainer, type CommunicationRecord } from '../graph/data-converter';
2026-02-08 15:59:14 +08:00
const TeleportContainer = defineComponent(getTeleport());
2026-03-15 19:32:20 +08:00
registerScenarioElement();
2026-02-08 15:59:14 +08:00
export default defineComponent({
components: {
2026-03-14 21:37:07 +08:00
PlatformCard,
2026-02-08 15:59:14 +08:00
NodesCard,
Wrapper,
Header,
SaveOutlined,
CheckCircleOutlined,
CheckOutlined,
RollbackOutlined,
ThunderboltOutlined,
DatabaseOutlined,
2026-02-08 15:59:14 +08:00
TeleportContainer,
},
setup() {
2026-03-31 11:10:43 +08:00
const currentRoute = useRoute();
2026-02-08 15:59:14 +08:00
const canvas = ref<HTMLDivElement | null>(null);
const graph = ref<Graph | null>(null);
const currentZoom = ref<number>(1);
2026-03-15 19:32:20 +08:00
const draggedNodeData = ref<PlatformWithComponents | null>(null);
2026-02-08 15:59:14 +08:00
const isDraggingOver = ref(false);
2026-03-15 19:32:20 +08:00
const currentScenarioEditing = ref<boolean>(false);
2026-03-15 16:15:23 +08:00
const currentScenario = ref<Scenario | null>(null);
2026-02-08 15:59:14 +08:00
const selectedModelNode = ref<Node<NodeProperties> | null>(null);
2026-02-08 20:27:40 +08:00
const selectedNodeTaskElement = ref<GraphTaskElement | null>(null);
2026-02-08 22:16:22 +08:00
const changed = ref<boolean>(false);
2026-03-15 19:32:20 +08:00
const scenariosCardRef = ref<InstanceType<typeof PlatformCard> | null>(null);
2026-03-31 11:10:43 +08:00
const currentScenarioId = ref<number | null>(null);
2026-02-08 15:59:14 +08:00
const {
handleGraphEvent,
createCanvas,
zoomIn,
zoomOut,
fitToScreen,
centerContent,
resizeCanvas,
} = useGraphCanvas();
2026-03-26 22:05:31 +08:00
const destroy = ()=> {
window.removeEventListener('resize', handleResize);
if (graph.value) {
try {
graph.value.clearCells();
} catch (error) {
console.warn('销毁画布时出错:', error);
}
graph.value = null;
console.log('画布已销毁');
}
}
2026-02-08 15:59:14 +08:00
// 处理拖动开始
2026-03-15 19:32:20 +08:00
const handleDragStart = (nm: PlatformWithComponents) => {
2026-02-08 15:59:14 +08:00
draggedNodeData.value = nm;
};
// 处理拖动结束
const handleDragEnd = () => {
isDraggingOver.value = false;
};
// 处理拖动进入
const handleDragEnter = (e: DragEvent) => {
safePreventDefault(e);
safeStopPropagation(e);
isDraggingOver.value = true;
};
// 处理拖动离开
const handleDragLeave = (e: DragEvent) => {
safePreventDefault(e);
safeStopPropagation(e);
if (canvas.value && e.relatedTarget &&
typeof e.relatedTarget === 'object' &&
'nodeType' in e.relatedTarget) {
// 使用 Element 类型而不是 x6 的 Node 类型
if (!canvas.value.contains(e.relatedTarget as Element)) {
isDraggingOver.value = false;
}
}
};
// 处理放置
const handleDrop = (e: DragEvent) => {
console.info('handleDrop', e);
safePreventDefault(e);
safeStopPropagation(e);
isDraggingOver.value = false;
2026-03-15 19:32:20 +08:00
currentScenarioEditing.value = false;
2026-02-08 15:59:14 +08:00
2026-03-14 22:35:21 +08:00
if (!currentScenario.value) {
2026-03-15 20:20:56 +08:00
message.error('请先选择场景.');
2026-02-08 15:59:14 +08:00
return;
}
if (!graph.value || !canvas.value || !draggedNodeData.value) {
message.error('无法放置节点,缺少必要数据');
return;
}
try {
// 获取拖动的数据
2026-03-15 19:32:20 +08:00
const pwc = draggedNodeData.value as PlatformWithComponents;
2026-02-08 15:59:14 +08:00
2026-03-15 19:32:20 +08:00
// if (!hasElements(graph.value as Graph)) {
// message.error('请先添加根节点.');
// return;
// }
2026-02-08 15:59:14 +08:00
2026-03-15 19:32:20 +08:00
// if (hasRootElementNode(graph.value as Graph)) {
// message.error('根节点已经存在.');
// return;
// }
2026-02-08 15:59:14 +08:00
// 计算相对于画布的位置(考虑缩放)
const rect = canvas.value.getBoundingClientRect();
const scale = currentZoom.value || 1;
const x = (e.clientX - rect.left) / scale;
const y = (e.clientY - rect.top) / scale;
2026-03-15 19:32:20 +08:00
console.log('放置节点:', { ...pwc, x, y });
2026-02-08 15:59:14 +08:00
// 创建节点数据
2026-03-15 19:32:20 +08:00
const settingTaskElement: GraphTaskElement = createGraphTaskElementFromScenario(pwc, { x, y });
2026-02-08 15:59:14 +08:00
// 创建节点
2026-03-15 20:20:56 +08:00
const settingTaskNode = createGraphScenarioElement(settingTaskElement);
2026-02-08 15:59:14 +08:00
console.info('create settingTaskNode: ', settingTaskElement, settingTaskNode);
// 将节点添加到画布
graph.value?.addNode(settingTaskNode as any);
console.log('节点已添加到画布:', settingTaskNode.id);
// 重置拖动数据
draggedNodeData.value = null;
} catch (error) {
console.error('放置节点时出错:', error);
}
};
const handleSelect = async (scenario: Scenario) => {
2026-03-15 19:32:20 +08:00
let nodeGraph: GraphContainer | null = null;
try {
nodeGraph = JSON.parse(scenario.communicationGraph as unknown as string) as unknown as GraphContainer;
} catch (e: any) {
console.error('parse error,cause:', e);
}
// 设置当前场景
2026-03-15 19:32:20 +08:00
currentScenario.value = {
...scenario,
graph: nodeGraph || { nodes: [], edges: [] },
2026-03-16 15:48:33 +08:00
relations: []
2026-03-15 19:32:20 +08:00
};
console.log('选中场景:', currentScenario.value);
2026-03-15 19:32:20 +08:00
currentScenarioEditing.value = true;
2026-04-14 18:08:03 +08:00
// 并行加载通信关系和行为树列表
if (scenario.id > 0) {
try {
2026-04-14 18:08:03 +08:00
// 1. 加载通信关系(如果没有已保存的图数据)
if (!nodeGraph) {
message.loading({ content: '正在加载通信关系...', key: 'loading-relations' });
const response = await findRelations(scenario.id);
2026-04-14 18:08:03 +08:00
console.log('API完整响应:', response);
2026-04-14 18:08:03 +08:00
// 解析API响应(支持多种格式)
let relations: any[] = [];
if (Array.isArray(response.data)) {
relations = response.data;
} else if (response.data && Array.isArray((response.data as any).data)) {
relations = (response.data as any).data;
} else if (response.data && Array.isArray((response.data as any).rows)) {
relations = (response.data as any).rows;
} else if (response.data && Array.isArray((response.data as any).list)) {
relations = (response.data as any).list;
}
2026-04-14 18:08:03 +08:00
console.log('解析后的通信关系数量:', relations.length);
2026-04-14 18:08:03 +08:00
if (relations.length > 0) {
// 字段名标准化(驼峰转下划线)
const normalizedRelations = relations.map((item: any) => ({
id: item.id,
command_platform: item.commandPlatform || item.command_platform,
subordinate_platform: item.subordinatePlatform || item.subordinate_platform,
command_comm: item.commandComm || item.command_comm,
subordinate_comm: item.subordinateComm || item.subordinate_comm,
scenary_id: item.scenaryId || item.scenary_id,
}));
console.log('标准化后的第一条记录:', normalizedRelations[0]);
2026-04-15 10:50:02 +08:00
// 获取平台列表(包含完整的组件信息)
message.loading({ content: '正在获取平台信息...', key: 'loading-platforms' });
const platformResponse = await findPlatformWithComponents(currentScenario.value.id);
if (!platformResponse.data || platformResponse.data.length === 0) {
console.warn('未能获取平台列表,将使用简化的组件信息');
message.destroy('loading-platforms');
// 即使没有平台数据也继续转换(传入场景ID)
const convertedGraph = convertRecordsToGraphContainer(
normalizedRelations,
undefined,
undefined,
currentScenario.value.id
);
console.log('转换后的图数据:', convertedGraph);
currentScenario.value.graph = convertedGraph;
currentScenario.value.communicationGraph = JSON.stringify(convertedGraph);
message.success({ content: `成功加载 ${normalizedRelations.length} 条通信关系(无详细组件信息)`, key: 'loading-relations' });
return;
}
console.log(`获取到 ${platformResponse.data.length} 个平台的完整数据`);
platformResponse.data.forEach(platform => {
console.log(` 平台 "${platform.name}" (ID=${platform.id}) 有 ${platform.components?.length || 0} 个组件:`,
platform.components?.map(c => c.name));
});
// 转换为图数据(传入完整的平台数据数组和场景ID)
const convertedGraph = convertRecordsToGraphContainer(
normalizedRelations,
undefined,
platformResponse.data,
currentScenario.value.id
);
// 验证转换后的节点数据结构
2026-04-14 18:08:03 +08:00
console.log('转换后的图数据:', convertedGraph);
// 更新当前场景的图数据
currentScenario.value.graph = convertedGraph;
currentScenario.value.communicationGraph = JSON.stringify(convertedGraph);
message.success({ content: `成功加载 ${normalizedRelations.length} 条通信关系`, key: 'loading-relations' });
} else {
message.warning({ content: '该场景暂无通信关系数据', key: 'loading-relations' });
}
}
// 2. 加载行为树列表并缓存到graph对象
const treesResponse = await getAllBehaviorTreesBySceneId(scenario.id);
if (treesResponse.code === 200 && treesResponse.data) {
console.log('[communication] 行为树列表加载完成:', treesResponse.data.length, '个');
// 将行为树列表存储到graph对象中供node.vue使用
if (graph.value) {
(graph.value as any).behaviorTrees = treesResponse.data;
}
} else {
2026-04-14 18:08:03 +08:00
console.warn('[communication] 行为树列表加载失败或为空');
if (graph.value) {
(graph.value as any).behaviorTrees = [];
}
}
} catch (error) {
2026-04-14 18:08:03 +08:00
console.error('从后端加载数据失败:', error);
message.error({ content: '加载数据失败', key: 'loading-relations' });
}
}
2026-03-15 19:32:20 +08:00
createElements();
2026-02-08 17:11:03 +08:00
};
2026-02-08 15:59:14 +08:00
const createElements = () => {
2026-02-08 17:57:40 +08:00
nextTick(() => {
2026-02-08 22:31:13 +08:00
try {
2026-02-08 22:16:22 +08:00
graph.value?.clearCells();
2026-02-08 22:31:13 +08:00
} catch (e: any) {
console.error('clear cells error, cause:', e);
2026-02-08 22:16:22 +08:00
}
2026-02-08 22:31:13 +08:00
setTimeout(() => {
2026-03-14 22:35:21 +08:00
if (currentScenario.value?.graph && graph.value) {
if (currentScenario.value?.graph.nodes) {
currentScenario.value?.graph.nodes.forEach(ele => {
2026-03-15 20:20:56 +08:00
const node = createGraphScenarioElement(ele as GraphTaskElement);
2026-02-08 22:16:22 +08:00
// 将节点添加到画布
graph.value?.addNode(node as Node);
2026-02-08 17:57:40 +08:00
});
2026-02-08 22:16:22 +08:00
}
2026-03-14 22:35:21 +08:00
if (currentScenario.value?.graph.edges) {
2026-02-08 22:16:22 +08:00
// 然后添加所有边,确保包含桩点信息
setTimeout(() => {
2026-03-14 22:35:21 +08:00
currentScenario.value?.graph.edges.forEach(edgeData => {
2026-02-08 22:16:22 +08:00
graph.value?.addEdge({
...edgeData,
...createLineOptions(),
});
});
}, 100); // 延迟一会儿,免得连线错位
}
2026-02-08 17:57:40 +08:00
}
2026-02-08 22:31:13 +08:00
}, 100);
2026-02-08 17:57:40 +08:00
});
2026-02-08 15:59:14 +08:00
};
2026-03-15 16:15:23 +08:00
const handleCreate = () => {
2026-03-14 22:35:21 +08:00
currentScenario.value = {
2026-02-08 22:28:52 +08:00
id: 0,
2026-03-15 19:32:20 +08:00
name: null,
2026-02-08 22:28:52 +08:00
description: null,
2026-03-15 19:32:20 +08:00
communicationGraph: null,
2026-03-16 15:48:33 +08:00
relations: [],
2026-02-08 22:28:52 +08:00
graph: {
edges: [],
nodes: [],
2026-03-16 15:48:33 +08:00
},
2026-02-08 22:31:13 +08:00
};
// 清空graph中的场景信息
if (graph.value) {
(graph.value as any).currentScenario = null;
}
2026-02-08 22:28:52 +08:00
selectedModelNode.value = null;
selectedNodeTaskElement.value = null;
createElements();
2026-02-08 22:31:13 +08:00
};
2026-02-08 22:28:52 +08:00
2026-02-08 15:59:14 +08:00
// 初始化X6画布
const initGraph = () => {
if (!canvas.value) {
console.error('画布容器不存在');
return;
}
try {
graph.value = createCanvas(canvas.value);
console.log('画布初始化成功');
createElements();
// 监听缩放变化
handleGraphEvent('scale', ({ sx }: { sx: number }) => {
currentZoom.value = sx;
});
2026-02-08 22:09:28 +08:00
handleGraphEvent('blank:click', () => {
selectedModelNode.value = null;
selectedNodeTaskElement.value = null;
2026-03-15 19:32:20 +08:00
currentScenarioEditing.value = null !== currentScenario.value;
2026-02-08 22:09:28 +08:00
});
2026-03-27 10:03:16 +08:00
handleGraphEvent('node:dblclick', (args: any) => {
const node = args.node as Node<NodeProperties>;
const element = node.getData() as GraphTaskElement;
console.error('element',element)
2026-03-31 11:10:43 +08:00
window.location.href = `/app/decision/designer?scenario=${currentScenario.value?.id}&platform=${element?.platformId?? ''}`
2026-03-27 10:03:16 +08:00
// destroy()
// window.location.href = '/app/decision/designer'
2026-03-26 22:05:31 +08:00
// router.push({
// path: '/app/decision/designer'
// })
});
2026-02-08 15:59:14 +08:00
handleGraphEvent('node:click', (args: any) => {
const node = args.node as Node<NodeProperties>;
2026-02-08 20:27:40 +08:00
const newElement = node.getData() as GraphTaskElement;
2026-02-08 15:59:14 +08:00
selectedModelNode.value = node;
2026-02-08 20:27:40 +08:00
selectedNodeTaskElement.value = JSON.parse(JSON.stringify(newElement || {})) as GraphTaskElement;
2026-02-08 15:59:14 +08:00
});
// 监听节点鼠标事件,显示/隐藏连接点
handleGraphEvent('node:mouseenter', (_ctx: any) => {
});
handleGraphEvent('node:mouseleave', (_ctx: any) => {
});
} catch (error) {
console.error('初始化画布失败:', error);
}
};
// 监听窗口大小变化
const handleResize = () => {
nextTick(() => {
resizeCanvas();
});
};
const init = () => {
console.info('init');
nextTick(() => {
initGraph();
window.addEventListener('resize', handleResize);
console.log('节点挂载完成');
2026-03-31 11:10:43 +08:00
let scenarioId = Number(currentRoute.query.scenario);
if (!isNaN(scenarioId)) {
findOneScenarioById(scenarioId).then(r=> {
if(r.data){
handleSelect(r.data)
}
})
}
2026-02-08 15:59:14 +08:00
});
};
2026-02-08 20:27:40 +08:00
const handleUpdateElement = (element: GraphTaskElement) => {
2026-02-08 15:59:14 +08:00
// 更新选中的节点数据
if (selectedModelNode.value) {
selectedModelNode.value.replaceData(element);
}
console.info('handleUpdateElement', element);
// 更新本地引用
selectedNodeTaskElement.value = element;
2026-02-08 22:31:13 +08:00
changed.value = true;
2026-02-08 15:59:14 +08:00
};
const handleSave = () => {
2026-03-15 19:32:20 +08:00
const graphData: GraphContainer = resolveGraph(graph.value as Graph);
2026-04-15 10:50:02 +08:00
console.log(graph.value);
2026-03-16 15:48:33 +08:00
2026-04-15 10:50:02 +08:00
2026-03-16 15:48:33 +08:00
const relations = resolveConnectionRelation(graph.value as Graph);
console.error('relations',relations)
2026-02-08 15:59:14 +08:00
console.info('handleSave', graphData);
2026-03-14 22:35:21 +08:00
if (!currentScenario.value) {
2026-02-08 15:59:14 +08:00
message.error('当前决策树不存在');
return;
}
2026-03-15 19:32:20 +08:00
const newScenario: Scenario = {
2026-03-14 22:35:21 +08:00
...currentScenario.value,
2026-02-08 15:59:14 +08:00
graph: graphData,
2026-03-15 19:32:20 +08:00
communicationGraph: JSON.stringify(graphData),
2026-03-16 15:48:33 +08:00
relations: relations
2026-02-08 15:59:14 +08:00
};
2026-03-15 19:32:20 +08:00
if (!newScenario.name) {
message.error('场景名称不能为空.');
2026-02-08 22:28:52 +08:00
return;
}
2026-02-08 15:59:14 +08:00
let res = null;
2026-03-14 22:35:21 +08:00
if (currentScenario.value.id > 0) {
2026-03-15 19:32:20 +08:00
res = saveScenario(newScenario);
2026-02-08 15:59:14 +08:00
} else {
2026-03-15 19:32:20 +08:00
res = saveScenario(newScenario);
2026-02-08 15:59:14 +08:00
}
res.then(r => {
if (r.code === 200) {
2026-03-15 19:32:20 +08:00
scenariosCardRef.value?.refresh();
2026-02-08 17:11:03 +08:00
message.success(r.msg ?? '操作成功.');
2026-02-08 15:59:14 +08:00
} else {
2026-02-08 17:11:03 +08:00
message.error(r.msg ?? '操作失败.');
2026-02-08 15:59:14 +08:00
}
});
};
// 随机生成节点流图
const handleGenerateRandom = () => {
if (!graph.value) {
message.error('画布未初始化');
return;
}
try {
// 生成随机数据
const { records, graph: randomGraph } = generateRandomCommunicationData(30);
console.log('生成的随机数据:', records);
console.log('转换后的图数据:', randomGraph);
// 清空现有内容
graph.value.clearCells();
// 设置当前场景
if (!currentScenario.value) {
currentScenario.value = {
id: 0,
name: `随机场景_${Date.now()}`,
description: '自动生成的测试场景',
communicationGraph: null,
relations: [],
graph: randomGraph,
};
} else {
currentScenario.value.graph = randomGraph;
currentScenario.value.communicationGraph = JSON.stringify(randomGraph);
}
// 渲染节点
setTimeout(() => {
if (randomGraph.nodes) {
randomGraph.nodes.forEach(ele => {
const node = createGraphScenarioElement(ele as GraphTaskElement);
graph.value?.addNode(node as Node);
});
}
// 延迟添加边,确保节点已渲染
setTimeout(() => {
if (randomGraph.edges) {
randomGraph.edges.forEach(edgeData => {
graph.value?.addEdge({
...edgeData,
...createLineOptions(),
});
});
}
// 自动适应视图
fitToScreen();
message.success(`已生成 ${randomGraph.nodes.length} 个节点和 ${randomGraph.edges.length} 条连接线`);
}, 100);
}, 50);
} catch (error) {
console.error('随机生成时出错:', error);
message.error('生成失败,请重试');
}
};
// 从后端加载平台数据并转换为通信关系图(当前使用模拟数据)
const handleLoadFromBackend = async () => {
if (!graph.value || !currentScenario.value) {
message.error('请先选择场景');
return;
}
try {
message.loading({ content: '正在加载通信关系数据...', key: 'loading' });
// 调用真实API获取通信关系
console.log(`正在从后端加载场景 ${currentScenario.value.id} 的通信关系...`);
const response = await findRelations(currentScenario.value.id);
console.log('API完整响应:', response);
console.log('response.data类型:', typeof response.data, Array.isArray(response.data) ? 'Array' : 'Object');
// API返回的是 CommunicationRelationRecord[],与 CommunicationRecord 结构兼容
// 处理可能的多种返回格式
let relations: any[] = [];
if (Array.isArray(response.data)) {
relations = response.data;
} else if (response.data && Array.isArray((response.data as any).data)) {
relations = (response.data as any).data;
} else if (response.data && Array.isArray((response.data as any).rows)) {
relations = (response.data as any).rows;
} else if (response.data && Array.isArray((response.data as any).list)) {
relations = (response.data as any).list;
}
console.log('解析后的通信关系数量:', relations.length);
if (relations.length > 0) {
console.log('第一条记录:', JSON.stringify(relations[0], null, 2));
}
// 后端返回的是驼峰命名,需要转换为下划线命名以匹配前端类型
const normalizedRelations = relations.map((item: any) => ({
id: item.id,
command_platform: item.commandPlatform || item.command_platform,
subordinate_platform: item.subordinatePlatform || item.subordinate_platform,
command_comm: item.commandComm || item.command_comm,
subordinate_comm: item.subordinateComm || item.subordinate_comm,
scenary_id: item.scenaryId || item.scenary_id,
}));
console.log('标准化后的第一条记录:', normalizedRelations[0]);
if (normalizedRelations.length === 0) {
console.warn('API未返回任何通信关系数据,使用模拟数据作为fallback');
// Fallback到模拟数据(保留以便测试)
relations.push(
{ id: 6, command_platform: 'chief', subordinate_platform: 'task1_commander', command_comm: 'radio', subordinate_comm: 'radio', scenary_id: currentScenario.value.id },
{ id: 7, command_platform: 'chief', subordinate_platform: 'task2_commander', command_comm: 'radio', subordinate_comm: 'radio', scenary_id: currentScenario.value.id },
{ id: 8, command_platform: 'chief', subordinate_platform: 'task3_commander', command_comm: 'radio', subordinate_comm: 'radio', scenary_id: currentScenario.value.id },
{ id: 9, command_platform: 'task1_commander', subordinate_platform: 'platform1', command_comm: 'radio', subordinate_comm: 'radio', scenary_id: currentScenario.value.id },
{ id: 10, command_platform: 'task1_commander', subordinate_platform: 'platform3', command_comm: 'radio', subordinate_comm: 'radio', scenary_id: currentScenario.value.id },
{ id: 11, command_platform: 'task1_commander', subordinate_platform: 'platform4', command_comm: 'radio', subordinate_comm: 'radio', scenary_id: currentScenario.value.id },
{ id: 12, command_platform: 'task1_commander', subordinate_platform: 'platform5', command_comm: 'radio', subordinate_comm: 'radio', scenary_id: currentScenario.value.id },
{ id: 13, command_platform: 'task1_commander', subordinate_platform: 'platform6', command_comm: 'radio', subordinate_comm: 'radio', scenary_id: currentScenario.value.id },
{ id: 14, command_platform: 'task2_commander', subordinate_platform: 'platform3', command_comm: 'radio', subordinate_comm: 'radio', scenary_id: currentScenario.value.id },
{ id: 15, command_platform: 'task2_commander', subordinate_platform: 'platform5', command_comm: 'radio', subordinate_comm: 'radio', scenary_id: currentScenario.value.id },
{ id: 16, command_platform: 'task2_commander', subordinate_platform: 'platform4', command_comm: 'radio', subordinate_comm: 'radio', scenary_id: currentScenario.value.id },
{ id: 17, command_platform: 'task3_commander', subordinate_platform: 'platform6', command_comm: 'radio', subordinate_comm: 'radio', scenary_id: currentScenario.value.id },
{ id: 18, command_platform: 'task3_commander', subordinate_platform: 'platform6', command_comm: 'radio', subordinate_comm: 'radio', scenary_id: currentScenario.value.id },
{ id: 19, command_platform: 'task3_commander', subordinate_platform: 'platform7', command_comm: 'radio', subordinate_comm: 'radio', scenary_id: currentScenario.value.id },
{ id: 20, command_platform: 'task3_commander', subordinate_platform: 'platform8', command_comm: 'radio', subordinate_comm: 'radio', scenary_id: currentScenario.value.id },
);
}
console.log('最终使用的通信记录:', normalizedRelations);
// 使用数据进行转换
const convertedGraph = convertRecordsToGraphContainer(normalizedRelations);
console.log('转换后的图数据:', convertedGraph);
// 清空现有内容
graph.value.clearCells();
// 更新当前场景
currentScenario.value.graph = convertedGraph;
currentScenario.value.communicationGraph = JSON.stringify(convertedGraph);
// 渲染节点
setTimeout(() => {
if (convertedGraph.nodes) {
convertedGraph.nodes.forEach(ele => {
const node = createGraphScenarioElement(ele as GraphTaskElement);
graph.value?.addNode(node as Node);
});
}
// 延迟添加边,确保节点已渲染
setTimeout(() => {
if (convertedGraph.edges) {
convertedGraph.edges.forEach(edgeData => {
graph.value?.addEdge({
...edgeData,
...createLineOptions(),
});
});
}
// 自动适应视图
fitToScreen();
message.success({
content: `已从后端加载 ${convertedGraph.nodes.length} 个平台和 ${convertedGraph.edges.length} 条连接关系`,
key: 'loading'
});
}, 100);
}, 50);
} catch (error) {
console.error('从后端加载时出错:', error);
message.error({
content: error instanceof Error ? error.message : '加载失败,请重试',
key: 'loading'
});
}
};
2026-02-08 15:59:14 +08:00
// 初始化
onMounted(() => {
init();
});
// 清理
2026-03-26 22:05:31 +08:00
onBeforeUnmount(() => destroy());
2026-02-08 15:59:14 +08:00
return {
2026-03-15 19:32:20 +08:00
scenariosCardRef,
2026-03-15 16:15:23 +08:00
handleCreate,
2026-03-15 19:32:20 +08:00
currentScenarioEditing,
2026-03-14 22:35:21 +08:00
currentScenario,
2026-02-08 15:59:14 +08:00
selectedNodeTaskElement,
selectedModelNode,
graph,
canvas,
zoomIn,
zoomOut,
fitToScreen,
centerContent,
handleDragStart,
handleDragEnd,
handleDragEnter,
handleDragLeave,
handleDrop,
isDraggingOver,
handleSave,
handleGenerateRandom,
handleLoadFromBackend,
2026-02-08 15:59:14 +08:00
handleUpdateElement,
2026-03-15 16:15:23 +08:00
handleSelect,
2026-02-08 15:59:14 +08:00
};
},
});
</script>