feat: 航线规划以及水域边界标绘

This commit is contained in:
2026-01-06 18:09:20 +08:00
parent 9a50476c62
commit a9f1e1f4d4
187 changed files with 14935 additions and 5334 deletions
Binary file not shown.
@@ -30,6 +30,7 @@ const DEVICE_TYPE_OPTIONS = [
{ label: '机场', value: 1 },
{ label: '无人机', value: 2 },
{ label: '遥控器', value: 3 },
{ label: 'boat', value: 4 },
];
const DeviceForm: React.FC<DeviceFormProps> = ({ title, visible, onVisibleChange, onFinish, initialValues }) => {
@@ -31,6 +31,7 @@ const DeviceTable = forwardRef<DeviceTableRef, DeviceTableProps>(({ params, onEd
1: '机场',
2: '无人机',
3: '遥控器',
4: 'boat',
};
const columns: ProColumns<any>[] = [
Binary file not shown.
@@ -0,0 +1,151 @@
/**
* 边界预览面板组件
* 显示边界的统计信息
* @author Claude
* @date 2026-01-06
*/
import React, { useMemo } from 'react';
import { Card, Descriptions, Tag } from 'antd';
import type { BoundaryPreviewProps, BoundaryType } from './types';
/**
* 计算多边形面积(使用Shoelace公式)
* @param vertices 顶点数组
* @returns 面积(平方米)
*/
function calculatePolygonArea(vertices: { longitude: number; latitude: number }[]): number {
if (vertices.length < 3) return 0;
// 将经纬度转换为米(简化计算,适用于小范围区域)
const R = 6371000; // 地球半径(米)
const toRadians = (deg: number) => deg * Math.PI / 180;
// 计算中心点
const centerLat = vertices.reduce((sum, v) => sum + v.latitude, 0) / vertices.length;
const centerLon = vertices.reduce((sum, v) => sum + v.longitude, 0) / vertices.length;
// 转换为平面坐标(局部投影)
const points = vertices.map(v => ({
x: R * toRadians(v.longitude - centerLon) * Math.cos(toRadians(centerLat)),
y: R * toRadians(v.latitude - centerLat),
}));
// Shoelace公式计算面积
let area = 0;
for (let i = 0; i < points.length; i++) {
const j = (i + 1) % points.length;
area += points[i].x * points[j].y;
area -= points[j].x * points[i].y;
}
area = Math.abs(area) / 2;
return area;
}
/**
* 获取边界类型显示信息
*/
function getBoundaryTypeInfo(type: BoundaryType): { label: string; color: string } {
switch (type) {
case 'navigable':
return { label: '可通行区域', color: 'green' };
case 'forbidden':
return { label: '禁止通行', color: 'red' };
case 'warning':
return { label: '警告区域', color: 'orange' };
default:
return { label: '未知', color: 'default' };
}
}
const BoundaryPreview: React.FC<BoundaryPreviewProps> = ({
vertices,
boundaryType,
area: providedArea,
}) => {
// 计算面积
const calculatedArea = useMemo(() => {
return providedArea ?? calculatePolygonArea(vertices);
}, [vertices, providedArea]);
// 格式化面积显示
const areaText = useMemo(() => {
if (calculatedArea === 0) return '-';
if (calculatedArea < 1000) {
return `${calculatedArea.toFixed(2)} m²`;
} else if (calculatedArea < 1000000) {
return `${(calculatedArea / 1000).toFixed(2)} 千m²`;
} else {
return `${(calculatedArea / 1000000).toFixed(2)} km²`;
}
}, [calculatedArea]);
const typeInfo = getBoundaryTypeInfo(boundaryType);
return (
<Card
size="small"
title="边界信息"
style={{
position: 'absolute',
top: 20,
right: 20,
width: 280,
zIndex: 1000,
background: 'rgba(10, 20, 40, 0.95)',
borderRadius: 8,
boxShadow: '0 4px 20px rgba(0, 0, 0, 0.3)',
border: '1px solid rgba(0, 240, 255, 0.3)',
}}
headStyle={{
color: '#fff',
borderBottom: '1px solid rgba(255, 255, 255, 0.1)',
}}
bodyStyle={{
color: 'rgba(255, 255, 255, 0.85)',
}}
>
<Descriptions column={1} size="small" bordered>
<Descriptions.Item label="边界类型">
<Tag color={typeInfo.color}>{typeInfo.label}</Tag>
</Descriptions.Item>
<Descriptions.Item label="顶点数量">
{vertices.length}
</Descriptions.Item>
<Descriptions.Item label="估算面积">
{areaText}
</Descriptions.Item>
</Descriptions>
{vertices.length > 0 && vertices.length < 3 && (
<div style={{
marginTop: 12,
padding: 8,
background: 'rgba(250, 173, 20, 0.1)',
border: '1px solid rgba(250, 173, 20, 0.3)',
borderRadius: 4,
fontSize: 12,
color: '#faad14',
}}>
⚠️ 至少需要3个顶点才能形成边界
</div>
)}
{vertices.length >= 3 && (
<div style={{
marginTop: 12,
padding: 8,
background: 'rgba(82, 196, 26, 0.1)',
border: '1px solid rgba(82, 196, 26, 0.3)',
borderRadius: 4,
fontSize: 12,
color: '#52c41a',
}}>
✓ 边界已形成,可以保存
</div>
)}
</Card>
);
};
export default BoundaryPreview;
@@ -0,0 +1,171 @@
/**
* 边界编辑器工具栏组件
* @author Claude
* @date 2026-01-06
*/
import React from 'react';
import { Button, Space, Tooltip } from 'antd';
import {
PlusOutlined,
CheckOutlined,
EditOutlined,
EyeOutlined,
DeleteOutlined,
UndoOutlined,
SaveOutlined,
CloseOutlined,
} from '@ant-design/icons';
import type { BoundaryToolbarProps } from './types';
const BoundaryToolbar: React.FC<BoundaryToolbarProps> = ({
mode,
hasVertices,
hasUnsavedChanges,
isDrawing,
onModeChange,
onStartDraw,
onFinishDraw,
onClear,
onSave,
onCancel,
}) => {
return (
<div style={{
position: 'absolute',
top: 20,
left: 20,
zIndex: 1000,
background: 'rgba(10, 20, 40, 0.95)',
borderRadius: 8,
padding: '12px 16px',
boxShadow: '0 4px 20px rgba(0, 0, 0, 0.3)',
border: '1px solid rgba(0, 240, 255, 0.3)',
}}>
<Space size="middle">
{/* 绘制按钮 */}
{!isDrawing && (
<Tooltip title="开始绘制边界">
<Button
type="primary"
icon={<PlusOutlined />}
onClick={onStartDraw}
style={{
background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
border: 'none',
}}
>
开始绘制
</Button>
</Tooltip>
)}
{/* 完成绘制按钮 */}
{isDrawing && (
<Tooltip title="完成绘制(至少3个顶点)">
<Button
type="primary"
icon={<CheckOutlined />}
onClick={onFinishDraw}
disabled={!hasVertices}
style={{
background: 'linear-gradient(135deg, #52c41a 0%, #389e0d 100%)',
border: 'none',
}}
>
完成绘制
</Button>
</Tooltip>
)}
{/* 模式切换按钮 */}
{hasVertices && !isDrawing && (
<>
<Tooltip title="查看模式">
<Button
type={mode === 'view' ? 'primary' : 'default'}
icon={<EyeOutlined />}
onClick={() => onModeChange('view')}
>
查看
</Button>
</Tooltip>
<Tooltip title="编辑模式(拖动顶点)">
<Button
type={mode === 'edit' ? 'primary' : 'default'}
icon={<EditOutlined />}
onClick={() => onModeChange('edit')}
>
编辑
</Button>
</Tooltip>
</>
)}
{/* 清空按钮 */}
{hasVertices && (
<Tooltip title="清空所有顶点">
<Button
danger
icon={<DeleteOutlined />}
onClick={onClear}
>
清空
</Button>
</Tooltip>
)}
{/* 分隔线 */}
{hasVertices && (
<div style={{
width: 1,
height: 24,
background: 'rgba(255, 255, 255, 0.2)',
}} />
)}
{/* 保存按钮 */}
{hasVertices && !isDrawing && (
<Tooltip title="保存边界到后台">
<Button
type="primary"
icon={<SaveOutlined />}
onClick={onSave}
style={{
background: hasUnsavedChanges
? 'linear-gradient(135deg, #fa8c16 0%, #d46b08 100%)'
: undefined,
}}
>
{hasUnsavedChanges ? '保存*' : '保存'}
</Button>
</Tooltip>
)}
{/* 取消按钮 */}
<Tooltip title="关闭编辑器">
<Button
icon={<CloseOutlined />}
onClick={onCancel}
>
取消
</Button>
</Tooltip>
</Space>
{/* 当前状态提示 */}
<div style={{
marginTop: 8,
fontSize: 12,
color: 'rgba(255, 255, 255, 0.7)',
}}>
{isDrawing && '点击地图添加顶点,完成后点击"完成绘制"'}
{!isDrawing && mode === 'view' && hasVertices && '查看模式 - 切换到编辑模式可调整顶点'}
{!isDrawing && mode === 'edit' && hasVertices && '编辑模式 - 拖动顶点调整边界'}
{!isDrawing && !hasVertices && '点击"开始绘制"标绘水域边界'}
</div>
</div>
);
};
export default BoundaryToolbar;
@@ -0,0 +1,265 @@
/**
* 边界绘制状态管理Hook
* 负责管理边界绘制的所有状态和操作逻辑
* @author Claude
* @date 2026-01-06
*/
import { useState, useCallback, useRef } from 'react';
import { message } from 'antd';
import type { BoundaryVertex, EditorMode, EditorState } from '../types';
interface UseBoundaryDrawingOptions {
/** 初始顶点 */
initialVertices?: BoundaryVertex[];
}
interface UseBoundaryDrawingReturn {
/** 所有顶点 */
vertices: BoundaryVertex[];
/** 编辑器状态 */
editorState: EditorState;
/** 是否正在绘制 */
isDrawing: boolean;
/** 设置编辑模式 */
setMode: (mode: EditorMode) => void;
/** 开始绘制 */
startDrawing: () => void;
/** 结束绘制 */
finishDrawing: () => void;
/** 添加顶点 */
addVertex: (point: { longitude: number; latitude: number }) => void;
/** 更新顶点 */
updateVertex: (index: number, point: { longitude: number; latitude: number }) => void;
/** 删除顶点 */
deleteVertex: (index: number) => void;
/** 移动顶点 */
moveVertex: (index: number, point: { longitude: number; latitude: number }) => void;
/** 选择顶点 */
selectVertex: (index: number | null) => void;
/** 清空所有顶点 */
clearVertices: () => void;
/** 设置顶点列表 */
setVertices: (vertices: BoundaryVertex[]) => void;
/** 标记已保存 */
markSaved: () => void;
/** 撤销上一步操作 */
undo: () => void;
/** 是否可以撤销 */
canUndo: boolean;
}
/**
* 边界绘制Hook
*
* 功能:
* 1. 管理顶点数组
* 2. 管理编辑器模式(view/draw/edit)
* 3. 提供顶点增删改操作
* 4. 历史记录管理(撤销功能)
* 5. 未保存变更追踪
*/
export function useBoundaryDrawing(options: UseBoundaryDrawingOptions = {}): UseBoundaryDrawingReturn {
const { initialVertices = [] } = options;
// 顶点列表
const [vertices, setVerticesState] = useState<BoundaryVertex[]>(initialVertices);
// 编辑器状态
const [editorState, setEditorState] = useState<EditorState>({
mode: 'view',
selectedVertexIndex: null,
hasUnsavedChanges: false,
});
// 是否正在绘制
const [isDrawing, setIsDrawing] = useState(false);
// 历史记录栈(用于撤销)
const historyRef = useRef<BoundaryVertex[][]>([]);
const maxHistorySize = 50;
/**
* 保存历史记录
*/
const saveHistory = useCallback(() => {
historyRef.current.push([...vertices]);
if (historyRef.current.length > maxHistorySize) {
historyRef.current.shift();
}
}, [vertices]);
/**
* 更新顶点并标记未保存
*/
const updateVertices = useCallback((newVertices: BoundaryVertex[]) => {
saveHistory();
setVerticesState(newVertices);
setEditorState(prev => ({ ...prev, hasUnsavedChanges: true }));
}, [saveHistory]);
/**
* 设置编辑模式
*/
const setMode = useCallback((mode: EditorMode) => {
setEditorState(prev => ({ ...prev, mode }));
}, []);
/**
* 开始绘制
*/
const startDrawing = useCallback(() => {
console.log('[BoundaryDrawing] 开始绘制模式');
setIsDrawing(true);
setMode('draw');
setVerticesState([]);
setEditorState(prev => ({
...prev,
mode: 'draw',
selectedVertexIndex: null,
hasUnsavedChanges: false,
}));
historyRef.current = [];
console.log('[BoundaryDrawing] 绘制模式已激活,mode=draw');
}, [setMode]);
/**
* 结束绘制
*/
const finishDrawing = useCallback(() => {
if (vertices.length < 3) {
message.warning('至少需要3个顶点才能形成边界');
return;
}
setIsDrawing(false);
setMode('view');
setEditorState(prev => ({ ...prev, hasUnsavedChanges: true }));
message.success(`边界绘制完成,共${vertices.length}个顶点`);
}, [vertices.length, setMode]);
/**
* 添加顶点
*/
const addVertex = useCallback((point: { longitude: number; latitude: number }) => {
const newVertex: BoundaryVertex = {
longitude: point.longitude,
latitude: point.latitude,
};
updateVertices([...vertices, newVertex]);
}, [vertices, updateVertices]);
/**
* 更新顶点
*/
const updateVertex = useCallback((index: number, point: { longitude: number; latitude: number }) => {
if (index < 0 || index >= vertices.length) {
console.warn(`Invalid vertex index: ${index}`);
return;
}
const newVertices = [...vertices];
newVertices[index] = {
longitude: point.longitude,
latitude: point.latitude,
};
updateVertices(newVertices);
}, [vertices, updateVertices]);
/**
* 删除顶点
*/
const deleteVertex = useCallback((index: number) => {
if (index < 0 || index >= vertices.length) {
console.warn(`Invalid vertex index: ${index}`);
return;
}
if (vertices.length <= 3) {
message.warning('边界至少需要3个顶点');
return;
}
const newVertices = vertices.filter((_, i) => i !== index);
updateVertices(newVertices);
setEditorState(prev => ({ ...prev, selectedVertexIndex: null }));
}, [vertices, updateVertices]);
/**
* 移动顶点(别名)
*/
const moveVertex = useCallback((index: number, point: { longitude: number; latitude: number }) => {
updateVertex(index, point);
}, [updateVertex]);
/**
* 选择顶点
*/
const selectVertex = useCallback((index: number | null) => {
setEditorState(prev => ({ ...prev, selectedVertexIndex: index }));
}, []);
/**
* 清空所有顶点
*/
const clearVertices = useCallback(() => {
if (vertices.length === 0) return;
saveHistory();
setVerticesState([]);
setIsDrawing(false);
setEditorState({
mode: 'view',
selectedVertexIndex: null,
hasUnsavedChanges: false,
});
historyRef.current = [];
}, [vertices.length, saveHistory]);
/**
* 设置顶点列表(加载已有边界)
*/
const setVertices = useCallback((newVertices: BoundaryVertex[]) => {
setVerticesState(newVertices);
historyRef.current = [];
setEditorState(prev => ({ ...prev, hasUnsavedChanges: false }));
}, []);
/**
* 标记已保存
*/
const markSaved = useCallback(() => {
setEditorState(prev => ({ ...prev, hasUnsavedChanges: false }));
}, []);
/**
* 撤销上一步操作
*/
const undo = useCallback(() => {
if (historyRef.current.length === 0) {
message.info('没有可撤销的操作');
return;
}
const lastState = historyRef.current.pop();
if (lastState) {
setVerticesState(lastState);
setEditorState(prev => ({ ...prev, hasUnsavedChanges: true }));
}
}, []);
const canUndo = historyRef.current.length > 0;
return {
vertices,
editorState,
isDrawing,
setMode,
startDrawing,
finishDrawing,
addVertex,
updateVertex,
deleteVertex,
moveVertex,
selectVertex,
clearVertices,
setVertices,
markSaved,
undo,
canUndo,
};
}
@@ -0,0 +1,537 @@
/**
* Cesium边界渲染Hook
* 负责在Cesium地图上渲染和管理水域边界的可视化
* @author Claude
* @date 2026-01-06
*/
import { useEffect, useRef, useCallback } from 'react';
import type { BoundaryVertex, BoundaryType, EditorMode } from '../types';
interface UseCesiumBoundaryRendererOptions {
viewerRef: React.RefObject<any>;
vertices: BoundaryVertex[];
selectedIndex: number | null;
mode: EditorMode;
boundaryType: BoundaryType;
onVertexAdd: (point: { longitude: number; latitude: number }) => void;
onVertexMove: (index: number, point: { longitude: number; latitude: number }) => void;
onVertexSelect: (index: number) => void;
}
/**
* 获取边界类型对应的颜色
*/
function getBoundaryColor(type: BoundaryType, Cesium: any) {
switch (type) {
case 'navigable': // 可通行 - 绿色
return Cesium.Color.fromCssColorString('#00ff00');
case 'forbidden': // 禁行 - 红色
return Cesium.Color.fromCssColorString('#ff0000');
case 'warning': // 警告 - 黄色
return Cesium.Color.fromCssColorString('#ffff00');
default:
return Cesium.Color.fromCssColorString('#00ff00');
}
}
/**
* 获取边界类型对应的透明度
*/
function getBoundaryAlpha(type: BoundaryType): number {
switch (type) {
case 'navigable':
return 0.2;
case 'forbidden':
return 0.3;
case 'warning':
return 0.2;
default:
return 0.2;
}
}
/**
* Cesium边界渲染Hook
*
* 功能:
* 1. 渲染边界多边形(polygon)
* 2. 渲染顶点marker(可拖动)
* 3. 处理地图点击事件(添加顶点)
* 4. 处理顶点拖动交互
* 5. 相机聚焦到边界
* 6. 内存泄漏防范
*/
export function useCesiumBoundaryRenderer(options: UseCesiumBoundaryRendererOptions) {
const {
viewerRef,
vertices,
selectedIndex,
mode,
boundaryType,
onVertexAdd,
onVertexMove,
onVertexSelect,
} = options;
// Entity ID集合,用于清理
const entityIdsRef = useRef<Set<string>>(new Set());
// 事件处理器引用
const handlerRef = useRef<any>(null);
// 拖动状态
const draggingEntityRef = useRef<any>(null);
const rafIdRef = useRef<number | null>(null);
/**
* 获取Cesium对象
*/
const getCesium = useCallback(() => {
return (window as any).Cesium;
}, []);
/**
* 清理所有Entity
*/
const cleanup = useCallback(() => {
const viewer = viewerRef.current;
if (!viewer || viewer.isDestroyed?.()) return;
entityIdsRef.current.forEach(id => {
try {
viewer.entities.removeById(id);
} catch (e) {
// 忽略删除失败
}
});
entityIdsRef.current.clear();
}, [viewerRef]);
/**
* 渲染边界多边形
*/
const renderPolygon = useCallback(() => {
const viewer = viewerRef.current;
const Cesium = getCesium();
if (!viewer || !Cesium || viewer.isDestroyed?.()) return;
if (vertices.length < 3) return; // 至少3个顶点才能形成多边形
const positions = vertices.map(v =>
Cesium.Cartesian3.fromDegrees(v.longitude, v.latitude, 0)
);
const baseColor = getBoundaryColor(boundaryType, Cesium);
const alpha = getBoundaryAlpha(boundaryType);
const entityId = 'boundary-polygon';
try {
viewer.entities.add({
id: entityId,
polygon: {
hierarchy: new Cesium.PolygonHierarchy(positions),
material: baseColor.withAlpha(alpha),
outline: true,
outlineColor: baseColor,
outlineWidth: 3,
classificationType: Cesium.ClassificationType.BOTH,
}
});
entityIdsRef.current.add(entityId);
} catch (e) {
console.error('添加边界多边形失败:', e);
}
}, [viewerRef, vertices, boundaryType, getCesium]);
/**
* 渲染顶点Marker
*/
const renderVertices = useCallback(() => {
const viewer = viewerRef.current;
const Cesium = getCesium();
if (!viewer || !Cesium || viewer.isDestroyed?.()) return;
vertices.forEach((v, index) => {
const isSelected = index === selectedIndex;
const entityId = `boundary-vertex-${index}`;
try {
const entity = viewer.entities.add({
id: entityId,
position: Cesium.Cartesian3.fromDegrees(v.longitude, v.latitude, 0),
point: {
pixelSize: isSelected ? 14 : 10,
color: isSelected ? Cesium.Color.YELLOW : Cesium.Color.WHITE,
outlineColor: Cesium.Color.BLACK,
outlineWidth: 2,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
},
label: {
text: `${index + 1}`,
font: isSelected ? '13px sans-serif' : '11px sans-serif',
fillColor: Cesium.Color.WHITE,
style: Cesium.LabelStyle.FILL_AND_OUTLINE,
outlineWidth: 2,
outlineColor: Cesium.Color.BLACK,
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
pixelOffset: new Cesium.Cartesian2(0, -15),
disableDepthTestDistance: Number.POSITIVE_INFINITY,
},
properties: {
type: 'boundary-vertex',
vertexIndex: index,
draggable: true,
}
});
entityIdsRef.current.add(entityId);
} catch (e) {
console.error('添加顶点entity失败:', e);
}
});
}, [viewerRef, vertices, selectedIndex, getCesium]);
/**
* 设置事件处理器
*/
const setupEventHandlers = useCallback(() => {
const viewer = viewerRef.current;
const Cesium = getCesium();
console.log('[BoundaryRenderer] setupEventHandlers 调试信息:', {
hasViewer: !!viewer,
hasCesium: !!Cesium,
viewerType: typeof viewer,
cesiumType: typeof Cesium,
isDestroyed: viewer?.isDestroyed?.(),
});
if (!viewer || !Cesium || viewer.isDestroyed?.()) {
console.error('[BoundaryRenderer] ❌ 初始化失败:', {
viewer: !!viewer,
Cesium: !!Cesium,
isDestroyed: viewer?.isDestroyed?.(),
});
return;
}
// 检查 screenSpaceEventController 是否存在
if (!viewer.scene?.screenSpaceEventController) {
// 尝试查找 screenSpaceEventController 的所有可能位置
const allSceneKeys = viewer.scene ? Object.keys(viewer.scene) : [];
const controllerKey = allSceneKeys.find(key => key.toLowerCase().includes('controller') || key.toLowerCase().includes('event'));
console.error('[BoundaryRenderer] screenSpaceEventController 不可用,调试信息:', {
hasScene: !!viewer.scene,
hasController: !!viewer.scene?.screenSpaceEventController,
allSceneKeys: allSceneKeys,
matchingKeys: allSceneKeys.filter(k => k.includes('screen') || k.includes('event') || k.includes('controller')),
// 尝试其他可能的路径
alternativePaths: {
'_screenSpaceEventController': !!viewer.scene?._screenSpaceEventController,
'screenSpaceEventHandler': !!viewer.scene?.screenSpaceEventHandler,
'_screenSpaceEventHandler': !!viewer.scene?._screenSpaceEventHandler,
}
});
return;
}
console.log('[BoundaryRenderer] ✓ 事件处理器初始化, mode=', mode);
// 启用深度测试,确保可以正确拾取3D模型上的点
try {
viewer.scene.globe.depthTestAgainstTerrain = true;
console.log('[BoundaryEditor] 已启用深度测试,支持在3D模型上绘制');
} catch (e) {
console.warn('[BoundaryEditor] 启用深度测试失败:', e);
}
// 清理旧的handler
if (handlerRef.current) {
try {
handlerRef.current.destroy();
} catch (e) {}
handlerRef.current = null;
}
const handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
handlerRef.current = handler;
// 根据模式设置不同的交互
if (mode === 'draw') {
console.log('[BoundaryRenderer] ✓ 进入绘制模式,设置十字光标');
// 绘制模式:点击地图添加顶点
try {
viewer.scene.screenSpaceEventController.enableRotate = false;
} catch (e) {
console.warn('禁用旋转失败:', e);
}
// 设置绘制模式光标 - 使用setProperty强制覆盖
viewer.scene.canvas.style.setProperty('cursor', 'crosshair', 'important');
console.log('[BoundaryRenderer] 光标已设置为 crosshair, 当前值=', viewer.scene.canvas.style.cursor);
handler.setInputAction((movement: any) => {
// 优先使用 pickPosition 获取点击位置(支持3D模型和地形)
let cartesian = viewer.scene.pickPosition(movement.position);
// 如果 pickPosition 失败(例如点击天空),尝试使用 globe.pick
if (!cartesian) {
const ray = viewer.camera.getPickRay(movement.position);
cartesian = viewer.scene.globe.pick(ray, viewer.scene);
}
if (cartesian) {
const cartographic = Cesium.Cartographic.fromCartesian(cartesian);
const longitude = Cesium.Math.toDegrees(cartographic.longitude);
const latitude = Cesium.Math.toDegrees(cartographic.latitude);
const height = cartographic.height;
console.log('[BoundaryEditor] ✓ 添加顶点:', {
longitude: longitude.toFixed(6),
latitude: latitude.toFixed(6),
height: height.toFixed(2) + 'm'
});
onVertexAdd({ longitude, latitude });
} else {
console.warn('[BoundaryEditor] ✗ 未能获取点击位置,请确保点击在地图或模型上');
}
}, Cesium.ScreenSpaceEventType.LEFT_CLICK);
// 双击结束绘制(由组件层处理)
// handler.setInputAction(() => {
// // 触发结束绘制
// }, Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
} else if (mode === 'edit') {
// 编辑模式:支持拖动和选择
try {
viewer.scene.screenSpaceEventController.enableRotate = true;
} catch (e) {
console.warn('启用旋转失败:', e);
}
// 设置编辑模式光标
viewer.scene.canvas.style.setProperty('cursor', 'pointer', 'important');
// LEFT_DOWN: 开始拖拽或选择
handler.setInputAction((movement: any) => {
const pickedObject = viewer.scene.pick(movement.position);
if (Cesium.defined(pickedObject) && pickedObject.id) {
const entity = pickedObject.id;
const properties = entity.properties;
if (properties?.type?.getValue() === 'boundary-vertex') {
const vertexIndex = properties.vertexIndex?.getValue();
if (typeof vertexIndex === 'number') {
// 选择顶点
onVertexSelect(vertexIndex);
// 准备拖动
if (properties.draggable?.getValue()) {
draggingEntityRef.current = entity;
viewer.scene.canvas.style.setProperty('cursor', 'grabbing', 'important'); // 拖动光标
try {
viewer.scene.screenSpaceEventController.enableRotate = false;
} catch (e) {
console.warn('禁用旋转失败:', e);
}
}
}
}
}
}, Cesium.ScreenSpaceEventType.LEFT_DOWN);
// MOUSE_MOVE: 拖拽中(使用requestAnimationFrame节流)
handler.setInputAction((movement: any) => {
if (draggingEntityRef.current && !rafIdRef.current) {
rafIdRef.current = requestAnimationFrame(() => {
const entity = draggingEntityRef.current;
if (!entity) {
rafIdRef.current = null;
return;
}
const ray = viewer.camera.getPickRay(movement.endPosition);
const cartesian = viewer.scene.globe.pick(ray, viewer.scene);
if (cartesian) {
// 更新entity位置
entity.position = cartesian;
// 通知外部更新vertex数据
const cartographic = Cesium.Cartographic.fromCartesian(cartesian);
const vertexIndex = entity.properties?.vertexIndex?.getValue();
if (typeof vertexIndex === 'number') {
onVertexMove(vertexIndex, {
longitude: Cesium.Math.toDegrees(cartographic.longitude),
latitude: Cesium.Math.toDegrees(cartographic.latitude),
});
}
}
rafIdRef.current = null;
});
}
}, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
// LEFT_UP: 结束拖拽
handler.setInputAction(() => {
if (draggingEntityRef.current) {
viewer.scene.canvas.style.setProperty('cursor', 'pointer', 'important'); // 恢复指针光标
try {
viewer.scene.screenSpaceEventController.enableRotate = true;
} catch (e) {
console.warn('启用旋转失败:', e);
}
draggingEntityRef.current = null;
}
}, Cesium.ScreenSpaceEventType.LEFT_UP);
} else {
// view模式:恢复默认交互
try {
viewer.scene.screenSpaceEventController.enableRotate = true;
} catch (e) {
console.warn('启用旋转失败:', e);
}
// 恢复默认光标
viewer.scene.canvas.style.setProperty('cursor', 'default', 'important');
}
}, [viewerRef, mode, getCesium, onVertexAdd, onVertexMove, onVertexSelect]);
/**
* 计算边界范围
*/
const calculateBounds = useCallback((points: BoundaryVertex[]) => {
if (points.length === 0) {
return { west: 0, south: 0, east: 0, north: 0 };
}
let west = points[0].longitude;
let east = points[0].longitude;
let south = points[0].latitude;
let north = points[0].latitude;
points.forEach(p => {
west = Math.min(west, p.longitude);
east = Math.max(east, p.longitude);
south = Math.min(south, p.latitude);
north = Math.max(north, p.latitude);
});
// 添加一些padding
const paddingLon = (east - west) * 0.1 || 0.01;
const paddingLat = (north - south) * 0.1 || 0.01;
return {
west: west - paddingLon,
south: south - paddingLat,
east: east + paddingLon,
north: north + paddingLat,
};
}, []);
/**
* 相机飞到边界
*/
const flyToBoundary = useCallback(() => {
const viewer = viewerRef.current;
const Cesium = getCesium();
if (!viewer || !Cesium || viewer.isDestroyed?.() || vertices.length === 0) return;
const bounds = calculateBounds(vertices);
try {
viewer.camera.flyTo({
destination: Cesium.Rectangle.fromDegrees(
bounds.west,
bounds.south,
bounds.east,
bounds.north
),
duration: 1.0,
});
} catch (e) {
console.error('飞到边界失败:', e);
}
}, [viewerRef, vertices, getCesium, calculateBounds]);
/**
* 渲染所有内容
*/
const render = useCallback(() => {
cleanup();
renderPolygon();
renderVertices();
}, [cleanup, renderPolygon, renderVertices]);
// vertices或selectedIndex变化时重新渲染
useEffect(() => {
render();
}, [vertices, selectedIndex, boundaryType, render]);
// mode变化时重新设置事件处理器
useEffect(() => {
setupEventHandlers();
}, [mode, setupEventHandlers]);
// 组件挂载时飞到边界(仅执行一次)
useEffect(() => {
if (vertices.length > 0) {
// 延迟执行,确保viewer已准备好
setTimeout(() => {
flyToBoundary();
}, 300);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []); // 空依赖数组,只在挂载时执行
// 组件卸载时清理
useEffect(() => {
return () => {
cleanup();
// 清理事件处理器
if (handlerRef.current) {
try {
handlerRef.current.destroy();
} catch (e) {}
handlerRef.current = null;
}
// 取消pending的RAF
if (rafIdRef.current) {
cancelAnimationFrame(rafIdRef.current);
rafIdRef.current = null;
}
// 恢复地图旋转(增加完整检查)
const viewer = viewerRef.current;
if (viewer && !viewer.isDestroyed?.() && viewer.scene?.screenSpaceEventController) {
try {
viewer.scene.screenSpaceEventController.enableRotate = true;
// 恢复默认光标
if (viewer.scene.canvas) {
viewer.scene.canvas.style.setProperty('cursor', 'default', 'important');
}
} catch (e) {
// 忽略清理失败
console.warn('恢复地图旋转失败:', e);
}
}
};
}, [cleanup, viewerRef]);
return {
cleanup,
render,
flyToBoundary,
};
}
@@ -0,0 +1,99 @@
.editor {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
pointer-events: none; // 允许点击穿透到地图
z-index: 900;
// 子元素需要恢复点击事件
> * {
pointer-events: auto;
}
}
.toolbar {
display: flex;
align-items: center;
padding: 8px 12px;
background: rgba(255, 255, 255, 0.95);
border-radius: 4px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}
.divider {
width: 1px;
height: 24px;
background: #e8e8e8;
margin: 0 8px;
}
.preview {
width: 280px;
max-height: 400px;
overflow-y: auto;
}
.saveModal {
:global {
.ant-modal-body {
padding: 24px;
}
}
}
.vertexMarker {
width: 20px;
height: 20px;
border-radius: 50%;
background: #fff;
border: 2px solid #000;
display: flex;
align-items: center;
justify-content: center;
color: #000;
font-size: 11px;
font-weight: bold;
cursor: pointer;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
transition: transform 0.2s;
&:hover {
transform: scale(1.2);
}
&.selected {
background: #faad14;
transform: scale(1.3);
}
}
.boundaryPolygon {
&.navigable {
fill: rgba(0, 255, 0, 0.2);
stroke: #00ff00;
stroke-width: 3;
}
&.forbidden {
fill: rgba(255, 0, 0, 0.3);
stroke: #ff0000;
stroke-width: 3;
}
&.warning {
fill: rgba(255, 255, 0, 0.2);
stroke: #ffff00;
stroke-width: 3;
}
}
.tip {
padding: 8px 12px;
background: rgba(0, 0, 0, 0.7);
color: #fff;
border-radius: 4px;
font-size: 12px;
margin-top: 8px;
}
@@ -0,0 +1,344 @@
/**
* 水域边界编辑器主组件
* @author Claude
* @date 2026-01-06
*/
import React, { useState, useEffect, useCallback } from 'react';
import { Modal, Form, Input, Select, message, Spin } from 'antd';
import type { BoundaryEditorProps, BoundaryType, BoundaryVertex } from './types';
import { useBoundaryDrawing } from './hooks/useBoundaryDrawing';
import { useCesiumBoundaryRenderer } from './hooks/useCesiumBoundaryRenderer';
import BoundaryToolbar from './BoundaryToolbar';
import BoundaryPreview from './BoundaryPreview';
import {
createWaterBoundary,
updateWaterBoundary,
getWaterBoundaryDetail,
} from '@/services/waterBoundary';
import styles from './index.less';
const { Option } = Select;
const BoundaryEditor: React.FC<BoundaryEditorProps> = ({
scenicId,
boundaryId,
initialVertices,
onSaveSuccess,
onCancel,
viewerRef,
}) => {
const [loading, setLoading] = useState(false);
const [saveModalVisible, setSaveModalVisible] = useState(false);
const [boundaryType, setBoundaryType] = useState<BoundaryType>('navigable');
const [form] = Form.useForm();
// 边界绘制Hook
const {
vertices,
editorState,
isDrawing,
setMode,
startDrawing,
finishDrawing,
addVertex,
moveVertex,
selectVertex,
clearVertices,
setVertices,
markSaved,
} = useBoundaryDrawing({ initialVertices });
// Cesium边界渲染Hook
useCesiumBoundaryRenderer({
viewerRef,
vertices,
selectedIndex: editorState.selectedVertexIndex,
mode: editorState.mode,
boundaryType,
onVertexAdd: handleMapClick,
onVertexMove: moveVertex,
onVertexSelect: selectVertex,
});
// 加载现有边界
useEffect(() => {
if (boundaryId) {
loadBoundary(boundaryId);
}
}, [boundaryId]);
const loadBoundary = async (id: string) => {
setLoading(true);
try {
const response = await getWaterBoundaryDetail(id);
if (response.resp_code === 0 && response.datas) {
const boundary = response.datas;
// 设置表单值
form.setFieldsValue({
boundaryName: boundary.boundaryName,
boundaryType: boundary.boundaryType,
remark: boundary.remark,
});
setBoundaryType(boundary.boundaryType);
// 解析GeoJSON并设置顶点
try {
const geoJson = JSON.parse(boundary.geoJson);
if (geoJson.type === 'Polygon' && geoJson.coordinates && geoJson.coordinates[0]) {
const coords = geoJson.coordinates[0];
const verts: BoundaryVertex[] = coords.map((coord: number[]) => ({
longitude: coord[0],
latitude: coord[1],
}));
// 移除最后一个点(GeoJSON的闭合点)
if (verts.length > 1) {
verts.pop();
}
setVertices(verts);
}
} catch (e) {
console.error('解析边界GeoJSON失败:', e);
message.error('加载边界数据失败');
}
}
} catch (error) {
message.error('加载边界失败');
} finally {
setLoading(false);
}
};
// 处理地图点击
function handleMapClick(event: { longitude: number; latitude: number }) {
if (editorState.mode === 'draw') {
addVertex(event);
}
}
// 处理模式切换
const handleModeChange = useCallback((mode: 'view' | 'draw' | 'edit') => {
setMode(mode);
if (mode !== 'edit') {
selectVertex(null);
}
}, [setMode, selectVertex]);
// 打开保存对话框
const handleOpenSaveModal = useCallback(() => {
if (vertices.length < 3) {
message.warning('边界至少需要3个顶点');
return;
}
setSaveModalVisible(true);
}, [vertices]);
// 处理保存
const handleSave = useCallback(async () => {
try {
const values = await form.validateFields();
if (vertices.length < 3) {
message.warning('边界至少需要3个顶点');
return;
}
setLoading(true);
// 构造GeoJSON
// GeoJSON Polygon格式要求第一个点和最后一个点相同(闭合)
const coordinates = [
...vertices.map(v => [v.longitude, v.latitude]),
[vertices[0].longitude, vertices[0].latitude], // 闭合多边形
];
const geoJson = JSON.stringify({
type: 'Polygon',
coordinates: [coordinates],
});
// 计算中心点
const centerLongitude =
vertices.reduce((sum, v) => sum + v.longitude, 0) / vertices.length;
const centerLatitude =
vertices.reduce((sum, v) => sum + v.latitude, 0) / vertices.length;
// TODO: 计算面积(可选)
const area = 0;
if (boundaryId) {
// 更新边界
const updateData = {
boundaryName: values.boundaryName,
boundaryType: values.boundaryType,
geoJson,
centerLongitude,
centerLatitude,
area,
remark: values.remark,
};
const response = await updateWaterBoundary(boundaryId, updateData);
if (response.resp_code === 0) {
message.success('边界更新成功');
markSaved();
setSaveModalVisible(false);
onSaveSuccess?.(boundaryId);
} else {
message.error(response.resp_msg || '更新失败');
}
} else {
// 创建边界
const createData = {
scenicId,
boundaryName: values.boundaryName,
boundaryType: values.boundaryType,
geoJson,
centerLongitude,
centerLatitude,
area,
remark: values.remark,
};
const response = await createWaterBoundary(createData);
if (response.resp_code === 0 && response.datas) {
message.success('边界创建成功');
markSaved();
setSaveModalVisible(false);
onSaveSuccess?.(response.datas);
} else {
message.error(response.resp_msg || '创建失败');
}
}
} catch (error) {
console.error('保存边界失败:', error);
} finally {
setLoading(false);
}
}, [form, vertices, boundaryId, scenicId, markSaved, onSaveSuccess]);
// 处理取消
const handleCancel = useCallback(() => {
if (editorState.hasUnsavedChanges) {
Modal.confirm({
title: '确认关闭?',
content: '有未保存的更改,确定要关闭编辑器吗?',
onOk: () => {
onCancel?.();
},
});
} else {
onCancel?.();
}
}, [editorState.hasUnsavedChanges, onCancel]);
// ESC键监听
useEffect(() => {
const handleEsc = (e: KeyboardEvent) => {
if (e.key === 'Escape') {
if (isDrawing) {
finishDrawing();
}
}
};
window.addEventListener('keydown', handleEsc);
return () => {
window.removeEventListener('keydown', handleEsc);
};
}, [isDrawing, finishDrawing]);
return (
<div className={styles.editor}>
{/* 工具栏 - 独立渲染,不受Spin影响 */}
<BoundaryToolbar
mode={editorState.mode}
hasVertices={vertices.length > 0}
hasUnsavedChanges={editorState.hasUnsavedChanges}
isDrawing={isDrawing}
onModeChange={handleModeChange}
onStartDraw={startDrawing}
onFinishDraw={finishDrawing}
onClear={clearVertices}
onSave={handleOpenSaveModal}
onCancel={handleCancel}
/>
{/* 预览面板 - 独立渲染,不受Spin影响 */}
{vertices.length > 0 && (
<BoundaryPreview
vertices={vertices}
boundaryType={boundaryType}
/>
)}
{/* 保存对话框 - 带Loading */}
<Modal
title={boundaryId ? '更新边界' : '保存边界'}
open={saveModalVisible}
onOk={handleSave}
onCancel={() => setSaveModalVisible(false)}
confirmLoading={loading}
width={480}
className={styles.saveModal}
>
<Form
form={form}
layout="vertical"
initialValues={{
boundaryType: 'navigable',
}}
>
<Form.Item
name="boundaryName"
label="边界名称"
rules={[{ required: true, message: '请输入边界名称' }]}
>
<Input placeholder="请输入边界名称" />
</Form.Item>
<Form.Item
name="boundaryType"
label="边界类型"
rules={[{ required: true, message: '请选择边界类型' }]}
>
<Select
placeholder="请选择边界类型"
onChange={(value) => setBoundaryType(value as BoundaryType)}
>
<Option value="navigable">可通行区域</Option>
<Option value="forbidden">禁止通行</Option>
<Option value="warning">警告区域</Option>
</Select>
</Form.Item>
<Form.Item name="remark" label="备注">
<Input.TextArea rows={2} placeholder="可选备注信息" />
</Form.Item>
<Form.Item label="边界信息" style={{ marginBottom: 0 }}>
<div style={{ color: 'rgba(0, 0, 0, 0.45)', fontSize: 12 }}>
顶点数量: {vertices.length}
</div>
</Form.Item>
</Form>
</Modal>
{/* 全局Loading遮罩 - 仅在加载时显示 */}
{loading && (
<div style={{
position: 'fixed',
top: 0,
left: 0,
right: 0,
bottom: 0,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
background: 'rgba(0, 0, 0, 0.3)',
zIndex: 1001,
}}>
<Spin size="large" tip="加载中..." />
</div>
)}
</div>
);
};
export default BoundaryEditor;
@@ -0,0 +1,120 @@
/**
* 水域边界编辑器类型定义
* @author Claude
* @date 2026-01-06
*/
/**
* 边界类型
*/
export type BoundaryType = 'navigable' | 'forbidden' | 'warning';
/**
* 边界顶点
*/
export interface BoundaryVertex {
longitude: number;
latitude: number;
}
/**
* 编辑器模式
*/
export type EditorMode = 'view' | 'draw' | 'edit';
/**
* 边界编辑器状态
*/
export interface EditorState {
mode: EditorMode;
selectedVertexIndex: number | null;
hasUnsavedChanges: boolean;
}
/**
* 边界创建DTO(对应后端)
*/
export interface WaterBoundaryCreateDTO {
scenicId: number;
boundaryName: string;
boundaryType: BoundaryType;
geoJson: string;
centerLongitude?: number;
centerLatitude?: number;
area?: number;
remark?: string;
}
/**
* 边界更新DTO(对应后端)
*/
export interface WaterBoundaryUpdateDTO {
boundaryName?: string;
boundaryType?: BoundaryType;
geoJson?: string;
centerLongitude?: number;
centerLatitude?: number;
area?: number;
remark?: string;
}
/**
* 边界详情VO(对应后端)
*/
export interface WaterBoundaryVO {
id: string;
scenicId: number;
boundaryName: string;
boundaryType: BoundaryType;
geoJson: string;
centerLongitude: number;
centerLatitude: number;
area: number;
vertexCount: number;
remark?: string;
createTime: string;
updateTime: string;
}
/**
* BoundaryEditor组件Props
*/
export interface BoundaryEditorProps {
/** 景区ID */
scenicId: number;
/** 编辑已有边界的ID(可选) */
boundaryId?: string;
/** 初始顶点(可选) */
initialVertices?: BoundaryVertex[];
/** 保存成功回调 */
onSaveSuccess?: (boundaryId: string) => void;
/** 取消回调 */
onCancel?: () => void;
/** Cesium Viewer引用 */
viewerRef: React.RefObject<any>;
}
/**
* 边界工具栏Props
*/
export interface BoundaryToolbarProps {
mode: EditorMode;
hasVertices: boolean;
hasUnsavedChanges: boolean;
isDrawing: boolean;
onModeChange: (mode: EditorMode) => void;
onStartDraw: () => void;
onFinishDraw: () => void;
onClear: () => void;
onSave: () => void;
onCancel: () => void;
}
/**
* 边界预览Props
*/
export interface BoundaryPreviewProps {
vertices: BoundaryVertex[];
boundaryType: BoundaryType;
area?: number;
}
@@ -0,0 +1,98 @@
.boatRouteTab {
padding: 0 4px;
}
.section {
margin-bottom: 16px;
}
.sectionHeader {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 8px;
}
.sectionTitle {
font-size: 13px;
font-weight: 500;
color: #333;
margin-bottom: 8px;
}
.routeOption {
display: flex;
align-items: center;
justify-content: space-between;
width: 100%;
}
.routeDetail {
background: #f5f5f5;
border-radius: 4px;
padding: 12px;
margin-bottom: 8px;
}
.detailRow {
display: flex;
justify-content: space-between;
align-items: center;
font-size: 12px;
color: #666;
& + & {
margin-top: 6px;
}
span:first-child {
color: #999;
}
span:last-child {
color: #333;
font-weight: 500;
}
}
.routeActions {
display: flex;
gap: 8px;
}
.deviceStatus {
display: flex;
align-items: center;
gap: 12px;
margin-bottom: 8px;
}
.battery {
display: flex;
align-items: center;
gap: 8px;
font-size: 12px;
color: #666;
}
.position {
display: flex;
align-items: center;
gap: 6px;
font-size: 12px;
color: #666;
:global(.anticon) {
color: #1890ff;
}
}
.controlButtons {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.emptyState {
padding: 24px 0;
}
@@ -0,0 +1,524 @@
/**
* 无人船航线Tab组件
* 用于在TaskPanel中显示无人船航线列表和操作
* @author dzc
* @date 2026-01-05
*/
import React, { useState, useEffect, useCallback, useMemo } from 'react';
import {
Button,
Select,
Tag,
Tooltip,
Empty,
Spin,
Modal,
message,
Progress,
Switch,
Space,
} from 'antd';
import {
PlusOutlined,
EditOutlined,
DeleteOutlined,
PlayCircleOutlined,
PauseCircleOutlined,
StopOutlined,
RollbackOutlined,
EnvironmentOutlined,
AimOutlined,
ReloadOutlined,
EyeOutlined,
} from '@ant-design/icons';
import { useCesiumBoatTrack } from '../hooks/useCesiumBoatTrack';
import type {
BoatRouteListVO,
BoatTelemetryData,
MissionType,
} from '@/types/boatRoute';
import {
getBoatRoutesByScenicId,
getBoatRoutesByDevice,
deleteBoatRoute,
} from '@/services/boatRoute';
import {
pauseBoatNavigation,
resumeBoatNavigation,
emergencyStopBoat,
returnBoatToStart,
} from '@/services/boatControl';
import { saveMission, executeMission } from '@/services/mission';
import styles from './BoatRouteTab.less';
interface BoatRouteTabProps {
deviceSn: string;
scenicId: number;
boatData?: BoatTelemetryData | null;
onEditRoute?: (routeId: string) => void;
onCreateRoute?: () => void;
viewerRef?: React.RefObject<any>; // Cesium viewer引用,用于实时轨迹渲染
}
const BoatRouteTab: React.FC<BoatRouteTabProps> = ({
deviceSn,
scenicId,
boatData,
onEditRoute,
onCreateRoute,
viewerRef,
}) => {
const [routeList, setRouteList] = useState<BoatRouteListVO[]>([]);
const [loading, setLoading] = useState(false);
const [selectedRouteId, setSelectedRouteId] = useState<string | null>(null);
const [executing, setExecuting] = useState(false);
// 实时跟踪状态
const [trackingEnabled, setTrackingEnabled] = useState(false);
// 使用无人船实时跟踪Hook
const { boatData: realtimeBoatData, clearTrack, flyToBoat } = useCesiumBoatTrack({
viewerRef: viewerRef || { current: null },
enabled: trackingEnabled,
deviceSn: trackingEnabled ? deviceSn : null,
});
// 加载航线列表
const loadRoutes = useCallback(async () => {
setLoading(true);
try {
const res = await getBoatRoutesByScenicId(scenicId, { page: 1, size: 50 });
if (res.resp_code === 0 && res.datas) {
// datas 可能直接是数组,也可能是分页对象
const routes = Array.isArray(res.datas) ? res.datas : (res.datas as any).records || [];
setRouteList(routes);
}
} catch (error) {
message.error('加载航线列表失败');
} finally {
setLoading(false);
}
}, [scenicId]);
useEffect(() => {
if (scenicId) {
loadRoutes();
}
}, [scenicId, loadRoutes]);
// 选中的航线
const selectedRoute = useMemo(() => {
return routeList.find((r) => r.routeId === selectedRouteId);
}, [routeList, selectedRouteId]);
// 设备状态
const deviceStatus = useMemo(() => {
return boatData?.status || 'unknown';
}, [boatData]);
const isExecuting = deviceStatus === 'executing';
const isPaused = deviceStatus === 'paused';
const isIdle = deviceStatus === 'idle' || deviceStatus === 'unknown';
// 创建并执行任务
const handleExecuteRoute = useCallback(async () => {
if (!selectedRouteId || !selectedRoute) {
message.warning('请先选择航线');
return;
}
Modal.confirm({
title: '确认执行航线',
content: (
<div>
<p>确定要执行航线 <strong>{selectedRoute.routeName}</strong> 吗?</p>
<p style={{ color: '#666', fontSize: 12 }}>
航点数: {selectedRoute.waypointCount} | 预计时长: {selectedRoute.totalDurationStr}
</p>
</div>
),
onOk: async () => {
setExecuting(true);
try {
// 1. 创建任务
const createRes = await saveMission({
deviceSn,
missionType: 3, // BOAT_ROUTE
boatRouteId: selectedRouteId,
boatRouteName: selectedRoute.routeName,
tourismId: scenicId,
});
if (createRes.resp_code !== 0) {
message.error(createRes.resp_msg || '创建任务失败');
return;
}
const missionCode = createRes.datas?.missionCode;
if (!missionCode) {
message.error('获取任务编码失败');
return;
}
// 2. 执行任务
const execRes = await executeMission(missionCode);
if (execRes.resp_code === 0) {
message.success('航线任务已下发执行');
} else {
message.error(execRes.resp_msg || '执行失败');
}
} catch (error) {
message.error('执行航线失败');
} finally {
setExecuting(false);
}
},
});
}, [selectedRouteId, selectedRoute, deviceSn, scenicId]);
// 暂停
const handlePause = useCallback(async () => {
try {
const res = await pauseBoatNavigation(deviceSn);
if (res.resp_code === 0) {
message.success('已暂停航行');
} else {
message.error(res.resp_msg || '操作失败');
}
} catch (error) {
message.error('操作失败');
}
}, [deviceSn]);
// 恢复
const handleResume = useCallback(async () => {
try {
const res = await resumeBoatNavigation(deviceSn);
if (res.resp_code === 0) {
message.success('已恢复航行');
} else {
message.error(res.resp_msg || '操作失败');
}
} catch (error) {
message.error('操作失败');
}
}, [deviceSn]);
// 返航
const handleReturn = useCallback(async () => {
Modal.confirm({
title: '确认返航',
content: '确定要让无人船返回起点吗?',
onOk: async () => {
try {
const res = await returnBoatToStart(deviceSn);
if (res.resp_code === 0) {
message.success('返航指令已下发');
} else {
message.error(res.resp_msg || '操作失败');
}
} catch (error) {
message.error('操作失败');
}
},
});
}, [deviceSn]);
// 紧急停止
const handleEmergencyStop = useCallback(async () => {
Modal.confirm({
title: '紧急停止',
content: '确定要紧急停止无人船吗?',
okType: 'danger',
okText: '紧急停止',
onOk: async () => {
try {
const res = await emergencyStopBoat(deviceSn);
if (res.resp_code === 0) {
message.warning('已紧急停止');
} else {
message.error(res.resp_msg || '操作失败');
}
} catch (error) {
message.error('操作失败');
}
},
});
}, [deviceSn]);
// 删除航线
const handleDeleteRoute = useCallback(
async (routeId: string) => {
const route = routeList.find((r) => r.routeId === routeId);
Modal.confirm({
title: '删除航线',
content: `确定要删除航线 "${route?.routeName}" 吗?`,
okType: 'danger',
onOk: async () => {
try {
const res = await deleteBoatRoute(routeId);
if (res.resp_code === 0) {
message.success('删除成功');
loadRoutes();
if (selectedRouteId === routeId) {
setSelectedRouteId(null);
}
} else {
message.error(res.resp_msg || '删除失败');
}
} catch (error) {
message.error('删除失败');
}
},
});
},
[routeList, selectedRouteId, loadRoutes]
);
return (
<div className={styles.boatRouteTab}>
{/* 航线选择 */}
<div className={styles.section}>
<div className={styles.sectionHeader}>
<span className={styles.sectionTitle}>选择航线</span>
<Tooltip title="刷新">
<Button
type="text"
icon={<ReloadOutlined />}
size="small"
onClick={loadRoutes}
loading={loading}
/>
</Tooltip>
</div>
<Select
placeholder="请选择航线"
style={{ width: '100%' }}
value={selectedRouteId}
onChange={setSelectedRouteId}
loading={loading}
allowClear
>
{routeList.map((route) => (
<Select.Option key={route.routeId} value={route.routeId}>
<div className={styles.routeOption}>
<span>{route.routeName}</span>
<Tag>{route.waypointCount}点</Tag>
</div>
</Select.Option>
))}
</Select>
</div>
{/* 航线详情 */}
{selectedRoute && (
<div className={styles.section}>
<div className={styles.sectionTitle}>航线详情</div>
<div className={styles.routeDetail}>
<div className={styles.detailRow}>
<span>航点数:</span>
<span>{selectedRoute.waypointCount}</span>
</div>
<div className={styles.detailRow}>
<span>总距离:</span>
<span>{(selectedRoute.totalDistance / 1000).toFixed(2)} km</span>
</div>
<div className={styles.detailRow}>
<span>预计时长:</span>
<span>{selectedRoute.totalDurationStr}</span>
</div>
<div className={styles.detailRow}>
<span>状态:</span>
<Tag color={selectedRoute.status === 1 ? 'success' : 'default'}>
{selectedRoute.statusDesc}
</Tag>
</div>
</div>
<div className={styles.routeActions}>
<Tooltip title="编辑航线">
<Button
icon={<EditOutlined />}
onClick={() => onEditRoute?.(selectedRoute.routeId)}
/>
</Tooltip>
<Tooltip title="删除航线">
<Button
icon={<DeleteOutlined />}
danger
onClick={() => handleDeleteRoute(selectedRoute.routeId)}
/>
</Tooltip>
</div>
</div>
)}
{/* 设备状态 */}
{boatData && (
<div className={styles.section}>
<div className={styles.sectionTitle}>无人船状态</div>
<div className={styles.deviceStatus}>
<Tag color={isExecuting ? 'processing' : isPaused ? 'warning' : 'default'}>
{isExecuting ? '执行中' : isPaused ? '已暂停' : '空闲'}
</Tag>
{boatData.battery !== undefined && (
<div className={styles.battery}>
<span>电量:</span>
<Progress
percent={boatData.battery}
size="small"
status={boatData.battery < 20 ? 'exception' : 'normal'}
style={{ width: 80 }}
/>
</div>
)}
</div>
{boatData.longitude && boatData.latitude && (
<div className={styles.position}>
<EnvironmentOutlined />
<span>
{boatData.longitude.toFixed(6)}, {boatData.latitude.toFixed(6)}
</span>
</div>
)}
</div>
)}
{/* 实时跟踪 */}
{viewerRef && (
<div className={styles.section}>
<div className={styles.sectionHeader}>
<span className={styles.sectionTitle}>实时跟踪</span>
<Tooltip title={trackingEnabled ? '关闭实时跟踪' : '开启实时跟踪'}>
<Switch
checked={trackingEnabled}
onChange={(checked) => {
setTrackingEnabled(checked);
if (!checked) {
clearTrack();
}
}}
checkedChildren="已开启"
unCheckedChildren="已关闭"
/>
</Tooltip>
</div>
{trackingEnabled && realtimeBoatData && (
<div className={styles.trackingInfo}>
<div className={styles.detailRow}>
<span>航向:</span>
<span>{realtimeBoatData.heading?.toFixed(0) || '--'}°</span>
</div>
<div className={styles.detailRow}>
<span>速度:</span>
<span>{realtimeBoatData.speed?.toFixed(1) || '--'} m/s</span>
</div>
<div className={styles.detailRow}>
<span>电量:</span>
<span>{realtimeBoatData.battery || '--'}%</span>
</div>
<Tooltip title="飞到无人船位置">
<Button
size="small"
icon={<AimOutlined />}
onClick={flyToBoat}
style={{ marginTop: 8, width: '100%' }}
>
定位到船
</Button>
</Tooltip>
</div>
)}
{trackingEnabled && !realtimeBoatData && (
<div style={{ textAlign: 'center', padding: '12px 0', color: 'rgba(255,255,255,0.5)', fontSize: 12 }}>
等待接收遥测数据...
</div>
)}
</div>
)}
{/* 控制按钮 */}
<div className={styles.section}>
<div className={styles.sectionTitle}>操作</div>
<div className={styles.controlButtons}>
{isIdle && (
<Button
type="primary"
icon={<PlayCircleOutlined />}
block
onClick={handleExecuteRoute}
disabled={!selectedRouteId}
loading={executing}
>
执行航线
</Button>
)}
{isExecuting && (
<>
<Button
icon={<PauseCircleOutlined />}
onClick={handlePause}
style={{ flex: 1 }}
>
暂停
</Button>
<Button
icon={<RollbackOutlined />}
onClick={handleReturn}
style={{ flex: 1 }}
>
返航
</Button>
</>
)}
{isPaused && (
<>
<Button
type="primary"
icon={<PlayCircleOutlined />}
onClick={handleResume}
style={{ flex: 1 }}
>
恢复
</Button>
<Button
icon={<RollbackOutlined />}
onClick={handleReturn}
style={{ flex: 1 }}
>
返航
</Button>
</>
)}
{(isExecuting || isPaused) && (
<Button
danger
icon={<StopOutlined />}
onClick={handleEmergencyStop}
block
style={{ marginTop: 8 }}
>
紧急停止
</Button>
)}
</div>
</div>
{/* 新建航线按钮 */}
<div className={styles.section}>
<Button
type="dashed"
icon={<PlusOutlined />}
block
onClick={onCreateRoute}
>
新建航线
</Button>
</div>
</div>
);
};
export default BoatRouteTab;
@@ -0,0 +1,178 @@
.layerPanel {
position: absolute;
bottom: 20px;
left: 20px;
width: 320px;
max-height: 600px;
z-index: 100;
}
.card {
background: rgba(10, 20, 40, 0.95) !important;
border-radius: 8px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
border: 1px solid rgba(0, 240, 255, 0.3);
:global {
.ant-card-head {
color: #fff;
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
min-height: 40px;
padding: 0 12px;
}
.ant-card-head-title {
padding: 8px 0;
font-size: 14px;
font-weight: 500;
}
.ant-card-extra {
padding: 8px 0;
}
.ant-card-body {
padding: 12px;
max-height: 520px;
overflow-y: auto;
color: rgba(255, 255, 255, 0.85);
/* 自定义滚动条 */
&::-webkit-scrollbar {
width: 6px;
}
&::-webkit-scrollbar-track {
background: rgba(255, 255, 255, 0.05);
border-radius: 3px;
}
&::-webkit-scrollbar-thumb {
background: rgba(0, 240, 255, 0.3);
border-radius: 3px;
&:hover {
background: rgba(0, 240, 255, 0.5);
}
}
}
}
}
.section {
margin-bottom: 16px;
&:last-child {
margin-bottom: 0;
}
}
.sectionHeader {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 8px;
padding-bottom: 6px;
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}
.sectionTitle {
font-size: 13px;
font-weight: 500;
color: #fff;
}
.listItem {
display: flex;
align-items: center;
justify-content: space-between;
padding: 6px 0 !important;
border-bottom: 1px solid rgba(255, 255, 255, 0.05) !important;
&:last-child {
border-bottom: none !important;
}
:global {
.ant-checkbox-wrapper {
flex: 1;
color: rgba(255, 255, 255, 0.85);
&:hover {
color: #00f0ff;
}
}
.ant-checkbox-inner {
background-color: rgba(255, 255, 255, 0.1);
border-color: rgba(0, 240, 255, 0.5);
}
.ant-checkbox-checked .ant-checkbox-inner {
background-color: #00f0ff;
border-color: #00f0ff;
}
.ant-tag {
margin: 0;
font-size: 11px;
line-height: 18px;
padding: 0 6px;
}
}
}
.itemName {
font-size: 12px;
margin-left: 6px;
}
.loading {
text-align: center;
padding: 20px 0;
color: rgba(255, 255, 255, 0.5);
font-size: 12px;
}
.footer {
margin-top: 12px;
padding-top: 8px;
border-top: 1px solid rgba(255, 255, 255, 0.1);
font-size: 11px;
color: rgba(255, 255, 255, 0.5);
text-align: center;
}
/* 按钮样式覆盖 */
:global {
.layerPanel {
.ant-btn-link {
color: rgba(0, 240, 255, 0.8);
font-size: 12px;
padding: 0 4px;
height: auto;
&:hover {
color: #00f0ff;
}
&:disabled {
color: rgba(255, 255, 255, 0.3);
}
}
.ant-btn-text {
color: rgba(255, 255, 255, 0.7);
&:hover {
color: #00f0ff;
background: rgba(0, 240, 255, 0.1);
}
}
.ant-empty-description {
color: rgba(255, 255, 255, 0.4);
font-size: 12px;
}
}
}
@@ -0,0 +1,588 @@
/**
* 图层管理面板组件
* 用于管理航线、边界等图层的显示/隐藏
* @author Claude
* @date 2026-01-06
*/
import React, { useState, useEffect, useRef, useCallback } from 'react';
import { Card, Checkbox, List, Tag, Button, message, Empty, Tooltip, Space } from 'antd';
import {
CloseOutlined,
ReloadOutlined,
EyeOutlined,
EyeInvisibleOutlined,
PlusOutlined,
} from '@ant-design/icons';
import { getBoatRoutesByScenicId, getBoatRouteDetail } from '@/services/boatRoute';
import { getWaterBoundariesByScenicId } from '@/services/waterBoundary';
import type { BoatRouteListVO, RouteStatus } from '@/types/boatRoute';
import type { WaterBoundaryVO } from '@/pages/map3d/components/BoundaryEditor/types';
import styles from './LayerPanel.less';
export interface LayerPanelProps {
visible: boolean;
onClose: () => void;
viewer: any;
Cesium: any;
scenicId?: number;
onBoundaryEditorOpen?: () => void; // 新增:打开边界编辑器的回调
}
interface LayerEntity {
id: string;
entityIds: string[];
}
/**
* 获取边界类型颜色
*/
function getBoundaryColor(type: string, Cesium: any) {
switch (type) {
case 'navigable':
return Cesium.Color.fromCssColorString('#00ff00');
case 'forbidden':
return Cesium.Color.fromCssColorString('#ff0000');
case 'warning':
return Cesium.Color.fromCssColorString('#ffff00');
default:
return Cesium.Color.fromCssColorString('#00ff00');
}
}
/**
* 获取边界类型透明度
*/
function getBoundaryAlpha(type: string): number {
switch (type) {
case 'navigable':
return 0.2;
case 'forbidden':
return 0.3;
case 'warning':
return 0.2;
default:
return 0.2;
}
}
const LayerPanel: React.FC<LayerPanelProps> = ({
visible,
onClose,
viewer,
Cesium,
scenicId,
onBoundaryEditorOpen, // 新增
}) => {
// 航线列表
const [routes, setRoutes] = useState<BoatRouteListVO[]>([]);
const [loadingRoutes, setLoadingRoutes] = useState(false);
const [visibleRoutes, setVisibleRoutes] = useState<Set<string>>(new Set());
// 边界列表
const [boundaries, setBoundaries] = useState<WaterBoundaryVO[]>([]);
const [loadingBoundaries, setLoadingBoundaries] = useState(false);
const [visibleBoundaries, setVisibleBoundaries] = useState<Set<string>>(new Set());
// Entity引用管理
const routeEntitiesRef = useRef<Map<string, string[]>>(new Map());
const boundaryEntitiesRef = useRef<Map<string, string[]>>(new Map());
/**
* 加载航线列表
*/
const loadRoutes = useCallback(async () => {
if (!scenicId) return;
setLoadingRoutes(true);
try {
const response = await getBoatRoutesByScenicId(scenicId);
if (response.resp_code === 0 && response.datas) {
const routeList = Array.isArray(response.datas) ? response.datas : (response.datas as any).records || [];
setRoutes(routeList);
}
} catch (error) {
console.error('加载航线列表失败:', error);
message.error('加载航线列表失败');
} finally {
setLoadingRoutes(false);
}
}, [scenicId]);
/**
* 加载边界列表
*/
const loadBoundaries = useCallback(async () => {
if (!scenicId) return;
setLoadingBoundaries(true);
try {
const response = await getWaterBoundariesByScenicId(scenicId);
if (response.resp_code === 0 && response.datas) {
setBoundaries(response.datas);
}
} catch (error) {
console.error('加载边界列表失败:', error);
message.error('加载边界列表失败');
} finally {
setLoadingBoundaries(false);
}
}, [scenicId]);
/**
* 渲染航线
*/
const renderRoute = useCallback(async (route: BoatRouteListVO) => {
if (!viewer || !Cesium || viewer.isDestroyed?.()) return;
const entityIds: string[] = [];
try {
// 获取航线详情以获取航点数据
const detailResponse = await getBoatRouteDetail(route.routeId);
if (detailResponse.resp_code !== 0 || !detailResponse.datas) {
message.warning(`获取航线 [${route.routeName}] 详情失败`);
return;
}
const routeDetail = detailResponse.datas;
if (!routeDetail.waypoints || routeDetail.waypoints.length < 2) {
message.warning(`航线 [${route.routeName}] 航点不足`);
return;
}
// 渲染航点marker
routeDetail.waypoints.forEach((wp: any, i: number) => {
const entityId = `layer-route-${route.routeId}-wp-${i}`;
const entity = viewer.entities.add({
id: entityId,
position: Cesium.Cartesian3.fromDegrees(wp.longitude, wp.latitude, 0),
point: {
pixelSize: 8,
color: Cesium.Color.CYAN.withAlpha(0.7),
outlineColor: Cesium.Color.WHITE,
outlineWidth: 1,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
},
label: {
text: `${i + 1}`,
font: '10px sans-serif',
fillColor: Cesium.Color.WHITE,
style: Cesium.LabelStyle.FILL_AND_OUTLINE,
outlineWidth: 1,
outlineColor: Cesium.Color.BLACK,
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
pixelOffset: new Cesium.Cartesian2(0, -12),
disableDepthTestDistance: Number.POSITIVE_INFINITY,
},
properties: {
type: 'layer-route-waypoint',
routeId: route.routeId,
},
});
entityIds.push(entityId);
});
// 渲染航线polyline
const positions = routeDetail.waypoints.map((wp: any) =>
Cesium.Cartesian3.fromDegrees(wp.longitude, wp.latitude, 0)
);
const polylineId = `layer-route-${route.routeId}-path`;
viewer.entities.add({
id: polylineId,
polyline: {
positions: positions,
width: 3,
material: new Cesium.PolylineGlowMaterialProperty({
glowPower: 0.2,
color: Cesium.Color.CYAN.withAlpha(0.8),
}),
clampToGround: true,
},
properties: {
type: 'layer-route-path',
routeId: route.routeId,
},
});
entityIds.push(polylineId);
routeEntitiesRef.current.set(route.routeId, entityIds);
console.log(`航线 [${route.routeName}] 渲染成功`);
} catch (error) {
console.error(`渲染航线 [${route.routeName}] 失败:`, error);
message.error(`渲染航线失败`);
}
}, [viewer, Cesium]);
/**
* 移除航线
*/
const removeRoute = useCallback((routeId: string) => {
if (!viewer || viewer.isDestroyed?.()) return;
const entityIds = routeEntitiesRef.current.get(routeId);
if (entityIds) {
entityIds.forEach(id => {
try {
viewer.entities.removeById(id);
} catch (e) {
console.warn(`移除entity ${id} 失败:`, e);
}
});
routeEntitiesRef.current.delete(routeId);
}
}, [viewer]);
/**
* 渲染边界
*/
const renderBoundary = useCallback((boundary: WaterBoundaryVO) => {
if (!viewer || !Cesium || viewer.isDestroyed?.()) return;
const entityIds: string[] = [];
try {
// 解析GeoJSON
const geoJson = JSON.parse(boundary.geoJson);
if (geoJson.type !== 'Polygon' || !geoJson.coordinates || !geoJson.coordinates[0]) {
message.warning(`边界 [${boundary.boundaryName}] 数据格式错误`);
return;
}
const coordinates = geoJson.coordinates[0];
const positions = coordinates.map((coord: number[]) =>
Cesium.Cartesian3.fromDegrees(coord[0], coord[1], 0)
);
// 渲染多边形
const baseColor = getBoundaryColor(boundary.boundaryType, Cesium);
const alpha = getBoundaryAlpha(boundary.boundaryType);
const polygonId = `layer-boundary-${boundary.id}-polygon`;
viewer.entities.add({
id: polygonId,
polygon: {
hierarchy: new Cesium.PolygonHierarchy(positions),
material: baseColor.withAlpha(alpha),
outline: true,
outlineColor: baseColor,
outlineWidth: 2,
classificationType: Cesium.ClassificationType.BOTH,
},
properties: {
type: 'layer-boundary',
boundaryId: boundary.id,
},
});
entityIds.push(polygonId);
boundaryEntitiesRef.current.set(boundary.id, entityIds);
console.log(`边界 [${boundary.boundaryName}] 渲染成功`);
} catch (error) {
console.error(`渲染边界 [${boundary.boundaryName}] 失败:`, error);
message.error(`渲染边界失败`);
}
}, [viewer, Cesium]);
/**
* 移除边界
*/
const removeBoundary = useCallback((boundaryId: string) => {
if (!viewer || viewer.isDestroyed?.()) return;
const entityIds = boundaryEntitiesRef.current.get(boundaryId);
if (entityIds) {
entityIds.forEach(id => {
try {
viewer.entities.removeById(id);
} catch (e) {
console.warn(`移除entity ${id} 失败:`, e);
}
});
boundaryEntitiesRef.current.delete(boundaryId);
}
}, [viewer]);
/**
* 处理航线勾选变化
*/
const handleRouteCheckChange = useCallback((routeId: string, checked: boolean) => {
if (checked) {
// 检查是否超过最大显示数量
if (visibleRoutes.size >= 5) {
message.warning('最多同时显示5条航线,请先取消勾选其他航线');
return;
}
const route = routes.find(r => r.routeId === routeId);
if (route) {
renderRoute(route);
setVisibleRoutes(prev => new Set(prev).add(routeId));
}
} else {
removeRoute(routeId);
setVisibleRoutes(prev => {
const newSet = new Set(prev);
newSet.delete(routeId);
return newSet;
});
}
}, [visibleRoutes, routes, renderRoute, removeRoute]);
/**
* 处理边界勾选变化
*/
const handleBoundaryCheckChange = useCallback((boundaryId: string, checked: boolean) => {
if (checked) {
const boundary = boundaries.find(b => b.id === boundaryId);
if (boundary) {
renderBoundary(boundary);
setVisibleBoundaries(prev => new Set(prev).add(boundaryId));
}
} else {
removeBoundary(boundaryId);
setVisibleBoundaries(prev => {
const newSet = new Set(prev);
newSet.delete(boundaryId);
return newSet;
});
}
}, [boundaries, renderBoundary, removeBoundary]);
/**
* 刷新数据
*/
const handleRefresh = useCallback(() => {
loadRoutes();
loadBoundaries();
}, [loadRoutes, loadBoundaries]);
/**
* 全部显示/隐藏航线
*/
const handleToggleAllRoutes = useCallback((show: boolean) => {
if (show) {
if (routes.length > 5) {
message.warning('最多同时显示5条航线,已自动选择前5条');
}
const routesToShow = routes.slice(0, 5);
routesToShow.forEach(route => {
renderRoute(route);
});
setVisibleRoutes(new Set(routesToShow.map(r => r.routeId)));
} else {
visibleRoutes.forEach(routeId => removeRoute(routeId));
setVisibleRoutes(new Set());
}
}, [routes, visibleRoutes, renderRoute, removeRoute]);
/**
* 全部显示/隐藏边界
*/
const handleToggleAllBoundaries = useCallback((show: boolean) => {
if (show) {
boundaries.forEach(boundary => {
renderBoundary(boundary);
});
setVisibleBoundaries(new Set(boundaries.map(b => b.id)));
} else {
visibleBoundaries.forEach(boundaryId => removeBoundary(boundaryId));
setVisibleBoundaries(new Set());
}
}, [boundaries, visibleBoundaries, renderBoundary, removeBoundary]);
// 初始加载
useEffect(() => {
if (visible && scenicId) {
loadRoutes();
loadBoundaries();
}
}, [visible, scenicId, loadRoutes, loadBoundaries]);
// 组件卸载时清理所有图层
useEffect(() => {
return () => {
visibleRoutes.forEach(routeId => removeRoute(routeId));
visibleBoundaries.forEach(boundaryId => removeBoundary(boundaryId));
};
}, [visibleRoutes, visibleBoundaries, removeRoute, removeBoundary]);
if (!visible) return null;
return (
<div className={styles.layerPanel}>
<Card
title={
<Space>
<span>图层管理</span>
<Tooltip title="刷新列表">
<Button
type="text"
size="small"
icon={<ReloadOutlined />}
onClick={handleRefresh}
loading={loadingRoutes || loadingBoundaries}
/>
</Tooltip>
</Space>
}
size="small"
extra={
<Button
type="text"
size="small"
icon={<CloseOutlined />}
onClick={onClose}
/>
}
className={styles.card}
>
{/* 航线图层 */}
<div className={styles.section}>
<div className={styles.sectionHeader}>
<span className={styles.sectionTitle}>📍 航线图层</span>
<Space size="small">
{routes.length > 0 && (
<>
<Button
type="link"
size="small"
icon={<EyeOutlined />}
onClick={() => handleToggleAllRoutes(true)}
disabled={routes.length === 0}
>
全显
</Button>
<Button
type="link"
size="small"
icon={<EyeInvisibleOutlined />}
onClick={() => handleToggleAllRoutes(false)}
disabled={visibleRoutes.size === 0}
>
全隐
</Button>
</>
)}
</Space>
</div>
{loadingRoutes ? (
<div className={styles.loading}>加载中...</div>
) : routes.length === 0 ? (
<Empty
image={Empty.PRESENTED_IMAGE_SIMPLE}
description="暂无航线"
style={{ padding: '12px 0' }}
/>
) : (
<List
size="small"
dataSource={routes}
renderItem={route => (
<List.Item className={styles.listItem}>
<Checkbox
checked={visibleRoutes.has(route.routeId)}
onChange={e => handleRouteCheckChange(route.routeId, e.target.checked)}
>
<span className={styles.itemName}>{route.routeName}</span>
</Checkbox>
<Space size={4}>
{route.status === 1 && <Tag color="green">已发布</Tag>}
{route.status === 0 && <Tag color="default">草稿</Tag>}
<Tag color="blue">{route.waypointCount || 0}点</Tag>
</Space>
</List.Item>
)}
/>
)}
</div>
{/* 边界图层 */}
<div className={styles.section}>
<div className={styles.sectionHeader}>
<span className={styles.sectionTitle}>🔲 边界图层</span>
<Space size="small">
<Button
type="primary"
size="small"
icon={<PlusOutlined />}
onClick={() => onBoundaryEditorOpen?.()}
>
新建边界
</Button>
{boundaries.length > 0 && (
<>
<Button
type="link"
size="small"
icon={<EyeOutlined />}
onClick={() => handleToggleAllBoundaries(true)}
disabled={boundaries.length === 0}
>
全显
</Button>
<Button
type="link"
size="small"
icon={<EyeInvisibleOutlined />}
onClick={() => handleToggleAllBoundaries(false)}
disabled={visibleBoundaries.size === 0}
>
全隐
</Button>
</>
)}
</Space>
</div>
{loadingBoundaries ? (
<div className={styles.loading}>加载中...</div>
) : boundaries.length === 0 ? (
<Empty
image={Empty.PRESENTED_IMAGE_SIMPLE}
description="暂无边界"
style={{ padding: '12px 0' }}
/>
) : (
<List
size="small"
dataSource={boundaries}
renderItem={boundary => (
<List.Item className={styles.listItem}>
<Checkbox
checked={visibleBoundaries.has(boundary.id)}
onChange={e => handleBoundaryCheckChange(boundary.id, e.target.checked)}
>
<span className={styles.itemName}>{boundary.boundaryName}</span>
</Checkbox>
<Space size={4}>
{boundary.boundaryType === 'navigable' && (
<Tag color="green">可通行</Tag>
)}
{boundary.boundaryType === 'forbidden' && (
<Tag color="red">禁行</Tag>
)}
{boundary.boundaryType === 'warning' && (
<Tag color="orange">警告</Tag>
)}
<Tag color="blue">{boundary.vertexCount || 0}点</Tag>
</Space>
</List.Item>
)}
/>
)}
</div>
{/* 提示信息 */}
{visibleRoutes.size > 0 || visibleBoundaries.size > 0 ? (
<div className={styles.footer}>
已显示: {visibleRoutes.size} 条航线, {visibleBoundaries.size} 个边界
</div>
) : null}
</Card>
</div>
);
};
export default LayerPanel;
@@ -15,11 +15,21 @@ import {
ClockCircleOutlined,
AimOutlined,
DisconnectOutlined,
CompassOutlined,
WarningOutlined,
} from '@ant-design/icons';
import { message, Modal, Tooltip, Spin } from 'antd';
import { deviceApi } from '@/services/device';
import { deviceControlWs } from '@/services/deviceControlWs';
import {
pauseBoatNavigation,
resumeBoatNavigation,
returnBoatToStart,
emergencyStopBoat,
} from '@/services/boatControl';
import { DroneData } from '../hooks/useDroneSSE';
import { useBoatSSE } from '../hooks/useBoatSSE';
import type { BoatTelemetryData } from '@/types/boatRoute';
import WhepPlayer from './WhepPlayer';
import styles from './LeftControlPanel.less';
@@ -44,6 +54,20 @@ const LeftControlPanel: React.FC<LeftControlPanelProps> = ({
const rawDroneData = realtimeData?.rawData?.droneData;
const deviceSn = device?.deviceSn;
// 判断是否为无人船设备 (deviceType === 4)
const isBoatDevice = useMemo(() => device?.deviceType === 4, [device?.deviceType]);
// 无人船 SSE
const {
boatData,
sseConnected: boatSseConnected,
connectBoatSSE,
disconnectBoatSSE,
} = useBoatSSE();
// 无人船控制 loading 状态
const [boatLoading, setBoatLoading] = useState<string | null>(null);
const flightData = useMemo(() => {
const data = droneData || rawDroneData;
let gimbal: any = {};
@@ -131,22 +155,31 @@ const LeftControlPanel: React.FC<LeftControlPanelProps> = ({
useEffect(() => {
if (visible && deviceSn) {
// 先注册状态监听,再连接(确保能收到连接成功的通知)
const sub = deviceControlWs.onStatusChange(c => {
setWsConnected(c);
if(!c) { setDrcMode(false); drcModeRef.current = false; }
});
deviceControlWs.connect(deviceSn);
// 注意:无人机SSE已在CesiumContainer中统一订阅,这里不再重复订阅
return () => {
sub();
deviceControlWs.disconnect();
};
if (isBoatDevice) {
// 无人船设备 - 连接 Boat SSE
connectBoatSSE(deviceSn);
} else {
// 无人机/机库设备 - 连接控制 WebSocket
const sub = deviceControlWs.onStatusChange(c => {
setWsConnected(c);
if(!c) { setDrcMode(false); drcModeRef.current = false; }
});
deviceControlWs.connect(deviceSn);
return () => {
sub();
deviceControlWs.disconnect();
};
}
} else {
setPosition({ x: 0, y: 0 });
setVideoSize('normal');
}
}, [visible, deviceSn]);
return () => {
if (isBoatDevice && deviceSn) {
disconnectBoatSSE(deviceSn);
}
};
}, [visible, deviceSn, isBoatDevice]);
// 全屏状态监听
useEffect(() => {
@@ -523,15 +556,101 @@ const LeftControlPanel: React.FC<LeftControlPanelProps> = ({
}
}, [handleMouseMove]);
// ========== 无人船控制命令 ==========
const handleBoatPause = async () => {
if (!deviceSn || boatLoading) return;
setBoatLoading('pause');
try {
const res = await pauseBoatNavigation(deviceSn);
if (res.resp_code === 0) {
message.success('已暂停航行');
} else {
message.error(res.resp_msg || '暂停失败');
}
} catch (e) {
message.error('暂停失败');
} finally {
setBoatLoading(null);
}
};
const handleBoatResume = async () => {
if (!deviceSn || boatLoading) return;
setBoatLoading('resume');
try {
const res = await resumeBoatNavigation(deviceSn);
if (res.resp_code === 0) {
message.success('已恢复航行');
} else {
message.error(res.resp_msg || '恢复失败');
}
} catch (e) {
message.error('恢复失败');
} finally {
setBoatLoading(null);
}
};
const handleBoatReturn = () => {
Modal.confirm({
title: '确认返航?',
content: '无人船将自动返回起点',
okText: '确认',
cancelText: '取消',
onOk: async () => {
setBoatLoading('return');
try {
const res = await returnBoatToStart(deviceSn!);
if (res.resp_code === 0) {
message.success('返航指令已发送');
} else {
message.error(res.resp_msg || '返航失败');
}
} catch (e) {
message.error('返航失败');
} finally {
setBoatLoading(null);
}
},
});
};
const handleBoatEmergencyStop = () => {
Modal.confirm({
title: '紧急停止',
content: '确定要紧急停止无人船吗?这将立即停止所有动作。',
okText: '确认停止',
okType: 'danger',
cancelText: '取消',
onOk: async () => {
setBoatLoading('emergency');
try {
const res = await emergencyStopBoat(deviceSn!);
if (res.resp_code === 0) {
message.success('已紧急停止');
} else {
message.error(res.resp_msg || '紧急停止失败');
}
} catch (e) {
message.error('紧急停止失败');
} finally {
setBoatLoading(null);
}
},
});
};
// 关闭面板时,断开设备控制连接
const handleClose = () => {
// 1. 断开设备控制WebSocket服务
deviceControlWs.disconnect();
// 2. 退出DRC模式
setDrcMode(false);
drcModeRef.current = false;
// 3. 调用父组件的关闭回调
// 注意:无人机SSE由CesiumContainer统一管理,这里不处理
if (isBoatDevice) {
// 无人船设备 - 断开 Boat SSE
disconnectBoatSSE(deviceSn);
} else {
// 无人机/机库设备 - 断开控制 WebSocket
deviceControlWs.disconnect();
setDrcMode(false);
drcModeRef.current = false;
}
onClose();
};
@@ -612,6 +731,115 @@ const LeftControlPanel: React.FC<LeftControlPanelProps> = ({
{/* UI 覆盖层 */}
<div className={styles.uiOverlay}>
{isBoatDevice ? (
/* ========== 无人船简化版界面 ========== */
<>
{/* 顶部栏 */}
<div className={styles.topBar} onMouseDown={handleMouseDown}>
<div className={styles.topLeft}>
<div className={`${styles.modeTag} ${boatData?.status === 'executing' ? styles.manual : ''}`}>
<CompassOutlined style={{ marginRight: 4 }} />
{boatData?.status === 'executing' ? '航行中' : boatData?.status === 'paused' ? '已暂停' : '空闲'}
</div>
<div className={styles.statusGroup}>
<div className={`${styles.statusItem} ${boatSseConnected ? styles.online : styles.offline}`}>
<span className={styles.dot}></span>
<span>{boatSseConnected ? '已连接' : '未连接'}</span>
</div>
</div>
</div>
<div className={styles.topRight}>
<div className={styles.batteryDisplay}>
<div className={styles.batteryIcon}>
<div className={styles.batteryLevel} style={{ width: `${boatData?.battery ?? 0}%` }}></div>
</div>
<div className={styles.batteryInfo}>
<span className={styles.percent}>{boatData?.battery ?? 0}%</span>
</div>
</div>
<button className={styles.closeBtn} onClick={handleClose} onMouseDown={e => e.stopPropagation()}>
<CloseOutlined />
</button>
</div>
</div>
{/* 左侧航行数据 */}
<div className={styles.leftDataPanel}>
<div className={styles.dataCard}>
<div className={styles.dataRow}>
<span className={styles.label}>航向角</span>
<span className={styles.value}>{boatData?.heading?.toFixed(1) ?? '--'}<span className={styles.unit}>°</span></span>
</div>
<div className={styles.dataRow}>
<span className={styles.label}>航行速度</span>
<span className={styles.value}>{boatData?.speed?.toFixed(1) ?? '--'}<span className={styles.unit}>m/s</span></span>
</div>
</div>
</div>
{/* 右侧位置数据 */}
<div className={styles.rightDataPanel}>
<div className={styles.dataCard}>
<div className={styles.dataRow}>
<span className={styles.label}>经度</span>
<span className={styles.value} style={{ fontSize: 12 }}>{boatData?.longitude?.toFixed(6) ?? '--'}</span>
</div>
<div className={styles.dataRow}>
<span className={styles.label}>纬度</span>
<span className={styles.value} style={{ fontSize: 12 }}>{boatData?.latitude?.toFixed(6) ?? '--'}</span>
</div>
</div>
</div>
{/* 底部控制栏 - 简化版 */}
<div className={styles.bottomControls}>
<div className={styles.quickActions} style={{ justifyContent: 'center', gap: 16, flex: 1 }}>
<Tooltip title="暂停航行" placement="top">
<button
className={styles.actionBtn}
onClick={handleBoatPause}
disabled={boatLoading === 'pause'}
>
{boatLoading === 'pause' ? <LoadingOutlined /> : <PauseCircleOutlined />}
<span>暂停</span>
</button>
</Tooltip>
<Tooltip title="恢复航行" placement="top">
<button
className={styles.actionBtn}
onClick={handleBoatResume}
disabled={boatLoading === 'resume'}
>
{boatLoading === 'resume' ? <LoadingOutlined /> : <CaretRightOutlined />}
<span>继续</span>
</button>
</Tooltip>
<Tooltip title="返回起点" placement="top">
<button
className={styles.actionBtn}
onClick={handleBoatReturn}
disabled={boatLoading === 'return'}
>
{boatLoading === 'return' ? <LoadingOutlined /> : <HomeOutlined />}
<span>返航</span>
</button>
</Tooltip>
<Tooltip title="紧急停止" placement="top">
<button
className={`${styles.actionBtn} ${styles.danger}`}
onClick={handleBoatEmergencyStop}
disabled={boatLoading === 'emergency'}
>
{boatLoading === 'emergency' ? <LoadingOutlined /> : <WarningOutlined />}
<span>急停</span>
</button>
</Tooltip>
</div>
</div>
</>
) : (
/* ========== 无人机/机库界面 ========== */
<>
{/* 顶部栏 */}
<div className={styles.topBar} onMouseDown={handleMouseDown}>
<div className={styles.topLeft}>
@@ -858,6 +1086,8 @@ const LeftControlPanel: React.FC<LeftControlPanelProps> = ({
</div>
</div>
</>
)}
</div>
</div>
);
@@ -12,10 +12,15 @@ import {
LoadingOutlined,
AimOutlined,
UnorderedListOutlined,
CompassOutlined,
EnvironmentOutlined,
EditOutlined,
} from '@ant-design/icons';
import { deviceApi } from '@/services/device';
import { saveMission, MissionType } from '@/services/mission';
import useDeviceSSE from '../hooks/useDeviceSSE';
import { useBoatSSE } from '../hooks/useBoatSSE';
import type { BoatTelemetryData } from '@/types/boatRoute';
import styles from './RightPanel.less';
interface RightPanelProps {
@@ -24,6 +29,7 @@ interface RightPanelProps {
onClose: () => void;
onControlClick: (device: any, realtimeData: any) => void;
onTaskPanelOpen?: (device: any, dockData: any) => void; // 打开任务管理面板回调
onRoutePlanningOpen?: (device: any) => void; // 打开航线规划面板回调(无人船)
viewer?: any; // Cesium Viewer 实例
Cesium?: any; // Cesium 库
}
@@ -34,35 +40,64 @@ const RightPanel: React.FC<RightPanelProps> = ({
onClose,
onControlClick,
onTaskPanelOpen,
onRoutePlanningOpen,
viewer,
Cesium
}) => {
const [takeoffLoading, setTakeoffLoading] = useState(false);
// 判断是否为无人船设备 (deviceType === 4)
const isBoatDevice = useMemo(() => device?.deviceType === 4, [device?.deviceType]);
// 无人机/机库 SSE
const { realtimeData, sseConnected, connectSSE, disconnectSSE } = useDeviceSSE();
// 无人船 SSE
const {
boatData,
sseConnected: boatSseConnected,
connectBoatSSE,
disconnectBoatSSE,
} = useBoatSSE();
// 当设备变化时,连接SSE
useEffect(() => {
if (device?.deviceSn && visible) {
connectSSE(device.deviceSn);
if (isBoatDevice) {
connectBoatSSE(device.deviceSn);
} else {
connectSSE(device.deviceSn);
}
}
return () => {
if (device?.deviceSn) {
disconnectSSE(device.deviceSn);
if (isBoatDevice) {
disconnectBoatSSE(device.deviceSn);
} else {
disconnectSSE(device.deviceSn);
}
}
};
}, [device?.deviceSn, visible]);
}, [device?.deviceSn, visible, isBoatDevice]);
useEffect(() => {
if (!visible && device?.deviceSn) {
disconnectSSE(device.deviceSn);
if (isBoatDevice) {
disconnectBoatSSE(device.deviceSn);
} else {
disconnectSSE(device.deviceSn);
}
}
}, [visible]);
}, [visible, isBoatDevice]);
// 关闭面板时,主动断开SSE连接
const handleClose = () => {
if (device?.deviceSn) {
disconnectSSE(device.deviceSn);
if (isBoatDevice) {
disconnectBoatSSE(device.deviceSn);
} else {
disconnectSSE(device.deviceSn);
}
}
onClose();
};
@@ -173,11 +208,14 @@ const RightPanel: React.FC<RightPanelProps> = ({
<div className={styles.titleRow}>
<div className={styles.titleInfo}>
<div className={styles.mainTitle}>
<HomeOutlined className={styles.icon} />
{isBoatDevice ? <CompassOutlined className={styles.icon} /> : <HomeOutlined className={styles.icon} />}
{device?.deviceName || device?.deviceSn || '设备详情'}
</div>
<div className={styles.subTitle}>
{realtimeData?.online ? 'ONLINE' : 'OFFLINE'}
{isBoatDevice
? (boatSseConnected ? 'ONLINE' : 'OFFLINE')
: (realtimeData?.online ? 'ONLINE' : 'OFFLINE')
}
</div>
</div>
<button className={styles.closeBtn} onClick={handleClose}><CloseOutlined /></button>
@@ -187,7 +225,71 @@ const RightPanel: React.FC<RightPanelProps> = ({
<div className={styles.content}>
{!device ? (
<Empty description="暂无设备数据" image={Empty.PRESENTED_IMAGE_SIMPLE} />
) : isBoatDevice ? (
/* ========== 无人船设备界面 ========== */
<div className={styles.detailContainer}>
{/* 无人船基本信息 */}
<div className={styles.section}>
<div className={styles.sectionHeader}>
<span>无人船信息 / BOAT INFO</span>
</div>
<div className={styles.statusCard}>
<div className={styles.statusHeader}>
<span className={styles.statusTitle}>{device?.deviceName || device?.deviceSn}</span>
<span className={`${styles.statusTag} ${boatSseConnected ? styles.success : styles.error}`}>
{boatSseConnected ? '在线' : '离线'}
</span>
</div>
<div className={styles.grid}>
{renderItem('设备SN', device?.deviceSn)}
{renderItem('航行状态', boatData?.status === 'executing' ? '航行中' : boatData?.status === 'paused' ? '已暂停' : '空闲', '', boatData?.status === 'executing' ? 'warning' : 'success')}
{renderItem('电池电量', boatData?.battery, '%', (boatData?.battery ?? 100) < 20 ? 'error' : 'success')}
{renderItem('信号强度', boatData?.signalStrength, '%')}
{renderItem('当前速度', boatData?.speed?.toFixed(1), 'm/s')}
{renderItem('航向角', boatData?.heading?.toFixed(1), '°')}
</div>
</div>
</div>
{/* 位置信息 */}
<div className={styles.section}>
<div className={styles.sectionHeader}>位置信息 / POSITION</div>
<div className={styles.grid}>
{renderItem('经度', boatData?.longitude?.toFixed(6))}
{renderItem('纬度', boatData?.latitude?.toFixed(6))}
{renderItem('当前任务', boatData?.taskId || '无')}
{renderItem('当前航点', boatData?.currentWaypointIndex !== undefined ? `第${boatData.currentWaypointIndex + 1}个` : '-')}
</div>
</div>
{/* 电池状态大图标 */}
<div className={styles.section}>
<div style={{display:'flex', alignItems:'center', marginBottom: 16, background:'rgba(255,255,255,0.05)', padding:12, borderRadius:4}}>
<div style={{marginRight:16}}>
<div style={{fontSize:12, color:'rgba(255,255,255,0.6)'}}>BATTERY</div>
<div style={{fontSize:24, fontWeight:'bold', color:(boatData?.battery ?? 100) < 20 ? '#ff4d4f' : '#00ff88'}}>{boatData?.battery ?? 0}%</div>
</div>
<div style={{flex:1}}>
<Progress percent={boatData?.battery ?? 0} showInfo={false} strokeColor={(boatData?.battery ?? 100) < 20 ? '#ff4d4f' : '#00ff88'} trailColor="rgba(255,255,255,0.1)" />
</div>
</div>
</div>
{/* 操作区 */}
<div className={styles.actions}>
<div className={styles.actionRow}>
<button className={styles.primary} onClick={() => onRoutePlanningOpen?.(device)}>
<EditOutlined /> 航线规划
</button>
<button className={styles.task} onClick={() => onTaskPanelOpen?.(device, null)}>
<UnorderedListOutlined /> 任务管理
</button>
</div>
</div>
</div>
) : (
/* ========== 无人机/机库设备界面 ========== */
<Tabs
defaultActiveKey="1"
className={styles.customTabs}
@@ -0,0 +1,318 @@
/**
* 无人船遥测数据SSE Hook
* @author dzc
* @date 2026-01-05
*/
import { useState, useRef, useEffect, useCallback } from 'react';
import { notification } from 'antd';
import type { BoatTelemetryData } from '@/types/boatRoute';
const IDLE_TIMEOUT_MS = 30 * 60 * 1000; // 30分钟无操作断开
export interface UseBoatSSEReturn {
boatData: BoatTelemetryData | null;
sseConnected: boolean;
loading: boolean;
hasData: boolean;
isIdleDisconnected: boolean;
connectBoatSSE: (deviceSn: string) => Promise<void>;
disconnectBoatSSE: (deviceSn?: string) => Promise<void>;
resetBoatData: () => void;
}
export const useBoatSSE = (): UseBoatSSEReturn => {
const [boatData, setBoatData] = useState<BoatTelemetryData | null>(null);
const [sseConnected, setSSEConnected] = useState(false);
const [loading, setLoading] = useState(false);
const [hasData, setHasData] = useState(false);
const [isIdleDisconnected, setIsIdleDisconnected] = useState(false);
const abortControllerRef = useRef<AbortController | null>(null);
const currentDeviceSnRef = useRef<string>('');
const clientSessionIdRef = useRef<string>(
`boat_client_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`
);
const dataReceivedRef = useRef<boolean>(false);
const reconnectTimerRef = useRef<NodeJS.Timeout | null>(null);
const reconnectAttemptsRef = useRef<number>(0);
const maxReconnectAttempts = 10;
const shouldReconnectRef = useRef<boolean>(true);
const idleTimerRef = useRef<NodeJS.Timeout | null>(null);
const performDisconnect = (deviceSn: string, sessionId: string, token: string | null) => {
if (!deviceSn || !token) return;
const deleteUrl = `/api-device/sse/boat/telemetry/${deviceSn}`;
fetch(deleteUrl, {
method: 'DELETE',
headers: {
'Authorization': `Bearer ${token}`,
'X-Client-Session-Id': sessionId,
},
keepalive: true,
}).catch(() => {});
};
const performBeaconDisconnect = (deviceSn: string, sessionId: string) => {
if (!deviceSn) return;
const beaconUrl = `/api-device/sse/boat/telemetry/${deviceSn}/disconnect`;
if (navigator.sendBeacon) {
const blob = new Blob([JSON.stringify({ sessionId })], { type: 'application/json' });
navigator.sendBeacon(beaconUrl, blob);
}
};
const disconnectBoatSSE = useCallback(async (deviceSn?: string) => {
const snToDisconnect = deviceSn || currentDeviceSnRef.current;
shouldReconnectRef.current = false;
if (reconnectTimerRef.current) {
clearTimeout(reconnectTimerRef.current);
reconnectTimerRef.current = null;
}
if (abortControllerRef.current) {
abortControllerRef.current.abort();
abortControllerRef.current = null;
}
if (snToDisconnect) {
const token = sessionStorage.getItem('access_token');
performDisconnect(snToDisconnect, clientSessionIdRef.current, token);
}
setSSEConnected(false);
setLoading(false);
setHasData(false);
dataReceivedRef.current = false;
currentDeviceSnRef.current = '';
reconnectAttemptsRef.current = 0;
}, []);
const disconnectDueToIdle = useCallback(() => {
setIsIdleDisconnected(true);
shouldReconnectRef.current = false;
disconnectBoatSSE();
notification.warning({
message: '页面长时间未操作',
description: '已断开无人船实时数据连接,请刷新页面重新连接',
duration: 0,
key: 'boat-page-idle-warning',
});
}, [disconnectBoatSSE]);
const resetIdleTimer = useCallback(() => {
if (isIdleDisconnected) return;
if (idleTimerRef.current) {
clearTimeout(idleTimerRef.current);
}
if (currentDeviceSnRef.current) {
idleTimerRef.current = setTimeout(() => {
disconnectDueToIdle();
}, IDLE_TIMEOUT_MS);
}
}, [isIdleDisconnected, disconnectDueToIdle]);
useEffect(() => {
const activityEvents = ['mousedown', 'mousemove', 'keydown', 'scroll', 'touchstart', 'click'];
const handleActivity = () => resetIdleTimer();
activityEvents.forEach(event => {
window.addEventListener(event, handleActivity, { passive: true });
});
resetIdleTimer();
return () => {
activityEvents.forEach(event => {
window.removeEventListener(event, handleActivity);
});
if (idleTimerRef.current) {
clearTimeout(idleTimerRef.current);
}
};
}, [resetIdleTimer]);
const handleSSEEvent = useCallback((eventName: string, data: string) => {
try {
if (eventName === 'connected') {
setSSEConnected(true);
setLoading(false);
} else if (eventName === 'boat-telemetry') {
const parsedData = JSON.parse(data) as BoatTelemetryData;
setBoatData(parsedData);
if (!dataReceivedRef.current) {
dataReceivedRef.current = true;
setHasData(true);
}
}
} catch {}
}, []);
const scheduleReconnect = useCallback((deviceSn: string) => {
if (!shouldReconnectRef.current) return;
if (reconnectAttemptsRef.current >= maxReconnectAttempts) return;
reconnectAttemptsRef.current++;
const delay = Math.min(2000 * Math.pow(1.5, reconnectAttemptsRef.current - 1), 30000);
reconnectTimerRef.current = setTimeout(() => {
if (shouldReconnectRef.current && currentDeviceSnRef.current === deviceSn) {
doConnect(deviceSn);
}
}, delay);
}, []);
const doConnect = useCallback(async (deviceSn: string) => {
if (!deviceSn) return;
setLoading(true);
try {
const token = sessionStorage.getItem('access_token');
const url = `/api-device/sse/boat/telemetry/${deviceSn}`;
const abortController = new AbortController();
abortControllerRef.current = abortController;
const response = await fetch(url, {
method: 'GET',
headers: {
'Accept': 'text/event-stream',
'Cache-Control': 'no-cache',
'Authorization': `Bearer ${token}`,
'X-Client-Session-Id': clientSessionIdRef.current,
},
cache: 'no-store',
signal: abortController.signal,
});
if (!response.ok) {
throw new Error(`SSE连接失败: ${response.status}`);
}
reconnectAttemptsRef.current = 0;
const reader = response.body?.getReader();
const decoder = new TextDecoder();
if (!reader) {
throw new Error('无法获取SSE流读取器');
}
let buffer = '';
const readStream = async () => {
try {
while (true) {
const { done, value } = await reader.read();
if (done) {
setSSEConnected(false);
if (shouldReconnectRef.current && currentDeviceSnRef.current === deviceSn) {
scheduleReconnect(deviceSn);
}
break;
}
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\n');
buffer = lines.pop() || '';
let eventName = 'message';
let data = '';
for (const line of lines) {
if (line.startsWith('event:')) {
eventName = line.substring(6).trim();
} else if (line.startsWith('data:')) {
data = line.substring(5).trim();
} else if (line === '') {
if (data) {
handleSSEEvent(eventName, data);
}
eventName = 'message';
data = '';
}
}
}
} catch (error: any) {
if (error?.name === 'AbortError') return;
setSSEConnected(false);
setLoading(false);
if (shouldReconnectRef.current && currentDeviceSnRef.current === deviceSn) {
scheduleReconnect(deviceSn);
}
}
};
readStream();
} catch (error: any) {
if (error?.name === 'AbortError') return;
setSSEConnected(false);
setLoading(false);
if (shouldReconnectRef.current && currentDeviceSnRef.current === deviceSn) {
scheduleReconnect(deviceSn);
}
}
}, [handleSSEEvent, scheduleReconnect]);
const connectBoatSSE = useCallback(async (deviceSn: string) => {
if (currentDeviceSnRef.current && currentDeviceSnRef.current !== deviceSn) {
await disconnectBoatSSE(currentDeviceSnRef.current);
}
if (!deviceSn) return;
setBoatData(null);
setHasData(false);
dataReceivedRef.current = false;
currentDeviceSnRef.current = deviceSn;
shouldReconnectRef.current = true;
reconnectAttemptsRef.current = 0;
setIsIdleDisconnected(false);
doConnect(deviceSn);
resetIdleTimer();
}, [disconnectBoatSSE, doConnect, resetIdleTimer]);
const resetBoatData = useCallback(() => {
setBoatData(null);
setHasData(false);
dataReceivedRef.current = false;
}, []);
useEffect(() => {
const handleBeforeUnload = () => {
if (currentDeviceSnRef.current) {
performBeaconDisconnect(currentDeviceSnRef.current, clientSessionIdRef.current);
}
};
window.addEventListener('beforeunload', handleBeforeUnload);
return () => {
window.removeEventListener('beforeunload', handleBeforeUnload);
};
}, []);
useEffect(() => {
return () => {
if (reconnectTimerRef.current) {
clearTimeout(reconnectTimerRef.current);
}
shouldReconnectRef.current = false;
if (currentDeviceSnRef.current) {
const token = sessionStorage.getItem('access_token');
performDisconnect(currentDeviceSnRef.current, clientSessionIdRef.current, token);
}
if (abortControllerRef.current) {
abortControllerRef.current.abort();
}
};
}, []);
return {
boatData,
sseConnected,
loading,
hasData,
isIdleDisconnected,
connectBoatSSE,
disconnectBoatSSE,
resetBoatData,
};
};
@@ -0,0 +1,279 @@
/**
* 无人船实时轨迹Cesium渲染Hook
* 用于在3D地图上实时显示无人船位置和轨迹
* @author Claude
* @date 2026-01-06
*/
import { useEffect, useRef, useCallback, useMemo } from 'react';
import { useBoatSSE } from './useBoatSSE';
interface UseCesiumBoatTrackOptions {
viewerRef: React.RefObject<any>;
enabled: boolean;
deviceSn: string | null;
}
export function useCesiumBoatTrack({
viewerRef,
enabled,
deviceSn,
}: UseCesiumBoatTrackOptions) {
const { boatData, connectBoatSSE, disconnectBoatSSE } = useBoatSSE();
// Entity引用
const boatEntityRef = useRef<any>(null);
const trackEntityRef = useRef<any>(null);
const trackPositionsRef = useRef<any[]>([]);
// 控制相机自动飞行(仅首次)
const hasFlownToBoatRef = useRef<boolean>(false);
// 节流控制
const lastUpdateTimeRef = useRef<number>(0);
const lastPositionRef = useRef<{ lon: number; lat: number } | null>(null);
/**
* 获取Cesium对象
*/
const getCesium = useCallback(() => {
return (window as any).Cesium;
}, []);
/**
* 飞到无人船位置
*/
const flyToBoat = useCallback(() => {
const viewer = viewerRef.current;
const Cesium = getCesium();
if (!viewer || !Cesium || viewer.isDestroyed?.()) return;
if (!boatData?.longitude || !boatData?.latitude) return;
try {
viewer.camera.flyTo({
destination: Cesium.Cartesian3.fromDegrees(
boatData.longitude,
boatData.latitude,
1000 // 视角高度1000米
),
orientation: {
heading: 0,
pitch: Cesium.Math.toRadians(-45), // 45度俯视
roll: 0,
},
duration: 1.5,
});
} catch (error) {
console.error('[useCesiumBoatTrack] 飞行到船位置失败:', error);
}
}, [viewerRef, boatData, getCesium]);
/**
* 清除轨迹和船位置Entity
*/
const clearTrack = useCallback(() => {
const viewer = viewerRef.current;
if (!viewer || viewer.isDestroyed?.()) return;
try {
if (boatEntityRef.current) {
viewer.entities.remove(boatEntityRef.current);
boatEntityRef.current = null;
}
if (trackEntityRef.current) {
viewer.entities.remove(trackEntityRef.current);
trackEntityRef.current = null;
}
trackPositionsRef.current = [];
hasFlownToBoatRef.current = false;
lastUpdateTimeRef.current = 0;
lastPositionRef.current = null;
console.log('[useCesiumBoatTrack] 清除无人船轨迹');
} catch (error) {
console.error('[useCesiumBoatTrack] 清除轨迹失败:', error);
}
}, [viewerRef]);
/**
* 订阅/取消SSE连接
*/
useEffect(() => {
if (enabled && deviceSn) {
console.log('[useCesiumBoatTrack] 开始订阅无人船SSE:', deviceSn);
connectBoatSSE(deviceSn);
} else {
console.log('[useCesiumBoatTrack] 断开无人船SSE');
disconnectBoatSSE();
clearTrack();
}
return () => {
disconnectBoatSSE();
};
}, [enabled, deviceSn, connectBoatSSE, disconnectBoatSSE, clearTrack]);
/**
* 计算实时位置数据
*/
const realtimePosition = useMemo(() => {
if (!boatData) return null;
return {
longitude: boatData.longitude,
latitude: boatData.latitude,
heading: boatData.heading ?? 0,
speed: boatData.speed ?? 0,
battery: boatData.battery ?? 0,
timestamp: Date.now(),
};
}, [boatData]);
/**
* 渲染无人船实时位置和轨迹
*/
useEffect(() => {
const viewer = viewerRef.current;
const Cesium = getCesium();
if (!viewer || !Cesium || viewer.isDestroyed?.()) return;
if (!realtimePosition) return;
if (!realtimePosition.longitude || !realtimePosition.latitude) return;
const now = Date.now();
const currentPos = {
lon: realtimePosition.longitude,
lat: realtimePosition.latitude,
};
// 节流:1秒内且位置没变化则跳过
const timeSinceLastUpdate = now - lastUpdateTimeRef.current;
const lastPos = lastPositionRef.current;
if (lastPos && timeSinceLastUpdate < 1000) {
const posChanged =
Math.abs(currentPos.lon - lastPos.lon) > 0.00001 ||
Math.abs(currentPos.lat - lastPos.lat) > 0.00001;
if (!posChanged) {
return;
}
}
// 更新时间和位置记录
lastUpdateTimeRef.current = now;
lastPositionRef.current = currentPos;
try {
const position = Cesium.Cartesian3.fromDegrees(
realtimePosition.longitude,
realtimePosition.latitude,
0 // 无人船在水面,高度为0
);
// 构建标签文本
const labelText = [
'无人船',
`航向:${realtimePosition.heading.toFixed(0)}°`,
`速度:${realtimePosition.speed.toFixed(1)}m/s`,
`电量:${realtimePosition.battery}%`,
].join(' ');
// 更新或创建船位置Entity
if (boatEntityRef.current) {
boatEntityRef.current.position = position;
if (boatEntityRef.current.label) {
boatEntityRef.current.label.text = labelText;
}
} else {
boatEntityRef.current = viewer.entities.add({
name: '无人船实时位置',
position: position,
point: {
pixelSize: 16,
color: Cesium.Color.BLUE,
outlineColor: Cesium.Color.WHITE,
outlineWidth: 3,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
},
label: {
text: labelText,
font: '14px sans-serif',
fillColor: Cesium.Color.WHITE,
style: Cesium.LabelStyle.FILL_AND_OUTLINE,
outlineWidth: 2,
outlineColor: Cesium.Color.BLACK,
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
pixelOffset: new Cesium.Cartesian2(0, -20),
disableDepthTestDistance: Number.POSITIVE_INFINITY,
},
properties: {
type: 'boat-realtime',
deviceSn: deviceSn,
},
});
console.log('[useCesiumBoatTrack] 创建无人船Entity');
}
// 添加到轨迹
trackPositionsRef.current.push(position);
// 限制轨迹点数量(最多保留最近500个点,避免内存泄漏)
if (trackPositionsRef.current.length > 500) {
trackPositionsRef.current = trackPositionsRef.current.slice(-500);
}
// 绘制飞行轨迹(至少2个点才能绘制线)
if (trackPositionsRef.current.length >= 2) {
if (trackEntityRef.current) {
trackEntityRef.current.polyline.positions = [...trackPositionsRef.current];
} else {
trackEntityRef.current = viewer.entities.add({
name: '无人船航行轨迹',
polyline: {
positions: [...trackPositionsRef.current],
width: 4,
material: new Cesium.PolylineGlowMaterialProperty({
glowPower: 0.3,
color: Cesium.Color.BLUE,
}),
clampToGround: true,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
},
properties: {
type: 'boat-track',
deviceSn: deviceSn,
},
});
console.log('[useCesiumBoatTrack] 创建无人船轨迹Entity');
}
}
// 强制渲染
viewer.scene.requestRender();
// 首次收到位置数据时,自动飞到无人船位置
if (!hasFlownToBoatRef.current && trackPositionsRef.current.length === 1) {
hasFlownToBoatRef.current = true;
flyToBoat();
}
} catch (error) {
console.error('[useCesiumBoatTrack] 更新无人船位置出错:', error);
}
}, [realtimePosition, viewerRef, deviceSn, getCesium, flyToBoat]);
/**
* 组件卸载时清理
*/
useEffect(() => {
return () => {
clearTrack();
};
}, [clearTrack]);
return {
boatData,
clearTrack,
flyToBoat,
};
}
@@ -93,12 +93,12 @@ export const useTilesetLoader = (): UseTilesetLoaderResult => {
});
try {
// 处理跨域问题:开发环境 (localhost) 将 CDN URL 转换为代理路径
// 处理跨域问题:非 localhost 访问时将 CDN URL 转换为代理路径
let tilesetUrl = config.url;
const isLocalhost = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1';
if (isLocalhost && tilesetUrl.includes('minicdn.goflytec.com')) {
if (!isLocalhost && tilesetUrl.includes('minicdn.goflytec.com')) {
tilesetUrl = tilesetUrl.replace('https://minicdn.goflytec.com', '');
console.log('[Tileset] 开发环境使用代理路径:', tilesetUrl);
console.log('[Tileset] 使用代理路径:', tilesetUrl);
}
// 创建3DTileset - 高清晰度渲染配置
@@ -223,7 +223,12 @@ export const useTilesetLoader = (): UseTilesetLoaderResult => {
}
}
// 添加到场景
// 添加到场景前检查viewer是否仍然有效
if (!viewer || viewer.isDestroyed?.() || !viewer.scene) {
console.warn(`模型 [${config.name}] 加载完成,但viewer已销毁,跳过添加`);
return null;
}
viewer.scene.primitives.add(tileset);
// 存储引用
@@ -267,7 +272,7 @@ export const useTilesetLoader = (): UseTilesetLoaderResult => {
*/
const unloadTileset = useCallback((id: string, viewer: any) => {
const tileset = tilesetsRef.current.get(id);
if (tileset && viewer) {
if (tileset && viewer && !viewer.isDestroyed?.() && viewer.scene) {
viewer.scene.primitives.remove(tileset);
tilesetsRef.current.delete(id);
@@ -285,7 +290,7 @@ export const useTilesetLoader = (): UseTilesetLoaderResult => {
* 卸载所有模型
*/
const unloadAllTilesets = useCallback((viewer: any) => {
if (!viewer) return;
if (!viewer || viewer.isDestroyed?.() || !viewer.scene) return;
tilesetsRef.current.forEach((tileset, id) => {
viewer.scene.primitives.remove(tileset);
@@ -301,7 +306,7 @@ export const useTilesetLoader = (): UseTilesetLoaderResult => {
*/
const flyToTileset = useCallback((id: string, viewer: any, Cesium: any) => {
const tileset = tilesetsRef.current.get(id);
if (!tileset || !viewer || !Cesium) return;
if (!tileset || !viewer || !Cesium || viewer.isDestroyed?.() || !viewer.camera) return;
const boundingSphere = tileset.boundingSphere;
const center = boundingSphere.center;
@@ -1,13 +1,16 @@
import React, { useEffect, useRef, useState, useCallback, useMemo } from 'react';
import { message, Button, Tooltip } from 'antd';
import { AppstoreOutlined } from '@ant-design/icons';
import { AppstoreOutlined, BarsOutlined } from '@ant-design/icons';
import RightPanel from './3d/BottomPanel/RightPanel';
import LeftControlPanel from './3d/BottomPanel/LeftControlPanel';
import TaskPanel from './3d/BottomPanel/TaskPanel';
import TilesetPanel from './3d/TilesetPanel';
import LayerPanel, { LayerPanelProps } from './3d/BottomPanel/LayerPanel';
import RouteEditor from '../RouteEditor';
import BoundaryEditor from '../BoundaryEditor';
import { useTilesetLoader, TilesetConfig } from './3d/hooks/useTilesetLoader';
import { useDroneSSE } from './3d/hooks/useDroneSSE';
import { getModelsByDeviceSn, convertToTilesetConfig } from '@/services/threeDModel';
import TilesetPanel from "@/pages/map3d/components/MapContainer/3d/TilesetPanel";
// 动态导入Cesium
let Cesium: any = null;
@@ -30,6 +33,7 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
const viewerRef = useRef<any>(null);
const entitiesRef = useRef<Map<string, any>>(new Map());
const [loading, setLoading] = useState(true);
const [viewerReady, setViewerReady] = useState(false); // 新增:viewer 是否完全就绪
// 3D 模式专属状态
const [selectedDevice, setSelectedDevice] = useState<any>(null);
@@ -45,6 +49,16 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
const [taskPanelDevice, setTaskPanelDevice] = useState<any>(null);
const [taskPanelDockData, setTaskPanelDockData] = useState<any>(null);
// 航线规划面板状态(无人船)
const [routePlanningVisible, setRoutePlanningVisible] = useState(false);
const [routePlanningDevice, setRoutePlanningDevice] = useState<any>(null);
// 边界编辑面板状态(水域边界)
const [boundaryEditorVisible, setBoundaryEditorVisible] = useState(false);
// 图层管理面板状态
const [layerPanelVisible, setLayerPanelVisible] = useState(false);
// 无人机SSE订阅(用于在3D地球上显示无人机位置)
const [droneDeviceSn, setDroneDeviceSn] = useState<string>('');
const { droneData, connectDroneSSE, disconnectDroneSSE, resetDroneData } = useDroneSSE();
@@ -392,6 +406,48 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
setTaskPanelVisible(true);
}, []);
// 处理从右侧面板点击"航线规划"(无人船)
const handleOpenRoutePlanning = useCallback((device: any) => {
setRoutePlanningDevice(device);
setRoutePlanningVisible(true);
// 关闭其他面板
setRightPanelVisible(false);
}, []);
// 关闭航线规划面板
const handleCloseRoutePlanning = useCallback(() => {
setRoutePlanningVisible(false);
setRoutePlanningDevice(null);
}, []);
// 航线保存成功回调
const handleRoutesSaveSuccess = useCallback((routeId: string) => {
message.success('航线保存成功');
setRoutePlanningVisible(false);
setRoutePlanningDevice(null);
}, []);
// 处理从图层管理面板点击"新建边界"
const handleOpenBoundaryEditor = useCallback(() => {
setBoundaryEditorVisible(true);
// 关闭其他面板
setLayerPanelVisible(false);
setRightPanelVisible(false);
}, []);
// 关闭边界编辑器
const handleCloseBoundaryEditor = useCallback(() => {
setBoundaryEditorVisible(false);
}, []);
// 边界保存成功回调
const handleBoundarySaveSuccess = useCallback((boundaryId: string) => {
message.success('边界保存成功');
setBoundaryEditorVisible(false);
// 重新打开图层管理面板,显示新创建的边界
setLayerPanelVisible(true);
}, []);
// 计算无人机实时位置
const realtimePosition = useMemo(() => {
if (!droneData) return null;
@@ -624,6 +680,11 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
if (!Cesium) {
const cesiumModule = await import('cesium');
Cesium = cesiumModule;
// 将 Cesium 挂载到 window 上,供其他组件使用(如 BoundaryEditor)
(window as any).Cesium = cesiumModule;
console.log('[CesiumContainer] ✓ Cesium 已挂载到 window');
const cesiumBaseUrl = process.env.CESIUM_BASE_URL || '/';
Cesium.buildModuleUrl.setBaseUrl(`${cesiumBaseUrl}cesium/`);
@@ -717,11 +778,14 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
}
setLoading(false);
setViewerReady(true); // Viewer 初始化完成
console.log('[CesiumContainer] ✓ Viewer 初始化完成,viewerReady=true');
message.success('3D地图加载完成');
} catch (error) {
console.error('Cesium初始化失败:', error);
message.error('3D地图加载失败');
setLoading(false);
setViewerReady(false); // 初始化失败
}
};
@@ -731,6 +795,7 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
if (viewerRef.current && !viewerRef.current.isDestroyed()) {
viewerRef.current.destroy();
}
setViewerReady(false); // 清理时重置状态
};
}, []);
@@ -833,6 +898,7 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
};
}, [loading, handleDeviceSelect]);
// @ts-ignore
return (
<div style={{ width: '100%', height: '100%', position: 'relative' }}>
<div ref={containerRef} style={{ width: '100%', height: '100%' }} />
@@ -915,8 +981,27 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
/>
</Tooltip>
)}
{/* 图层管理按钮 - 航线和边界图层控制 */}
{!loading && selectedDevice && (
<Tooltip title="图层管理">
<Button
type="primary"
icon={<BarsOutlined />}
onClick={() => setLayerPanelVisible(!layerPanelVisible)}
style={{
position: 'absolute',
top: 10,
right: 230,
zIndex: 700,
background: layerPanelVisible ? '#00f0ff' : 'rgba(10, 20, 40, 0.9)',
borderColor: '#00f0ff',
}}
/>
</Tooltip>
)}
{/* 3D Tiles模型管理面板 - TODO: TilesetPanel组件未实现,暂时注释 */}
{/* 3D Tiles模型管理面板 */}
<TilesetPanel
visible={tilesetPanelVisible}
tilesets={tilesets}
@@ -945,6 +1030,7 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
onClose={handleRightPanelClose}
onControlClick={handleOpenControl}
onTaskPanelOpen={handleOpenTaskPanel}
onRoutePlanningOpen={handleOpenRoutePlanning}
viewer={viewerRef.current}
Cesium={Cesium}
/>
@@ -959,6 +1045,48 @@ const CesiumContainer: React.FC<CesiumContainerProps> = (props) => {
droneData={droneData}
dockData={taskPanelDockData}
/>
{/* 图层管理面板 - 左下角 */}
<LayerPanel
visible={layerPanelVisible}
onClose={() => setLayerPanelVisible(false)}
viewer={viewerRef.current}
Cesium={Cesium}
scenicId={selectedDevice?.scenicId}
onBoundaryEditorOpen={handleOpenBoundaryEditor}
/>
{/* 无人船航线规划面板 */}
{routePlanningVisible && routePlanningDevice && (
<div style={{
position: 'fixed',
top: 0,
left: 0,
right: 0,
bottom: 0,
zIndex: 1000,
background: 'rgba(0, 0, 0, 0.5)',
}}>
<RouteEditor
scenicId={routePlanningDevice.scenicId || 1}
deviceSn={routePlanningDevice.deviceSn}
onSaveSuccess={handleRoutesSaveSuccess}
onCancel={handleCloseRoutePlanning}
viewerRef={viewerRef}
/>
</div>
)}
{/* 水域边界编辑器 - 工具栏浮层形式,不遮挡地图 */}
{/* 只有当 viewer 完全就绪后才渲染 */}
{boundaryEditorVisible && viewerReady && (
<BoundaryEditor
scenicId={selectedDevice?.scenicId || 1}
onSaveSuccess={handleBoundarySaveSuccess}
onCancel={handleCloseBoundaryEditor}
viewerRef={viewerRef}
/>
)}
</div>
);
};
@@ -0,0 +1,147 @@
/**
* 航线预览组件
* @author dzc
* @date 2026-01-05
*/
import React from 'react';
import { Card, Descriptions, Alert, List, Tag, Progress } from 'antd';
import {
EnvironmentOutlined,
ClockCircleOutlined,
DashboardOutlined,
WarningOutlined,
CheckCircleOutlined,
CloseCircleOutlined,
} from '@ant-design/icons';
import type { RoutePreviewProps } from './types';
import styles from './index.less';
const RoutePreview: React.FC<RoutePreviewProps> = ({
waypoints,
cruiseSpeed,
totalDistance,
estimatedDuration,
validationResult,
}) => {
// 格式化距离
const formatDistance = (meters: number) => {
if (meters >= 1000) {
return `${(meters / 1000).toFixed(2)} km`;
}
return `${meters.toFixed(0)} m`;
};
// 格式化时长
const formatDuration = (seconds: number) => {
if (seconds < 60) {
return `${seconds} 秒`;
}
const minutes = Math.floor(seconds / 60);
const secs = seconds % 60;
if (minutes < 60) {
return secs > 0 ? `${minutes} 分 ${secs} 秒` : `${minutes} 分钟`;
}
const hours = Math.floor(minutes / 60);
const mins = minutes % 60;
return `${hours} 小时 ${mins} 分钟`;
};
return (
<div className={styles.preview}>
<Card size="small" title="航线预览" bordered={false}>
<Descriptions column={2} size="small">
<Descriptions.Item label={<><EnvironmentOutlined /> 航点数</>}>
{waypoints.length}
</Descriptions.Item>
<Descriptions.Item label={<><DashboardOutlined /> 巡航速度</>}>
{cruiseSpeed} m/s
</Descriptions.Item>
<Descriptions.Item label="总距离">
{formatDistance(totalDistance)}
</Descriptions.Item>
<Descriptions.Item label={<><ClockCircleOutlined /> 预计时长</>}>
{formatDuration(estimatedDuration)}
</Descriptions.Item>
</Descriptions>
{/* 校验结果 */}
{validationResult && (
<div style={{ marginTop: 12 }}>
{validationResult.valid ? (
<Alert
message="校验通过"
type="success"
icon={<CheckCircleOutlined />}
showIcon
style={{ marginBottom: 8 }}
/>
) : (
<Alert
message="校验失败"
type="error"
icon={<CloseCircleOutlined />}
showIcon
style={{ marginBottom: 8 }}
/>
)}
{/* 错误列表 */}
{validationResult.errors.length > 0 && (
<div style={{ marginBottom: 8 }}>
<div style={{ fontSize: 12, color: '#ff4d4f', marginBottom: 4 }}>
<CloseCircleOutlined /> 错误:
</div>
{validationResult.errors.map((err, i) => (
<Tag key={i} color="error" style={{ marginBottom: 4 }}>
{err}
</Tag>
))}
</div>
)}
{/* 警告列表 */}
{validationResult.warnings.length > 0 && (
<div>
<div style={{ fontSize: 12, color: '#faad14', marginBottom: 4 }}>
<WarningOutlined /> 警告:
</div>
{validationResult.warnings.map((warn, i) => (
<Tag key={i} color="warning" style={{ marginBottom: 4 }}>
{warn}
</Tag>
))}
</div>
)}
</div>
)}
</Card>
{/* 航点列表 */}
{waypoints.length > 0 && (
<Card size="small" title="航点列表" bordered={false} style={{ marginTop: 8 }}>
<List
size="small"
dataSource={waypoints}
style={{ maxHeight: 200, overflowY: 'auto' }}
renderItem={(wp, index) => (
<List.Item style={{ padding: '4px 0' }}>
<span style={{ width: 80 }}>
{wp.isKeyPoint && <Tag color="blue" style={{ marginRight: 4 }}>关键</Tag>}
{wp.pointName || `航点${index + 1}`}
</span>
<span style={{ fontSize: 11, color: '#999' }}>
{wp.longitude.toFixed(4)}, {wp.latitude.toFixed(4)}
</span>
{wp.stayDuration && wp.stayDuration > 0 && (
<Tag style={{ marginLeft: 4 }}>{wp.stayDuration}s</Tag>
)}
</List.Item>
)}
/>
</Card>
)}
</div>
);
};
export default RoutePreview;
@@ -0,0 +1,152 @@
/**
* 航线编辑器工具栏组件
* @author dzc
* @date 2026-01-05
*/
import React from 'react';
import { Button, Space, Tooltip, Popconfirm } from 'antd';
import {
EditOutlined,
SelectOutlined,
DeleteOutlined,
UndoOutlined,
CheckCircleOutlined,
SaveOutlined,
CloseOutlined,
AimOutlined,
EyeOutlined,
PauseCircleOutlined,
} from '@ant-design/icons';
import type { RouteToolbarProps } from './types';
import styles from './index.less';
const RouteToolbar: React.FC<RouteToolbarProps> = ({
mode,
hasWaypoints,
hasUnsavedChanges,
isValidating,
isPreviewing,
onModeChange,
onClear,
onUndo,
onValidate,
onSave,
onCancel,
onPreview,
onStopPreview,
}) => {
return (
<div className={styles.toolbar}>
<Space size="small">
{/* 绘制模式 */}
<Tooltip title="绘制航点">
<Button
type={mode === 'draw' ? 'primary' : 'default'}
icon={<AimOutlined />}
onClick={() => onModeChange('draw')}
disabled={isPreviewing}
>
绘制
</Button>
</Tooltip>
{/* 选择模式 */}
<Tooltip title="选择航点">
<Button
type={mode === 'select' || mode === 'edit' ? 'primary' : 'default'}
icon={<SelectOutlined />}
onClick={() => onModeChange('select')}
disabled={!hasWaypoints || isPreviewing}
>
选择
</Button>
</Tooltip>
<div className={styles.divider} />
{/* 第一视角预览 */}
{isPreviewing ? (
<Tooltip title="停止预览">
<Button
type="primary"
danger
icon={<PauseCircleOutlined />}
onClick={onStopPreview}
>
停止预览
</Button>
</Tooltip>
) : (
<Tooltip title="第一视角预览航线">
<Button
icon={<EyeOutlined />}
onClick={onPreview}
disabled={!hasWaypoints || (hasWaypoints && !onPreview)}
>
预览
</Button>
</Tooltip>
)}
<div className={styles.divider} />
{/* 撤销 */}
<Tooltip title="撤销">
<Button
icon={<UndoOutlined />}
onClick={onUndo}
disabled={!hasUnsavedChanges || isPreviewing}
/>
</Tooltip>
{/* 清空 */}
<Popconfirm
title="确定清空所有航点?"
onConfirm={onClear}
disabled={!hasWaypoints || isPreviewing}
>
<Tooltip title="清空航点">
<Button
icon={<DeleteOutlined />}
danger
disabled={!hasWaypoints || isPreviewing}
/>
</Tooltip>
</Popconfirm>
<div className={styles.divider} />
{/* 校验 */}
<Button
icon={<CheckCircleOutlined />}
onClick={onValidate}
loading={isValidating}
disabled={!hasWaypoints || isPreviewing}
>
校验
</Button>
{/* 保存 */}
<Button
type="primary"
icon={<SaveOutlined />}
onClick={onSave}
disabled={!hasWaypoints || isPreviewing}
>
保存
</Button>
{/* 取消 */}
<Popconfirm
title={hasUnsavedChanges ? "有未保存的更改,确定取消?" : "确定取消?"}
onConfirm={onCancel}
disabled={isPreviewing}
>
<Button icon={<CloseOutlined />} disabled={isPreviewing}>取消</Button>
</Popconfirm>
</Space>
</div>
);
};
export default RouteToolbar;
@@ -0,0 +1,205 @@
/**
* 航点编辑器组件
* @author dzc
* @date 2026-01-05
*/
import React from 'react';
import {
Drawer,
Form,
Input,
InputNumber,
Select,
Switch,
Button,
Space,
Divider,
List,
Tag,
} from 'antd';
import { DeleteOutlined, PlusOutlined } from '@ant-design/icons';
import type { BoatWaypointDTO, WaypointAction, WaypointActionType, TurnMode } from '@/types/boatRoute';
import type { WaypointEditorProps } from './types';
const { Option } = Select;
const { TextArea } = Input;
const turnModeOptions: { value: TurnMode; label: string }[] = [
{ value: 'sharp', label: '锐角转弯' },
{ value: 'smooth', label: '平滑转弯' },
{ value: 'arc', label: '弧线转弯' },
];
const actionTypeOptions: { value: WaypointActionType; label: string }[] = [
{ value: 'hover', label: '悬停' },
{ value: 'take_photo', label: '拍照' },
{ value: 'record_video', label: '录像' },
{ value: 'horn', label: '鸣笛' },
{ value: 'light', label: '灯光' },
{ value: 'spray', label: '喷洒' },
];
const WaypointEditor: React.FC<WaypointEditorProps> = ({
waypoint,
index,
onUpdate,
onDelete,
onClose,
}) => {
const [form] = Form.useForm();
const handleFinish = (values: any) => {
const updated: BoatWaypointDTO = {
...waypoint,
...values,
};
onUpdate(index, updated);
onClose();
};
const handleAddAction = () => {
const actions = form.getFieldValue('actions') || [];
form.setFieldsValue({
actions: [...actions, { actionType: 'hover', duration: 5 }],
});
};
const handleRemoveAction = (actionIndex: number) => {
const actions = form.getFieldValue('actions') || [];
form.setFieldsValue({
actions: actions.filter((_: any, i: number) => i !== actionIndex),
});
};
return (
<Drawer
title={`编辑航点 ${index + 1}`}
placement="right"
width={360}
onClose={onClose}
open={true}
extra={
<Space>
<Button danger onClick={() => { onDelete(index); onClose(); }}>
删除
</Button>
<Button type="primary" onClick={() => form.submit()}>
保存
</Button>
</Space>
}
>
<Form
form={form}
layout="vertical"
initialValues={{
pointName: waypoint.pointName || `航点${index + 1}`,
speed: waypoint.speed,
stayDuration: waypoint.stayDuration || 0,
turnMode: waypoint.turnMode || 'smooth',
isKeyPoint: waypoint.isKeyPoint || false,
actions: waypoint.actions || [],
remark: waypoint.remark,
}}
onFinish={handleFinish}
>
{/* 位置信息(只读) */}
<div style={{ marginBottom: 16, padding: '8px 12px', background: '#f5f5f5', borderRadius: 4 }}>
<div style={{ fontSize: 12, color: '#666' }}>
经度: {waypoint.longitude.toFixed(6)}
</div>
<div style={{ fontSize: 12, color: '#666' }}>
纬度: {waypoint.latitude.toFixed(6)}
</div>
</div>
<Form.Item name="pointName" label="航点名称">
<Input placeholder="请输入航点名称" />
</Form.Item>
<Form.Item name="speed" label="航点速度 (m/s)">
<InputNumber
min={0.1}
max={10}
step={0.1}
placeholder="使用默认速度"
style={{ width: '100%' }}
/>
</Form.Item>
<Form.Item name="stayDuration" label="停留时间 (秒)">
<InputNumber
min={0}
max={600}
step={1}
style={{ width: '100%' }}
/>
</Form.Item>
<Form.Item name="turnMode" label="转弯模式">
<Select>
{turnModeOptions.map(opt => (
<Option key={opt.value} value={opt.value}>{opt.label}</Option>
))}
</Select>
</Form.Item>
<Form.Item name="isKeyPoint" label="关键航点" valuePropName="checked">
<Switch />
</Form.Item>
<Divider>航点动作</Divider>
<Form.List name="actions">
{(fields, { remove }) => (
<>
{fields.map(({ key, name, ...restField }) => (
<div key={key} style={{ display: 'flex', gap: 8, marginBottom: 8 }}>
<Form.Item
{...restField}
name={[name, 'actionType']}
style={{ flex: 1, marginBottom: 0 }}
>
<Select placeholder="动作类型">
{actionTypeOptions.map(opt => (
<Option key={opt.value} value={opt.value}>{opt.label}</Option>
))}
</Select>
</Form.Item>
<Form.Item
{...restField}
name={[name, 'duration']}
style={{ width: 80, marginBottom: 0 }}
>
<InputNumber min={1} max={300} placeholder="秒" />
</Form.Item>
<Button
icon={<DeleteOutlined />}
onClick={() => remove(name)}
danger
/>
</div>
))}
<Button
type="dashed"
onClick={handleAddAction}
block
icon={<PlusOutlined />}
>
添加动作
</Button>
</>
)}
</Form.List>
<Divider />
<Form.Item name="remark" label="备注">
<TextArea rows={2} placeholder="可选备注信息" />
</Form.Item>
</Form>
</Drawer>
);
};
export default WaypointEditor;
@@ -0,0 +1,450 @@
/**
* Cesium航线渲染Hook
* 负责在Cesium地图上渲染和管理航线的可视化
* @author Claude
* @date 2026-01-06
*/
import { useEffect, useRef, useCallback } from 'react';
import type { BoatWaypointDTO } from '@/types/boatRoute';
import type { EditorMode } from '../types';
interface UseCesiumRouteRendererOptions {
viewerRef?: React.RefObject<any>;
waypoints: BoatWaypointDTO[];
selectedIndex: number | null;
mode: EditorMode; // 'view' | 'draw' | 'select' | 'edit'
boundaryGeoJson?: string; // 用于边界检测
onWaypointAdd: (point: { longitude: number; latitude: number }) => void;
onWaypointMove: (index: number, point: { longitude: number; latitude: number }) => void;
onWaypointSelect: (index: number) => void;
}
/**
* Cesium航线渲染Hook
*
* 功能:
* 1. 渲染航点marker(带编号、可拖动)
* 2. 渲染航线polyline
* 3. 处理地图点击事件(添加航点)
* 4. 处理航点拖动交互
* 5. 边界检测和告警(可选)
* 6. 相机聚焦到航线
*/
export function useCesiumRouteRenderer(options: UseCesiumRouteRendererOptions) {
const {
viewerRef,
waypoints,
selectedIndex,
mode,
boundaryGeoJson,
onWaypointAdd,
onWaypointMove,
onWaypointSelect,
} = options;
// Entity ID集合,用于清理
const entityIdsRef = useRef<Set<string>>(new Set());
// 事件处理器引用
const handlerRef = useRef<any>(null);
// 拖动状态
const draggingEntityRef = useRef<any>(null);
const rafIdRef = useRef<number | null>(null);
/**
* 获取Cesium对象
*/
const getCesium = useCallback(() => {
return (window as any).Cesium;
}, []);
/**
* 计算航点颜色
*/
const getWaypointColor = useCallback((index: number, isSelected: boolean, isOutOfBounds: boolean) => {
const Cesium = getCesium();
if (!Cesium) return null;
if (isOutOfBounds) {
return Cesium.Color.ORANGE; // 超出边界
}
if (isSelected) {
return Cesium.Color.YELLOW; // 选中
}
if (index === 0) {
return Cesium.Color.GREEN; // 起点
}
if (index === waypoints.length - 1 && waypoints.length > 1) {
return Cesium.Color.RED; // 终点
}
return Cesium.Color.CYAN; // 正常航点
}, [waypoints.length, getCesium]);
/**
* 检测点是否在边界内(射线法)
* 简化版本,如果需要完整实现可以从后端调用API
*/
const isPointInBoundary = useCallback((lon: number, lat: number): boolean => {
if (!boundaryGeoJson) return true; // 没有边界则认为都在范围内
try {
const boundary = JSON.parse(boundaryGeoJson);
// TODO: 实现射线法判断点是否在多边形内
// 这里暂时返回true,实际应该调用后端API或实现射线法
return true;
} catch (e) {
console.error('解析边界GeoJSON失败:', e);
return true;
}
}, [boundaryGeoJson]);
/**
* 清理所有Entity
*/
const cleanup = useCallback(() => {
const viewer = viewerRef?.current;
if (!viewer || viewer.isDestroyed?.()) return;
entityIdsRef.current.forEach(id => {
try {
viewer.entities.removeById(id);
} catch (e) {
// 忽略删除失败
}
});
entityIdsRef.current.clear();
}, [viewerRef]);
/**
* 渲染航点Marker
*/
const renderWaypoints = useCallback(() => {
const viewer = viewerRef?.current;
const Cesium = getCesium();
if (!viewer || !Cesium || viewer.isDestroyed?.()) return;
waypoints.forEach((wp, index) => {
const isSelected = index === selectedIndex;
const isOutOfBounds = !isPointInBoundary(wp.longitude, wp.latitude);
const color = getWaypointColor(index, isSelected, isOutOfBounds);
if (!color) return;
const entityId = `route-waypoint-${index}`;
try {
const entity = viewer.entities.add({
id: entityId,
position: Cesium.Cartesian3.fromDegrees(wp.longitude, wp.latitude, 0),
point: {
pixelSize: isSelected ? 18 : 14,
color: color,
outlineColor: Cesium.Color.WHITE,
outlineWidth: 2,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
},
label: {
text: `${index + 1}`,
font: isSelected ? '14px sans-serif' : '12px sans-serif',
fillColor: Cesium.Color.WHITE,
style: Cesium.LabelStyle.FILL_AND_OUTLINE,
outlineWidth: 2,
outlineColor: Cesium.Color.BLACK,
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
pixelOffset: new Cesium.Cartesian2(0, -20),
disableDepthTestDistance: Number.POSITIVE_INFINITY,
},
properties: {
type: 'route-waypoint',
waypointIndex: index,
draggable: true,
}
});
entityIdsRef.current.add(entityId);
} catch (e) {
console.error('添加航点entity失败:', e);
}
});
}, [viewerRef, waypoints, selectedIndex, getCesium, getWaypointColor, isPointInBoundary]);
/**
* 渲染航线Polyline
*/
const renderPolyline = useCallback(() => {
const viewer = viewerRef?.current;
const Cesium = getCesium();
if (!viewer || !Cesium || viewer.isDestroyed?.()) return;
if (waypoints.length < 2) return;
const positions = waypoints.map(wp =>
Cesium.Cartesian3.fromDegrees(wp.longitude, wp.latitude, 0)
);
const entityId = 'route-path';
try {
viewer.entities.add({
id: entityId,
polyline: {
positions: positions,
width: 4,
material: new Cesium.PolylineGlowMaterialProperty({
glowPower: 0.3,
color: Cesium.Color.CYAN,
}),
clampToGround: true,
}
});
entityIdsRef.current.add(entityId);
} catch (e) {
console.error('添加航线polyline失败:', e);
}
}, [viewerRef, waypoints, getCesium]);
/**
* 设置事件处理器
*/
const setupEventHandlers = useCallback(() => {
const viewer = viewerRef?.current;
const Cesium = getCesium();
if (!viewer || !Cesium || viewer.isDestroyed?.()) return;
// 清理旧的handler
if (handlerRef.current) {
try {
handlerRef.current.destroy();
} catch (e) {}
handlerRef.current = null;
}
const handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
handlerRef.current = handler;
// 根据模式设置不同的交互
if (mode === 'draw') {
// 绘制模式:点击地图添加航点
if (viewer.scene?.screenSpaceEventController) {
viewer.scene.screenSpaceEventController.enableRotate = false;
}
handler.setInputAction((movement: any) => {
const ray = viewer.camera.getPickRay(movement.position);
const cartesian = viewer.scene.globe.pick(ray, viewer.scene);
if (cartesian) {
const cartographic = Cesium.Cartographic.fromCartesian(cartesian);
const longitude = Cesium.Math.toDegrees(cartographic.longitude);
const latitude = Cesium.Math.toDegrees(cartographic.latitude);
onWaypointAdd({ longitude, latitude });
}
}, Cesium.ScreenSpaceEventType.LEFT_CLICK);
} else if (mode === 'select' || mode === 'edit') {
// 选择/编辑模式:支持拖动和选择
if (viewer.scene?.screenSpaceEventController) {
viewer.scene.screenSpaceEventController.enableRotate = true;
}
// LEFT_DOWN: 开始拖拽或选择
handler.setInputAction((movement: any) => {
const pickedObject = viewer.scene.pick(movement.position);
if (Cesium.defined(pickedObject) && pickedObject.id) {
const entity = pickedObject.id;
const properties = entity.properties;
if (properties?.type?.getValue() === 'route-waypoint') {
const waypointIndex = properties.waypointIndex?.getValue();
if (typeof waypointIndex === 'number') {
// 选择航点
onWaypointSelect(waypointIndex);
// 如果是编辑模式,准备拖动
if (mode === 'edit' && properties.draggable?.getValue()) {
draggingEntityRef.current = entity;
if (viewer.scene?.screenSpaceEventController) {
viewer.scene.screenSpaceEventController.enableRotate = false;
}
}
}
}
}
}, Cesium.ScreenSpaceEventType.LEFT_DOWN);
// MOUSE_MOVE: 拖拽中(使用requestAnimationFrame节流)
handler.setInputAction((movement: any) => {
if (draggingEntityRef.current && !rafIdRef.current) {
rafIdRef.current = requestAnimationFrame(() => {
const entity = draggingEntityRef.current;
if (!entity) {
rafIdRef.current = null;
return;
}
const ray = viewer.camera.getPickRay(movement.endPosition);
const cartesian = viewer.scene.globe.pick(ray, viewer.scene);
if (cartesian) {
// 更新entity位置
entity.position = cartesian;
// 通知外部更新waypoint数据
const cartographic = Cesium.Cartographic.fromCartesian(cartesian);
const waypointIndex = entity.properties?.waypointIndex?.getValue();
if (typeof waypointIndex === 'number') {
onWaypointMove(waypointIndex, {
longitude: Cesium.Math.toDegrees(cartographic.longitude),
latitude: Cesium.Math.toDegrees(cartographic.latitude),
});
}
}
rafIdRef.current = null;
});
}
}, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
// LEFT_UP: 结束拖拽
handler.setInputAction(() => {
if (draggingEntityRef.current) {
if (viewer.scene?.screenSpaceEventController) {
viewer.scene.screenSpaceEventController.enableRotate = true;
}
draggingEntityRef.current = null;
}
}, Cesium.ScreenSpaceEventType.LEFT_UP);
} else {
// view模式:恢复默认交互
if (viewer.scene?.screenSpaceEventController) {
viewer.scene.screenSpaceEventController.enableRotate = true;
}
}
}, [viewerRef, mode, getCesium, onWaypointAdd, onWaypointMove, onWaypointSelect]);
/**
* 计算航线边界
*/
const calculateBounds = useCallback((points: BoatWaypointDTO[]) => {
if (points.length === 0) {
return { west: 0, south: 0, east: 0, north: 0 };
}
let west = points[0].longitude;
let east = points[0].longitude;
let south = points[0].latitude;
let north = points[0].latitude;
points.forEach(p => {
west = Math.min(west, p.longitude);
east = Math.max(east, p.longitude);
south = Math.min(south, p.latitude);
north = Math.max(north, p.latitude);
});
// 添加一些padding
const paddingLon = (east - west) * 0.1 || 0.01;
const paddingLat = (north - south) * 0.1 || 0.01;
return {
west: west - paddingLon,
south: south - paddingLat,
east: east + paddingLon,
north: north + paddingLat,
};
}, []);
/**
* 相机飞到航线
*/
const flyToRoute = useCallback(() => {
const viewer = viewerRef?.current;
const Cesium = getCesium();
if (!viewer || !Cesium || viewer.isDestroyed?.() || waypoints.length === 0) return;
const bounds = calculateBounds(waypoints);
try {
viewer.camera.flyTo({
destination: Cesium.Rectangle.fromDegrees(
bounds.west,
bounds.south,
bounds.east,
bounds.north
),
duration: 1.0,
});
} catch (e) {
console.error('飞到航线失败:', e);
}
}, [viewerRef, waypoints, getCesium, calculateBounds]);
/**
* 渲染所有内容
*/
const render = useCallback(() => {
cleanup();
renderWaypoints();
renderPolyline();
}, [cleanup, renderWaypoints, renderPolyline]);
// waypoints或selectedIndex变化时重新渲染
useEffect(() => {
render();
}, [waypoints, selectedIndex, render]);
// mode变化时重新设置事件处理器
useEffect(() => {
setupEventHandlers();
}, [mode, setupEventHandlers]);
// 组件挂载时飞到航线(仅执行一次)
useEffect(() => {
if (waypoints.length > 0) {
// 延迟执行,确保viewer已准备好
setTimeout(() => {
flyToRoute();
}, 300);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []); // 空依赖数组,只在挂载时执行
// 组件卸载时清理
useEffect(() => {
return () => {
cleanup();
// 清理事件处理器
if (handlerRef.current) {
try {
handlerRef.current.destroy();
} catch (e) {}
handlerRef.current = null;
}
// 取消pending的RAF
if (rafIdRef.current) {
cancelAnimationFrame(rafIdRef.current);
rafIdRef.current = null;
}
// 恢复地图旋转
const viewer = viewerRef?.current;
if (viewer && !viewer.isDestroyed?.() && viewer.scene?.screenSpaceEventController) {
viewer.scene.screenSpaceEventController.enableRotate = true;
}
};
}, [cleanup, viewerRef]);
return {
cleanup,
render,
flyToRoute,
};
}
@@ -0,0 +1,237 @@
/**
* 航线绘制Hook
* 管理航线绘制、编辑、历史记录等状态
* @author dzc
* @date 2026-01-05
*/
import { useState, useCallback, useRef, useMemo } from 'react';
import type { BoatWaypointDTO } from '@/types/boatRoute';
import type { EditorMode, EditorState, MapClickEvent, HistoryItem } from '../types';
const MAX_HISTORY = 50;
export interface UseRouteDrawingOptions {
initialWaypoints?: BoatWaypointDTO[];
maxWaypoints?: number;
}
export interface UseRouteDrawingReturn {
waypoints: BoatWaypointDTO[];
editorState: EditorState;
setMode: (mode: EditorMode) => void;
addWaypoint: (point: MapClickEvent) => void;
updateWaypoint: (index: number, waypoint: BoatWaypointDTO) => void;
deleteWaypoint: (index: number) => void;
moveWaypoint: (index: number, point: MapClickEvent) => void;
selectWaypoint: (index: number | null) => void;
clearWaypoints: () => void;
setWaypoints: (waypoints: BoatWaypointDTO[]) => void;
undo: () => void;
canUndo: boolean;
markSaved: () => void;
}
export const useRouteDrawing = (options: UseRouteDrawingOptions = {}): UseRouteDrawingReturn => {
const { initialWaypoints = [], maxWaypoints = 100 } = options;
const [waypoints, setWaypointsState] = useState<BoatWaypointDTO[]>(initialWaypoints);
const [editorState, setEditorState] = useState<EditorState>({
mode: 'view',
selectedWaypointIndex: null,
isDrawing: false,
isDragging: false,
hasUnsavedChanges: false,
});
// 历史记录
const historyRef = useRef<HistoryItem[]>([]);
const historyIndexRef = useRef<number>(-1);
// 添加到历史记录
const pushHistory = useCallback((newWaypoints: BoatWaypointDTO[]) => {
// 截断当前位置之后的历史
historyRef.current = historyRef.current.slice(0, historyIndexRef.current + 1);
// 添加新记录
historyRef.current.push({
waypoints: JSON.parse(JSON.stringify(newWaypoints)),
timestamp: Date.now(),
});
// 限制历史记录数量
if (historyRef.current.length > MAX_HISTORY) {
historyRef.current.shift();
} else {
historyIndexRef.current++;
}
}, []);
// 设置模式
const setMode = useCallback((mode: EditorMode) => {
setEditorState(prev => ({
...prev,
mode,
isDrawing: mode === 'draw',
selectedWaypointIndex: mode === 'draw' ? null : prev.selectedWaypointIndex,
}));
}, []);
// 添加航点
const addWaypoint = useCallback((point: MapClickEvent) => {
if (waypoints.length >= maxWaypoints) {
console.warn(`已达到最大航点数量: ${maxWaypoints}`);
return;
}
const newWaypoint: BoatWaypointDTO = {
longitude: point.longitude,
latitude: point.latitude,
pointName: `航点${waypoints.length + 1}`,
turnMode: 'smooth',
isKeyPoint: false,
};
const newWaypoints = [...waypoints, newWaypoint];
setWaypointsState(newWaypoints);
pushHistory(newWaypoints);
setEditorState(prev => ({
...prev,
hasUnsavedChanges: true,
selectedWaypointIndex: newWaypoints.length - 1,
}));
}, [waypoints, maxWaypoints, pushHistory]);
// 更新航点
const updateWaypoint = useCallback((index: number, waypoint: BoatWaypointDTO) => {
if (index < 0 || index >= waypoints.length) return;
const newWaypoints = [...waypoints];
newWaypoints[index] = waypoint;
setWaypointsState(newWaypoints);
pushHistory(newWaypoints);
setEditorState(prev => ({
...prev,
hasUnsavedChanges: true,
}));
}, [waypoints, pushHistory]);
// 删除航点
const deleteWaypoint = useCallback((index: number) => {
if (index < 0 || index >= waypoints.length) return;
const newWaypoints = waypoints.filter((_, i) => i !== index);
// 重新编号
newWaypoints.forEach((wp, i) => {
if (wp.pointName?.startsWith('航点')) {
wp.pointName = `航点${i + 1}`;
}
});
setWaypointsState(newWaypoints);
pushHistory(newWaypoints);
setEditorState(prev => ({
...prev,
hasUnsavedChanges: true,
selectedWaypointIndex: prev.selectedWaypointIndex === index ? null : prev.selectedWaypointIndex,
}));
}, [waypoints, pushHistory]);
// 移动航点
const moveWaypoint = useCallback((index: number, point: MapClickEvent) => {
if (index < 0 || index >= waypoints.length) return;
const newWaypoints = [...waypoints];
newWaypoints[index] = {
...newWaypoints[index],
longitude: point.longitude,
latitude: point.latitude,
};
setWaypointsState(newWaypoints);
pushHistory(newWaypoints);
setEditorState(prev => ({
...prev,
hasUnsavedChanges: true,
}));
}, [waypoints, pushHistory]);
// 选择航点
const selectWaypoint = useCallback((index: number | null) => {
setEditorState(prev => ({
...prev,
selectedWaypointIndex: index,
mode: index !== null ? 'edit' : prev.mode,
}));
}, []);
// 清空航点
const clearWaypoints = useCallback(() => {
pushHistory([]);
setWaypointsState([]);
setEditorState(prev => ({
...prev,
hasUnsavedChanges: true,
selectedWaypointIndex: null,
}));
}, [pushHistory]);
// 设置航点 (加载时使用)
const setWaypoints = useCallback((newWaypoints: BoatWaypointDTO[]) => {
setWaypointsState(newWaypoints);
historyRef.current = [{
waypoints: JSON.parse(JSON.stringify(newWaypoints)),
timestamp: Date.now(),
}];
historyIndexRef.current = 0;
setEditorState(prev => ({
...prev,
hasUnsavedChanges: false,
selectedWaypointIndex: null,
}));
}, []);
// 撤销
const undo = useCallback(() => {
if (historyIndexRef.current > 0) {
historyIndexRef.current--;
const prevState = historyRef.current[historyIndexRef.current];
setWaypointsState(JSON.parse(JSON.stringify(prevState.waypoints)));
setEditorState(prev => ({
...prev,
hasUnsavedChanges: true,
selectedWaypointIndex: null,
}));
}
}, []);
// 是否可撤销
const canUndo = useMemo(() => historyIndexRef.current > 0, [waypoints]);
// 标记已保存
const markSaved = useCallback(() => {
setEditorState(prev => ({
...prev,
hasUnsavedChanges: false,
}));
}, []);
return {
waypoints,
editorState,
setMode,
addWaypoint,
updateWaypoint,
deleteWaypoint,
moveWaypoint,
selectWaypoint,
clearWaypoints,
setWaypoints,
undo,
canUndo,
markSaved,
};
};
@@ -0,0 +1,111 @@
/**
* 航线校验Hook
* @author dzc
* @date 2026-01-05
*/
import { useState, useCallback } from 'react';
import { message } from 'antd';
import type { BoatWaypointDTO, BoatRouteCreateDTO, RouteValidateResultVO } from '@/types/boatRoute';
import { validateBoatRoute, calculateRoutePreview } from '@/services/boatRoute';
export interface UseRouteValidationOptions {
boundaryId?: string;
scenicId: number;
}
export interface UseRouteValidationReturn {
validating: boolean;
validationResult: RouteValidateResultVO | null;
previewInfo: {
totalDistance: number;
estimatedDuration: number;
};
validate: (waypoints: BoatWaypointDTO[], cruiseSpeed: number) => Promise<boolean>;
clearValidation: () => void;
updatePreview: (waypoints: BoatWaypointDTO[], cruiseSpeed: number) => void;
}
export const useRouteValidation = (options: UseRouteValidationOptions): UseRouteValidationReturn => {
const { boundaryId, scenicId } = options;
const [validating, setValidating] = useState(false);
const [validationResult, setValidationResult] = useState<RouteValidateResultVO | null>(null);
const [previewInfo, setPreviewInfo] = useState({
totalDistance: 0,
estimatedDuration: 0,
});
// 更新预览信息 (本地计算)
const updatePreview = useCallback((waypoints: BoatWaypointDTO[], cruiseSpeed: number) => {
const preview = calculateRoutePreview(waypoints, cruiseSpeed);
setPreviewInfo(preview);
}, []);
// 校验航线
const validate = useCallback(async (
waypoints: BoatWaypointDTO[],
cruiseSpeed: number
): Promise<boolean> => {
if (waypoints.length < 2) {
message.warning('航线至少需要2个航点');
return false;
}
setValidating(true);
try {
const dto: BoatRouteCreateDTO = {
routeName: '临时校验',
scenicId,
cruiseSpeed,
waypoints,
};
const response = await validateBoatRoute(dto, boundaryId);
if (response.resp_code === 0 && response.datas) {
setValidationResult(response.datas);
if (!response.datas.valid) {
message.error(`航线校验失败: ${response.datas.errors.join(', ')}`);
return false;
}
if (response.datas.warnings.length > 0) {
message.warning(`校验通过,但有警告: ${response.datas.warnings.join(', ')}`);
} else {
message.success('航线校验通过');
}
// 更新预览信息
setPreviewInfo({
totalDistance: response.datas.totalDistance,
estimatedDuration: response.datas.estimatedDuration,
});
return true;
} else {
message.error(response.resp_msg || '校验失败');
return false;
}
} catch (error) {
console.error('航线校验失败:', error);
message.error('航线校验失败');
return false;
} finally {
setValidating(false);
}
}, [boundaryId, scenicId]);
// 清除校验结果
const clearValidation = useCallback(() => {
setValidationResult(null);
}, []);
return {
validating,
validationResult,
previewInfo,
validate,
clearValidation,
updatePreview,
};
};
@@ -0,0 +1,101 @@
.toolbar {
display: flex;
align-items: center;
padding: 8px 12px;
background: rgba(255, 255, 255, 0.95);
border-radius: 4px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}
.divider {
width: 1px;
height: 24px;
background: #e8e8e8;
margin: 0 8px;
}
.preview {
width: 280px;
max-height: 400px;
overflow-y: auto;
}
.editor {
position: relative;
}
.editorOverlay {
position: absolute;
top: 12px;
left: 12px;
z-index: 100;
}
.editorSidebar {
position: absolute;
top: 12px;
right: 12px;
z-index: 100;
}
.saveModal {
:global {
.ant-modal-body {
padding: 24px;
}
}
}
.waypointMarker {
width: 24px;
height: 24px;
border-radius: 50%;
background: #1890ff;
border: 2px solid #fff;
display: flex;
align-items: center;
justify-content: center;
color: #fff;
font-size: 12px;
font-weight: bold;
cursor: pointer;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
transition: transform 0.2s;
&:hover {
transform: scale(1.2);
}
&.selected {
background: #ff4d4f;
transform: scale(1.2);
}
&.keyPoint {
background: #52c41a;
}
}
.routeLine {
stroke: #1890ff;
stroke-width: 3;
fill: none;
stroke-linecap: round;
stroke-linejoin: round;
}
.boundaryFill {
fill: rgba(24, 144, 255, 0.1);
stroke: #1890ff;
stroke-width: 2;
stroke-dasharray: 5, 5;
}
.tip {
padding: 8px 12px;
background: rgba(0, 0, 0, 0.7);
color: #fff;
border-radius: 4px;
font-size: 12px;
margin-top: 8px;
}
@@ -0,0 +1,527 @@
/**
* 无人船航线编辑器主组件
* @author dzc
* @date 2026-01-05
*/
import React, { useState, useEffect, useCallback, useMemo, useRef } from 'react';
import { Modal, Form, Input, InputNumber, Switch, Select, message, Spin } from 'antd';
import type { BoatRouteCreateDTO, BoatRouteUpdateDTO } from '@/types/boatRoute';
import type { RouteEditorProps, EditorMode } from './types';
import { useRouteDrawing } from './hooks/useRouteDrawing';
import { useRouteValidation } from './hooks/useRouteValidation';
import { useCesiumRouteRenderer } from './hooks/useCesiumRouteRenderer';
import RouteToolbar from './RouteToolbar';
import RoutePreview from './RoutePreview';
import WaypointEditor from './WaypointEditor';
import { createBoatRoute, updateBoatRoute, getBoatRouteDetail } from '@/services/boatRoute';
import styles from './index.less';
const { Option } = Select;
const RouteEditor: React.FC<RouteEditorProps> = ({
scenicId,
deviceSn,
boundaryId,
routeId,
initialWaypoints,
onSaveSuccess,
onCancel,
viewerRef,
}) => {
const [loading, setLoading] = useState(false);
const [saveModalVisible, setSaveModalVisible] = useState(false);
const [form] = Form.useForm();
// 航线绘制Hook
const {
waypoints,
editorState,
setMode,
addWaypoint,
updateWaypoint,
deleteWaypoint,
moveWaypoint,
selectWaypoint,
clearWaypoints,
setWaypoints,
undo,
canUndo,
markSaved,
} = useRouteDrawing({ initialWaypoints });
// 航线校验Hook
const {
validating,
validationResult,
previewInfo,
validate,
clearValidation,
updatePreview,
} = useRouteValidation({ boundaryId, scenicId });
// 处理地图点击(需要在 useCesiumRouteRenderer 之前定义)
const handleMapClick = useCallback((event: { longitude: number; latitude: number }) => {
if (editorState.mode === 'draw') {
addWaypoint(event);
clearValidation();
}
}, [editorState.mode, addWaypoint, clearValidation]);
// 处理航点选择(需要在 useCesiumRouteRenderer 之前定义)
const handleWaypointSelect = useCallback((index: number) => {
selectWaypoint(index);
setMode('edit');
}, [selectWaypoint, setMode]);
// Cesium航线渲染Hook
useCesiumRouteRenderer({
viewerRef,
waypoints,
selectedIndex: editorState.selectedWaypointIndex,
mode: editorState.mode,
onWaypointAdd: handleMapClick,
onWaypointMove: moveWaypoint,
onWaypointSelect: handleWaypointSelect,
});
// 第一视角预览状态
const [isPreviewing, setIsPreviewing] = useState(false);
const previewAnimationRef = useRef<number | null>(null);
const savedCameraStateRef = useRef<any>(null);
// 计算两点之间的航向角(度)
const calculateHeading = useCallback((from: { longitude: number; latitude: number }, to: { longitude: number; latitude: number }) => {
const dLon = (to.longitude - from.longitude) * Math.PI / 180;
const lat1 = from.latitude * Math.PI / 180;
const lat2 = to.latitude * Math.PI / 180;
const y = Math.sin(dLon) * Math.cos(lat2);
const x = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(dLon);
const bearing = Math.atan2(y, x) * 180 / Math.PI;
return (bearing + 360) % 360;
}, []);
// 开始第一视角预览
const handlePreview = useCallback(() => {
if (!viewerRef?.current || waypoints.length < 2) {
message.warning('至少需要2个航点才能预览');
return;
}
const viewer = viewerRef.current;
const Cesium = (window as any).Cesium;
if (!Cesium) {
message.error('Cesium 未加载');
return;
}
// 保存当前相机状态
savedCameraStateRef.current = {
position: viewer.camera.position.clone(),
heading: viewer.camera.heading,
pitch: viewer.camera.pitch,
roll: viewer.camera.roll,
};
setIsPreviewing(true);
message.info('开始航线预览,点击"停止预览"或按ESC退出');
// 计算预览路径和时间
const speed = form.getFieldValue('cruiseSpeed') || 2; // m/s
const viewHeight = 10; // 观察高度(米)
const pitchAngle = -15; // 俯视角度
let currentIndex = 0;
let progress = 0;
const animatePreview = () => {
if (currentIndex >= waypoints.length - 1) {
// 预览完成
handleStopPreview();
message.success('航线预览完成');
return;
}
const from = waypoints[currentIndex];
const to = waypoints[currentIndex + 1];
// 计算两点距离
const dLon = (to.longitude - from.longitude) * Math.PI / 180 * 6371000 * Math.cos(from.latitude * Math.PI / 180);
const dLat = (to.latitude - from.latitude) * Math.PI / 180 * 6371000;
const distance = Math.sqrt(dLon * dLon + dLat * dLat);
// 计算移动时间(毫秒)
const duration = (distance / speed) * 1000;
const deltaTime = 50; // 动画帧间隔(毫秒)
const step = deltaTime / duration;
progress += step;
if (progress >= 1) {
progress = 0;
currentIndex++;
if (currentIndex >= waypoints.length - 1) {
handleStopPreview();
message.success('航线预览完成');
return;
}
}
// 插值计算当前位置
const currentWp = waypoints[currentIndex];
const nextWp = waypoints[currentIndex + 1];
const currentLon = currentWp.longitude + (nextWp.longitude - currentWp.longitude) * progress;
const currentLat = currentWp.latitude + (nextWp.latitude - currentWp.latitude) * progress;
// 计算航向
const heading = calculateHeading(currentWp, nextWp);
// 设置相机位置(第一视角)
viewer.camera.setView({
destination: Cesium.Cartesian3.fromDegrees(currentLon, currentLat, viewHeight),
orientation: {
heading: Cesium.Math.toRadians(heading),
pitch: Cesium.Math.toRadians(pitchAngle),
roll: 0,
},
});
previewAnimationRef.current = requestAnimationFrame(animatePreview);
};
// 启动动画
previewAnimationRef.current = requestAnimationFrame(animatePreview);
// ESC 键监听
const handleEsc = (e: KeyboardEvent) => {
if (e.key === 'Escape') {
handleStopPreview();
}
};
window.addEventListener('keydown', handleEsc);
// 保存清理函数引用
(previewAnimationRef as any).escHandler = handleEsc;
}, [viewerRef, waypoints, form, calculateHeading]);
// 停止预览
const handleStopPreview = useCallback(() => {
setIsPreviewing(false);
// 取消动画
if (previewAnimationRef.current) {
cancelAnimationFrame(previewAnimationRef.current);
previewAnimationRef.current = null;
}
// 移除 ESC 监听
if ((previewAnimationRef as any).escHandler) {
window.removeEventListener('keydown', (previewAnimationRef as any).escHandler);
(previewAnimationRef as any).escHandler = null;
}
// 恢复相机状态
if (savedCameraStateRef.current && viewerRef?.current) {
const viewer = viewerRef.current;
viewer.camera.setView({
destination: savedCameraStateRef.current.position,
orientation: {
heading: savedCameraStateRef.current.heading,
pitch: savedCameraStateRef.current.pitch,
roll: savedCameraStateRef.current.roll,
},
});
savedCameraStateRef.current = null;
}
}, [viewerRef]);
// 组件卸载时清理预览
useEffect(() => {
return () => {
if (previewAnimationRef.current) {
cancelAnimationFrame(previewAnimationRef.current);
}
if ((previewAnimationRef as any).escHandler) {
window.removeEventListener('keydown', (previewAnimationRef as any).escHandler);
}
};
}, []);
// 加载现有航线
useEffect(() => {
if (routeId) {
loadRoute(routeId);
}
}, [routeId]);
// 更新预览信息
useEffect(() => {
const speed = form.getFieldValue('cruiseSpeed') || 2;
updatePreview(waypoints, speed);
}, [waypoints, updatePreview]);
const loadRoute = async (id: string) => {
setLoading(true);
try {
const response = await getBoatRouteDetail(id);
if (response.resp_code === 0 && response.datas) {
const route = response.datas;
// 设置表单值
form.setFieldsValue({
routeName: route.routeName,
cruiseSpeed: route.cruiseSpeed,
loopEnabled: route.loopEnabled,
loopCount: route.loopCount,
returnMode: route.returnMode,
safeDistance: route.safeDistance,
remark: route.remark,
});
// 设置航点
const waypointDTOs = route.waypoints.map(wp => ({
longitude: wp.longitude,
latitude: wp.latitude,
speed: wp.speed,
stayDuration: wp.stayDuration,
turnMode: wp.turnMode as any,
pointName: wp.pointName,
isKeyPoint: wp.isKeyPoint,
actions: wp.actions,
remark: wp.remark,
}));
setWaypoints(waypointDTOs);
}
} catch (error) {
message.error('加载航线失败');
} finally {
setLoading(false);
}
};
// 处理模式切换
const handleModeChange = useCallback((mode: EditorMode) => {
setMode(mode);
if (mode !== 'edit') {
selectWaypoint(null);
}
}, [setMode, selectWaypoint]);
// 处理校验
const handleValidate = useCallback(async () => {
const speed = form.getFieldValue('cruiseSpeed') || 2;
await validate(waypoints, speed);
}, [form, waypoints, validate]);
// 打开保存对话框
const handleOpenSaveModal = useCallback(() => {
if (waypoints.length < 2) {
message.warning('航线至少需要2个航点');
return;
}
setSaveModalVisible(true);
}, [waypoints]);
// 处理保存
const handleSave = useCallback(async () => {
try {
const values = await form.validateFields();
// 先校验
const isValid = await validate(waypoints, values.cruiseSpeed);
if (!isValid) {
return;
}
setLoading(true);
if (routeId) {
// 更新航线
const updateDTO: BoatRouteUpdateDTO = {
routeName: values.routeName,
cruiseSpeed: values.cruiseSpeed,
loopEnabled: values.loopEnabled,
loopCount: values.loopCount,
returnMode: values.returnMode,
safeDistance: values.safeDistance,
waypoints,
remark: values.remark,
};
const response = await updateBoatRoute(routeId, updateDTO);
if (response.resp_code === 0) {
message.success('航线更新成功');
markSaved();
setSaveModalVisible(false);
onSaveSuccess?.(routeId);
} else {
message.error(response.resp_msg || '更新失败');
}
} else {
// 创建航线
const createDTO: BoatRouteCreateDTO = {
routeName: values.routeName,
deviceSn,
scenicId,
cruiseSpeed: values.cruiseSpeed,
loopEnabled: values.loopEnabled,
loopCount: values.loopCount,
returnMode: values.returnMode,
safeDistance: values.safeDistance,
waypoints,
remark: values.remark,
};
const response = await createBoatRoute(createDTO);
if (response.resp_code === 0 && response.datas) {
message.success('航线创建成功');
markSaved();
setSaveModalVisible(false);
onSaveSuccess?.(response.datas);
} else {
message.error(response.resp_msg || '创建失败');
}
}
} catch (error) {
console.error('保存航线失败:', error);
} finally {
setLoading(false);
}
}, [form, waypoints, routeId, deviceSn, scenicId, validate, markSaved, onSaveSuccess]);
// 处理取消
const handleCancel = useCallback(() => {
onCancel?.();
}, [onCancel]);
// 提示信息
const tipText = useMemo(() => {
switch (editorState.mode) {
case 'draw':
return '点击地图添加航点,双击结束绘制';
case 'select':
return '点击航点进行选择编辑';
case 'edit':
return '拖动航点移动位置,或在右侧面板编辑属性';
default:
return '选择工具开始编辑航线';
}
}, [editorState.mode]);
return (
<div className={styles.editor}>
<Spin spinning={loading}>
{/* 工具栏 */}
<div className={styles.editorOverlay}>
<RouteToolbar
mode={editorState.mode}
hasWaypoints={waypoints.length > 0}
hasUnsavedChanges={editorState.hasUnsavedChanges}
isValidating={validating}
isPreviewing={isPreviewing}
onModeChange={handleModeChange}
onClear={clearWaypoints}
onUndo={undo}
onValidate={handleValidate}
onSave={handleOpenSaveModal}
onCancel={handleCancel}
onPreview={viewerRef ? handlePreview : undefined}
onStopPreview={handleStopPreview}
/>
<div className={styles.tip}>{isPreviewing ? '第一视角预览中... 按ESC或点击"停止预览"退出' : tipText}</div>
</div>
{/* 右侧预览面板 */}
<div className={styles.editorSidebar}>
<RoutePreview
waypoints={waypoints}
cruiseSpeed={form.getFieldValue('cruiseSpeed') || 2}
totalDistance={previewInfo.totalDistance}
estimatedDuration={previewInfo.estimatedDuration}
validationResult={validationResult || undefined}
/>
</div>
{/* 航点编辑抽屉 */}
{editorState.selectedWaypointIndex !== null && waypoints[editorState.selectedWaypointIndex] && (
<WaypointEditor
waypoint={waypoints[editorState.selectedWaypointIndex]}
index={editorState.selectedWaypointIndex}
onUpdate={updateWaypoint}
onDelete={deleteWaypoint}
onClose={() => selectWaypoint(null)}
/>
)}
{/* 保存对话框 */}
<Modal
title={routeId ? '更新航线' : '保存航线'}
open={saveModalVisible}
onOk={handleSave}
onCancel={() => setSaveModalVisible(false)}
confirmLoading={loading}
width={480}
className={styles.saveModal}
>
<Form
form={form}
layout="vertical"
initialValues={{
cruiseSpeed: 2,
loopEnabled: false,
loopCount: 1,
returnMode: 'origin',
safeDistance: 5,
}}
>
<Form.Item
name="routeName"
label="航线名称"
rules={[{ required: true, message: '请输入航线名称' }]}
>
<Input placeholder="请输入航线名称" />
</Form.Item>
<Form.Item
name="cruiseSpeed"
label="巡航速度 (m/s)"
rules={[{ required: true, message: '请输入巡航速度' }]}
>
<InputNumber min={0.1} max={10} step={0.1} style={{ width: '100%' }} />
</Form.Item>
<Form.Item name="loopEnabled" label="启用循环" valuePropName="checked">
<Switch />
</Form.Item>
<Form.Item
noStyle
shouldUpdate={(prev, cur) => prev.loopEnabled !== cur.loopEnabled}
>
{({ getFieldValue }) =>
getFieldValue('loopEnabled') && (
<Form.Item name="loopCount" label="循环次数">
<InputNumber min={1} max={99} style={{ width: '100%' }} />
</Form.Item>
)
}
</Form.Item>
<Form.Item name="returnMode" label="返航模式">
<Select>
<Option value="origin">返回起点</Option>
<Option value="nearest">最近岸边</Option>
<Option value="current">当前位置停留</Option>
</Select>
</Form.Item>
<Form.Item name="safeDistance" label="安全距离 (米)">
<InputNumber min={1} max={50} style={{ width: '100%' }} />
</Form.Item>
<Form.Item name="remark" label="备注">
<Input.TextArea rows={2} placeholder="可选备注信息" />
</Form.Item>
</Form>
</Modal>
</Spin>
</div>
);
};
export default RouteEditor;
@@ -0,0 +1,113 @@
/**
* 航线编辑器本地类型定义
* @author dzc
* @date 2026-01-05
*/
import type { BoatWaypointDTO, TurnMode, WaypointAction } from '@/types/boatRoute';
/** 编辑器模式 */
export type EditorMode = 'view' | 'draw' | 'edit' | 'select';
/** 编辑状态 */
export interface EditorState {
mode: EditorMode;
selectedWaypointIndex: number | null;
isDrawing: boolean;
isDragging: boolean;
hasUnsavedChanges: boolean;
}
/** 地图点击事件 */
export interface MapClickEvent {
longitude: number;
latitude: number;
altitude?: number;
}
/** 航点编辑表单值 */
export interface WaypointFormValues {
pointName: string;
speed?: number;
stayDuration?: number;
turnMode: TurnMode;
isKeyPoint: boolean;
actions: WaypointAction[];
remark?: string;
}
/** 航线编辑器Props */
export interface RouteEditorProps {
/** 景区ID */
scenicId: number;
/** 设备SN (可选) */
deviceSn?: string;
/** 水域边界ID (可选) */
boundaryId?: string;
/** 编辑现有航线时传入routeId */
routeId?: string;
/** 初始航点 (复制模板时) */
initialWaypoints?: BoatWaypointDTO[];
/** 保存成功回调 */
onSaveSuccess?: (routeId: string) => void;
/** 取消回调 */
onCancel?: () => void;
/** Cesium Viewer引用 */
viewerRef?: React.RefObject<any>;
}
/** 航线工具栏Props */
export interface RouteToolbarProps {
mode: EditorMode;
hasWaypoints: boolean;
hasUnsavedChanges: boolean;
isValidating: boolean;
isPreviewing?: boolean;
onModeChange: (mode: EditorMode) => void;
onClear: () => void;
onUndo: () => void;
onValidate: () => void;
onSave: () => void;
onCancel: () => void;
onPreview?: () => void;
onStopPreview?: () => void;
}
/** 航点编辑器Props */
export interface WaypointEditorProps {
waypoint: BoatWaypointDTO;
index: number;
onUpdate: (index: number, waypoint: BoatWaypointDTO) => void;
onDelete: (index: number) => void;
onClose: () => void;
}
/** 航线预览Props */
export interface RoutePreviewProps {
waypoints: BoatWaypointDTO[];
cruiseSpeed: number;
totalDistance: number;
estimatedDuration: number;
validationResult?: {
valid: boolean;
errors: string[];
warnings: string[];
};
}
/** 航线绘制器Props */
export interface RouteDrawerProps {
waypoints: BoatWaypointDTO[];
selectedIndex: number | null;
mode: EditorMode;
boundaryGeoJson?: string;
onWaypointAdd: (point: MapClickEvent) => void;
onWaypointSelect: (index: number) => void;
onWaypointMove: (index: number, point: MapClickEvent) => void;
viewerRef?: React.RefObject<any>;
}
/** 历史记录项 */
export interface HistoryItem {
waypoints: BoatWaypointDTO[];
timestamp: number;
}
+171
View File
@@ -0,0 +1,171 @@
/**
* 无人船控制命令API服务
* @author dzc
* @date 2026-01-05
*/
import { request } from 'umi';
import type {
BoatManualControlDTO,
BoatTelemetryData,
TrackPointVO,
TaskTrackVO,
} from '@/types/boatRoute';
const API_PREFIX = '/api-device';
// ========== 控制命令 ==========
/**
* 执行航线任务
*/
export async function executeBoatRoute(deviceSn: string, boatRouteId: string, missionCode: string) {
return request<API.Result<string>>(`${API_PREFIX}/device/boat/command/route/execute`, {
method: 'POST',
params: { deviceSn, boatRouteId, missionCode },
});
}
/**
* 暂停航行
*/
export async function pauseBoatNavigation(deviceSn: string) {
return request<API.Result<void>>(`${API_PREFIX}/device/boat/command/pause`, {
method: 'POST',
params: { deviceSn },
});
}
/**
* 恢复航行
*/
export async function resumeBoatNavigation(deviceSn: string) {
return request<API.Result<void>>(`${API_PREFIX}/device/boat/command/resume`, {
method: 'POST',
params: { deviceSn },
});
}
/**
* 返回起点
*/
export async function returnBoatToStart(deviceSn: string) {
return request<API.Result<void>>(`${API_PREFIX}/device/boat/command/return`, {
method: 'POST',
params: { deviceSn },
});
}
/**
* 紧急停止
*/
export async function emergencyStopBoat(deviceSn: string) {
return request<API.Result<void>>(`${API_PREFIX}/device/boat/command/emergency-stop`, {
method: 'POST',
params: { deviceSn },
});
}
/**
* 手动控制
*/
export async function manualControlBoat(deviceSn: string, data: BoatManualControlDTO) {
return request<API.Result<void>>(`${API_PREFIX}/device/boat/command/manual`, {
method: 'POST',
params: { deviceSn },
data,
});
}
/**
* 检查设备是否在线
*/
export async function isBoatOnline(deviceSn: string) {
return request<API.Result<boolean>>(`${API_PREFIX}/device/boat/command/online/${deviceSn}`, {
method: 'GET',
});
}
/**
* 获取设备状态
*/
export async function getBoatStatus(deviceSn: string) {
return request<API.Result<string>>(`${API_PREFIX}/device/boat/command/status/${deviceSn}`, {
method: 'GET',
});
}
// ========== 轨迹查询 ==========
/**
* 获取实时位置
*/
export async function getBoatRealtimePosition(deviceSn: string) {
return request<API.Result<BoatTelemetryData>>(`${API_PREFIX}/device/boat/track/realtime/${deviceSn}`, {
method: 'GET',
});
}
/**
* 获取历史轨迹
*/
export async function getBoatHistoryTrack(
deviceSn: string,
startTime: string,
endTime: string
) {
return request<API.Result<TrackPointVO[]>>(`${API_PREFIX}/device/boat/track/history/${deviceSn}`, {
method: 'GET',
params: { startTime, endTime },
});
}
/**
* 获取任务执行轨迹
*/
export async function getBoatTaskTrack(taskId: string) {
return request<API.Result<TaskTrackVO>>(`${API_PREFIX}/device/boat/track/task/${taskId}`, {
method: 'GET',
});
}
// ========== 水域边界 ==========
/**
* 获取景区水域边界列表
*/
export async function getWaterBoundaries(scenicId: number) {
return request<API.Result<any[]>>(`${API_PREFIX}/device/water/boundary/list/${scenicId}`, {
method: 'GET',
});
}
/**
* 检测点是否在边界内
*/
export async function checkPointInBoundary(
boundaryId: string,
longitude: number,
latitude: number
) {
return request<API.Result<boolean>>(`${API_PREFIX}/device/water/boundary/check/point`, {
method: 'GET',
params: { boundaryId, longitude, latitude },
});
}
/**
* 检测航线是否在边界内
*/
export async function checkRouteInBoundary(
boundaryId: string,
waypoints: { longitude: number; latitude: number }[]
) {
return request<API.Result<{ allInBoundary: boolean; outOfBoundarySegments: string[] }>>(
`${API_PREFIX}/device/water/boundary/check/route`,
{
method: 'POST',
params: { boundaryId },
data: waypoints,
}
);
}
+181
View File
@@ -0,0 +1,181 @@
/**
* 无人船航线API服务
* @author dzc
* @date 2026-01-05
*/
import { request } from 'umi';
import type {
BoatRouteCreateDTO,
BoatRouteUpdateDTO,
BoatRouteDetailVO,
BoatRouteListVO,
RouteValidateResultVO,
BoatWaypointDTO,
} from '@/types/boatRoute';
const API_PREFIX = '/api-device';
/**
* 创建航线
*/
export async function createBoatRoute(data: BoatRouteCreateDTO) {
return request<API.Result<string>>(`${API_PREFIX}/device/boat/route/create`, {
method: 'POST',
data,
});
}
/**
* 更新航线
*/
export async function updateBoatRoute(routeId: string, data: BoatRouteUpdateDTO) {
return request<API.Result<void>>(`${API_PREFIX}/device/boat/route/${routeId}`, {
method: 'PUT',
data,
});
}
/**
* 获取航线详情
*/
export async function getBoatRouteDetail(routeId: string) {
return request<API.Result<BoatRouteDetailVO>>(`${API_PREFIX}/device/boat/route/${routeId}`, {
method: 'GET',
});
}
/**
* 获取设备绑定的航线列表
*/
export async function getBoatRoutesByDevice(deviceSn: string) {
return request<API.Result<BoatRouteListVO[]>>(`${API_PREFIX}/device/boat/route/list/device/${deviceSn}`, {
method: 'GET',
});
}
/**
* 获取景区航线列表(分页)
*/
export async function getBoatRoutesByScenicId(
scenicId: number,
params?: { page?: number; size?: number }
) {
return request<API.Result<API.PageResult<BoatRouteListVO>>>(`${API_PREFIX}/device/boat/route/list/scenic/${scenicId}`, {
method: 'GET',
params: {
page: params?.page || 1,
size: params?.size || 10,
},
});
}
/**
* 绑定航线到设备
*/
export async function bindBoatRouteToDevice(routeId: string, deviceSn: string) {
return request<API.Result<void>>(`${API_PREFIX}/device/boat/route/${routeId}/bind`, {
method: 'POST',
params: { deviceSn },
});
}
/**
* 解绑航线和设备
*/
export async function unbindBoatRoute(routeId: string) {
return request<API.Result<void>>(`${API_PREFIX}/device/boat/route/${routeId}/unbind`, {
method: 'POST',
});
}
/**
* 校验航线
*/
export async function validateBoatRoute(data: BoatRouteCreateDTO, boundaryId?: string) {
return request<API.Result<RouteValidateResultVO>>(`${API_PREFIX}/device/boat/route/validate`, {
method: 'POST',
data,
params: boundaryId ? { boundaryId } : undefined,
});
}
/**
* 删除航线
*/
export async function deleteBoatRoute(routeId: string) {
return request<API.Result<void>>(`${API_PREFIX}/device/boat/route/${routeId}`, {
method: 'DELETE',
});
}
/**
* 保存为模板
*/
export async function saveBoatRouteAsTemplate(routeId: string, templateName: string) {
return request<API.Result<string>>(`${API_PREFIX}/device/boat/route/${routeId}/template`, {
method: 'POST',
params: { templateName },
});
}
/**
* 获取模板列表
*/
export async function getBoatRouteTemplates() {
return request<API.Result<BoatRouteListVO[]>>(`${API_PREFIX}/device/boat/route/templates`, {
method: 'GET',
});
}
/**
* 发布航线
*/
export async function publishBoatRoute(routeId: string) {
return request<API.Result<void>>(`${API_PREFIX}/device/boat/route/${routeId}/publish`, {
method: 'POST',
});
}
/**
* 计算航线预览信息 (前端本地计算)
*/
export function calculateRoutePreview(waypoints: BoatWaypointDTO[], cruiseSpeed: number) {
if (!waypoints || waypoints.length < 2) {
return { totalDistance: 0, estimatedDuration: 0 };
}
let totalDistance = 0;
for (let i = 0; i < waypoints.length - 1; i++) {
const p1 = waypoints[i];
const p2 = waypoints[i + 1];
totalDistance += haversineDistance(p1.longitude, p1.latitude, p2.longitude, p2.latitude);
}
// 航行时间
const travelTime = cruiseSpeed > 0 ? totalDistance / cruiseSpeed : 0;
// 停留时间
const stayTime = waypoints.reduce((sum, wp) => sum + (wp.stayDuration || 0), 0);
return {
totalDistance: Math.round(totalDistance),
estimatedDuration: Math.round(travelTime + stayTime),
};
}
/**
* Haversine公式计算两点间距离(米)
*/
function haversineDistance(lon1: number, lat1: number, lon2: number, lat2: number): number {
const R = 6371000; // 地球半径(米)
const dLat = toRad(lat2 - lat1);
const dLon = toRad(lon2 - lon1);
const a =
Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) * Math.sin(dLon / 2) * Math.sin(dLon / 2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return R * c;
}
function toRad(deg: number): number {
return (deg * Math.PI) / 180;
}
@@ -0,0 +1,89 @@
/**
* 水域边界API服务
* @author Claude
* @date 2026-01-06
*/
import { request } from 'umi';
import type {
WaterBoundaryCreateDTO,
WaterBoundaryUpdateDTO,
WaterBoundaryVO,
} from '@/pages/map3d/components/BoundaryEditor/types';
const API_PREFIX = '/api-device';
/**
* 创建水域边界
*/
export async function createWaterBoundary(data: WaterBoundaryCreateDTO) {
return request<API.Result<string>>(`${API_PREFIX}/device/water/boundary/create`, {
method: 'POST',
data,
});
}
/**
* 更新水域边界
*/
export async function updateWaterBoundary(boundaryId: string, data: WaterBoundaryUpdateDTO) {
return request<API.Result<void>>(`${API_PREFIX}/device/water/boundary/${boundaryId}`, {
method: 'PUT',
data,
});
}
/**
* 获取水域边界详情
*/
export async function getWaterBoundaryDetail(boundaryId: string) {
return request<API.Result<WaterBoundaryVO>>(`${API_PREFIX}/device/water/boundary/${boundaryId}`, {
method: 'GET',
});
}
/**
* 获取景区水域边界列表
*/
export async function getWaterBoundariesByScenicId(scenicId: number) {
return request<API.Result<WaterBoundaryVO[]>>(`${API_PREFIX}/device/water/boundary/list/scenic/${scenicId}`, {
method: 'GET',
});
}
/**
* 删除水域边界
*/
export async function deleteWaterBoundary(boundaryId: string) {
return request<API.Result<void>>(`${API_PREFIX}/device/water/boundary/${boundaryId}`, {
method: 'DELETE',
});
}
/**
* 检测点是否在边界内
*/
export async function checkPointInBoundary(
boundaryId: string,
point: { longitude: number; latitude: number }
) {
return request<API.Result<boolean>>(`${API_PREFIX}/device/water/boundary/${boundaryId}/check/point`, {
method: 'POST',
data: point,
});
}
/**
* 检测航线是否在边界内
*/
export async function checkRouteInBoundary(
boundaryId: string,
waypoints: Array<{ longitude: number; latitude: number }>
) {
return request<API.Result<{
allInside: boolean;
outsidePoints: number[];
}>>(`${API_PREFIX}/device/water/boundary/${boundaryId}/check/route`, {
method: 'POST',
data: { waypoints },
});
}
+238
View File
@@ -0,0 +1,238 @@
/**
* 无人船航线相关类型定义
* @author dzc
* @date 2026-01-05
*/
// ========== 航点相关 ==========
/** 航点动作类型 */
export type WaypointActionType =
| 'hover' // 悬停
| 'take_photo' // 拍照
| 'record_video'// 录像
| 'horn' // 鸣笛
| 'light' // 灯光
| 'spray'; // 喷洒
/** 转弯模式 */
export type TurnMode =
| 'sharp' // 锐角转弯
| 'smooth' // 平滑转弯
| 'arc'; // 弧线转弯
/** 航点动作 */
export interface WaypointAction {
actionType: WaypointActionType;
duration?: number; // 持续时间(秒)
params?: Record<string, any>; // 额外参数
}
/** 航点DTO (创建/更新用) */
export interface BoatWaypointDTO {
longitude: number;
latitude: number;
speed?: number; // 航点速度 (m/s)
stayDuration?: number; // 停留时间 (秒)
turnMode?: TurnMode;
pointName?: string;
isKeyPoint?: boolean;
actions?: WaypointAction[];
remark?: string;
}
/** 航点VO (显示用) */
export interface BoatWaypointVO {
waypointId: string;
routeId: string;
waypointIndex: number;
longitude: number;
latitude: number;
speed: number;
stayDuration: number;
turnMode: string;
pointName: string;
isKeyPoint: boolean;
headingAngle?: number;
actions?: WaypointAction[];
remark?: string;
}
// ========== 航线相关 ==========
/** 航线状态 */
export enum RouteStatus {
DRAFT = 0, // 草稿
PUBLISHED = 1, // 已发布
EXECUTING = 2, // 执行中
DISABLED = 3, // 已禁用
}
/** 返航模式 */
export type ReturnMode =
| 'origin' // 返回起点
| 'nearest' // 最近岸边
| 'current'; // 当前位置
/** 创建航线DTO */
export interface BoatRouteCreateDTO {
routeName: string;
deviceSn?: string;
scenicId: number;
cruiseSpeed: number; // 巡航速度 (m/s)
loopEnabled?: boolean; // 是否循环
loopCount?: number; // 循环次数
returnMode?: ReturnMode;
safeDistance?: number; // 安全距离 (米)
waypoints: BoatWaypointDTO[];
remark?: string;
}
/** 更新航线DTO */
export interface BoatRouteUpdateDTO {
routeName?: string;
cruiseSpeed?: number;
loopEnabled?: boolean;
loopCount?: number;
returnMode?: ReturnMode;
safeDistance?: number;
waypoints?: BoatWaypointDTO[];
remark?: string;
}
/** 航线列表VO */
export interface BoatRouteListVO {
routeId: string;
routeName: string;
deviceSn?: string;
deviceName?: string;
scenicId: number;
status: RouteStatus;
statusDesc: string;
waypointCount: number;
totalDistance: number; // 总距离 (米)
totalDuration: number; // 预计时长 (秒)
totalDurationStr: string;
isTemplate: boolean;
createTime: string;
updateTime: string;
}
/** 航线详情VO */
export interface BoatRouteDetailVO extends BoatRouteListVO {
cruiseSpeed: number;
loopEnabled: boolean;
loopCount: number;
returnMode: string;
safeDistance: number;
startPoint: string;
endPoint: string;
waypoints: BoatWaypointVO[];
remark?: string;
}
// ========== 航线校验 ==========
/** 校验结果 */
export interface RouteValidateResultVO {
valid: boolean;
errors: string[];
warnings: string[];
totalDistance: number;
estimatedDuration: number;
}
// ========== 水域边界 ==========
/** 边界类型 */
export enum BoundaryType {
NAVIGABLE = 1, // 可通行区域
FORBIDDEN = 2, // 禁行区域
WARNING = 3, // 警告区域
}
/** 水域边界VO */
export interface WaterBoundaryVO {
boundaryId: string;
boundaryName: string;
scenicId: number;
boundaryType: BoundaryType;
boundaryTypeDesc: string;
geoJson: string; // GeoJSON格式多边形
status: number;
statusDesc: string;
createTime: string;
}
/** 边界检测结果 */
export interface BoundaryCheckResultVO {
allInBoundary: boolean;
outOfBoundarySegments: string[];
}
// ========== 实时遥测数据 ==========
/** 无人船实时数据 */
export interface BoatTelemetryData {
deviceSn: string;
longitude: number;
latitude: number;
heading: number; // 航向角 (度)
speed: number; // 当前速度 (m/s)
battery: number; // 电量 (%)
signalStrength?: number;// 信号强度 (%)
status: string; // 状态
recordTime: string;
taskId?: string;
currentWaypointIndex?: number;
}
// ========== 轨迹相关 ==========
/** 轨迹点 */
export interface TrackPointVO {
longitude: number;
latitude: number;
heading?: number;
speed?: number;
recordTime: string;
status?: string;
}
/** 任务轨迹 */
export interface TaskTrackVO {
taskId: string;
deviceSn: string;
trackPoints: TrackPointVO[];
pointCount: number;
startTime?: string;
endTime?: string;
totalDistance?: number;
}
// ========== 控制命令 ==========
/** 手动控制参数 */
export interface BoatManualControlDTO {
throttle: number; // 油门 (-100 到 100)
rudder: number; // 舵角 (-100 到 100)
}
// ========== 任务类型扩展 ==========
/** 任务类型 (扩展) */
export enum MissionType {
WAYLINE = 1, // 无人机航线任务
TAKEOFF = 2, // 一键起飞任务
BOAT_ROUTE = 3, // 无人船航线任务
}
/** 创建无人船任务参数 */
export interface CreateBoatMissionParams {
missionName: string;
deviceSn: string;
boatRouteId: string;
boatRouteName: string;
tourismId: number;
remark?: string;
}