Files
web-Iot/src/components/devices/DeviceControl.tsx
2026-05-12 14:13:54 +08:00

2336 lines
82 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import React, { useState, useEffect, useRef, useCallback } from 'react';
import {
Power, RefreshCw, Play, Pause, Settings,
MapPin, Navigation, Video, Wifi, AlertTriangle,
RotateCcw, RotateCw, ArrowUp, ArrowDown, ArrowLeft, ArrowRight,
ChevronLeft, Plus, Trash2, Save, Send, Target, Map, Layers, Box,
Battery, Signal, Square,
Activity, BarChart3, Cpu,
Eye,
X
} from 'lucide-react';
import XboxController from './XboxController';
import { getControlRight, getFlightTaskDetail, getJurisdiction, getLiveStream, getPlaneDeviceList, getsinglePlan, getsinglePlanTrack, getWayLine, getWorkData, getWorkList, postFlightCommmand, saveDeviceTask, updateFlightTaskStatus } from '@/api/api';
import { message as antdMessage, Button, DatePicker, Input, InputNumber, Modal, Select, Tooltip } from 'antd';
import CesiumMap from './Map';
import { MOCK_DEVICES, OBSTACLE_TYPE } from '../const';
import { useWebRTCPlayer } from "./useWebRTCStream";
import VideoPlayer from "./VideoPlayer.tsx";
import { wsManager, WSStatus } from "@/api/websocket/WebSocketManager.ts";
import Cookies from "js-cookie";
import DroneLivePlayer from './VolcRtcPlayer.jsx';
antdMessage.config({
top: 100,
});
interface Robot {
id: string;
name: string;
status: 'online' | 'offline' | 'maintenance';
mode: 'standby' | 'working' | 'maintaining';
area: string;
battery: number;
signal: 'connected' | 'disconnected' | 'pending';
mqttTopic: string;
position: { lon: string; lat: string };
speed: number;
angularSpeed: number;
gpsPlan: string;
taskStatus: string;
remoteStatus: 'SAFE' | 'CONTROL';
mqttLink: 'WAIT' | 'CONNECTED' | 'DISCONNECTED';
type: 'robot' | 'plane' | 'mower';
gateway_sn?: string;
deviceAlias?: string;
capacity_percent?: number;
onlineStatus?: string | number;
lastRunningStatus?: {
latitude: string | number;
longitude: string | number;
battery: number;
};
drone_callsign?: string;
serialNumber?: string;
}
interface Waypoint {
id: number;
lon: string;
lat: string;
alt?: number;
}
const INITIAL_WAYPOINTS: Waypoint[] = [];
const StatusTagMap = {
working: { text: '工作中', color: 'bg-[#00e5ff]/10 text-[#00e5ff] border-[#00e5ff]/30' },
online: { text: '在线', color: 'bg-[#00e5ff]/10 text-[#00e5ff] border-[#00e5ff]/30' },
offline: { text: '离线', color: 'bg-[#ff4d4f]/10 text-[#ff4d4f] border-[#ff4d4f]/30' },
maintenance: { text: '维护', color: 'bg-[#ffad0d]/10 text-[#ffad0d] border-[#ffad0d]/30' },
configured: { text: '视频已配', color: 'bg-[#00e5ff]/10 text-[#00e5ff] border-[#00e5ff]/30' },
no_video: { text: '无视频', color: 'bg-[#6b7280]/10 text-[#9ca3af] border-[#6b7280]/30' },
failed: { text: '连接失败', color: 'bg-[#ff4d4f]/10 text-[#ff4d4f] border-[#ff4d4f]/30' }
};
const RobotControlCenter = ({ setView }) => {
const FILTERED_MOCKS = MOCK_DEVICES.filter(
item => item.type === 'robot' || item.type === 'mower' || item.type === 'cut'
);
const [selectedDevice, setSelectedDevice] = useState(FILTERED_MOCKS[0]);
const [isRemoteEnabled, setIsRemoteEnabled] = useState(false);
const [isControlled, setIsControlled] = useState(false);
const [selectedRoute, setSelectedRoute] = useState(null); // ✅ 新增
const [activeTab, setActiveTab] = useState<'remote' | 'gps' | 'vizanti'>('remote');
const [waypoints, setWaypoints] = useState(INITIAL_WAYPOINTS);
const [newWaypoint, setNewWaypoint] = useState({ id: 0, lon: '', lat: '' });
const [taskIssued, setTaskIssued] = useState(false);
const [taskRunning, setTaskRunning] = useState(false);
const [points, setPoints] = useState([]);
const [deviceRoute, setDeviceRoute] = useState([])
const mapClearRef = useRef(null);
const controlRef = useRef(null);
const [robotRoutes, setRobotRoutes] = useState<any[]>([]);
const [planeDevice, setPlaneDevice] = useState([]);
const [allDevices, setAllDevices] = useState([...FILTERED_MOCKS]);
const [planList, setPlanList] = useState([]);
const [selectedTask, setSelectedTask] = useState(null);
const [taskDetail, setTaskDetail] = useState(null);
const connectedDeviceSnRef = useRef<string | null>(null);
const requestDeviceId = useRef('');
// 无人机任务控制按钮状态
const [taskstatus, setTaskStatus] = useState<'suspended' | 'executing' | 'restored'>('suspended');
const [isReturningHome, setIsReturningHome] = useState(false);
const [isTaskPaused, setIsTaskPaused] = useState(false);
const [flightCommandLoading, setFlightCommandLoading] = useState(false);
//飞机创建航线
const [taskDetailModal, setTaskDetailModal] = useState(false);
const [uploadModal, setUploadModal] = useState(false);
const [createTaskModal, setCreateTaskModal] = useState(false);
const [loading, setLoading] = useState(false);
const [beginTime, setBeginTime] = useState(null);
const [endTime, setEndTime] = useState(null);
const [waylineUuid, setWaylineUuid] = useState('');
const [waylineList, setWaylineList] = useState([]);
const [selectedDrone, setSelectedDrone] = useState(null);
const [isModalOpen, setIsModalOpen] = useState(false);//权限请求的弹窗
const [hasControlRight, setHasContronRight] = useState(false);//是否有控制权限
//远程控制相关
const [modalcontent, setmodalcontent] = useState({ title: '权限请求', content: '是否请求控制权限?' });
const [modelType, setmodelType] = useState('');
const [taskForm, setTaskForm] = useState({
name: '',
wayline_uuid: '',
sn: '',
landing_dock_sn: '',
rth_altitude: 110,
rth_mode: 'optimal',
wayline_precision_type: 'rtk',
out_of_control_action_in_flight: 'return_home',
resumable_status: 'manual',
task_type: 'immediate',
time_zone: '',
repeat_type: 'nonrepeating',
repeat_option: { interval: 1 },
begin_at: null,
end_at: null,
recurring_task_start_time_list: [],
continuous_task_periods: [],
min_battery_capacity: 50
});
//====新增:websocket状态=======
const [wsStatus, setWsStatus] = useState<WSStatus>('disconnected');
const [wsDeviceInfo, setWsDeviceInfo] = useState([]);
// 悬浮视频相关状态 - 【修改1】:删除悬浮相关状态,改为固定显示
const [mowerView, setMowerView] = useState<'front' | 'back' | 'left' | 'right' | 'top' | 'all'>('front');
// 主视频
const { video: video, error: error, ready: ready } = useWebRTCPlayer(
selectedDevice?.serialNumber || '',
selectedDevice?.type === 'robot'
? ''
: `webrtc://ri.satabot.com/live/livestream/${selectedDevice?.serialNumber}`
);
// detect1
const { video: video1, error: error1, ready: ready1 } = useWebRTCPlayer(
selectedDevice?.serialNumber || '',
selectedDevice?.type === 'robot' ?
`webrtc://ri.satabot.com/live/livestream/${selectedDevice?.serialNumber}/detect1` : ''
);
// detect2
const { video: video2, error: error2, ready: ready2 } = useWebRTCPlayer(
selectedDevice?.serialNumber || '',
selectedDevice?.type === 'robot' ?
`webrtc://ri.satabot.com/live/livestream/${selectedDevice?.serialNumber}/detect2` : ''
);
// detect3
const { video: video3, error: error3, ready: ready3 } = useWebRTCPlayer(
selectedDevice?.serialNumber || '',
selectedDevice?.type === 'robot' ?
`webrtc://ri.satabot.com/live/livestream/${selectedDevice?.serialNumber}/detect3` : ''
);
const { video: video4, error: error4, ready: ready4 } = useWebRTCPlayer(
selectedDevice?.serialNumber || '',
selectedDevice?.type === 'cut' ?
`webrtc://ri.satabot.com/live/livestream/MC700PLUS-CN-JS-1768444624736-0000000A-09/detect1` : ''
);
// 拖拽状态
const [dragPos, setDragPos] = useState({ x: 0, y: 0 });
const dragRef = useRef<any>(null);
const isDragging = useRef(false);
const startPos = useRef({ x: 0, y: 0 });
// 拖拽逻辑
const handleMouseDown = useCallback((e: React.MouseEvent) => {
isDragging.current = true;
startPos.current = {
x: e.clientX - dragPos.x,
y: e.clientY - dragPos.y
};
document.addEventListener('mousemove', handleMouseMove);
document.addEventListener('mouseup', handleMouseUp);
}, [dragPos]);
const handleMouseMove = useCallback((e: MouseEvent) => {
if (!isDragging.current) return;
const newX = e.clientX - startPos.current.x;
const newY = e.clientY - startPos.current.y;
setDragPos({ x: newX, y: newY });
}, []);
const handleMouseUp = useCallback(() => {
isDragging.current = false;
document.removeEventListener('mousemove', handleMouseMove);
document.removeEventListener('mouseup', handleMouseUp);
}, []);
const [urlInfo, setUrlInfo] = useState(null);
// 下发无人机飞行指令:返航 / 取消返航 / 暂停 / 恢复
const sendFlightCommand = async (command: 'return_home' | 'return_home_cancel' | 'flighttask_pause' | 'flighttask_recovery') => {
if (!selectedDevice?.gateway_sn) {
antdMessage.warning('未选中无人机或无人机SN不存在');
return;
}
setFlightCommandLoading(true);
const data = {
command,
deviceSn: selectedDevice.gateway_sn,
}
try {
// 这里换成你的真实接口
const res = await postFlightCommmand(data);
if (res.data.code == 0) {
antdMessage.success('指令下发成功');
// 切换状态
if (command === 'return_home') setIsReturningHome(true);
if (command === 'return_home_cancel') setIsReturningHome(false);
if (command === 'flighttask_pause') setIsTaskPaused(true);
if (command === 'flighttask_recovery') setIsTaskPaused(false);
} else {
antdMessage.error(res.data.msg || '指令下发失败');
}
} catch (err) {
antdMessage.error('接口请求异常');
} finally {
setFlightCommandLoading(false);
}
};
// 更新任务状态:执行 / 挂起 / 继续
const updateTaskStatus = async (taskId: string, status: string) => {
if (!taskId) {
antdMessage.warning('请先选择航线任务');
return;
}
setLoading(true);
try {
const res = await updateFlightTaskStatus(taskId, status);
if (res.data.code === 0) {
const statusText = {
executing: '任务执行成功',
suspended: '任务已挂起',
restored: '任务已继续',
return_home: '任务已返航'
}[status] || '状态更新成功';
setTaskStatus(status as any);
antdMessage.success(statusText);
getAllPlan(selectedDevice);
} else {
antdMessage.error(res.data.msg || '操作失败');
}
} catch (err) {
antdMessage.error('操作接口异常');
} finally {
setLoading(false);
}
};
//获取飞机直播
const getLive = () => {
console.log("获取直播的设备信息", selectedDevice);
if (!selectedDevice.gateway_sn) return;
const data = {
getway_sn: selectedDevice.gateway_sn,
drone_sn: selectedDevice.device_sn,
getway_camera_list: selectedDevice.gateway_camera_list ?? [],
drone_camera_list: selectedDevice.drone_camera_list ?? [],
video_expire: 7200,
quality_type: "adaptive",
}
getLiveStream(data).then(res => {
if (res.data.code == 200) {
setUrlInfo(res.data.data);
}
console.log(res, "获取")
})
}
useEffect(() => {
return () => {
document.removeEventListener('mousemove', handleMouseMove);
document.removeEventListener('mouseup', handleMouseUp);
};
}, [handleMouseMove, handleMouseUp]);
const handleWsMessage = useCallback((message: any) => {
//接受的推送信息
console.log("接受的推送信息", message);
switch (message.type) {
case 'deviceInfo':
const deviceData = {};
message.data.forEach(item => {
deviceData[item.name] = item.value;
});
// @ts-ignore
setWsDeviceInfo(deviceData);
break;
case 'AUTH'://连接失败 重新连接
if (message.isAuth == true) {
getControl(connectedDeviceSnRef.current);
}
break;
case 'switchResult'://连接失败 重新连接
antdMessage.success({
content: '权限获取成功',
key: 'control',
duration: 2,
});
controlRef.current = true;
setIsControlled(true);
console.log("权限切换结果");
break;
case 'switchPermission'://连接失败 重新连接
console.log("平台请求权限", message.platform)
const platform = (message.platform || '').toLowerCase().trim();
if (platform == "web" || !platform) {
console.log("检测到web平台,执行return终止逻辑");
return; // 这里的return会终止整个handleMessage函数的执行
}
requestDeviceId.current = message.deviceId;
console.log(requestDeviceId.current, connectedDeviceSnRef.current)
// if(isControlled||isRequestControl) return;
showModal({ title: "权限请求", content: `${message.platform || '未知平台'}请求控制${requestDeviceId.current == connectedDeviceSnRef.current ? "" : requestDeviceId.current}权限,是否同意?` }, 'switchResult');
// setmodalcontent({title:'权限切换请求',content:`${message.platform|| '未知平台'}请求控制权限`});
break;
case 'detectionReport'://连接失败 重新连接
const obsData = message.data;
if (obsData && obsData.deviceId == connectedDeviceSnRef.current) {
const type = obsData?.obstacle?.type;
const isSecure = obsData?.isSecure;
const distance = obsData?.obstacle?.distance?.toFixed(2);
console.log("收到障碍物检测报告1122", type, isSecure);
if (isSecure) return;
antdMessage.warning({
key: 'obstacle-warning',
content: `设备检测到${OBSTACLE_TYPE[type] ?? '未知物'},距离 ${distance}!`,
duration: 3,
});
console.log("收到障碍物检测报告1122333");
}
break;
}
}, [])
// 修复版:WebSocket 状态监听 + 自动重连
useEffect(() => {
if (!selectedDevice) return;
// 获取最新状态
const currentStatus = wsManager.getStatus();
setWsStatus(currentStatus);
// 监听状态
const unsubStatus = wsManager.onStatusChange((newStatus) => {
setWsStatus(newStatus);
// 断开时清空状态
if (newStatus === "disconnected") {
connectedDeviceSnRef.current = null;
}
});
// 监听消息
const unsubMsg = wsManager.onMessage(handleWsMessage);
return () => {
unsubStatus();
unsubMsg();
};
}, [selectedDevice, handleWsMessage]);
const getTaskDetail = async (taskId) => {
if (!taskId) return;
setTaskDetailModal(true);
setTaskDetail(null);
setLoading(true);
try {
const res = await getFlightTaskDetail(taskId);
if (res.data.code === 0) {
setTaskDetail(res.data.data);
} else {
setTaskDetail(null);
antdMessage.error('暂无详情');
}
} catch (err) {
setTaskDetail(null);
antdMessage.error('获取详情接口异常');
} finally {
setLoading(false);
}
};
const getRouteList = () => {
const userId = JSON.parse(localStorage.getItem("userInfo"))?.userId;
getWorkList({ userId }).then(res => {
console.log(res, "获取任务数据")
if (res.data.code == 200) {
setDeviceRoute(res.data.data);
} else {
setDeviceRoute([])
}
}).catch(err => {
console.error(err, "获取任务出错");
setDeviceRoute([]);
});
}
const getControl = (serialnum) => {
const data = { platform: "web", deviceId: serialnum };
getJurisdiction(data).then(res => {
if (res?.data?.code === 200 && res?.data?.data?.remoteControl == true) {
console.log("获取远程遥控权限成功");
controlRef.current = true;
setIsControlled(true);
} else {
controlRef.current = false;
setIsControlled(false);
}
}).catch(err => {
controlRef.current = false;
setIsControlled(false);
})
};
const handleSelectRobot = async (robot) => {
// 1. 防御判断(必须放最前面)
if (!robot || !robot.serialNumber) {
antdMessage.warning("设备信息异常");
return;
}
//// 2. 判断是否是同一台设备
//const isSameDevice = connectedDeviceSnRef.current === robot.serialNumber;
//// 3. 无论是否同一设备,都要更新选中状态(UI必须同步)
setSelectedDevice(robot);
//// 4. 如果是同一台设备 → 不重连 WS,直接结束
//if (isSameDevice) {
// console.log("✅ 同一设备,不重新连接 WS");
// return;
//}
// 5. 不同设备 → 关闭旧连接
wsManager.close();
connectedDeviceSnRef.current = null;
setWsDeviceInfo([]);//清空设备信息
// 6. 安全解析用户信息
let userParse = null;
try {
const dataStr = localStorage.getItem("userInfo");
userParse = dataStr ? JSON.parse(dataStr) : null;
} catch (e) {
console.error("用户信息解析失败", e);
}
if (!userParse) {
setIsControlled(false);
antdMessage.warning("请先登录");
return;
}
const token = userParse.token || Cookies.get("Admin-Token");
const userName = userParse.username;
if (!token || !userName) {
setIsControlled(false);
antdMessage.warning("登录信息失效,请重新登录");
return;
}
if (robot.type == "plane") return;
wsManager.connect(robot.serialNumber, "wss://ri.satabot.com/ws/");
try {
// 7. 校验权限
const res = await getControlRight({
userName,
sourceType: 1,
token,
});
if (res?.data?.code === 200) {
setHasContronRight(true);
connectedDeviceSnRef.current = robot.serialNumber;
await getControl(robot.serialNumber);
} else {
setHasContronRight(false);
antdMessage.warning("其他web端正在控制");
connectedDeviceSnRef.current = null;
}
} catch (err) {
console.error("权限校验失败", err);
setHasContronRight(false);
antdMessage.error("网络异常或请求失败,请重试");
connectedDeviceSnRef.current = null;
}
};
const sendGamepad = useCallback((data: any) => {
}, []);
useEffect(() => {
if (!selectedDevice) return;
if (selectedDevice?.type === 'plane') {
getLive();
return;
}
try {
const saved = localStorage.getItem(`robot_route_${selectedDevice.id}`);
if (saved) {
const data = JSON.parse(saved);
setWaypoints(data?.waypoints || []);
antdMessage.success(`已加载 ${selectedDevice.name} 的本地航线`);
} else {
setWaypoints([]);
}
} catch (e) {
setWaypoints([]);
}
}, [selectedDevice]);
useEffect(() => {
const routes = [];
for (let key in localStorage) {
if (key.startsWith('robot_route_')) {
const item = localStorage.getItem(key);
if (item) {
const data = JSON.parse(item);
routes.push({
robotId: data?.robotId,
robotName: data?.robotName,
waypoints: data?.waypoints,
createTime: data?.createTime
});
}
}
}
setRobotRoutes(routes);
}, [waypoints]);
// ==============================================
// 【终极修复】页面切后台不会断开 + 切回来自动重连
// ==============================================
useEffect(() => {
const handleVisibilityChange = () => {
if (document.visibilityState === 'visible') {
console.log('✅ 页面切回前台,强制重连 WebSocket');
// 切回来时:如果当前有选中设备,直接自动重连
if (selectedDevice?.serialNumber && selectedDevice.type !== 'plane') {
setTimeout(() => {
handleSelectRobot(selectedDevice);
}, 500);
}
}
};
// 监听页面切换
document.addEventListener('visibilitychange', handleVisibilityChange);
// 页面隐藏时也保持心跳(浏览器不会杀死)
const keepAlive = setInterval(() => {
if (
connectedDeviceSnRef.current &&
wsStatus !== 'connected' &&
selectedDevice?.type !== 'plane'
) {
console.log('🔄 后台保活:尝试重连 WebSocket');
handleSelectRobot(selectedDevice);
}
}, 8000); // 8秒后台保活
return () => {
document.removeEventListener('visibilitychange', handleVisibilityChange);
clearInterval(keepAlive);
};
}, [selectedDevice, wsStatus, handleSelectRobot]);
useEffect(() => {
getRouteList();
getPlaneDeviceList().then(res => {
if (res.data.code == 200) {
const drones = res.data.data.detail.map((item, i) => ({
...item,
id: `drone_${item.device_sn || i}`,
name: item.drone_callsign || `无人机 ${i + 1}`,
deviceAlias: item.drone_callsign,
status: item.onlineStatus == 1 ? 'online' : 'offline',
mode: 'standby',
area: '无人机空域',
battery: item.capacity_percent || 0,
capacity_percent: item.capacity_percent,
signal: 'connected',
position: {
lon: item.longitude?.toString() || '0',
lat: item.latitude?.toString() || '0'
},
lastRunningStatus: {
latitude: item.latitude,
longitude: item.longitude,
battery: item.capacity_percent
},
onlineStatus: item.onlineStatus,
gateway_sn: item.gateway_sn,
serialNumber: item.device_sn,
drone_callsign: item.drone_callsign,
speed: 0.00,
angularSpeed: 0.00,
gpsPlan: '无人机航线',
taskStatus: '待命',
remoteStatus: 'SAFE',
mqttLink: 'CONNECTED',
type: 'plane'
}));
setPlaneDevice(drones);
setAllDevices([...FILTERED_MOCKS, ...drones]);
}
});
}, []);
const sendPermissionRequest = (data, type) => {
// type: "switchPermission",switchResult 请求控制权 和请求切换请求
const wsdata = {
type: type,
switchResult: data,
token: localStorage.getItem("token"),
deviceId: type == "switchPermission" ? connectedDeviceSnRef.current : requestDeviceId.current,
userName: localStorage.getItem("userInfo") ? JSON.parse(localStorage.getItem("userInfo")!).username : "",
};
console.log("发送的权限请求数据", wsdata);
wsManager.send(wsdata);
}
const handleOk = () => {
sendPermissionRequest(true, modelType);
if (modelType == "switchPermission") {
antdMessage.loading({
key: "control",
type: 'loading',
content: '权限请求中...',
duration: 0,
});
} else {
console.log(requestDeviceId.current, connectedDeviceSnRef.current)
if (requestDeviceId.current == connectedDeviceSnRef.current) {
console.log("同意权限给其他平台")
controlRef.current = false;
setIsControlled(false);
}
}
console.log("同意权限请求");
setIsModalOpen(false);
};
const handleCancel = () => {
if (modelType == "switchPermission") {
}
console.log("同意权限请求关闭");
setIsModalOpen(false);
};
const getAllPlan = (device) => {
if (!device.gateway_sn) return;
getsinglePlan({ gateway_sn: device.gateway_sn }).then(res => {
if (res.data.code == 0) {
setPlanList(res.data.data.list || []);
} else {
setPlanList([]);
}
}).catch(() => setPlanList([]));
};
const handleGetTask = (data) => {
setSelectedTask(data);
getsinglePlanTrack({ uuid: data.uuid }).then(res => {
if (res.data.code == 0 && res.data.data.track?.points?.length) {
const points = res.data.data.track.points.map(item => ({
lon: item.longitude || item.lon,
lat: item.latitude || item.lat
}));
setPoints(points);
} else {
antdMessage.warning("暂无航线数据");
setPoints([]);
}
}).catch(() => {
antdMessage.warning("获取航线失败");
setPoints([]);
});
};
useEffect(() => {
setTaskIssued(false);
setTaskRunning(false);
setSelectedTask(null);
setPoints([]); // 🔥 关键:清空上一个设备的轨迹
if (selectedDevice?.type === 'plane') {
setPlanList([]);
setPoints([]);
if (selectedDevice.gateway_sn) {
getAllPlan(selectedDevice);
}
return;
}
setPlanList([]);
try {
const pts = selectedDevice.points;
if (!pts || !Array.isArray(pts) || pts.length < 2 || pts.length % 2 !== 0) {
setPoints([]);
return;
}
const formatPoints = [];
for (let i = 0; i + 1 < pts.length; i += 2) {
const lon = Number(pts[i]);
const lat = Number(pts[i + 1]);
if (!isNaN(lon) && !isNaN(lat) && lon !== 0 && lat !== 0) {
formatPoints.push({ lon, lat });
}
}
setPoints(formatPoints);
} catch (e) {
console.error('路线解析失败', e);
setPoints([]);
}
}, [selectedDevice]);
const getPathPoints = (coords) => {
if (!coords || coords.length === 0) return;
const newWps = coords.map((p, i) => ({
id: i + 1,
lon: p.lon.toFixed(6),
lat: p.lat.toFixed(6),
}));
setWaypoints(newWps);
antdMessage.success(`已添加 ${coords.length} 个地图点击航点`);
};
const deleteWaypoint = (id) => {
const newWps = waypoints.filter(w => w.id !== id);
setWaypoints(newWps);
const mapPoints = newWps.map(w => ({
lon: parseFloat(w.lon),
lat: parseFloat(w.lat)
}));
setPoints(mapPoints);
if (mapClearRef.current) mapClearRef.current();
antdMessage.success("已删除航点并同步地图");
};
const clearWaypoints = () => {
setWaypoints([]);
setTaskIssued(false);
setTaskRunning(false);
setPoints([]);
if (mapClearRef.current) mapClearRef.current();
antdMessage.success("已清空所有航点与地图轨迹");
};
const createFlightTask = async () => {
if (!taskForm.name) {
antdMessage.warning('请输入任务名称');
return;
}
if (!waylineUuid) {
antdMessage.warning('请选择航线');
return;
}
const params = {
...taskForm,
sn: selectedDevice.gateway_sn,
wayline_uuid: waylineUuid,
rth_altitude: Number(taskForm.rth_altitude),
min_battery_capacity: Number(taskForm.min_battery_capacity),
begin_at: beginTime ? Math.floor(beginTime.unix()) : null,
end_at: endTime ? Math.floor(endTime.unix()) : null,
};
if (taskForm.task_type !== 'immediate' && !params.begin_at) {
antdMessage.warning('请选择任务开始时间');
return;
}
setLoading(true);
try {
// 请确保你已在顶部引入:import { createWaylineTask } from '@/api/api'
const res = await saveDeviceTask(params);
if (res.data.code === 0) {
antdMessage.success('创建成功');
setCreateTaskModal(false);
getAllPlan(selectedDevice);
resetModals();
} else {
antdMessage.error(res.data.msg || '创建失败');
}
} catch (err) {
antdMessage.error('接口异常,请检查');
} finally {
setLoading(false);
}
};
const saveWaypoints = () => {
if (waypoints.length === 0) {
antdMessage.warning("无航点可保存");
return;
}
if (selectedDevice?.type === 'plane') {
antdMessage.warning("无人机不支持保存本地航线");
return;
}
const key = `robot_route_${selectedDevice.id}_${Date.now()}`;
const data = {
robotId: selectedDevice.id,
robotName: selectedDevice.name,
waypoints,
createTime: new Date().toLocaleString()
};
localStorage.setItem(key, JSON.stringify(data));
antdMessage.success("✅ 航线已新增保存到本地");
refreshRobotRoutes();
};
const resetModals = () => {
setUploadModal(false);
setCreateTaskModal(false);
setTaskDetailModal(false);
setBeginTime(null);
setEndTime(null);
setTaskForm({
name: '',
wayline_uuid: '',
sn: selectedDevice?.gateway_sn,
landing_dock_sn: '',
rth_altitude: 110,
rth_mode: 'optimal',
wayline_precision_type: 'rtk',
out_of_control_action_in_flight: 'return_home',
resumable_status: 'manual',
task_type: 'immediate',
time_zone: '',
repeat_type: 'nonrepeating',
repeat_option: { interval: 1 },
begin_at: null,
end_at: null,
recurring_task_start_time_list: [],
continuous_task_periods: [],
min_battery_capacity: 50
});
};
const refreshRobotRoutes = () => {
const routes = [];
for (let key in localStorage) {
if (key.startsWith('robot_route_')) {
const item = localStorage.getItem(key);
if (item) {
try {
routes.push(JSON.parse(item));
} catch (e) { }
}
}
}
setRobotRoutes(routes);
};
const fetchWaylineList = async () => {
try {
const res = await getWayLine();
if (res.data.code === 0) {
const _list = res.data.data.list.map(item => {
return {
...item,
label: item.name || `航线_${item.id || '未知'}`,
value: item.id
}
})
setWaylineList(_list || []); // 取list数组
}
} catch (err) {
antdMessage.error('获取航线列表失败');
}
};
useEffect(() => {
if (createTaskModal) {
fetchWaylineList();
// 重置表单时间
setBeginTime(null);
setEndTime(null);
}
}, [createTaskModal]);
useEffect(() => {
if (!selectedDevice || selectedDevice?.type === 'plane') {
setWaypoints([]);
refreshRobotRoutes();
if (selectedDevice?.type === 'plane') {
setActiveTab('gps');
} else {
setActiveTab('remote');
}
return;
}
try {
let latestWaypoints = [];
let maxTime = 0;
for (let key in localStorage) {
if (key.startsWith(`robot_route_${selectedDevice.id}`)) {
const item = localStorage.getItem(key);
if (item) {
const data = JSON.parse(item);
const time = new Date(data?.createTime).getTime();
if (time > maxTime) {
maxTime = time;
latestWaypoints = data?.waypoints;
}
}
}
}
setWaypoints(latestWaypoints);
refreshRobotRoutes();
} catch (e) {
setWaypoints([]);
refreshRobotRoutes();
}
}, [selectedDevice]);
const loadRoute = (route) => {
setSelectedRoute(route); // ✅ 加上这句
setWaypoints(route.waypoints);
const mapPoints = route.waypoints.map(w => ({
lon: parseFloat(w.lon),
lat: parseFloat(w.lat)
}));
setPoints(mapPoints);
antdMessage.success(`已加载航线:${route.robotName}`);
};
const issueGPSTask = () => {
//if (waypoints.length === 0) return;
setTaskIssued(true);
setTaskRunning(false);
antdMessage.success("GPS任务已下发");
};
const toggleTaskRunning = () => {
if (!taskIssued) {
antdMessage.warning("请先下发任务");
return;
}
setTaskRunning(!taskRunning);
antdMessage.success(taskRunning ? "已暂停" : "已开始执行");
};
const stopGPSTask = () => {
setTaskRunning(false);
setTaskIssued(false);
antdMessage.success("任务已停止");
};
const mapFocus = selectedDevice ? {
lat: selectedDevice.lastRunningStatus.latitude,
lon: selectedDevice.lastRunningStatus.longitude,
height: 500
} : { lat: '31.030129089704428', lon: '120.76671769055027', height: 800 };
//手柄数据
const handleGamepad = (data) => {
/* if (!wsRef.current || // 1. WebSocket 是否存在
wsRef.current.readyState !== WebSocket.OPEN || // 2. 连接是否打开
!controlRef.current) { // 3. 是否有控制权限
return;
}*/
const dataStr = localStorage.getItem('userInfo');
let parse = JSON.parse(dataStr);
var token = parse.token;
// @ts-ignore
var token = parse?.token;
console.log(wsStatus);
// 📦 数据包装
const wsdata = {
type: "remoteControl", // 消息类型
remoteData: data, // 原始手柄数据
token: token, // 认证令牌
userName: parse.username,
};
wsManager.send(wsdata);
//console.log(data)
};
const showModal = (content, type) => {
setmodalcontent(content);
setmodelType(type);
console.log("显示弹窗", content, type);
setIsModalOpen(true);
};
const handleControlModal = (data) => {
if (!hasControlRight) return;
if (data.control == true) {
showModal({ title: "权限请求", content: "是否请求控制权限?" }, 'switchPermission');
} else {
setIsModalOpen(false);
}
}
const calcPercent = (value, max) => {
const num = Number(value);
if (!Number.isFinite(num) || max <= 0) return 0;
return Math.min(100, Math.round((num / max) * 100));
};
const handleGetRoute = (work) => {
setSelectedRoute(work); // ✅ 加上这句
const data = {
workName: work.workName
}
getWorkData(data).then(res => {
if (res.data?.code === 200) {
console.log(res, "获取单独列表数据");
// 安全解析 jsonData
let jsonData = {};
try {
const rawJson = res.data?.data?.jsonData;
if (rawJson) jsonData = JSON.parse(rawJson);
} catch (e) {
console.warn("路径数据解析失败", e);
}
// 按优先级取路径:path → outer → 空数组
const path =
jsonData?.path?.length > 0
? jsonData.path
: jsonData.outer?.length > 0
? jsonData.outer
: [];
// 格式化坐标
const formatPoints = path.map(p => ({
lon: p.lon ?? p.longitude ?? p[0],
lat: p.lat ?? p.latitude ?? p[1]
}));
setPoints(formatPoints);
} else {
setPoints([]);
}
}).catch(err => {
console.error("获取数据失败", err);
setPoints([]);
});
}
const Gauge = ({ label, value, unit, color, percent }) => {
const colorMap = { cyan: 'stroke-cyan-400', rose: 'stroke-rose-400', yellow: 'stroke-yellow-400', purple: 'stroke-purple-400' };
return (
<div className="flex flex-col items-center gap-2 h-full">
<div className="relative w-43 h-43">
<svg className="w-full h-full -rotate-90" viewBox="0 0 100 100">
<circle cx="50" cy="50" r="42" fill="transparent" stroke="#0f172a" strokeWidth="8" />
<circle cx="50" cy="50" r="42" fill="transparent" stroke="rgba(255,255,255,0.05)" strokeWidth="4" strokeDasharray="1 3" />
<circle cx="50" cy="50" r="42" fill="transparent" className={`${colorMap[color]} transition-all duration-1000 ease-out`} strokeWidth="8" strokeDasharray={`${(percent / 100) * 264} 264`} strokeLinecap="round" />
</svg>
<div className="absolute inset-0 flex flex-col items-center justify-center">
<span className="text-[28px] font-black digital-font text-white glow-text">{value}</span>
<span className="text-[10px] text-slate-500 font-bold uppercase tracking-widest">{unit}</span>
</div>
</div>
<span className="text-[10px] text-slate-400 font-bold uppercase tracking-tighter opacity-70">{label}</span>
</div>
);
};
const onlineCount = allDevices.filter(r => r.status === 'online' || r.onlineStatus == 1 || r.status == "working").length;
// 【新增】视频渲染组件 - 提取成独立函数,方便复用
const renderVideoContent = () => {
return (
<div className="w-full h-full flex items-center justify-center overflow-hidden">
{/* 割草机视角切换 */}
{selectedDevice?.type === 'cut' && (
<div className="absolute top-2 left-2 z-50 flex gap-1 bg-black/70 rounded-lg p-1">
{['front', 'back', 'left', 'right', 'all'].map(v => (
<button
key={v}
onClick={() => setMowerView(v as any)}
className={`px-2 py-1 text-[10px] rounded-md ${mowerView === v ? 'bg-blue-500 text-white' : 'text-slate-300'}`}
>
{v === 'front' ? '前' : v === 'back' ? '后' : v === 'left' ? '左' : v === 'right' ? '右' : v === 'top' ? '上' : '全部'}
</button>
))}
</div>
)}
{selectedDevice?.type === 'mower' && (
<div className="absolute top-2 left-2 z-50 flex gap-1 bg-black/70 rounded-lg p-1">
{['front', 'back', 'left', 'right', 'all'].map(v => (
<button
key={v}
onClick={() => setMowerView(v as any)}
className={`px-2 py-1 text-[10px] rounded-md ${mowerView === v ? 'bg-blue-500 text-white' : 'text-slate-300'}`}
>
{v === 'front' ? '前' : v === 'back' ? '后' : v === 'left' ? '左' : v === 'right' ? '右' : '全部'}
</button>
))}
</div>
)}
{/* 巡检机器人:3路视频 → 紧凑横向,不滚动,全部可见 */}
{selectedDevice?.type === 'robot' && (
<div className="w-[92%] h-auto max-h-full flex items-center gap-3 justify-center">
<div className="relative w-[25%] aspect-[16/9] rounded bg-black">
<VideoPlayer deviceId={selectedDevice.serialNumber} idx={1} className="w-full h-full object-contain" video={video2} error={error2} ready={ready2} noCrop
/>
</div>
{/* 主画面:小一点 */}
<div className="relative w-[40%] aspect-[16/9] rounded bg-black">
<VideoPlayer
deviceId={selectedDevice.serialNumber}
idx={1}
className="w-full h-full object-contain"
video={video1}
error={error1}
ready={ready1}
/>
</div>
<div className="relative w-[25%] aspect-[16/9] rounded bg-black">
<VideoPlayer deviceId={selectedDevice.serialNumber} idx={1} className="w-full h-full object-contain" video={video3} error={error3} ready={ready3}
/>
</div>
</div>
)}
{/* 割草机单路 */}
{selectedDevice?.type === 'cut' && mowerView !== 'all' && (
<div className="relative w-[70%] aspect-[16/9] rounded-md overflow-hidden bg-black">
{mowerView != "top" && <VideoPlayer
deviceId={`CAM_${mowerView.toUpperCase()}`}
idx={mowerView === "front" ? 1 : mowerView === "back" ? 2 : mowerView === "left" ? 3 : 4}
className="w-full h-full object-contain"
video={video}
error={error}
ready={ready}
noCrop={false}
/>}
{mowerView == "top" && <VideoPlayer
deviceId={`CAM_${mowerView.toUpperCase()}`}
idx={5}
className="w-full h-full object-contain"
video={video4}
error={error4}
ready={ready4}
/>}
<VideoPlayer
deviceId={`CAM_${mowerView.toUpperCase()}`}
idx={mowerView === "front" ? 1 : mowerView === "back" ? 2 : mowerView === "left" ? 3 : 4}
className="w-full h-full object-contain"
video={video}
error={error}
ready={ready}
noCrop={false}
/>
</div>
)}
{selectedDevice?.type === 'mower' && mowerView !== 'all' && (
<div className="relative w-[70%] aspect-[16/9] rounded-md overflow-hidden bg-black">
{mowerView != "top" && <VideoPlayer
deviceId={`CAM_${mowerView.toUpperCase()}`}
idx={mowerView === "front" ? 1 : mowerView === "back" ? 2 : mowerView === "left" ? 3 : 4}
className="w-full h-full object-contain"
video={video}
error={error}
ready={ready}
noCrop={false}
/>}
</div>
)}
{/* ✅ 修复:割草机4路视频 —— 绝不压扁,保持16:9 */}
{/* {selectedDevice?.type === 'mower' && mowerView === 'all' && (
<div className="w-[80%] h-auto flex flex-col justify-center gap-2">
<div className="flex justify-center gap-2">
<div className="relative w-[45%] aspect-[16/9] rounded bg-black">
<VideoPlayer deviceId="CAM_FRONT" idx={1} className="w-full h-full object-contain" video={video} error={error} ready={ready} noCrop={false} />
</div>
<div className="relative w-[45%] aspect-[16/9] rounded bg-black">
<VideoPlayer deviceId="CAM_LEFT" idx={2} className="w-full h-full object-contain" video={video} error={error} ready={ready} noCrop />
</div>
</div>
<div className="flex justify-center gap-2">
<div className="relative w-[45%] aspect-[16/9] rounded bg-black">
<VideoPlayer deviceId="CAM_RIGHT" idx={3} className="w-full h-full object-contain" video={video} error={error} ready={ready} noCrop={false} />
</div>
<div className="relative w-[45%] aspect-[16/9] rounded bg-black">
<VideoPlayer deviceId="CAM_BACK" idx={4} className="w-full h-full object-contain" video={video} error={error} ready={ready} noCrop={false} />
</div>
</div>
</div>
)}*/}
{selectedDevice?.type === 'mower' && mowerView === 'all' && (
<div className="w-full h-full flex flex-col items-center justify-between gap-2">
{/* 上 */}
{/*<div className="relative w-[33%] h-[180px] rounded bg-black">
<VideoPlayer deviceId="CAM_TOP" idx={5} className="w-full h-full object-contain" video={video1} error={error1} ready={ready1} noCrop />
</div>*/}
{/* 左 + 中 + 右 */}
<div className="flex justify-center items-center gap-2 w-full ">
<div className="relative w-[40%] h-full rounded bg-black">
<VideoPlayer deviceId="CAM_LEFT" idx={3} className="w-full h-full object-contain" video={video} error={error} ready={ready} noCrop={false} />
</div>
<div className="relative w-[40%] h-full rounded bg-black">
<VideoPlayer deviceId="CAM_FRONT" idx={1} className="w-full h-full object-contain" video={video} error={error} ready={ready} noCrop={false} />
</div>
<div className="relative w-[40%] h-full rounded bg-black">
<VideoPlayer deviceId="CAM_RIGHT" idx={4} className="w-full h-full object-contain" video={video} error={error} ready={ready} noCrop={false} />
</div>
</div>
{/* 下 */}
<div className="relative w-[33%] h-[180px] rounded bg-black">
<VideoPlayer deviceId="CAM_BACK" idx={2} className="w-full h-full object-contain" video={video} error={error} ready={ready} noCrop={false} />
</div>
</div>
)}
{selectedDevice?.type === 'cut' && mowerView === 'all' && (
<div className="w-full h-full flex flex-col items-center justify-between gap-2">
{/* 上 */}
{/*<div className="relative w-[33%] h-[180px] rounded bg-black">
<VideoPlayer deviceId="CAM_TOP" idx={5} className="w-full h-full object-contain" video={video4} error={error4} ready={ready4} noCrop />
</div>*/}
{/* 左 + 中 + 右 */}
<div className="flex justify-center items-center gap-2 w-full ">
<div className="relative w-[40%] h-full rounded bg-black">
<VideoPlayer deviceId="CAM_LEFT" idx={3} className="w-full h-full object-contain" video={video} error={error} ready={ready} noCrop={false} />
</div>
<div className="relative w-[40%] h-full rounded bg-black">
<VideoPlayer deviceId="CAM_FRONT" idx={1} className="w-full h-full object-contain" video={video} error={error} ready={ready} noCrop={false} />
</div>
<div className="relative w-[40%] h-full rounded bg-black">
<VideoPlayer deviceId="CAM_RIGHT" idx={4} className="w-full h-full object-contain" video={video} error={error} ready={ready} noCrop={false} />
</div>
</div>
{/* 下 */}
<div className="relative w-[33%] h-[180px] rounded bg-black">
<VideoPlayer deviceId="CAM_BACK" idx={2} className="w-full h-full object-contain" video={video} error={error} ready={ready} noCrop={false} />
</div>
</div>
)}
{/*其他设备
{selectedDevice?.type !== 'robot' && selectedDevice?.type !== 'mower' && (
<div className="relative w-[80%] aspect-[16/9] rounded-md overflow-hidden bg-black">
<VideoPlayer
deviceId="887"
idx={1}
className="w-full h-full object-contain"
video={video}
error={error}
ready={ready}
noCrop
/>
<div className="absolute top-1 left-1 bg-black/70 text-white px-1.5 py-0.5 rounded text-[10px]">
{selectedDevice?.name}|实时视频
</div>
</div>
)}*/}
</div>
);
};
return (
<div className="flex text-white overflow-hidden w-full">
{/* 左侧设备列表 */}
<div className="w-100 border-r border-[#1a243a] backdrop-blur-sm p-5 flex flex-col shadow-xl">
<div className="mb-6">
<div className="flex gap-2 mb-2">
<button onClick={() => setView('overview')} className="p-2 bg-[#1e294a]/50 hover:bg-[#2a375c]/70 rounded-lg border border-[#2a375c]/50 transition-all">
<ChevronLeft className="w-5 h-5 text-[#a0aec0] rotate-180" />
</button>
<h2 className="text-lg font-bold text-[#00e5ff] flex items-center gap-2">
<Navigation className="w-4 h-4 text-[#00e5ff]" /> 设备列表
</h2>
</div>
<div className="flex gap-3">
<div className="flex items-center justify-between bg-white/5 backdrop-blur-sm rounded-xl p-4 w-full shadow-sm border border-[#243157]/40">
<span className="text-[18px] font-bold text-[#9ca3af] mb-1">在线设备</span>
<span className="text-2xl font-bold text-white">{onlineCount}/{allDevices.length}</span>
</div>
{/*<div className="bg-white/5 backdrop-blur-sm rounded-xl p-4 w-1/2 shadow-sm border border-[#243157]/40">
<p className="text-xs text-[#9ca3af] mb-1">任务态势</p>
<p className="text-2xl font-bold text-white">{selectedDevice.taskStatus}</p>
</div>*/}
</div>
</div>
<div className="flex-1 overflow-y-auto space-y-3 max-h-[960px] overflow-auto scrollbar-hide">
{allDevices.map(device => (
<div
key={device.id}
onClick={() => {
handleSelectRobot(device);
}}
className={`bg-white/5 backdrop-blur-sm rounded-xl p-4 border transition-all duration-200 hover:scale-[1.01] cursor-pointer ${selectedDevice.id === device.id ? 'border-[#00e5ff]/50 bg-[#00e5ff]/5 shadow-lg shadow-[#00e5ff]/5' : 'border-[#243157]/40'}`}
>
<div className="flex justify-between items-start mb-2.5">
<h3 className="font-medium text-white text-sm flex items-center gap-1.5">
{device?.type === 'plane' && <Box className="w-4 h-4 text-blue-400" />}
{device.name}
<span className="text-[10px] text-slate-400">[{device?.type == 'plane' ? '无人机' : device?.type === 'mower' ? '割草机' : '巡检机'}]</span>
<span className="text-[8px] text-slate-400">[{device?.type == 'plane' ? '支持GPS规划' : "支持摇控、GPS规划"}]</span>
</h3>
<span className={`text-xs px-2 py-1 rounded-full border ${StatusTagMap[device?.status]?.color}`}>
{StatusTagMap[device?.status]?.text}
</span>
</div>
{/*<p className="text-xs text-[#d1d5db] mb-2.5 flex items-center gap-1.5">
<MapPin className="w-3 h-3 text-[#9ca3af]" />区域: {device?.area}
</p>*/}
<div className="flex gap-2 text-xs mb-3">
<span className="bg-[#1e294a]/60 text-[#d1d5db] px-2 py-1 rounded-full text-xs flex items-center gap-1">
<Battery className={`w-3 h-3 ${device.battery < 30 ? 'text-red-400' : 'text-green-400'}`} />
电量: {device?.battery}%
</span>
</div>
{device?.type === 'plane' && <div className="flex justify-between text-xs text-[#d1d5db] pt-2 border-t border-[#243157]/40">
<span className="text-blue-400">SN: {device?.gateway_sn?.slice(-6) || '--'}</span>
</div>}
{device?.type !== 'plane' && <div className="flex justify-between text-xs text-[#d1d5db] pt-2 border-t border-[#243157]/40">
<span className="text-blue-400"> {device?.serialNumber || '--'}</span>
</div>}
</div>
))}
</div>
</div>
{/* 中间操作区 */}
<div className="flex-1 p-5 flex flex-col ">
<div >
<div className="flex justify-between items-center mb-4">
<div>
<h1 className="text-xl font-bold text-white mb-1">
{selectedDevice?.name}
</h1>
</div>
<div className="flex gap-2">
<span className="bg-[#00e5ff]/10 text-[#00e5ff] text-xs px-3 py-1.5 rounded-lg border border-[#00e5ff]/30">视频链路已配置</span>
</div>
</div>
{/*<div className="grid grid-cols-5 gap-3">
<div className="bg-white/5 backdrop-blur-sm rounded-xl p-4 border border-[#243157]/40 shadow-sm">
<p className="text-xs text-[#9ca3af] mb-1.5">当前位置</p>
<p className="text-sm font-mono text-white">
{selectedDevice?.position?.lon
? Number(selectedDevice.position.lon).toFixed(2)
: '--'},
{selectedDevice?.position?.lat
? Number(selectedDevice.position.lat).toFixed(2)
: '--'}
</p> </div>
<div className="bg-white/5 backdrop-blur-sm rounded-xl p-4 border border-[#243157]/40 shadow-sm">
<p className="text-xs text-[#9ca3af] mb-1.5">当前模式</p>
<p className="text-sm font-bold text-white">{selectedDevice?.type === 'plane' ? '无人机待命' : selectedDevice?.type === 'mower' ? '割草待命' : '待命'}</p>
</div>
<div className="bg-white/5 backdrop-blur-sm rounded-xl p-4 border border-[#243157]/40 shadow-sm">
<p className="text-xs text-[#9ca3af] mb-1.5">电量/航向</p>
<p className="text-sm font-bold text-white">{selectedDevice?.battery}% / 92°</p>
</div>
<div className="bg-white/5 backdrop-blur-sm rounded-xl p-4 border border-[#243157]/40 shadow-sm">
<p className="text-xs text-[#9ca3af] mb-1.5">速度</p>
<p className="text-sm font-bold text-white">{selectedDevice?.speed} m/s</p>
</div>
<div className="bg-white/5 backdrop-blur-sm rounded-xl p-4 border border-[#243157]/40 shadow-sm flex items-center justify-between">
<span className="text-xs text-[#9ca3af]">启用遥控</span>
<label className="relative inline-flex items-center cursor-pointer">
<input type="checkbox" checked={isRemoteEnabled} onChange={() => setIsRemoteEnabled(!isRemoteEnabled)} className="sr-only peer" />
<div className="w-10 h-5 bg-[#243157] peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-2 peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-[#00e5ff]"></div>
</label>
</div>
</div>*/}
</div>
<div className="border-b border-[#243157]/40 mb-5">
<div className="flex gap-6">
{selectedDevice.type !== 'plane' && <button onClick={() => setActiveTab('remote')} className={`px-3 py-2 font-medium transition-colors ${activeTab === 'remote' ? 'text-[#00e5ff] border-b-2 border-[#00e5ff]' : 'text-[#9ca3af] hover:text-white'}`}>遥控与态势</button>
}
<button onClick={() => setActiveTab('gps')} className={`px-3 py-2 font-medium transition-colors ${activeTab === 'gps' ? 'text-[#00e5ff] border-b-2 border-[#00e5ff]' : 'text-[#9ca3af] hover:text-white'}`}>GPS规划</button>
</div>
</div>
{/* 遥控与态势 - 【修改2】:把视频嵌入到这里 */}
{activeTab === 'remote' && (
<div className="flex-1 overflow-y-auto pr-2 flex flex-col gap-4">
{/* 视频区域 - 独立大窗口 */}
{selectedDevice.type !== 'plane' && (
<div className="bg-[#16203a]/40 backdrop-blur-sm rounded-xl p-3 border border-[#243157]/20 relative">
{renderVideoContent()}
</div>
)}
{/* 状态卡片行 */}
{/*<div className="grid grid-cols-4 gap-3">
<div className="bg-white/5 backdrop-blur-sm rounded-xl p-4 border border-[#243157]/40 shadow-sm">
<p className="text-xs text-[#9ca3af] mb-1.5">TCP链路</p>
<p className="text-lg font-bold text-white">{selectedDevice?.mqttLink}</p>
</div>
<div className="bg-white/5 backdrop-blur-sm rounded-xl p-4 border border-[#243157]/40 shadow-sm">
<p className="text-xs text-[#9ca3af] mb-1.5">遥控接管</p>
<p className="text-lg font-bold text-white">{selectedDevice.remoteStatus}</p>
</div>
<div className="bg-white/5 backdrop-blur-sm rounded-xl p-4 border border-[#243157]/40 shadow-sm">
<p className="text-xs text-[#9ca3af] mb-1.5">规划态势</p>
<p className="text-lg font-bold text-white">{selectedDevice.gpsPlan}</p>
</div>
<div className="bg-white/5 backdrop-blur-sm rounded-xl p-4 border border-[#243157]/40 shadow-sm">
<p className="text-xs text-[#9ca3af] mb-1.5">任务状态</p>
<p className="text-lg font-bold text-white">{selectedDevice.taskStatus}</p>
</div>
</div>*/}
{/* 控制区:左轮 + Xbox + 右轮 —— 紧凑布局 */}
<div className="flex gap-4 items-start">
{/* 左轮速度面板 - 缩小 */}
<div className="w-[28%]">
<div className="bg-[#0f172a]/90 backdrop-blur-xl rounded-2xl p-6 border border-[#1e293b]/60 shadow-lg">
{/* 顶部标题 */}
<div className="flex items-center justify-between mb-5">
<h3 className="text-sm font-semibold text-[#f1f5f9]">左轮驱动</h3>
<span className="text-xs bg-cyan-500/15 text-cyan-300 px-2.5 py-1 rounded-full font-medium">
正常运行
</span>
</div>
{/* 仪表盘(居中放大) */}
<div className="flex justify-center items-center -mt-1 mb-6">
<div className="scale-100 transform-gpu">
<Gauge
label=""
value={wsDeviceInfo?.leftMeasureSpeed || 0}
unit="rpm"
color="cyan"
percent={calcPercent(wsDeviceInfo?.leftMeasureSpeed || 0, 3000)}
/>
</div>
</div>
{/* 速度 + 电流 一体化卡片(核心视觉) */}
<div className="grid grid-cols-2 gap-3">
{/* 速度 */}
<div className="bg-gradient-to-br from-cyan-500/10 to-blue-600/5 rounded-xl p-4 border border-cyan-500/20">
<p className="text-xs text-cyan-200/70 font-medium">实时速度</p>
<p className="text-xl font-bold text-white mt-1">
{Number(wsDeviceInfo?.leftMeasureSpeed || 0).toFixed(2)}
<span className="text-xs text-cyan-300 ml-1 font-normal">rpm</span>
</p>
</div>
{/* 电流 */}
<div className="bg-gradient-to-br from-blue-500/10 to-indigo-600/5 rounded-xl p-4 border border-blue-500/20">
<p className="text-xs text-blue-200/70 font-medium">工作电流</p>
<p className="text-xl font-bold text-white mt-1">
{Number(wsDeviceInfo?.leftCurrent || 0).toFixed(2)}
<span className="text-xs text-blue-300 ml-1 font-normal">A</span>
</p>
</div>
</div>
</div>
</div>
{/* Xbox 手柄 - 缩小、居中 */}
<div className="w-[44%] scale-90 transform-gpu flex justify-center ">
<XboxController
onGamepadUpdate={handleGamepad}
handleControlModal={handleControlModal}
isControlled={isControlled}
/>
</div>
{/* 右轮速度面板 - 缩小 */}
<div className="w-[28%]">
<div className="bg-[#0f172a]/90 backdrop-blur-xl rounded-2xl p-6 border border-[#1e293b]/60 shadow-lg">
{/* 顶部标题 + 状态 */}
<div className="flex items-center justify-between mb-5">
<h3 className="text-sm font-semibold text-[#f1f5f9]">右轮驱动</h3>
<span className="text-xs bg-cyan-500/15 text-cyan-300 px-2.5 py-1 rounded-full font-medium">
正常运行
</span>
</div>
{/* 仪表盘(居中优化) */}
<div className="flex justify-center items-center -mt-1 mb-6">
<div className="scale-100 transform-gpu">
<Gauge
label=""
value={wsDeviceInfo?.rightMeasureSpeed || 0}
unit="rpm"
color="cyan"
percent={calcPercent(wsDeviceInfo?.rightMeasureSpeed || 0, 3000)}
/>
</div>
</div>
{/* 核心数据卡片:速度 + 目标值(干净对称) */}
<div className="grid grid-cols-2 gap-3">
{/* 实时速度 */}
<div className="bg-gradient-to-br from-cyan-500/10 to-blue-600/5 rounded-xl p-4 border border-cyan-500/20">
<p className="text-xs text-cyan-200/70 font-medium">实时速度</p>
<p className="text-xl font-bold text-white mt-1">
{Number(wsDeviceInfo?.rightMeasureSpeed || 0).toFixed(2)}
<span className="text-xs text-cyan-300 ml-1 font-normal">rpm</span>
</p>
</div>
{/* 速度输出 */}
<div className="bg-gradient-to-br from-blue-500/10 to-indigo-600/5 rounded-xl p-4 border border-blue-500/20">
<p className="text-xs text-blue-200/70 font-medium">工作电流</p>
<p className="text-xl font-bold text-white mt-1">
{(Number(wsDeviceInfo?.rightMeasureSpeed || 0)).toFixed(2)}
<span className="text-xs text-blue-300 ml-1 font-normal">A</span>
</p>
</div>
</div>
</div>
</div>
</div>
</div>
)}
{/* GPS规划 */}
{activeTab === 'gps' && (
<div className="flex-1 overflow-y-auto pr-2">
<div className="bg-[#16203a]/40 backdrop-blur-sm rounded-xl p-4 mb-5 border border-[#243157]/20 flex justify-between items-center">
<p className="text-sm text-[#d1d5db]">GPS航点规划</p>
<div className="flex gap-2">
{selectedDevice?.type !== 'plane' && (
<button onClick={saveWaypoints} className="text-xs bg-[#243157]/60 text-[#d1d5db] px-2.5 py-1.5 rounded-lg border border-[#2a375c]/50 flex items-center gap-1.5 hover:bg-[#2a375c]/70 transition-colors">
<Save className="w-3 h-3" />保存规划
</button>
)}
<button onClick={clearWaypoints} className="text-xs bg-[#ff4d4f]/10 text-[#ff4d4f] px-2.5 py-1.5 rounded-lg border border-[#ff4d4f]/30 flex items-center gap-1.5 hover:bg-[#ff4d4f]/20 transition-colors">
<Trash2 className="w-3 h-3" />清空航线
</button>
</div>
</div>
{selectedDevice?.type === 'plane' && (
<div className="mb-4">
<div className='flex justify-between items-center mb-2'>
<div className="text-sm font-bold text-blue-400 mb-2">无人机航线任务</div>
<Button
type="text"
size="small"
onClick={() => { resetModals(); setCreateTaskModal(true); }}
className="!bg-transparent hover:!bg-slate-700/50 !text-blue-400 hover:!text-blue-300"
>
+ 创建任务
</Button>
</div>
<div className="grid grid-cols-2 gap-4 mb-4 max-h-60 overflow-y-auto
scrollbar-hide
[-ms-overflow-style:none]
[scrollbar-width:none]
after:content-['']
hover:overflow-y-auto"> {planList.length > 0 ? planList.map((task, index) => {
// 状态映射(和你上面的风格完全统一)
const statusMap = {
"waiting": { text: "待开始", color: "bg-yellow-500" },
"starting_failure": { text: "启动失败", color: "bg-red-500" },
"executing": { text: "执行中", color: "bg-blue-500" },
"suspended": { text: "已挂起", color: "bg-orange-500" },
"restored": { text: "执行中", color: "bg-blue-500" },
"terminated": { text: "终止", color: "bg-black" },
"success": { text: "成功", color: "bg-green-500" },
"timeout": { text: "超时", color: "bg-red-600" }
};
const status = statusMap[task.status] || { text: "未知", color: "bg-gray-400" };
const isSelected = selectedTask?.uuid === task.uuid;
return (
<div
key={task.uuid || index}
className={`h-[73px] bg-slate-800/50 rounded-lg p-3 border border-slate-700/50 relative cursor-pointer transition-all
${isSelected ? 'border-blue-500 bg-blue-600/20' : 'hover:border-slate-500'}`}
onClick={(e) => {
e.stopPropagation();
handleGetTask(task);
}}
>
<div className="flex justify-between items-center mb-1">
<div className="text-[10px] text-slate-400 truncate w-[70%]">{task.name}</div>
<Tooltip title="查看详情">
<Eye className="w-3 h-3 text-blue-400 cursor-pointer" onClick={(e) => {
e.stopPropagation();
getTaskDetail(task.uuid);
}} />
</Tooltip>
</div>
{/* 状态标签(和你原版完全一样) */}
<span className={`px-2 py-1 rounded-full text-xs ${status.color}`}>
{status.text}
</span>
</div>
);
}) : (
<div className="col-span-2 bg-slate-800/50 rounded-lg p-3 border border-slate-700/50 text-center text-slate-400">
暂无航线任务
</div>
)}
</div>
</div>
)}
{(selectedDevice?.type === 'robot' || selectedDevice?.type === 'mower') && (
<div className="mb-4">
<div className="text-sm font-bold text-blue-400 mb-2">机器人任务数据</div>
<div className="grid grid-cols-2 gap-2 max-h-40 overflow-y-auto">
{deviceRoute.length > 0 ? deviceRoute.map((task) => (
<div
key={task.id}
onClick={() => handleGetRoute(task)}
className={`p-3 rounded-lg border cursor-pointer transition-all
${selectedRoute?.id === task.id
? 'bg-[#00e5ff]/15 border-[#00e5ff] shadow-lg shadow-[#00e5ff]/10'
: 'bg-slate-80/50 border-blue-900/50 hover:border-blue-500'
}`}
>
<div className="text-xs truncate text-white">{task.workName}</div>
</div>
)) : (
<div className="col-span-2 text-center text-slate-400 text-xs p-3">暂无数据</div>
)}
</div>
</div>
)}
<div className="bg-white/5 backdrop-blur-sm rounded-xl p-4 border border-[#243157]/40 shadow-sm mb-5 h-80 flex items-center justify-center">
<div className="w-full h-full relative">
<CesiumMap
devices={[selectedDevice]}
points={points}
focusLocation={mapFocus}
from="device-control"
onPathChange={getPathPoints}
onClearDraw={(fn) => { mapClearRef.current = fn; }}
realtimePosition={{ lat: wsDeviceInfo?.latitude, lon: wsDeviceInfo?.longitude }}
/>
</div>
</div>
{selectedDevice?.type !== 'plane' && (
<div className="grid grid-cols-2 gap-5 mb-5">
<div className="bg-white/5 backdrop-blur-sm rounded-xl p-4 border border-[#243157]/40 shadow-sm">
<h3 className="text-sm font-bold text-[#00e5ff] mb-3 flex items-center gap-2">
<Target className="w-4 h-4 text-[#00e5ff]" />航点列表 ({waypoints.length})
</h3>
{waypoints.length === 0 ? (
<div className="text-center py-6 text-[#9ca3af] text-xs">
<AlertTriangle className="w-6 h-6 mx-auto mb-2" />暂无航点
</div>
) : (
<div className="space-y-2 max-h-60 overflow-y-auto custom-scrollbar">
{waypoints.map((wp) => (
<div key={wp.id} className="bg-[#1e294a]/60 rounded-lg p-3 border border-[#2a375c]/30 flex justify-between items-center">
<div>
<p className="text-xs text-white font-medium">航点 {wp.id}</p>
<p className="text-[10px] text-[#9ca3af] font-mono">{wp.lon}, {wp.lat}</p>
</div>
</div>
))}
</div>
)}
</div>
<div className="bg-white/5 backdrop-blur-sm rounded-xl p-4 border border-[#243157]/40 shadow-sm">
<h3 className="text-sm font-bold text-[#00e5ff] mb-3 flex items-center gap-2">
<Layers className="w-4 h-4 text-[#00e5ff]" />机器人本地航线
</h3>
{robotRoutes.length === 0 ? (
<div className="text-center py-6 text-[#9ca3af] text-xs">暂无保存航线</div>
) : (
<div className="space-y-2 max-h-60 overflow-y-auto custom-scrollbar">
{robotRoutes.map((rt, i) => (
<div
key={i}
onClick={() => loadRoute(rt)}
className={`p-3 rounded-lg border cursor-pointer transition-all
${selectedTask?.robotId === rt.robotId
? 'bg-[#00e5ff]/15 border-[#00e5ff] shadow-lg shadow-[#00e5ff]/10'
: 'bg-slate-800/50 border-slate-700/50 hover:border-cyan-500'
}`}
>
<p className="text-xs text-white truncate">{rt.robotName}</p>
<p className="text-[10px] text-slate-400">航点:{rt.waypoints.length} 个</p>
</div>
))}
</div>
)}
</div>
</div>
)}
{/*{selectedDevice.type !== 'plane' && (*/}
{/*<div className="flex gap-3 mt-5">
<button onClick={issueGPSTask} className="px-4 py-2 bg-green-600 hover:bg-green-500 rounded-lg text-white flex items-center gap-2">
<Send className="w-4 h-4" /> 下发任务
</button>
<button onClick={toggleTaskRunning} className="px-4 py-2 bg-blue-600 hover:bg-blue-500 rounded-lg text-white flex items-center gap-2">
{taskRunning ? <Pause className="w-4 h-4" /> : <Play className="w-4 h-4" />}
{taskRunning ? "暂停" : "执行"}
</button>
<button onClick={stopGPSTask} className="px-4 py-2 bg-red-600 hover:bg-red-500 rounded-lg text-white flex items-center gap-2">
<Square className="w-4 h-4" /> 停止
</button>
</div>*/}
{/* 无人机专用任务控制按钮 */}
{selectedDevice?.type === 'plane' ? (
<div className="grid grid-cols-3 gap-2 mt-auto">
{/* 动态按钮:执行中 → 挂起 / 已挂起 → 继续 */}
{taskstatus === 'suspended' ? (
<button
className="flex flex-col items-center justify-center gap-1 p-3 bg-green-600/20 hover:bg-green-600/40 border border-green-600/50 rounded-lg text-green-400 transition-all"
onClick={() => updateTaskStatus(selectedTask?.uuid, 'restored')}
>
<Play className="w-5 h-5" />
<span className="text-[10px] font-bold uppercase">下发任务</span>
</button>
) : (
<button
className="flex flex-col items-center justify-center gap-1 p-3 bg-slate-700/30 hover:bg-slate-700/50 border border-slate-600 rounded-lg text-slate-300 transition-all"
onClick={() => updateTaskStatus(selectedTask?.uuid, 'suspended')}
>
<Square className="w-5 h-5" />
<span className="text-[10px] font-bold uppercase">挂起任务</span>
</button>
)}
{/* 暂停 / 恢复 */}
{isTaskPaused ? (
<button
className="flex flex-col items-center justify-center gap-1 p-3 bg-green-600/20 hover:bg-green-600/40 border border-green-600/50 rounded-lg text-green-400 transition-all"
onClick={() => sendFlightCommand('flighttask_recovery')}
disabled={flightCommandLoading}
>
<RotateCw className="w-5 h-5" />
<span className="text-[10px] font-bold uppercase">恢复</span>
</button>
) : (
<button
className="flex flex-col items-center justify-center gap-1 p-3 bg-slate-700/30 hover:bg-slate-700/50 border border-slate-600 rounded-lg text-slate-300 transition-all"
onClick={() => sendFlightCommand('flighttask_pause')}
disabled={flightCommandLoading}
>
<Square className="w-5 h-5" />
<span className="text-[10px] font-bold uppercase">暂停</span>
</button>
)}
{/* 动态:返航 / 取消返航 */}
{isReturningHome ? (
<button
className="flex flex-col items-center justify-center gap-1 p-3 bg-red-600/20 hover:bg-red-600/40 border border-red-600/50 rounded-lg text-red-400 transition-all"
onClick={() => sendFlightCommand('return_home_cancel')}
disabled={flightCommandLoading}
>
<X className="w-5 h-5" />
<span className="text-[10px] font-bold uppercase">取消返航</span>
</button>
) : (
<button
className="flex flex-col items-center justify-center gap-1 p-3 bg-blue-600/20 hover:bg-blue-600/40 border border-blue-600/50 rounded-lg text-blue-400 transition-all"
onClick={() => sendFlightCommand('return_home')}
disabled={flightCommandLoading}
>
<MapPin className="w-5 h-5" />
<span className="text-[10px] font-bold uppercase">返航</span>
</button>
)}
</div>
) : (
// 机器人/割草机保留原来的按钮
<div className="flex gap-3 mt-5">
<button onClick={issueGPSTask} className="px-4 py-2 bg-green-600 hover:bg-green-500 rounded-lg text-white flex items-center gap-2">
<Send className="w-4 h-4" /> 下发任务
</button>
<button onClick={toggleTaskRunning} className="px-4 py-2 bg-blue-600 hover:bg-blue-500 rounded-lg text-white flex items-center gap-2">
{taskRunning ? <Pause className="w-4 h-4" /> : <Play className="w-4 h-4" />}
{taskRunning ? "暂停" : "执行"}
</button>
<button onClick={stopGPSTask} className="px-4 py-2 bg-red-600 hover:bg-red-500 rounded-lg text-white flex items-center gap-2">
<Square className="w-4 h-4" /> 停止
</button>
</div>
)}
{/*//)}*/}
</div>
)}
</div>
{/* 右侧视频面板(遥控页隐藏)- 保持不变 */}
{activeTab !== 'remote' && (
<div className="w-96 border-l border-[#1a243a] backdrop-blur-sm p-5 flex flex-col shadow-xl overflow-auto">
<div className="mb-5">
<h2 className="text-lg font-bold text-[#00e5ff] mb-4 flex items-center gap-2">
<Video className="w-4 h-4 text-[#00e5ff]" />视频与配置
</h2>
<div className="bg-white/5 backdrop-blur-sm rounded-xl p-4 border border-[#243157]/40 shadow-sm mb-4">
<div className="flex justify-between items-center">
<div className="flex items-center gap-2">
<Video className="w-4 h-4 text-[#ff4d4f]" />
<span className="text-sm font-medium text-white">{selectedDevice.name}</span>
</div>
</div>
</div>
{/* 设备类型:机器人 → 显示 4 路视频 */}
{selectedDevice?.type == 'robot' && (
<>
<div
className="rounded-xl h-72 flex items-center justify-center mb-5 relative overflow-hidden border border-[#243157]/40 shadow-inner"
>
<div className="text-center w-full h-full">
<VideoPlayer
deviceId={selectedDevice.serialNumber}
idx={5}
className="w-full h-full object-contain"
video={video1}
error={error1}
ready={ready1}
noCrop
/>
</div>
</div>
<div
className="rounded-xl h-72 flex items-center justify-center mb-5 relative overflow-hidden border border-[#243157]/40 shadow-inner"
>
<div className="text-center w-full h-full">
<VideoPlayer
deviceId={selectedDevice.serialNumber}
idx={5}
className="w-full h-full object-contain"
video={video2}
error={error2}
ready={ready2}
noCrop
/>
</div>
</div>
<div
className="rounded-xl h-72 flex items-center justify-center mb-5 relative overflow-hidden border border-[#243157]/40 shadow-inner"
>
<div className="text-center w-full h-full">
<VideoPlayer
deviceId={selectedDevice.serialNumber}
idx={5}
className="w-full h-full object-contain"
video={video3}
error={error3}
ready={ready3}
noCrop
/>
</div>
</div>
</>
)}
{/* 设备类型:割草机 → 显示 1 路视频 */}
{(selectedDevice?.type == 'mower' || selectedDevice?.type == 'cut') && (
<>
<div className="rounded-xl h-72 flex items-center justify-center mb-5 relative border border-[#243157]/40 shadow-inner">
<div className="text-center w-full h-full">
<VideoPlayer
deviceId={selectedDevice.serialNumber}
idx={1}
className="w-full h-full object-contain"
video={video}
error={error}
ready={ready}
noCrop={false}
/>
</div>
</div>
<div className="rounded-xl h-72 flex items-center justify-center mb-5 relative border border-[#243157]/40 shadow-inner">
<div className="text-center w-full h-full">
<VideoPlayer
deviceId={selectedDevice.serialNumber}
idx={4}
className="w-full h-full object-contain"
video={video}
error={error}
ready={ready}
noCrop={false}
/>
</div>
</div>
<div className="rounded-xl h-72 flex items-center justify-center mb-5 relative border border-[#243157]/40 shadow-inner">
<div className="text-center w-full h-full">
<VideoPlayer
deviceId={selectedDevice.serialNumber}
idx={2}
className="w-full h-full object-contain"
video={video}
error={error}
ready={ready}
noCrop={false}
/>
</div>
</div>
<div className="rounded-xl h-72 flex items-center justify-center mb-5 relative border border-[#243157]/40 shadow-inner">
<div className="text-center w-full h-full">
<VideoPlayer
deviceId={selectedDevice.serialNumber}
idx={3}
className="w-full h-full object-contain"
video={video}
error={error}
ready={ready}
noCrop={false}
/>
</div>
</div>
</>
)}
{/* 设备类型:无人机 → 遍历显示视频流 */}
{selectedDevice?.type !== 'robot' && selectedDevice?.type !== 'mower' && (
<>
{urlInfo?.length > 0 ? (
urlInfo.map((stream, index) => (
<div
key={index}
className="rounded-xl h-72 flex items-center justify-center mb-5 relative overflow-hidden border border-[#243157]/40 shadow-inner"
>
<div className="text-center w-full h-full">
<DroneLivePlayer streamData={stream} />
</div>
</div>
))
) : (
<div className="text-gray-400 text-sm py-10 text-center">暂无视频流</div>
)}
</>
)}
</div>
</div>
)}
{/* 【修改3】:删除原来的悬浮视频窗口代码 */}
<Modal
open={taskDetailModal}
title="航线详情"
onCancel={resetModals}
footer={null}
width={600}
>
<div className="py-4">
{taskDetail ? (
<div className="grid grid-cols-2 gap-x-6 gap-y-3">
{Object.entries(taskDetail).map(([k, v]) => {
// 过滤不需要的字段
if (k === 'folder_info' || k === 'folder_id' || k == 'week_of_month' || k == "days_of_month" || k == "days_of_week" || k == "interval") return null;
// 空值、null、undefined 直接不显示
if (v === null || v === undefined || v === '') return null;
// 字段中文名映射
const keyMap = {
name: '任务名称',
uuid: '任务ID',
wayline_uuid: '航线UUID',
sn: '机场SN',
landing_dock_sn: '降落地场SN',
rth_altitude: '返航高度(m)',
rth_mode: '返航模式',
wayline_precision_type: '航线精度',
out_of_control_action_in_flight: '失控动作',
resumable_status: '断点续飞',
task_type: '任务类型',
repeat_type: '重复模式',
begin_at: '开始时间',
end_at: '结束时间',
min_battery_capacity: '最低电量(%)',
status: '任务状态',
time_zone: '时区',
current_waypoint_index: '当前航点',
};
// 枚举汉化
const enumMap = {
rth_mode: { optimal: '智能高度', preset: '设定高度' },
wayline_precision_type: { gps: 'GPS模式', rtk: 'RTK高精度' },
resumable_status: { auto: '自动', manual: '手动' },
task_type: {
immediate: '立即任务',
timed: '单次定时',
recurring: '重复任务',
continuous: '连续任务',
},
repeat_type: {
nonrepeating: '不重复',
daily: '每日',
weekly: '每周',
absolute_monthly: '每月(日期)',
relative_monthly: '每月(星期)',
},
status: {
waiting: '待开始',
starting_failure: '启动失败',
executing: '执行中',
suspended: '已挂起',
restored: '继续执行',
terminated: '已终止',
success: '已完成',
timeout: '执行超时',
},
};
// 渲染值
const renderValue = () => {
if (enumMap[k]?.[v]) return enumMap[k][v];
if ((k === 'begin_at' || k === 'end_at') && !isNaN(Number(v))) {
return new Date(Number(v) * 1000).toLocaleString('zh-CN');
}
return v;
};
const label = keyMap[k] || k;
return (
<div key={k} className="flex items-center">
<span className="text-black font-semibold min-w-[90px]">{label}:</span>
<span className="text-black font-medium">{renderValue()}</span>
</div>
);
})}
</div>
) : (
<div className="flex flex-col items-center justify-center h-full text-black">
{/* 旋转加载圈 */}
<div className="w-6 h-6 border-2 border-gray-500 border-t-white rounded-full animate-spin mb-2"></div>
<p className="text-sm text-blue">加载中...</p>
</div>
)}
</div>
</Modal>
<Modal
open={createTaskModal}
title="创建航线任务"
onCancel={() => {
resetModals();
}}
footer={null}
maskClosable={false}
width={600}
>
<div className="py-4 space-y-4">
<div className="grid grid-cols-2 gap-4">
<div>
<label className="text-sm block mb-1 text-black">航线名称 <span className="text-red-500">*</span></label>
<Input
value={taskForm.name}
onChange={(e) => setTaskForm({ ...taskForm, name: e.target.value })}
placeholder="请输入航线名称"
/>
</div>
<div>
<label className="text-sm block mb-1 text-black">选择航线 <span className="text-red-500">*</span></label>
<Select
showSearch
placeholder="请选择航线"
value={waylineUuid}
onChange={setWaylineUuid}
options={waylineList}
style={{ width: '100%' }}
locale={{ emptyText: '暂无航线数据' }}
/>
</div>
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<label className="text-sm block mb-1 text-black">机场SN <span className="text-red-500">*</span></label>
<Input value={taskForm.sn} disabled placeholder="自动获取" />
</div>
<div>
<label className="text-sm block mb-1 text-black">降落地场SN</label>
<Input
value={taskForm.landing_dock_sn}
onChange={(e) => setTaskForm({ ...taskForm, landing_dock_sn: e.target.value })}
placeholder="可不填"
/>
</div>
</div>
{/* 飞行参数 */}
<div className="grid grid-cols-2 gap-4">
<div>
<label className="text-sm block mb-1 text-black">返航高度(m) <span className="text-red-500">*</span></label>
<InputNumber
min={0}
value={taskForm.rth_altitude}
onChange={(val) => setTaskForm({ ...taskForm, rth_altitude: val || 0 })}
style={{ width: '100%' }}
/>
</div>
<div>
<label className="text-sm block mb-1 text-black">返航模式 <span className="text-red-500">*</span></label>
<Select
value={taskForm.rth_mode}
onChange={(val) => setTaskForm({ ...taskForm, rth_mode: val })}
options={[
{ label: '智能高度', value: 'optimal' },
{ label: '设定高度', value: 'preset' }
]}
style={{ width: '100%' }}
/>
</div>
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<label className="text-sm block mb-1 text-black">航线精度 <span className="text-red-500">*</span></label>
<Select
value={taskForm.wayline_precision_type}
onChange={(val) => setTaskForm({ ...taskForm, wayline_precision_type: val })}
options={[
{ label: 'GPS模式(无需RTK收敛)', value: 'gps' },
{ label: 'RTK高精度(需等待收敛)', value: 'rtk' }
]}
style={{ width: '100%' }}
/>
</div>
<div>
<label className="text-sm block mb-1 text-black">自动断点续飞 <span className="text-red-500">*</span></label>
<Select
value={taskForm.resumable_status}
onChange={(val) => setTaskForm({ ...taskForm, resumable_status: val })}
options={[
{ label: '自动断点续飞', value: 'auto' },
{ label: '手动断点续飞', value: 'manual' }
]}
style={{ width: '100%' }}
/>
</div>
</div>
<div className="grid grid-cols-2 gap-4">
<div>
<label className="text-sm block mb-1 text-black">最低执行电量(%) <span className="text-red-500">*</span></label>
<InputNumber
min={50} max={100}
value={taskForm.min_battery_capacity}
onChange={(val) => setTaskForm({ ...taskForm, min_battery_capacity: val || 50 })}
style={{ width: '100%' }}
/>
</div>
<div>
<label className="text-sm block mb-1 text-black">任务航线类型 <span className="text-red-500">*</span></label>
<Select
value={taskForm.task_type}
onChange={(val) => setTaskForm({ ...taskForm, task_type: val })}
options={[
{ label: '立即任务', value: 'immediate' },
//{ label: '单次定时任务', value: 'timed' },
//{ label: '重复任务', value: 'recurring' },
//{ label: '连续任务', value: 'continuous' }
]}
style={{ width: '100%' }}
/>
</div>
</div>
{/* 时间选择 */}
{taskForm.task_type !== 'immediate' && (
<div className="grid grid-cols-2 gap-4">
<div>
<label className="text-sm block mb-1 text-black">任务开始时间 <span className="text-red-500">*</span></label>
<DatePicker
showTime
value={beginTime}
onChange={(date) => setBeginTime(date)}
style={{ width: '100%' }}
placeholder="选择开始时间"
/>
</div>
{['recurring', 'continuous'].includes(taskForm.task_type) && (
<div>
<label className="text-sm block mb-1 text-black">任务结束时间 <span className="text-red-500">*</span></label>
<DatePicker
showTime
value={endTime}
onChange={(date) => setEndTime(date)}
style={{ width: '100%' }}
/>
</div>
)}
</div>
)}
{/* 重复任务 */}
{taskForm.task_type === 'recurring' && (
<div className="grid grid-cols-2 gap-4">
<div>
<label className="text-sm block mb-1 text-black">重复模式</label>
<Select
value={taskForm.repeat_type}
onChange={(val) => setTaskForm({ ...taskForm, repeat_type: val })}
options={[
{ label: '不重复', value: 'nonrepeating' },
{ label: '每日', value: 'daily' },
{ label: '每周', value: 'weekly' },
{ label: '每月(日期)', value: 'absolute_monthly' },
{ label: '每月(星期)', value: 'relative_monthly' }
]}
style={{ width: '100%' }}
/>
</div>
{taskForm.repeat_type !== 'nonrepeating' && (
<div>
<label className="text-sm block mb-1 text-black">重复间隔</label>
<InputNumber
min={1}
value={taskForm.repeat_option.interval}
onChange={(val) => setTaskForm({ ...taskForm, repeat_option: { interval: val || 1 } })}
style={{ width: '100%' }}
/>
</div>
)}
</div>
)}
<div className="text-xs text-slate-400 mt-2">
<div>绑定无人机:{selectedDevice?.deviceAlias || '--'}</div>
<div>机场编号:{selectedDevice?.gateway_sn || '--'}</div>
</div>
<div className="flex justify-end gap-2 mt-4">
<Button onClick={resetModals}>取消</Button>
<Button type="primary" loading={loading} onClick={createFlightTask}>创建航线任务</Button>
</div>
</div>
</Modal>
<Modal
title={modalcontent.title}
closable={{ 'aria-label': 'Custom Close Button' }}
open={isModalOpen}
onOk={handleOk}
onCancel={handleCancel}
okText="确定"
cancelText="取消"
>
<p>{modalcontent.content}</p>
</Modal>
</div>
);
};
export default RobotControlCenter;