增加地图编辑界面,该界面支持增删改查 返航点,一个机器对应一个返航点,增删改查场站分区,将原本机器状态界面的 路径规划功能移植到该页面,地图上支持显示 返航点和分区,点击分区和返航点,地图支持定位和高亮,等待测试

机器状态界面返航 功能接口对接,还未对接实机测试
This commit is contained in:
mmc
2026-10-24 13:38:05 +08:00
parent a17a19fdc4
commit fb363882ac
10 changed files with 2137 additions and 214 deletions

View File

@@ -1,4 +1,4 @@
import React, { useEffect, useRef, useState, useMemo, useImperativeHandle, forwardRef, useCallback } from 'react';
import React, { useEffect, useRef, useState, useMemo, useImperativeHandle, forwardRef, useCallback, useLayoutEffect } from 'react';
import carImg from '../assets/images/carplane.png';
import inspectImg from "../assets/images/inspectCar.png"
import planeImg from '../assets/images/planeicon.png';
@@ -10,6 +10,8 @@ import iotImg from '../assets/images/iot.png';
import envConfig from '../../env';
import { TracePoint, TPAction, TPMode } from '../lib/TracePoint/tracePoint';
import { useTranslation } from 'react-i18next';
import { useSelector } from 'react-redux';
import { getSiteMapInfo, getStationRegions } from '../api/stationManage';
const CYAN_ALARM_COLOR = new window.Cesium.Color(
@@ -27,7 +29,7 @@ const CYAN_GLOW_COLOR = new window.Cesium.Color(
);
window.Cesium.Ion.defaultAccessToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJmNjk0NjI1MC0wZGYyLTQ1YzItYjJmZi0wY2M5ODEwODllYzIiLCJpZCI6Mzk3MTQxLCJpYXQiOjE3NzI1MjkwMjV9.U6qmakhDgXJVXwLFyWzSxAUOFZRrDkIsRUPP6CCdnKg";
const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine, finishPoint, drawRealTime, realtimePosition, realtimeType, pathPoints = [], devices = [], onCameraClick, focusLocation, points = [], markedPoints = [], onPathChange, from, onClearDraw, onMarkPoint, routeMode = '', polyPoints, mapLayer }, ref) => {
const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine, finishPoint, drawRealTime, realtimePosition, realtimeType, pathPoints = [], devices = [], onCameraClick, focusLocation, points = [], markedPoints = [], onPathChange, from, onClearDraw, onMarkPoint, routeMode = '', polyPoints, mapLayer, activeType, overlayRefreshKey = 0, focusOverlay = null }, ref) => {
const containerRef = useRef(null);
const viewerRef = useRef(null);
const tooltipRef = useRef(null);
@@ -41,10 +43,20 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
const navLineRef = useRef(null); // 完成点实时轨迹
const markedPointsRef = useRef([]); // 标记点实体
const markedLineRef = useRef(null); // 标记点连线实体
const lastMarkedPointsRef = useRef([]); // 上次渲染的标记点数据,用于增量更新
const onMarkPointRef = useRef(onMarkPoint); // 总是指向最新的 onMarkPoint,避免闭包滞后
const onCameraClickRef = useRef(onCameraClick); // 同样处理,避免闭包滞后
const { t } = useTranslation();
// 场站已配置的返航点 / 分区叠加显示
const stationId = useSelector((state) => state?.station?.stationId || state?.station?.currentStation?.id);
const [stationOverlay, setStationOverlay] = useState({ returnPoints: [], regions: [] });
const stationOverlayIdsRef = useRef([]);
const returnPointPinUrlRef = useRef(null);
// 被点击聚焦的返航点 id / 图例高亮类型
const [highlightReturnPointId, setHighlightReturnPointId] = useState('');
const [legendHighlight, setLegendHighlight] = useState('');
const realtimeEntityRef = useRef(null);
const realtimeLineRef = useRef(null);
@@ -679,63 +691,94 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
}
}, [points]);
// 渲染标记点 + 连线(唯一系统,避免重复标记)
// 渲染标记点 + 连线(增量更新:只增删改真正变化的点)
const drawMarkedPoints = (points) => {
const viewer = viewerRef.current;
if (!viewer) return;
// 先清空之前的标记点与连线
markedPointsRef.current.forEach(id => {
viewer.entities.removeById(id);
});
markedPointsRef.current = [];
const newPoints = points || [];
const prevPoints = lastMarkedPointsRef.current || [];
if (markedLineRef.current) {
try {
viewer.entities.remove(markedLineRef.current);
} catch (e) { }
markedLineRef.current = null;
const nextIds = new Set(newPoints.map((p, i) => `marked-point-${p.id ?? i}`));
// 1) 删除不在新列表中的旧 entity
markedPointsRef.current = markedPointsRef.current.filter(id => {
if (!nextIds.has(id)) {
viewer.entities.removeById(id);
return false;
}
return true;
});
// 2) 新增或更新标记点 entity
newPoints.forEach((p, i) => {
const id = `marked-point-${p.id ?? i}`;
const entity = viewer.entities.getById(id);
const position = window.Cesium.Cartesian3.fromDegrees(Number(p.lon), Number(p.lat));
const labelText = `${i + 1}`;
if (entity) {
// 只更新位置和 label,避免销毁重建
entity.position = position;
if (entity.label) entity.label.text = labelText;
} else {
viewer.entities.add({
id,
position,
point: {
color: window.Cesium.Color.GREEN,
pixelSize: 15,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
},
label: {
text: labelText,
font: '14px sans-serif',
pixelOffset: new window.Cesium.Cartesian2(0, -20),
fillColor: window.Cesium.Color.WHITE,
outlineColor: window.Cesium.Color.BLACK,
outlineWidth: 2,
style: window.Cesium.LabelStyle.FILL_AND_OUTLINE,
}
});
markedPointsRef.current.push(id);
}
});
// 3) 连线:只有坐标/数量真正变化时才重建
if (activeType !== "routeGen") {
viewer.scene.requestRender();
return;
}
const lineChanged = newPoints.length !== prevPoints.length ||
newPoints.some((p, i) => {
const pp = prevPoints[i];
return !pp || Number(pp.lon) !== Number(p.lon) || Number(pp.lat) !== Number(p.lat);
});
if (lineChanged) {
if (markedLineRef.current) {
try { viewer.entities.remove(markedLineRef.current); } catch (e) { }
markedLineRef.current = null;
}
if (newPoints.length >= 2) {
const linePositions = newPoints.map(p =>
window.Cesium.Cartesian3.fromDegrees(Number(p.lon), Number(p.lat))
);
markedLineRef.current = viewer.entities.add({
polyline: {
positions: linePositions,
width: 4,
material: window.Cesium.Color.SKYBLUE,
clampToGround: true,
}
});
}
}
if (!points || points.length === 0) return;
lastMarkedPointsRef.current = newPoints.map(p => ({ ...p }));
// 先绘制连线:有 2 个及以上打点才连线
if (points.length >= 2) {
const linePositions = points.map(p =>
window.Cesium.Cartesian3.fromDegrees(Number(p.lon), Number(p.lat))
);
markedLineRef.current = viewer.entities.add({
polyline: {
positions: linePositions,
width: 4,
material: window.Cesium.Color.SKYBLUE,
clampToGround: true,
}
});
}
points.forEach((p, i) => {
const id = `marked-point-${i}`;
viewer.entities.add({
id,
position: window.Cesium.Cartesian3.fromDegrees(p.lon, p.lat),
point: {
color: window.Cesium.Color.GREEN,
pixelSize: 15,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
},
label: {
text: `${i + 1}`,
font: '14px sans-serif',
pixelOffset: new window.Cesium.Cartesian2(0, -20),
fillColor: window.Cesium.Color.WHITE,
outlineColor: window.Cesium.Color.BLACK,
outlineWidth: 2,
style: window.Cesium.LabelStyle.FILL_AND_OUTLINE,
}
});
markedPointsRef.current.push(id);
});
// 强制 Cesium 立即渲染(requestRenderMode=true 时必须手动触发)
viewer.scene.requestRender();
};
useEffect(() => {
@@ -834,6 +877,25 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
}
}
// 返航点悬浮提示:显示别名与该返航点绑定的机器
function showReturnPointTooltip(tooltip, position, point) {
if (!tooltip) return;
tooltip.style.display = "block";
tooltip.style.left = position.x + 12 + "px";
tooltip.style.top = position.y + 12 + "px";
tooltip.style.whiteSpace = "nowrap";
const boundDevice = devices.find(d => d?.serialNumber === point.bindDeviceId);
const deviceLabel = point.bindDeviceId
? (boundDevice?.deviceAlias || boundDevice?.deviceName || point.bindDeviceId)
: t('devices.mapEditor.unbound');
tooltip.innerHTML = `
<div style="font-weight:600;margin-bottom:4px;">📍 ${point.alias || '-'}</div>
<div>🤖 ${deviceLabel}</div>
`;
}
function fetchPublishedLayers() {
const baseUrl = envConfig.geoserver_url;
//const baseUrl = 'https://gis.caasrobot.com/geoserver';
@@ -1271,6 +1333,163 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
flyToLayer(mapLayer, envConfig.geoserver_url, 100);
}, [mapLayer]);
// 拉取当前场站已配置的返航点与分区
useEffect(() => {
if (!stationId) {
setStationOverlay({ returnPoints: [], regions: [] });
return;
}
let cancelled = false;
getSiteMapInfo({ siteId: stationId })
.then((res) => {
if (cancelled) return;
const pts = res?.code === 200 ? (res?.data?.restPoints || []) : [];
setStationOverlay(prev => ({ ...prev, returnPoints: Array.isArray(pts) ? pts : [] }));
})
.catch(() => { });
getStationRegions({ siteId: stationId })
.then((res) => {
if (cancelled) return;
const list = res?.code === 200 ? (res?.data || res?.rows || []) : [];
setStationOverlay(prev => ({ ...prev, regions: Array.isArray(list) ? list : [] }));
})
.catch(() => { });
return () => { cancelled = true; };
}, [stationId, overlayRefreshKey]);
// 在地图上叠加显示:返航点用标志图标,分区用小框
useEffect(() => {
const viewer = viewerRef.current;
const Cesium = window.Cesium;
if (!viewer || !Cesium) return;
// 清理上一次叠加实体
stationOverlayIdsRef.current.forEach(id => viewer.entities.removeById(id));
stationOverlayIdsRef.current = [];
// 返航点标志图标(PinBuilder 生成,失败则退化为圆点)
if (!returnPointPinUrlRef.current && Cesium.PinBuilder) {
try {
returnPointPinUrlRef.current = Cesium.PinBuilder.fromColor(Cesium.Color.fromCssColorString('#165DFF'), 36).toDataURL();
} catch (e) { /* ignore */ }
}
(stationOverlay.returnPoints || []).forEach((pt, idx) => {
const lon = Number(pt?.position?.lng ?? pt?.lng);
const lat = Number(pt?.position?.lat ?? pt?.lat);
if (!isFinite(lon) || !isFinite(lat) || lon === 0 || lat === 0) return;
const id = `station-return-point-${idx}`;
const isHighlighted = id === highlightReturnPointId;
viewer.entities.add({
id,
returnPointData: {
alias: pt?.alias || '',
bindDeviceId: pt?.bindDeviceId || '',
},
position: Cesium.Cartesian3.fromDegrees(lon, lat, 0),
...(returnPointPinUrlRef.current
? {
billboard: {
image: returnPointPinUrlRef.current,
width: isHighlighted ? 36 : 24,
height: isHighlighted ? 48 : 32,
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
}
}
: {
point: {
pixelSize: isHighlighted ? 16 : 10,
color: Cesium.Color.fromCssColorString(isHighlighted ? '#FA8C16' : '#165DFF'),
disableDepthTestDistance: Number.POSITIVE_INFINITY,
}
}),
label: pt?.alias ? {
text: pt.alias,
font: 'bold 12px sans-serif',
fillColor: Cesium.Color.WHITE,
showBackground: true,
backgroundColor: Cesium.Color.fromCssColorString(isHighlighted ? '#FA8C16' : '#165DFF').withAlpha(0.8),
pixelOffset: new Cesium.Cartesian2(0, isHighlighted ? -48 : -34),
disableDepthTestDistance: Number.POSITIVE_INFINITY,
} : undefined,
});
stationOverlayIdsRef.current.push(id);
});
// 分区:用小框(多边形)显示
(stationOverlay.regions || []).forEach((region, idx) => {
const scope = Array.isArray(region?.scope) ? region.scope : [];
const positions = scope
.map(p => {
const lon = Number(p?.lng ?? p?.lon);
const lat = Number(p?.lat);
if (!isFinite(lon) || !isFinite(lat) || lon === 0 || lat === 0) return null;
return Cesium.Cartesian3.fromDegrees(lon, lat, 0);
})
.filter(Boolean);
if (positions.length < 3) return;
const id = `station-region-${region?.id ?? idx}`;
viewer.entities.add({
id,
polygon: {
hierarchy: positions,
material: Cesium.Color.fromCssColorString('#13C2C2').withAlpha(0.18),
outline: true,
outlineColor: Cesium.Color.fromCssColorString('#13C2C2').withAlpha(0.9),
height: 0,
clampToGround: true,
},
label: region?.regionName ? {
text: region.regionName,
font: '12px sans-serif',
fillColor: Cesium.Color.WHITE,
showBackground: true,
backgroundColor: Cesium.Color.fromCssColorString('#13C2C2').withAlpha(0.8),
disableDepthTestDistance: Number.POSITIVE_INFINITY,
} : undefined,
});
stationOverlayIdsRef.current.push(id);
});
viewer.scene.requestRender();
}, [stationOverlay, highlightReturnPointId]);
// 点击已配置列表:定位到对应返航点/分区;返航点额外高亮
useEffect(() => {
const viewer = viewerRef.current;
const Cesium = window.Cesium;
if (!viewer || !Cesium || !focusOverlay) return;
if (focusOverlay.type === 'returnPoint') {
const pt = (stationOverlay.returnPoints || [])[focusOverlay.index];
const lon = Number(pt?.position?.lng ?? pt?.lng);
const lat = Number(pt?.position?.lat ?? pt?.lat);
if (!isFinite(lon) || !isFinite(lat) || lon === 0 || lat === 0) return;
setLegendHighlight('returnPoint');
setHighlightReturnPointId(`station-return-point-${focusOverlay.index}`);
viewer.camera.flyTo({
destination: Cesium.Cartesian3.fromDegrees(lon, lat, 500),
duration: 0.8,
});
} else if (focusOverlay.type === 'region') {
const region = (stationOverlay.regions || []).find(r => String(r.id) === String(focusOverlay.id));
const scope = Array.isArray(region?.scope) ? region.scope : [];
const lons = scope.map(p => Number(p?.lng ?? p?.lon)).filter(n => isFinite(n) && n !== 0);
const lats = scope.map(p => Number(p?.lat)).filter(n => isFinite(n) && n !== 0);
if (!lons.length || !lats.length) return;
setLegendHighlight('region');
setHighlightReturnPointId('');
viewer.camera.flyTo({
destination: Cesium.Rectangle.fromDegrees(
Math.min(...lons), Math.min(...lats), Math.max(...lons), Math.max(...lats)
),
duration: 0.8,
});
}
}, [focusOverlay, stationOverlay]);
useEffect(() => {
// 如果有 realtimePosition,不显示 focusEntity
@@ -1960,10 +2179,13 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
handler.setInputAction((movement) => {
const picked = viewer.scene.pick(movement.endPosition);
const pickedReturnPoint = (window.Cesium.defined(picked) && picked.id?.returnPointData) ? picked.id.returnPointData : null;
const pickedRobot = (window.Cesium.defined(picked) && picked.id?.properties?.robot) ? picked.id.properties.robot.getValue() : null;
// ✅ 只有拾取到设备实体,才显示tooltip,空白区域直接隐藏
if (pickedRobot) {
// 返航点优先显示「别名 + 绑定机器」,设备显示设备信息,空白区域隐藏
if (pickedReturnPoint) {
showReturnPointTooltip(tooltipRef.current, movement.endPosition, pickedReturnPoint);
} else if (pickedRobot) {
const { lon, lat } = getCursorLngLat(viewer, movement.endPosition);
showCoordinateTooltip(tooltipRef.current, movement.endPosition, t, lon, lat, pickedRobot);
} else {
@@ -2000,11 +2222,11 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
}
}
}
console.log('点击地图,拾取到设备', robot);
if (robot) {
onCameraClickRef.current?.(robot);
}
if (from !== "deviceStatus")
const _allowedFrom = ["mapEditor"];
if (!_allowedFrom.includes(from))
return;
const cartesian = viewer.camera.pickEllipsoid(movement.position, viewer.scene.globe.ellipsoid);
if (!cartesian) return;
@@ -2596,6 +2818,66 @@ const CesiumMap = React.forwardRef(({ ifClear, ifClearPlanLine, ifClearNavLine,
whiteSpace: "nowrap",
}}
/>
{/* 图例:返航点 / 分区 */}
{(stationOverlay.returnPoints.length > 0 || stationOverlay.regions.length > 0) && (
<div
style={{
position: "absolute",
right: 12,
top: 12,
zIndex: 20,
background: "rgba(255,255,255,0.92)",
borderRadius: 6,
padding: "8px 10px",
fontSize: 12,
color: "#333",
lineHeight: "18px",
boxShadow: "0 2px 8px rgba(0,0,0,0.12)",
}}
>
<div style={{ fontWeight: 600, marginBottom: 6 }}>{t('devices.mapEditor.legend')}</div>
<div style={{
display: "flex",
alignItems: "center",
gap: 6,
padding: "2px 4px",
borderRadius: 4,
fontWeight: legendHighlight === "returnPoint" ? 600 : 400,
color: legendHighlight === "returnPoint" ? "#165DFF" : "#333",
background: legendHighlight === "returnPoint" ? "#e8f3ff" : "transparent",
}}>
<span style={{
display: "inline-block",
width: 10,
height: 10,
background: "#165DFF",
borderRadius: "50% 50% 50% 0",
transform: "rotate(-45deg)",
}} />
<span>{t('devices.mapEditor.returnPoint')}</span>
</div>
<div style={{
display: "flex",
alignItems: "center",
gap: 6,
marginTop: 4,
padding: "2px 4px",
borderRadius: 4,
fontWeight: legendHighlight === "region" ? 600 : 400,
color: legendHighlight === "region" ? "#13C2C2" : "#333",
background: legendHighlight === "region" ? "rgba(19,194,194,0.12)" : "transparent",
}}>
<span style={{
display: "inline-block",
width: 12,
height: 10,
border: "1px solid #13C2C2",
background: "rgba(19,194,194,0.18)",
}} />
<span>{t('devices.mapEditor.restArea')}</span>
</div>
</div>
)}
</div>
);

View File

@@ -154,6 +154,7 @@ import { useUnitFormatter } from '@/lib/units';
import { PauseOutlined, PlayCircleOutlined } from '@ant-design/icons';
import { useTranslation } from 'react-i18next';
import { backToRestPointCommand } from '@/api/mapEdit';
@@ -1498,19 +1499,19 @@ export default function DeviceStatusPage() {
// 无控制权限时:不发送消息,且只发起一次权限申请(避免手柄/方向盘高频更新刷屏)
//if (!isControlled) {
if (!isControlled) {
// //if (!hasRequestedControlRef.current && !connecting) {
//if (!hasRequestedControlRef.current && !connecting) {
// // hasRequestedControlRef.current = true;
// hasRequestedControlRef.current = true;
// // handleControlModal();
// handleControlModal();
// //}
//}
// return;
return;
//}
}
console.log('Gamepad state updated:', state);
@@ -1658,6 +1659,22 @@ export default function DeviceStatusPage() {
return Number(val).toFixed(2);
};
const handleAutoBack = () => {
const payload = {
deviceId: selectedSn,
orgId: currentStation?.orgId,
siteId: stationId,
}
backToRestPointCommand(payload).then(res => { }).catch(err => {
console.error('返回休息点失败', err);
})
}
@@ -1920,9 +1937,9 @@ export default function DeviceStatusPage() {
/**
* 修改handleComplete:计算完成后 return路径对象;失败返回null
*/
const handleComplete = async () => {
@@ -2159,7 +2176,7 @@ export default function DeviceStatusPage() {
{/* 页面顶部按钮区域 */}
{!isUAV && (
{/*{!isUAV && (
<div
@@ -2269,7 +2286,7 @@ export default function DeviceStatusPage() {
</Button>*/}
<Button
{/*<Button
type="primary"
@@ -2287,7 +2304,7 @@ export default function DeviceStatusPage() {
</div>
)}
)}}*/}
@@ -3114,6 +3131,7 @@ export default function DeviceStatusPage() {
onToggle={(feature, enabled) => { console.log('[DeviceStatusPage] Feature toggled: ' + feature + ' = ' + enabled); }}
sendFindCar={() => handleFindCar()}
sendAutoBack={() => handleAutoBack()}
/>

File diff suppressed because it is too large Load Diff

View File

@@ -49,7 +49,8 @@ interface RobotFeatureButtonsProps {
onToggle?: (feature: RobotFeature, enabled: boolean) => void;
className?: string;
showEmergencyStop?: boolean;
sendFindCar: () => {}
sendFindCar: () => {};
sendAutoBack?: () => {};
}
const RobotFeatureButtons: React.FC<RobotFeatureButtonsProps> = ({
@@ -58,6 +59,7 @@ const RobotFeatureButtons: React.FC<RobotFeatureButtonsProps> = ({
className = '',
showEmergencyStop = true,
sendFindCar,
sendAutoBack
}) => {
const { t } = useTranslation();
const { userInfo } = useSelector((state: RootState) => state.user);
@@ -76,6 +78,9 @@ const RobotFeatureButtons: React.FC<RobotFeatureButtonsProps> = ({
if (feature === 'findCar') {
sendFindCar?.();
}
if (feature === 'autoback') {
sendAutoBack?.();
}
const next = !active.has(feature);
const nextSet = new Set(active);
if (next) nextSet.add(feature);
@@ -100,6 +105,7 @@ const RobotFeatureButtons: React.FC<RobotFeatureButtonsProps> = ({
backgroundColor: isActive ? `${f.activeColor}1a` : '#fafafa',
borderColor: isActive ? f.activeColor : '#e5e7eb',
boxShadow: isActive ? `0 0 12px ${f.activeColor}33` : 'none',
cursor: 'pointer',
}}
title={t(`devices.features.${f.key}`)}
>

View File

@@ -1,4 +1,4 @@
import React, { useState, useEffect, useRef, useMemo } from 'react';
import React, { useState, useEffect, useRef, useMemo } from 'react';
import {
Row, Col, Card, Button, Space, Table, Tag, Typography, Progress, Badge,
Tabs, Input, Switch, Divider, Tooltip, Timeline, Select, message, DatePicker,
@@ -1767,22 +1767,11 @@ export default function RobotTaskPage() {
{route.workName || route.name || t('devices.unnamedRoute')}
</div>
<div style={{ fontSize: 12, color: '#86909C', marginTop: 4 }}>
ID: {route.id}
{t('devices.rtMode')}: {route.mode == "coverage" ? t('devices.coverageMode') : t('devices.singleMode')}
</div>
</div>
{/* 删除按钮 */}
<Tooltip title={t('devices.deleteRoute')}>
<Button
type="text"
icon={<DeleteOutlined style={{ color: '#F53F3F', fontSize: 20 }} />}
onClick={(e) => {
e.stopPropagation();
setSelectedPathWork(route);
// 替换为你的删除处理函数
handleDeleteRoute(route);
}}
/>
</Tooltip>
<Tooltip title={t('devices.createTask')}>
<Button
type="text"
@@ -2048,6 +2037,22 @@ const NewTaskModal = ({ isOpen, onClose, robots, selectedPathWork, handlGetTaskL
}, [selectedPathWork]);
// ====================== Tab / 返航任务 ======================
const [activeTab, setActiveTab] = useState('scheduled');
const [returnRoute, setReturnRoute] = useState(null);
const [returnDevice, setReturnDevice] = useState(null);
// 预设路径:仅保留单次任务路径
const singleRouteList = useMemo(
() => (routeList || []).filter(route => route.mode == 'single_point'),
[routeList]
);
const handleSaveReturnTask = () => {
// TODO: 返航任务保存接口待接入,暂时打印
console.log('新建返航任务', { route: returnRoute, device: returnDevice });
};
// ====================== 周/月选择 ======================
const weekDays = [
{ label: t('devices.wdSun'), value: 'SUNDAY' },
@@ -2170,144 +2175,208 @@ const NewTaskModal = ({ isOpen, onClose, robots, selectedPathWork, handlGetTaskL
>
<div className="space-y-4">
{/* 任务名称 */}
<div>
<label className="block mb-2 font-medium">{t('devices.taskName')}</label>
<Input
value={formData.planName}
onChange={(e) => setFormData({ ...formData, planName: e.target.value })}
placeholder={t('devices.inputTaskName')}
/>
</div>
{/*<Tabs
activeKey={activeTab}
onChange={setActiveTab}
items={[
{ key: 'scheduled', label: t('devices.scheduledTaskTab') },
{ key: 'return', label: t('devices.returnTaskTab') },
]}
/>*/}
{/* 执行路线 */}
<div>
<label className="block mb-2 font-medium">{t('devices.executeRouteLabel')}</label>
<Select
className="w-full"
placeholder={t('devices.selectRoute')}
onSelect={(_, option) => {
const route = routeList.find(r => r.id === option.value);
setFormData(prev => ({ ...prev, path: route }));
}}
value={formData.path?.id}
>
{routeList.map(route => (
<Select.Option
key={route.id}
value={route.id}
>
{route.workName || route.name}
</Select.Option>
))}
</Select>
</div>
{/* 选择设备 */}
<div className="relative">
<label className="block mb-2 font-medium">{t('video.selectDevice')}</label>
<Select
className="w-full"
placeholder={t('video.selectDevice')}
onSelect={(_, option) => {
const robot = robots.find(r => r.serialNumber === option.value);
setFormData(prev => ({ ...prev, device: robot }));
}}
value={formData.device?.serialNumber}
>
{robots.map(robot => (
<Select.Option
key={robot.serialNumber}
value={robot.serialNumber}
>
{robot.deviceAlias} ({robot.serialNumber})
</Select.Option>
))}
</Select>
</div>
{/* 重复计划 */}
<div>
<label className="block mb-2 font-medium">{t('devices.repeatPlan')}</label>
<Select
value={formData.repeatPlan}
onChange={(val) => setFormData({ ...formData, repeatPlan: val })}
className="w-full"
>
<Select.Option value="DAY">{t('devices.day')}</Select.Option>
<Select.Option value="WEEK">{t('devices.week')}</Select.Option>
<Select.Option value="MONTH">{t('devices.month')}</Select.Option>
</Select>
</div>
{/* 周选择 */}
{formData.repeatPlan === 'WEEK' && (
<div className="flex gap-1 flex-wrap">
{weekDays.map(day => (
<Button
key={day.value}
type={formData.days.includes(day.value) ? 'primary' : 'default'}
onClick={() => handleToggleDay(day.value)}
size="small"
shape="circle"
>
{day.label}
</Button>
))}
</div>
)}
{/* 月选择 */}
{formData.repeatPlan === 'MONTH' && (
<div className="grid grid-cols-7 gap-1">
{monthDays.map(day => (
<Button
key={day}
type={formData.dayOfMonth.includes(day) ? 'primary' : 'default'}
onClick={() => handleToggleMonthDay(day)}
size="small"
>
{day}
</Button>
))}
</div>
)}
{/* 按天:选择日期 */}
{formData.repeatPlan === 'DAY' && (
{activeTab === 'scheduled' ? (
<>
<label className="block mb-2 font-medium">{t('devices.execDate')}</label>
<DatePicker
onChange={handleDateChange}
{/* 任务名称 */}
<div>
<label className="block mb-2 font-medium">{t('devices.taskName')}</label>
<Input
value={formData.planName}
onChange={(e) => setFormData({ ...formData, planName: e.target.value })}
placeholder={t('devices.inputTaskName')}
/>
</div>
{/* 执行路线 */}
<div>
<label className="block mb-2 font-medium">{t('devices.executeRouteLabel')}</label>
<Select
className="w-full"
placeholder={t('devices.selectRoute')}
onSelect={(_, option) => {
const route = routeList.find(r => r.id === option.value);
setFormData(prev => ({ ...prev, path: route }));
}}
value={formData.path?.id}
>
{routeList.map(route => (
<Select.Option
key={route.id}
value={route.id}
>
{route.workName || route.name}
</Select.Option>
))}
</Select>
</div>
{/* 选择设备 */}
<div className="relative">
<label className="block mb-2 font-medium">{t('video.selectDevice')}</label>
<Select
className="w-full"
placeholder={t('video.selectDevice')}
onSelect={(_, option) => {
const robot = robots.find(r => r.serialNumber === option.value);
setFormData(prev => ({ ...prev, device: robot }));
}}
value={formData.device?.serialNumber}
>
{robots.map(robot => (
<Select.Option
key={robot.serialNumber}
value={robot.serialNumber}
>
{robot.deviceAlias} ({robot.serialNumber})
</Select.Option>
))}
</Select>
</div>
{/* 重复计划 */}
<div>
<label className="block mb-2 font-medium">{t('devices.repeatPlan')}</label>
<Select
value={formData.repeatPlan}
onChange={(val) => setFormData({ ...formData, repeatPlan: val })}
className="w-full"
>
<Select.Option value="DAY">{t('devices.day')}</Select.Option>
<Select.Option value="WEEK">{t('devices.week')}</Select.Option>
<Select.Option value="MONTH">{t('devices.month')}</Select.Option>
</Select>
</div>
{/* 周选择 */}
{formData.repeatPlan === 'WEEK' && (
<div className="flex gap-1 flex-wrap">
{weekDays.map(day => (
<Button
key={day.value}
type={formData.days.includes(day.value) ? 'primary' : 'default'}
onClick={() => handleToggleDay(day.value)}
size="small"
shape="circle"
>
{day.label}
</Button>
))}
</div>
)}
{/* 月选择 */}
{formData.repeatPlan === 'MONTH' && (
<div className="grid grid-cols-7 gap-1">
{monthDays.map(day => (
<Button
key={day}
type={formData.dayOfMonth.includes(day) ? 'primary' : 'default'}
onClick={() => handleToggleMonthDay(day)}
size="small"
>
{day}
</Button>
))}
</div>
)}
{/* 按天:选择日期 */}
{formData.repeatPlan === 'DAY' && (
<>
<label className="block mb-2 font-medium">{t('devices.execDate')}</label>
<DatePicker
onChange={handleDateChange}
className="w-full"
placeholder={t('devices.selectExecDate')}
/>
</>
)}
{/* 时间 */}
<label className="block mb-2 font-medium">{t('devices.execTime')}</label>
<TimePicker
format="HH:mm:ss"
onChange={handleTimeChange}
className="w-full"
placeholder={t('devices.selectExecDate')}
placeholder={t('devices.selectExecTime')}
/>
{/* 执行周期 */}
<label className="block mb-2 font-medium">{t('devices.executionCycle')}</label>
<RangePicker
onChange={handleCycleChange}
className="w-full"
placeholder={[t('devices.startDate'), t('devices.endDate')]}
showTime
format="YYYY-MM-DD HH:mm:ss"
/>
</>
) : (
<div className="space-y-4">
{/* 预设路径列表 */}
<div>
<label className="block mb-2 font-medium">{t('devices.presetRoutes')}</label>
<div className="max-h-64 overflow-y-auto space-y-2 pr-1">
{singleRouteList.length === 0 ? (
<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={t('devices.noReturnRoute')} />
) : (
singleRouteList.map(route => {
const selected = returnRoute?.id === route.id;
return (
<div
key={route.id}
onClick={() => setReturnRoute(route)}
className={`flex items-center gap-3 p-3 rounded-lg border cursor-pointer transition-colors ${selected ? 'border-blue-500 bg-blue-50' : 'border-gray-200 hover:border-blue-300'}`}
>
<div className="w-10 h-10 rounded overflow-hidden bg-gray-100 flex items-center justify-center shrink-0">
{route.imgUrl ? (
<img src={route.imgUrl} alt="" className="w-full h-full object-cover" />
) : (
<EyeOutlined className="text-gray-400" />
)}
</div>
<div className="flex-1 min-w-0 font-medium truncate">{route.workName || route.name}</div>
{selected && <CheckCircle2 size={18} className="text-blue-500 shrink-0" />}
</div>
);
})
)}
</div>
</div>
{/* 选择机器 */}
<div>
<label className="block mb-2 font-medium">{t('video.selectDevice')}</label>
<Select
className="w-full"
placeholder={t('video.selectDevice')}
allowClear
value={returnDevice?.serialNumber}
onChange={(val) => setReturnDevice((robots || []).find(r => r.serialNumber === val) || null)}
options={(robots || []).map(robot => ({
value: robot.serialNumber,
label: `${robot.deviceAlias ?? ''} ${robot.serialNumber}`,
}))}
/>
</div>
</div>
)}
{/* 时间 */}
<label className="block mb-2 font-medium">{t('devices.execTime')}</label>
<TimePicker
format="HH:mm:ss"
onChange={handleTimeChange}
className="w-full"
placeholder={t('devices.selectExecTime')}
/>
{/* 执行周期 */}
<label className="block mb-2 font-medium">{t('devices.executionCycle')}</label>
<RangePicker
onChange={handleCycleChange}
className="w-full"
placeholder={[t('devices.startDate'), t('devices.endDate')]}
showTime
format="YYYY-MM-DD HH:mm:ss"
/>
{/* 底部按钮 */}
<div className="flex justify-end gap-2 mt-6">
<Button onClick={onClose}>{t('common.cancel')}</Button>
<Button type="primary" onClick={handleSave}>{t('devices.saveTask')}</Button>
<Button type="primary" onClick={activeTab === 'scheduled' ? handleSave : handleSaveReturnTask}>{t('devices.saveTask')}</Button>
</div>
</div>
</Modal>