Files
web-Iot/src/pages/RealTimeMonitor.tsx

1513 lines
64 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, useMemo, useRef, useCallback } from 'react';
import {
Card, Row, Col, Table, Select, Input, Tag,
Typography, Button, Space, Avatar, Pagination,
Modal, Drawer, List, Badge, Empty, App, Tooltip,
Progress, Divider, Radio, Tabs, DatePicker, message,
Form, Switch, Alert, Descriptions, Statistic, Spin, Segmented, InputNumber
} from 'antd';
import {
CloudOutlined, CheckCircleOutlined, WarningOutlined,
MinusCircleOutlined, ThunderboltOutlined,
RiseOutlined, SunOutlined, BarChartOutlined,
VideoCameraOutlined, RocketOutlined, AppstoreOutlined,
RobotOutlined, BranchesOutlined, ExperimentOutlined,
SearchOutlined, MoreOutlined, ArrowRightOutlined,
FullscreenOutlined, SyncOutlined, PlayCircleOutlined,
PauseCircleOutlined, StopOutlined, InfoCircleOutlined,
ClockCircleOutlined, EnvironmentOutlined, PlusOutlined,
SettingOutlined, ExclamationCircleOutlined, FileTextOutlined,
DeleteOutlined, AimOutlined, SendOutlined, LockOutlined,
NodeIndexOutlined, SaveOutlined, MaximizeOutlined, ReloadOutlined
} from '@ant-design/icons';
import { Line, Bar, Pie } from '@ant-design/charts';
import bgMain from '../assets/images/bgmain.jpg';
import { UniversalBarChart, UniversalLineChart, UniversalPieChart } from '../components/recharts';
import CesiumMap from '../components/Map';
import { useTranslation } from 'react-i18next';
import { useSelector } from 'react-redux';
import dayjs from 'dayjs';
import envConfig from '../../env';
import { useMqtt } from '../hooks/useMqtt';
import DeviceController from '../components/devices/deviceController';
import {
getSiteDevice, getRobotRouteList,
getDeviceTastPool, getSiteDeviceTaskHistory,
excuetRoute, cancelRoute, pauseRoute, recoverRoute,
getRouteByTask, getTaskPath, getSingleRouteList,
getSiteUAVList, getWayLine, createWaylineTask, getUAVState,
postFlightCommmand, getFlightTaskDetail
} from '../api/device';
import utils from '../lib/utils';
const { Option } = Select;
const { Search } = Input;
const { Text, Title } = Typography;
const { RangePicker } = DatePicker;
const powerTrendData = [
{ time: '00:00', value: 0, type: '实时功率' },
{ time: '04:00', value: 50, type: '实时功率' },
{ time: '08:00', value: 350, type: '实时功率' },
{ time: '12:00', value: 750, type: '实时功率' },
{ time: '16:00', value: 500, type: '实时功率' },
{ time: '20:00', value: 50, type: '实时功率' },
{ time: '24:00', value: 0, type: '实时功率' },
];
const inverterPowerData = [
{ name: 'INV-01', power: 164.2 },
{ name: 'INV-02', power: 166.8 },
{ name: 'INV-03', power: 162.1 },
{ name: 'INV-04', power: 159.7 },
{ name: 'INV-05', power: 159.8 }
];
const heatmapColors = ['#52c41a', '#1890ff', '#faad14', '#1890ff', '#52c41a'];
const taskStatusColor = (status) => {
const map = {
'NEW': '#1677ff',
'EXECUTING': '#52c41a',
'PAUSE': '#faad14',
'FINISH': '#13c2c2',
'CANCEL': '#999',
'ERROR': '#f5222d'
};
return map[status] || '#999';
};
const getDeviceTypeIcon = (type) => {
if (type?.includes?.('ROBOT') || type?.includes?.('CLEANING') || type?.includes?.('INSPECT')) {
return <RobotOutlined />;
}
if (type?.includes?.('DRONE') || type?.includes?.('UAV')) {
return <RocketOutlined />;
}
if (type?.includes?.('CAMERA')) {
return <VideoCameraOutlined />;
}
if (type?.includes?.('INVERTER') || type?.includes?.('INV')) {
return <ThunderboltOutlined />;
}
if (type?.includes?.('COMBINER') || type?.includes?.('CMB')) {
return <BranchesOutlined />;
}
return <AppstoreOutlined />;
};
const RealTimeMonitorPage = () => {
const { t } = useTranslation();
const { modal } = App.useApp();
const { stationId, currentStation } = useSelector((state: any) => state.station);
const { userInfo } = useSelector((state: any) => state.user);
const [filterStatus, setFilterStatus] = useState('all');
const [filterType, setFilterType] = useState('all');
const [searchName, setSearchName] = useState('');
const [mapViewMode, setMapViewMode] = useState('all');
const cardStyle = { borderRadius: 12, border: '1px solid #f0f0f0', boxShadow: '0 2px 8px rgba(0,0,0,0.04)' };
// ========= 设备/任务/路径基础数据 =========
const [devices, setDevices] = useState([]);
const [loading, setLoading] = useState(false);
const [taskPoolList, setTaskPoolList] = useState([]);
const [routeList, setRouteList] = useState([]);
const [refreshKey, setRefreshKey] = useState(0);
const [planeDevices, setPlaneDevices] = useState([]);
const [listPage, setListPage] = useState(1);
const [listPageSize, setListPageSize] = useState(8);
// ========= WebSocket + 地图交互相关 =========
const controllerRef = useRef(null);
const isFirstConnect = useRef(true);
const [focusLocation, setFocusLocation] = useState(null);
const [execute, setExecute] = useState(false);
const [excuteStatus, setExcuteStatus] = useState('stop');
const [points, setPoints] = useState([]);
const [polyPoints, setPolyPoints] = useState([]);
const [routeMode, setRouteMode] = useState('');
const [clearNavLine, setClearNavLine] = useState(0);
const [clearPlanLine, setClearPlanLine] = useState(0);
const [arrivedPoint, setArrivedPoint] = useState(null);
const [robotRealtimePosition, setRobotRealtimePosition] = useState(null);
const runningRealtimePosition = useMemo(() => {
return {
lon: robotRealtimePosition?.longitude || robotRealtimePosition?.lon || 0,
lat: robotRealtimePosition?.latitude || robotRealtimePosition?.lat || 0,
heading: robotRealtimePosition?.yaw || robotRealtimePosition?.heading || 0,
};
}, [robotRealtimePosition]);
const [runningPoolTask, setRunningPoolTask] = useState(null);
const [proPoints, setProPoints] = useState({});//规划点
// ========= UI 状态 =========
const [selectedDevice, setSelectedDevice] = useState(null);
const [selectedDeviceSn, setSelectedDeviceSn] = useState(null);
const [deviceDrawerOpen, setDeviceDrawerOpen] = useState(false);
const [routeSearch, setRouteSearch] = useState('');
const [waylineList, setWaylineList] = useState([]);
const [waylineSearch, setWaylineSearch] = useState('');
const [selectedWayline, setSelectedWayline] = useState(null);
const [rthModalVisible, setRthModalVisible] = useState(false);
const [tempRthAltitude, setTempRthAltitude] = useState(100);
const [waylineLoading, setWaylineLoading] = useState(false);
const [mqttDrone, setMqttDrone] = useState(null);
const [droneMqttMap, setDroneMqttMap] = useState({});
const [activeDroneTask, setActiveDroneTask] = useState(null);
const [droneReturningHome, setDroneReturningHome] = useState(false);
const [droneTaskPaused, setDroneTaskPaused] = useState(false);
const [droneCommandLoading, setDroneCommandLoading] = useState(false);
const [messageApi, contextHolder] = message.useMessage();
// ============================================================
// DeviceController 初始化(仅一次)
// ============================================================
useEffect(() => {
if (!userInfo) return;
const controller = new DeviceController(userInfo, messageApi);
controller.onLocationInfoUpdate = (pos) => {
setRobotRealtimePosition(pos);
};
controller.onIsFinished = handleFinish;
controller.onRoutePost = (msg) => {
const { taskId, data } = msg;
//const matchedTask = taskPoolList.find(task => String(task.id) === String(taskId));
//const sameAsSelected = runningPoolTask && String(runningPoolTask.id) === String(taskId);
//if ((!runningPoolTask && matchedTask) || sameAsSelected) {
// if (!runningPoolTask && matchedTask) setRunningPoolTask(matchedTask);
console.log('[RTMonitor] route_post:', data)
setProPoints(msg);
//}
};
controller.init();
controllerRef.current = controller;
return () => {
if (controllerRef.current) {
controllerRef.current.destroy?.();
}
controllerRef.current = null;
};
// eslint-disable-next-line
}, []);
useEffect(() => {
//console.log('runningPoolTask?.id, proPoints?.taskId', proPoints)
if (!runningPoolTask?.id || !proPoints?.taskId) return;
if (runningPoolTask?.id == proPoints?.taskId) {
console.log('1111111111', proPoints?.data);
setPoints(proPoints?.data);
}
}, [runningPoolTask, proPoints]);
const handleFinish = (data) => {
setExecute(false);
utils.message.success(t('devices.fixed2TaskSuspended2Fixed2CompletedFixed2'));
setPoints([]);
setPolyPoints([]);
setRunningPoolTask(null);
setExcuteStatus('stop');
};
// ============================================================
// WebSocket 连接
// ============================================================
// 拉取基础数据
// ============================================================
const fetchAllData = async () => {
if (!stationId) return;
setLoading(true);
try {
const [deviceRes, routeRes, planeRes] = await Promise.all([
getSiteDevice({ siteId: stationId, pageSize: 9999, pageNum: 1, orgId: currentStation?.orgId }),
getRobotRouteList({ siteId: stationId }),
getSiteUAVList(stationId).catch(() => null)
]);
if (deviceRes?.code === 200) setDevices(deviceRes.rows || []);
if (routeRes?.code === 200) setRouteList(routeRes.data || []);
if (planeRes?.code === 200) setPlaneDevices(planeRes.rows || []);
} catch (err) {
console.error('[RTMonitor] 拉取监控数据失败', err);
} finally {
setLoading(false);
}
};
const fetchTaskPoolList = async (deviceId = null) => {
if (!stationId) return [];
try {
const params = { userId: userInfo?.userId, siteId: stationId, orgId: currentStation?.orgId, pageNum: 1, pageSize: 999999 };
if (deviceId) params.deviceId = deviceId;
const res = await getDeviceTastPool(params);
if (res.code === 200) {
const rows = res.rows || [];
setTaskPoolList(rows);
return rows;
}
} catch (err) { console.error('[RTMonitor] 拉取任务池失败:', err); }
return [];
};
// 加载任务路径并显示在地图
const loadTaskPath = async (taskId) => {
if (!taskId) return;
try {
const res = await getRouteByTask({ taskId });
if (res?.code === 200 && res?.data) {
const data = res.data;
let pathPoints = [];
try {
pathPoints = data.jsonData?.path || [];
setRouteMode(data?.mode || 'coverage');
} catch (err) {
console.error('[RTMonitor] 解析任务路径数据失败:', err);
}
const mapPoints = pathPoints.map(p => ({
lng: Number(p.lng ?? p.lon ?? p.longitude ?? p[0]),
lat: Number(p.lat ?? p.latitude ?? p[1]),
}));
setPolyPoints(mapPoints);
}
} catch (err) {
console.error('[RTMonitor] 加载任务路径失败', err);
}
};
// 获取算法回传的实际行驶路径(路线)
const fetchDetailTaskPath = async (taskId) => {
if (!taskId) return;
try {
const res = await getTaskPath({ taskId });
if (res?.code === 200 && res?.data) {
setPoints((res.data || []));
}
} catch (err) {
console.error('[RTMonitor] 获取算法回传路径失败', err);
}
};
// 加载路线详情(预设路径点击执行时)
// 加载路线详情(预设路径点击执行时)
const fetchRouteDetailAndShow = async (routeId, routeData) => {
try {
// 参考机器人任务界面:优先用路由自带点展示;否则按 ID 获取预设路径详情(区域 + 路线)
let path = [];
let mode = "";
if (routeId) {
const res = await getSingleRouteList({ id: routeId });
if (res?.code === 200 && res?.data) {
mode = res.data.mode;
path = res.data.jsonData?.path || [];
}
}
const mapPoints = (path || [])
.map(p => ({
lng: Number(p.lng ?? p.lon ?? p.longitude ?? p[0]),
lat: Number(p.lat ?? p.latitude ?? p[1]),
}))
.filter(p => !isNaN(p.lng) && !isNaN(p.lat) && Math.abs(p.lng) < 180 && Math.abs(p.lat) < 90 && p.lng !== 0 && p.lat !== 0);
console.log('[RTMonitor] fetchRouteDetailAndShow:', routeId, mapPoints);
if (mapPoints.length) {
setPolyPoints(mapPoints);
setRouteMode(mode || '');
}
} catch (err) {
console.error('[RTMonitor] 展示路线失败', err);
}
};
useEffect(() => {
fetchAllData();
}, [stationId, refreshKey]);
const handleRefresh = () => {
setRefreshKey(prev => prev + 1);
messageApi.success(t('common.refresh'));
};
// ============================================================
// 设备数据封装
// ============================================================
const planeDeviceRows = useMemo(() => {
return (planeDevices || []).map((d, idx) => {
const m = droneMqttMap[d.device_sn] || {};
const lon = m.longitude || d.longitude;
const lat = m.latitude || d.latitude;
return {
id: d.device_sn || d.id || 'plane-' + idx,
name: d.drone_callsign || d.device_sn || t('devices.drone'),
deviceAlias: d.drone_callsign || d.device_sn,
serialNumber: d.device_sn,
device_sn: d.device_sn,
gateway_sn: d.gateway_sn,
type: 'plane',
category: 'plane',
typeText: t('devices.drone'),
status: d.onlineStatus === 1 ? t('devices.s59') : t('devices.offline'),
onlineStatus: d.onlineStatus === 1 ? 1 : 3,
data: d.onlineStatus === 1 ? t('devices.idle') : '-',
communication: d.onlineStatus === 1 ? '通讯正常' : '通讯中断',
updateTime: d.update_time ? dayjs(d.update_time).format('YYYY-MM-DD HH:mm:ss') : dayjs().format('YYYY-MM-DD HH:mm:ss'),
feStatus: d.onlineStatus === 1 ? 2 : 3,
longitude: lon,
latitude: lat,
lastRunningStatus: (lon && lat) ? { longitude: lon, latitude: lat } : undefined,
batteryLevel: d.battery ? d.battery.capacity_percent : undefined,
raw: Object.assign({}, d, { type: 'plane', deviceAlias: d.drone_callsign || d.device_sn })
};
});
}, [planeDevices, droneMqttMap]);
const deviceList = useMemo(() => {
const robots = devices.map((d, idx) => ({
id: d.id || idx,
name: d.deviceAlias || d.deviceName || `设备-${d.serialNumber?.slice(-4) || idx}`,
serialNumber: d.serialNumber,
type: d.deviceType || 'ROBOT',
category: 'robot',
typeText: d.deviceTypeName || d.deviceType || t('devices.robot'),
status: d.feStatus == 1 ? t('devices.s59') : (d.feStatus == 2 ? t('devices.idle') : t('devices.offline')),
onlineStatus: d.onlineStatus,
data: d.currentTask ? t('devices.executing') : (d.onlineStatus === 1 ? t('devices.idle') : '-'),
communication: d.onlineStatus === 1 ? '通讯正常' : '通讯中断',
updateTime: d.updateTime || dayjs().format('YYYY-MM-DD HH:mm:ss'),
feStatus: d.feStatus,
longitude: d.longitude,
latitude: d.latitude,
batteryLevel: d.batteryLevel,
raw: d
}));
const mocks = [
{ id: 'mock-inv-1', name: '逆变器 INV-01', type: 'INVERTER', category: 'inverter', typeText: t('home.inverter'), status: t('roles.normal'), onlineStatus: 1, data: '164.2 KW', communication: '通讯正常', updateTime: '2025-05-25 10:24:15', longitude: currentStation ? currentStation.longitude + 0.0005 : 0, latitude: currentStation ? currentStation.latitude + 0.0005 : 0, isMock: true },
{ id: 'mock-inv-2', name: '逆变器 INV-02', type: 'INVERTER', category: 'inverter', typeText: t('home.inverter'), status: t('roles.normal'), onlineStatus: 1, data: '166.8 KW', communication: '通讯正常', updateTime: '2025-05-25 10:24:15', longitude: currentStation ? currentStation.longitude - 0.0003 : 0, latitude: currentStation ? currentStation.latitude + 0.0004 : 0, isMock: true },
{ id: 'mock-cb-1', name: '汇流箱 01', type: 'COMBINER_BOX', category: 'combiner', typeText: t('home.combinerBox'), status: t('roles.normal'), onlineStatus: 1, data: '32 组 / 32 组', communication: '通讯正常', updateTime: '2025-05-25 10:24:15', longitude: currentStation ? currentStation.longitude + 0.0007 : 0, latitude: currentStation ? currentStation.latitude - 0.0003 : 0, isMock: true },
{ id: 'mock-ws-1', name: '气象站', type: 'WEATHER_STATION', category: 'weather', typeText: '气象站', status: t('roles.normal'), onlineStatus: 1, data: '28.0 ℃ / 815W/m²', communication: '通讯正常', updateTime: '2025-05-25 10:24:15', longitude: currentStation ? currentStation.longitude - 0.0006 : 0, latitude: currentStation ? currentStation.latitude - 0.0005 : 0, isMock: true },
];
return [...robots, ...planeDeviceRows, ...mocks];
}, [devices, planeDeviceRows, currentStation]);
const mapDevices = useMemo(() => {
const all = [...devices, ...planeDeviceRows];
if (mapViewMode === 'selected' && (selectedDevice?.serialNumber || selectedDevice?.device_sn)) {
const sn = selectedDevice?.serialNumber || selectedDevice?.device_sn;
return all
.filter(d => (d.serialNumber == sn) || (d.device_sn == sn))
}
return all
.filter(d => (d?.lastRunningStatus?.latitude && d?.lastRunningStatus?.longitude) || (d?.locationMessage?.latitude && d?.locationMessage?.longitude) || (d?.longitude && d?.latitude));
}, [devices, planeDeviceRows, mapViewMode, selectedDevice]);
// ============================================================
// 点击设备:WebSocket 连接 + 地图定位
// ============================================================
const handleDeviceClick = (robot) => {
console.log('[RTMonitor] 点击设备:', robot);
const dev = robot;
setSelectedDevice(dev);
setSelectedDeviceSn(dev.serialNumber || dev.device_sn);
const isMockDevice = dev?.isMock || ['INVERTER', 'COMBINER_BOX', 'WEATHER_STATION', 'METER'].includes(dev?.type);
const isDroneDevice = dev?.type === 'plane' || !!dev?.gateway_sn;
// ---- 地图定位 ----
if ((dev?.lastRunningStatus?.longitude && dev?.lastRunningStatus?.latitude) || (dev?.locationMessage?.longitude && dev?.locationMessage?.latitude) || (dev?.longitude && dev?.latitude)) {
setFocusLocation({
lon: Number(dev.lastRunningStatus?.longitude || dev.locationMessage?.longitude || dev.longitude),
lat: Number(dev.lastRunningStatus?.latitude || dev.locationMessage?.latitude || dev.latitude),
type: isDroneDevice ? 'plane' : 'robot',
name: dev.deviceAlias || dev.deviceName || dev.drone_callsign || dev.serialNumber || dev.device_sn,
});
}
// ---- 逆变器/模拟设备:仅地图定位,不打开抽屉 ----
if (isMockDevice) {
setClearPlanLine(c => c + 1)
setDeviceDrawerOpen(false);
setMqttDrone(null);
return;
}
setExecute(true);
setDeviceDrawerOpen(true);
// ---- 无人机:先断开 WebSocket,再订阅该无人机 MQTT 实时数据 ----
if (isDroneDevice) {
controllerRef.current?.disconnect?.();
setMqttDrone(dev);
if (activeDroneTask?.device_sn !== dev.device_sn) {
setDroneReturningHome(false);
setDroneTaskPaused(false);
} else {
syncDroneTaskStatus();
}
setClearNavLine(c => c + 1);
fetchWaylineList();
fetchAndFocusDrone(dev);
return;
}
// ---- 机器人:先取消 MQTT 订阅,再连接 WebSocket ----
setMqttDrone(null);
if (dev.serialNumber && controllerRef.current) {
const isSameDevice = controllerRef.current.connectedDeviceSn === dev.serialNumber;
if (isSameDevice) {
console.log('[RTMonitor] 已连接相同设备,跳过');
} else if (isFirstConnect.current) {
isFirstConnect.current = false;
controllerRef.current.connectDevice(dev);
} else {
controllerRef.current.switchDevice(dev);
}
setClearNavLine(c => c + 1);
}
// ---- 刷新该设备任务数据,并在地图显示该设备正在执行任务的路线和区域 ----
fetchTaskPoolList(dev.serialNumber).then(poolRows => {
const rows = poolRows || [];
const runningTask = rows.find(t =>
(t.deviceId === dev.serialNumber) &&
['EXECUTING', 'PAUSE', 'NEW'].includes(t.taskStaus)
);
console.log('[RTMonitor] 设备正在执行的任务:', runningTask);
if (runningTask) {
setRunningPoolTask(runningTask);
loadTaskPath(runningTask.id);
fetchDetailTaskPath(runningTask.id);
setExcuteStatus(runningTask.taskStaus === 'EXECUTING' ? 'running' : 'pause');
} else {
setRunningPoolTask(null);
setPoints([]);
setPolyPoints([]);
setExcuteStatus('stop');
}
});
};
const typeCounts = useMemo(() => {
const c = { all: deviceList.length, robot: 0, plane: 0, inverter: 0, combiner: 0, weather: 0 };
deviceList.forEach(d => { if (c[d.category] !== undefined) c[d.category] += 1; });
return c;
}, [deviceList]);
const filteredDeviceList = useMemo(() => {
return deviceList.filter(d => {
if (filterType !== 'all' && d.category !== filterType) return false;
if (searchName) {
const kw = searchName.trim().toLowerCase();
if (!String(d.name || '').toLowerCase().includes(kw) && !String(d.serialNumber || '').toLowerCase().includes(kw) && !String(d.typeText || '').toLowerCase().includes(kw)) return false;
}
return true;
});
}, [deviceList, filterStatus, filterType, searchName]);
const pagedDeviceList = useMemo(() => {
const start = (listPage - 1) * listPageSize;
return filteredDeviceList.slice(start, start + listPageSize);
}, [filteredDeviceList, listPage, listPageSize]);
const getStatusTag = (status) => {
let color = '#999';
let text = '离线';
if (status === 1) {
color = '#1677ff';
text = '工作中';
} else if (status === 2) {
color = '#52c41a';
text = '空闲';
}
return (
<Space size={4}>
<span style={{ width: 8, height: 8, borderRadius: '50%', background: color, display: 'inline-block' }} />
<span style={{ color }}>{text}</span>
</Space>
);
};
const columns = [
{
title: t('devices.deviceName'), dataIndex: 'name', key: 'name',
render: (text, record) => (
<a onClick={() => handleDeviceClick(record.raw || record)} style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
<div style={{ width: 24, height: 24, background: '#f5f5f5', borderRadius: 4, display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
{record.type?.includes?.('INV') ? <ThunderboltOutlined style={{ fontSize: 14 }} /> : getDeviceTypeIcon(record.type)}
</div>
<span style={{ fontSize: 13 }}>{text}</span>
</a>
)
},
{ title: t('common.type'), dataIndex: 'typeText', render: (t) => <span style={{ fontSize: 13, color: '#666' }}>{t}</span> },
{ title: t('workOrder.currentStatus'), dataIndex: 'feStatus', render: getStatusTag },
//{ title: t('page.fixed2RealtimePower'), dataIndex: 'data', render: (d) => <span style={{ fontSize: 13, fontWeight: 500 }}>{d}</span> },
//{
// title: t('page.statusFixed2'), dataIndex: 'communication',
// render: (c) => (
// <Space size={4}>
// <span style={{ fontSize: 13 }}>{c}</span>
// <RiseOutlined style={{ color: '#52c41a' }} />
// </Space>
// )
//},
//{
// title: t('common.action'), key: 'action', width: 80,
// render: (_, record) => (
// <Tooltip title={t('page.viewDeviceDetailAndTask')}>
// <Button type="link" size="small" onClick={() => handleDeviceClick(record.raw || record)} icon={<LockOutlined />}>
// {t('common.locate')}
// </Button>
// </Tooltip>
// )
//}
];
// 任务池(当前选中设备)
const deviceTasks = useMemo(() => {
if (!selectedDeviceSn) return { pool: [], current: null };
const pool = taskPoolList.filter(t => t.deviceId === selectedDeviceSn);
const current = pool.find(t => ['EXECUTING', 'PAUSE', 'NEW'].includes(t.taskStaus)) || null;
return { pool, current };
}, [selectedDeviceSn, taskPoolList,]);
// 同步 runningPoolTask -> excuteStatus
useEffect(() => {
if (runningPoolTask) {
setExcuteStatus(runningPoolTask.taskStaus === 'EXECUTING' ? 'running' : runningPoolTask.taskStaus === 'PAUSE' ? 'pause' : 'stop');
} else if (!deviceTasks.current) {
setExcuteStatus('stop');
}
}, [runningPoolTask, deviceTasks.current]);
// ============================================================
// 无人机:MQTT 实时数据订阅(复用航线任务页逻辑)
// ============================================================
const handleMqttMessage = useCallback((topic, message) => {
try {
const parsed = JSON.parse(message);
const host = parsed?.data?.host;
if (!host || host.job_number) return;
if (host.battery === undefined) return;
const sn = String(topic).split('/')[2] || '';
setDroneMqttMap(prev => {
const nd = { ...(prev[sn] || {}) };
if (host.battery?.capacity_percent !== undefined) nd.capacity_percent = host.battery.capacity_percent;
if (host.attitude_head !== undefined) nd.heading = host.attitude_head;
if (host.horizontal_speed !== undefined) nd.horizontal_speed = host.horizontal_speed;
if (host.vertical_speed !== undefined) nd.vertical_speed = host.vertical_speed;
if (host.height !== undefined) nd.height = host.height;
if (host.wind_speed !== undefined) nd.wind_speed = host.wind_speed;
if (host.position_state !== undefined) nd.position_state = host.position_state;
if (host.longitude !== undefined) nd.longitude = host.longitude;
if (host.latitude !== undefined) nd.latitude = host.latitude;
if (host.mode_code !== undefined) nd.mode_code = host.mode_code;
return { ...prev, [sn]: nd };
});
} catch (err) {
console.error('[RTMonitor] MQTT 消息解析失败:', err);
}
}, []);
const mqttTopics = useMemo(() => {
if (!mqttDrone) return [];
const topics = [];
if (mqttDrone.device_sn) topics.push('thing/product/' + mqttDrone.device_sn + '/osd');
if (mqttDrone.gateway_sn) topics.push('thing/product/' + mqttDrone.gateway_sn + '/osd');
return topics;
}, [mqttDrone]);
const selectedDroneRealtime = useMemo(() => droneMqttMap[selectedDevice?.device_sn] || {}, [droneMqttMap, selectedDevice]);
useMqtt({
url: envConfig.mqtt_url,
topic: mqttTopics,
onMessage: handleMqttMessage,
enabled: mqttTopics.length > 0,
});
// ============================================================
// 无人机:航线列表 + 执行(复用航线任务页逻辑)
// ============================================================
const fetchWaylineList = async () => {
try {
const res = await getWayLine();
if (res?.code === 200 || res?.code === 0) {
setWaylineList((res?.data?.list || []).map(item => ({ ...item, label: item.name, value: item.id })));
} else {
messageApi.error(t('devices.waylineListFetchFail'));
}
} catch (err) {
console.error('[RTMonitor] 获取航线列表失败', err);
messageApi.error(t('devices.waylineListFetchFail'));
}
};
const handleWaylineClick = (wayline) => {
setSelectedWayline(wayline);
const pts = wayline.points || [];
const mapped = pts.map(p => ({ lng: Number(p.longitude || p.lon || 0), lat: Number(p.latitude || p.lat || 0) }));
if (mapped.length) setPoints(mapped);
};
const handleDroneExecuteClick = (wayline) => {
if (!selectedDevice?.gateway_sn) {
messageApi.warning(t('devices.selectExecuteDroneFirst'));
return;
}
setSelectedWayline(wayline);
setTempRthAltitude(100);
setRthModalVisible(true);
};
const confirmExecuteWayline = async () => {
if (!selectedWayline || !selectedDevice?.gateway_sn) return;
setWaylineLoading(true);
try {
const payload = {
name: selectedWayline.name + '_' + dayjs().format('MMDDHHmm'),
sn: selectedDevice.gateway_sn,
wayline_uuid: selectedWayline.id || selectedWayline.uuid,
rth_altitude: tempRthAltitude,
task_type: 'immediate',
rth_mode: 'optimal',
wayline_precision_type: 'gps',
resumable_status: 'auto',
min_battery_capacity: 50,
repeat_type: 'nonrepeating',
time_zone: Intl.DateTimeFormat().resolvedOptions().timeZone,
};
const res = await createWaylineTask(payload);
if (res?.code === 200 || res?.code === 0) {
messageApi.success(t('devices.waylineTaskCreated'));
setRthModalVisible(false);
setActiveDroneTask({
device_sn: selectedDevice.device_sn,
taskId: res?.data?.id || res?.data?.uuid || selectedWayline.id || selectedWayline.uuid || '',
name: payload.name,
createTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
status: 'EXECUTING',
});
setDroneReturningHome(false);
setDroneTaskPaused(false);
} else {
messageApi.error(res?.msg || t('devices.waylineExecFail'));
}
} catch (err) {
console.error('[RTMonitor] 执行航线失败', err);
messageApi.error(t('devices.createTaskException'));
} finally {
setWaylineLoading(false);
}
};
const sendDroneFlightCommand = async (command) => {
const dev = selectedDevice;
if (!dev?.device_sn) {
messageApi.warning(t('devices.noDeviceSelected'));
return;
}
setDroneCommandLoading(true);
try {
const res = await postFlightCommmand({ command, deviceSn: dev.device_sn });
if (res?.code === 200 || res?.code === 0) {
messageApi.success(t('devices.commandSent'));
if (command === 'return_home') {
setDroneReturningHome(true);
setActiveDroneTask(t => (t ? { ...t, status: 'RETURN_HOME' } : t));
}
if (command === 'return_home_cancel') setDroneReturningHome(false);
if (command === 'flighttask_pause') {
setDroneTaskPaused(true);
setActiveDroneTask(t => (t ? { ...t, status: 'PAUSE' } : t));
}
if (command === 'flighttask_recovery') {
setDroneTaskPaused(false);
setActiveDroneTask(t => (t ? { ...t, status: 'EXECUTING' } : t));
}
} else {
messageApi.error(res?.msg || t('devices.commandSendFail'));
}
} catch (err) {
console.error('[RTMonitor] 下发无人机指令失败', err);
messageApi.error(t('devices.commandSendFail'));
} finally {
setDroneCommandLoading(false);
}
};
const syncDroneTaskStatus = async () => {
if (!activeDroneTask?.taskId) return;
try {
const res = await getFlightTaskDetail(activeDroneTask.taskId);
const st = res?.data?.status || '';
const paused = ['paused', 'suspended', 'PAUSE', 'SUSPENDED'].includes(st);
const returning = ['return_home', 'RETURN_HOME', 'returnHome'].includes(st);
setDroneTaskPaused(paused);
setDroneReturningHome(returning);
setActiveDroneTask(t => (t ? { ...t, status: returning ? 'RETURN_HOME' : paused ? 'PAUSE' : 'EXECUTING' } : t));
} catch (err) {
// ignore sync error
}
};
const fetchAndFocusDrone = async (dev) => {
if (!dev?.gateway_sn || !dev?.device_sn) return;
try {
const res = await getUAVState({ sn: dev.gateway_sn, droneSn: dev.device_sn });
const pos = res?.data;
if (pos && pos.longitude && pos.latitude) {
setFocusLocation({
lon: Number(pos.longitude),
lat: Number(pos.latitude),
type: 'plane',
name: dev.deviceAlias || dev.device_sn,
});
}
} catch (err) {
console.error('[RTMonitor] 获取无人机位置失败', err);
}
};
// ============================================================
// 路径操作:执行/暂停/恢复/取消
// ============================================================
const handleRouteExecute = async (route) => {
if (!selectedDevice) { messageApi.error(t('devices.selectExecuteDevice')); return; }
if (!selectedDevice?.serialNumber) { messageApi.error(t('devices.deviceSerialNumberMissing')); return; }
modal.confirm({
title: t('devices.confirmExecuteRoute'),
content: (
<div>
<p>{t('devices.targetDevice')}: <strong>{selectedDevice.deviceAlias || selectedDevice.name || selectedDevice.serialNumber}</strong></p>
<p>{t('devices.routeName')}: <strong>{route.workName || route.name}</strong></p>
{route.points?.length && <p>{t('devices.routePointCount')}: {route.points.length}</p>}
</div>
),
okText: t('common.confirm'),
cancelText: t('common.cancel'),
onOk: async () => {
try {
const params = { deviceId: selectedDevice.serialNumber, routeId: route.id, siteId: stationId };
if (currentStation?.orgId) params.orgId = currentStation.orgId;
const res = await excuetRoute(params);
if (res.code == 200) {
messageApi.success(t('devices.taskExecSuccess'));
// 先立即显示该路线在地图
fetchRouteDetailAndShow(route.id, route);
// 刷新任务池
const freshPool = await fetchTaskPoolList(selectedDevice.serialNumber);
// 自动设置当前执行任务,并在地图显示该任务的路线和区域
const rest = (freshPool && freshPool.length ? freshPool : taskPoolList)
.filter(t => t.deviceId === selectedDevice.serialNumber);
const newTask = [...rest].sort((a, b) => new Date(b.createTime) - new Date(a.createTime))[0];
if (newTask) {
setRunningPoolTask(newTask);
await loadTaskPath(newTask.id);
setExcuteStatus('running');
}
} else {
console.log('[RTMonitor] 执行路径失败:', res);
messageApi.error(res.msg || t('devices.taskExecuteFailed'));
}
} catch (err) {
console.error(err);
messageApi.error(t('devices.taskExecuteException'));
}
}
});
};
const handlePauseTask = async (task = runningPoolTask) => {
if (!task) return;
try {
const res = await pauseRoute({ taskId: task.id, orgId: task.orgId, siteId: stationId });
if (res.code === 200) {
messageApi.success(t('devices.taskPaused'));
setExcuteStatus('pause');
if (runningPoolTask?.id === task.id) setRunningPoolTask({ ...runningPoolTask, taskStaus: 'PAUSE' });
fetchTaskPoolList(selectedDeviceSn);
}
} catch (err) { console.error(err); messageApi.error(t('devices.taskPauseAbnormal')); }
};
const handleRecoverTask = async (task = runningPoolTask) => {
if (!task) return;
try {
const res = await recoverRoute({ taskId: task.id, orgId: task.orgId, siteId: stationId });
if (res.code === 200) {
messageApi.success(t('devices.taskResumed'));
setExcuteStatus('running');
if (runningPoolTask?.id === task.id) setRunningPoolTask({ ...runningPoolTask, taskStaus: 'EXECUTING' });
fetchTaskPoolList(selectedDeviceSn);
}
} catch (err) { console.error(err); }
};
const handleCancelTask = async (task = runningPoolTask) => {
if (!task) return;
modal.confirm({
title: t('devices.confirmCancelTask'),
content: `${t('devices.areYouSureCancelTask')} ${task.planName || task.id}?`,
onOk: async () => {
try {
const res = await cancelRoute({ taskId: task.id, orgId: task.orgId, siteId: stationId });
if (res.code === 200) {
messageApi.success(t('devices.taskCancelled'));
setRunningPoolTask(null);
setExcuteStatus('stop');
setPoints([]);
setPolyPoints([]);
setClearNavLine(c => c + 1);
setClearPlanLine(c => c + 1);
fetchTaskPoolList(selectedDeviceSn);
}
} catch (err) { console.error(err); messageApi.error(t('devices.taskCancelAbnormal')); }
}
});
};
// 过滤后的路径列表
const filteredRoutes = useMemo(() => {
if (!routeSearch) return routeList;
const s = routeSearch.toLowerCase();
return routeList.filter(r =>
String(r.workName || r.name || '').toLowerCase().includes(s) ||
String(r.workDescription || r.description || '').toLowerCase().includes(s)
);
}, [routeList, routeSearch]);
// ============================================================
// 渲染
// ============================================================
return (
<div style={{ background: '#f8fafc', padding: '8px 0px', minHeight: '100vh', width: '100%', boxSizing: 'border-box' }}>
{contextHolder}
<div style={{ marginBottom: 8, display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end' }}>
<div>
<Title level={4} style={{ margin: 0, fontSize: 'clamp(14px, 1.2vw, 18px)' }}>{t('router.realtimeMonitorCenter')}</Title>
<Text type="secondary" style={{ fontSize: '12px' }}>{t('page.deviceFixed2StatusAndGeneration')} · {currentStation?.siteName || t('common.loading')}</Text>
</div>
<Space>
<Segmented
value={mapViewMode}
onChange={setMapViewMode}
size="small"
options={[
{ label: t('page.showAllDevices'), value: 'all' },
{ label: t('page.showOnlySelected'), value: 'selected' }
]}
/>
<Button type="text" icon={<SyncOutlined spin={loading} />} onClick={handleRefresh} style={{ color: '#1677ff' }}>
{t('common.refresh')}
</Button>
</Space>
</div>
<Row gutter={[8, 8]}>
<Col xs={24} xl={16}>
<Space direction="vertical" size={8} style={{ width: '100%' }}>
{/* ---------- 地图 ---------- */}
<Card
title={
<span style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<span style={{ fontWeight: 800, fontSize: 13 }}>{t('page.stationTopology')}</span>
<Tooltip title={t('page.clickDeviceOnMapTip')}>
<InfoCircleOutlined style={{ color: '#999', fontSize: 12 }} />
</Tooltip>
{focusLocation && (
<Tag color="blue" style={{ marginLeft: 8 }}>
<LockOutlined /> {t('page.focusingDevice', { name: focusLocation.name || '-' })}
</Tag>
)}
</span>
}
extra={
<Space size={8}>
<span style={{ display: 'flex', alignItems: 'center', gap: 4, fontSize: 11 }}>
<span style={{ width: 6, height: 6, borderRadius: '50%', background: '#52c41a' }}></span>{t('roles.normal')}
</span>
<span style={{ display: 'flex', alignItems: 'center', gap: 4, fontSize: 11 }}>
<span style={{ width: 6, height: 6, borderRadius: '50%', background: '#faad14' }}></span>{t('constants.sourceAlert')}
</span>
<span style={{ display: 'flex', alignItems: 'center', gap: 4, fontSize: 11 }}>
<span style={{ width: 6, height: 6, borderRadius: '50%', background: '#888' }}></span>{t('devices.offline')}
</span>
<Divider type="vertical" />
<Button size="small" icon={<DeleteOutlined />} onClick={() => setClearNavLine(c => c + 1)}>
{t('devices.clearRealtimeTrack')}
</Button>
<Button size="small" danger icon={<DeleteOutlined />} onClick={() => { setPoints([]); setPolyPoints([]); setRouteMode(''); setClearPlanLine(c => c + 1); }}>
{t('devices.clearPlanRoute')}
</Button>
</Space>
}
variant="borderless"
style={{ ...cardStyle, borderRadius: 8 }}
styles={{ body: { padding: 0, position: 'relative', height: 500, overflow: 'hidden' } }}
>
<div style={{ height: '100%', background: '#111827', borderRadius: 8, width: '100%', overflow: 'hidden', position: 'relative' }}>
<CesiumMap
from="devicesTask"
mapLayer={currentStation?.siteMapName}
devices={mapDevices}
onCameraClick={handleDeviceClick}
points={points}
focusLocation={focusLocation}
realtimePosition={runningRealtimePosition}
polyPoints={polyPoints}
realtimeType="robot"
drawRealTime={execute}
finishPoint={arrivedPoint}
ifClearNavLine={clearNavLine}
ifClearPlanLine={clearPlanLine}
routeMode={routeMode}
/>
{/* 地图左上浮窗:已找到N台 + 当前任务状态 */}
<div style={{ position: 'absolute', top: 12, left: 12, display: 'flex', flexDirection: 'column', gap: 8, zIndex: 10 }}>
<div style={{ background: 'rgba(0,0,0,0.55)', color: 'white', padding: '8px 12px', borderRadius: 8, fontSize: 12, backdropFilter: 'blur(4px)' }}>
<Space size={8}>
<EnvironmentOutlined />
{t('page.foundDevices', { count: mapDevices.length })}
</Space>
</div>
{runningPoolTask && (
<div style={{ background: excuteStatus === 'running' ? 'rgba(82,196,26,0.95)' : 'rgba(250,173,20,0.95)', color: 'white', padding: '8px 12px', borderRadius: 8, fontSize: 12, backdropFilter: 'blur(4px)', maxWidth: 280 }}>
<div style={{ fontWeight: 600, marginBottom: 4, display: 'flex', alignItems: 'center', gap: 6 }}>
{excuteStatus === 'running' ? <PlayCircleOutlined spin /> : <PauseCircleOutlined />}
{t('devices.currentTask')}
</div>
<div style={{ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
{runningPoolTask.planName || runningPoolTask.planId || runningPoolTask.id}
</div>
</div>
)}
{robotRealtimePosition && (
<div style={{ background: 'rgba(22,119,255,0.9)', color: 'white', padding: '8px 12px', borderRadius: 8, fontSize: 11, backdropFilter: 'blur(4px)' }}>
<div>📡 {t('devices.realtimePosition')}</div>
<div>Lng: {Number(robotRealtimePosition.longitude || robotRealtimePosition.lng || 0).toFixed(5)}</div>
<div>Lat: {Number(robotRealtimePosition.latitude || robotRealtimePosition.lat || 0).toFixed(5)}</div>
<div>yaw: {Number(robotRealtimePosition.heading || 0).toFixed(5)}</div>
</div>
)}
</div>
</div>
</Card>
{/* ---------- 设备列表 ---------- */}
<Card
title={<span style={{ fontWeight: 800, fontSize: 13 }}>{t('page.fixed2DeviceFixed2RealtimeMonitorListFixed2')}</span>}
variant="borderless"
style={{ ...cardStyle, borderRadius: 8 }}
extra={
<Space size={8}>
<Select value={filterType} size="small" style={{ width: 120 }} onChange={(v) => { setFilterType(v); setListPage(1); }}>
<Option value="all">{t('devices.all')} ({typeCounts.all})</Option>
<Option value="robot">{t('devices.robot')} ({typeCounts.robot})</Option>
<Option value="plane">{t('devices.drone')} ({typeCounts.plane})</Option>
<Option value="inverter">{t('home.inverter')} ({typeCounts.inverter})</Option>
<Option value="combiner">{t('home.combinerBox')} ({typeCounts.combiner})</Option>
<Option value="weather">{t('home.weatherStation')} ({typeCounts.weather})</Option>
</Select>
<Input size="small" placeholder={t('devices.searchDeviceName')} prefix={<SearchOutlined />} style={{ width: 150 }}
onChange={(e) => { setSearchName(e.target.value); setListPage(1); }} />
{(searchName || filterType !== 'all' || filterStatus !== 'all') && (
<Button size="small" icon={<ReloadOutlined />} onClick={() => { setFilterType('all'); setFilterStatus('all'); setSearchName(''); setListPage(1); }} />
)}
</Space>
}
>
<Table
rowKey="id"
columns={columns}
dataSource={pagedDeviceList}
loading={loading}
pagination={false}
size="small"
/>
<div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 12, alignItems: 'center' }}>
<span style={{ color: '#999', fontSize: 11 }}>{t('common.totalCount', { count: filteredDeviceList.length })}</span>
<Pagination size="small" current={listPage} pageSize={listPageSize} total={filteredDeviceList.length} showSizeChanger onChange={(page, size) => { setListPage(page); setListPageSize(size); }} />
</div>
</Card>
</Space>
</Col>
<Col xs={24} xl={8}>
<Space direction="vertical" size={8} style={{ width: '100%' }}>
<Row gutter={[4, 4]}>
{[
{ title: t('page.fixed2CurrentFixed2TotalPowerFixed2'), value: '812.6', unit: 'kW', sub: t('home.ratPower') + ' 1,000 kW', color: '#165DFF', icon: <ThunderboltOutlined /> },
{ title: t('page.statusFixed2'), value: t('page.gridNorm'), unit: '', sub: t('home.frequency') + ' 50.02 Hz', color: '#00B42A', icon: <CheckCircleOutlined /> },
{ title: t('home.gridVoltage'), value: '380.2', unit: 'V', sub: t('home.phaseA') + ' 380.1 V', color: '#165DFF', icon: <BarChartOutlined /> },
{ title: t('page.fixed2TodayAccumulatedBatteryFixed2'), value: '4,752', unit: t('home.kWh'), sub: t('home.yesterday') + ' 5,000 kWh', color: '#00B42A', icon: <RiseOutlined /> },
{ title: t('home.currentIrradiance'), value: '815', unit: 'W/m²', sub: 'MoM +5.6%', color: '#faad14', icon: <SunOutlined /> },
{ title: t('home.ambientTemperature'), value: '28.0', unit: '℃', sub: 'MoM +1.2 ℃', color: '#165DFF', icon: <CloudOutlined /> },
].map((item, idx) => (
<Col span={8} key={idx}>
<Card variant="borderless" style={{ ...cardStyle, height: '100%', borderRadius: 8 }} styles={{ body: { padding: '8px' } }}>
<div style={{ display: 'flex', alignItems: 'flex-start', gap: 6 }}>
<div style={{ color: item.color, fontSize: 18 }}>{item.icon}</div>
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontSize: 'clamp(10px, 0.8vw, 11px)', color: '#666', marginBottom: 4, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{item.title}</div>
<div style={{ display: 'flex', alignItems: 'baseline', flexWrap: 'wrap' }}>
<span style={{ fontSize: 'clamp(14px, 1.2vw, 18px)', fontWeight: 700 }}>{item.value}</span>
<span style={{ fontSize: 10, marginLeft: 2 }}>{item.unit}</span>
</div>
<div style={{ fontSize: 9, color: '#999', marginTop: 4 }}>{item.sub}</div>
</div>
</div>
</Card>
</Col>
))}
</Row>
<Card title={<span style={{ fontWeight: 800 }}>{t('page.powerCurveFixed2')}</span>} extra={<Select defaultValue="today" size="small"><Option value="today">{t('page.s11')}</Option></Select>} variant="borderless" style={cardStyle} styles={{ body: { padding: '12px' } }}>
<UniversalLineChart height={160} data={powerTrendData} xKey="time" smooth dot showLegend={false} backgroundColor="transparent"
series={[{ key: 'value', name: t('page.fixed2RealtimePower'), color: '#1677ff', strokeWidth: 3 }]} />
</Card>
<Card title={<span style={{ fontWeight: 800 }}>{t('page.inverterPowerCompare')}</span>} variant="borderless" style={cardStyle} styles={{ body: { padding: '12px' } }}>
<UniversalBarChart height={160} data={inverterPowerData} xKey="name" barSize={22} showLegend={false} backgroundColor="transparent"
series={[{ key: 'power', name: t('page.fixed2RealtimePower'), color: '#1677ff' }]} />
</Card>
<Row gutter={8}>
<Col span={12}>
<Card title={<span style={{ fontWeight: 800 }}>{t('page.stringCurrentHeatmap')}</span>} variant="borderless" style={cardStyle} styles={{ body: { padding: '12px' } }}>
<div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
{['INV-01', 'INV-02', 'INV-03', 'INV-04', 'INV-05'].map((name, i) => (
<div key={i} style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
<span style={{ fontSize: 10, width: 40 }}>{name}</span>
<div style={{ display: 'flex', gap: 2, flex: 1 }}>
{Array.from({ length: 12 }).map((_, j) => (
<div key={j} style={{ flex: 1, height: 16, background: heatmapColors[Math.floor(Math.random() * 5)], borderRadius: 2 }} />
))}
</div>
</div>
))}
</div>
</Card>
</Col>
<Col span={12}>
<Card title={<span style={{ fontWeight: 800 }}>{t('devices.deviceOnlineRate')}</span>} variant="borderless" style={{ ...cardStyle, height: '100%' }} styles={{ body: { padding: '12px' } }}>
<div style={{ position: 'relative', height: 140 }}>
<UniversalPieChart height={140} backgroundColor="transparent" showLegend={false} showLabel={false} innerRadius={40} outerRadius={58}
data={[
{ name: t('devices.online'), value: deviceList.filter(d => d.onlineStatus === 1).length, color: '#52c41a' },
{ name: t('devices.offline'), value: deviceList.filter(d => d.onlineStatus === 3).length, color: '#d9d9d9' },
{ name: t('constants.sourceAlert'), value: deviceList.filter(d => d.onlineStatus === 2).length, color: '#faad14' },
]}
/>
<div style={{ position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%, -50%)', textAlign: 'center' }}>
<div style={{ fontSize: 14, fontWeight: 800 }}>
{deviceList.length > 0 ? Math.round(deviceList.filter(d => d.onlineStatus === 1).length / deviceList.length * 100) : 0}%
</div>
<div style={{ fontSize: 10, color: '#999' }}>{t('devices.statOnlineRate')}</div>
</div>
</div>
<div style={{ fontSize: 10, display: 'flex', flexWrap: 'wrap', gap: 8, marginTop: 8 }}>
<span><span style={{ display: 'inline-block', width: 6, height: 6, borderRadius: '50%', background: '#52c41a', marginRight: 4 }}></span>{t('devices.online')} {deviceList.filter(d => d.onlineStatus === 1).length}</span>
<span><span style={{ display: 'inline-block', width: 6, height: 6, borderRadius: '50%', background: '#f5f5f5', marginRight: 4 }}></span>{t('devices.offline')} {deviceList.filter(d => d.onlineStatus === 3).length}</span>
<span><span style={{ display: 'inline-block', width: 6, height: 6, borderRadius: '50%', background: '#faad14', marginRight: 4 }}></span>{t('constants.sourceAlert')} {deviceList.filter(d => d.onlineStatus === 2).length}</span>
</div>
</Card>
</Col>
</Row>
</Space>
</Col>
</Row>
{/* ============================================================ */}
{/* 设备详情 Drawer */}
{/* ============================================================ */}
<Drawer
title={
<div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
<div style={{
width: 42,
height: 42,
background: `rgba(${selectedDevice?.onlineStatus === 1 ? '82,196,26' : selectedDevice?.onlineStatus === 2 ? '250,173,20' : '153,153,153'}, 0.1)`,
borderRadius: 12,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
color: selectedDevice?.onlineStatus === 1 ? '#52c41a' : (selectedDevice?.onlineStatus === 2 ? '#faad14' : '#999'),
fontSize: 20
}}>
{getDeviceTypeIcon(selectedDevice?.type || selectedDevice?.deviceType)}
</div>
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 6, }}>
<div style={{ fontWeight: 600, fontSize: 15 }}>{selectedDevice?.deviceAlias || selectedDevice?.deviceName || '-'}</div>
<Badge status={selectedDevice?.onlineStatus === 1 ? 'success' : 'default'}
text={selectedDevice?.onlineStatus === 1 ? t('devices.online') : t('devices.offline')} />
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 2 }}>
<span style={{ color: '#999', fontSize: 10 }}>SN: {selectedDevice?.serialNumber || '-'}</span>
</div>
</div>
</div>
}
width={560}
open={deviceDrawerOpen}
onClose={() => {
; setDeviceDrawerOpen(false); setMqttDrone(null);
}}
destroyOnClose
extra={(selectedDevice?.gateway_sn || selectedDevice?.type === 'plane') ? null : <Button size="small" icon={<SyncOutlined />} onClick={() => { fetchTaskPoolList(selectedDeviceSn); }}></Button>}
>
{selectedDevice ? (
(selectedDevice?.type === 'plane' || selectedDevice?.gateway_sn) ? (
<Space direction="vertical" size={12} style={{ width: '100%' }}>
<Card
size="small"
title={
<span style={{ fontWeight: 600, fontSize: 13 }}>
<RocketOutlined style={{ color: '#1677ff', marginRight: 6 }} />
{t('devices.currentTask')}
</span>
}
extra={
<Space size={4}>
<Tooltip title={t('devices.pauseTask')}>
<Button size="small" type="text" icon={<PauseCircleOutlined />}
loading={droneCommandLoading}
disabled={activeDroneTask?.device_sn !== selectedDevice?.device_sn || droneTaskPaused}
onClick={() => sendDroneFlightCommand('flighttask_pause')} />
</Tooltip>
<Tooltip title={t('devices.resumeTask')}>
<Button size="small" type="primary" ghost={!droneTaskPaused} icon={<PlayCircleOutlined />}
loading={droneCommandLoading}
disabled={activeDroneTask?.device_sn !== selectedDevice?.device_sn || !droneTaskPaused}
onClick={() => sendDroneFlightCommand('flighttask_recovery')} />
</Tooltip>
<Tooltip title={droneReturningHome ? t('devices.cancelReturnHome') : t('devices.returnHome')}>
<Button size="small" danger={droneReturningHome} icon={<AimOutlined />}
loading={droneCommandLoading}
disabled={activeDroneTask?.device_sn !== selectedDevice?.device_sn}
onClick={() => sendDroneFlightCommand(droneReturningHome ? 'return_home_cancel' : 'return_home')} />
</Tooltip>
</Space>
}
style={{
borderRadius: 10,
border: '1px solid ' + (droneTaskPaused ? 'rgba(250,173,20,0.3)' : droneReturningHome ? 'rgba(22,119,255,0.3)' : 'rgba(82,196,26,0.3)'),
background: droneTaskPaused ? 'rgba(250,173,20,0.03)' : droneReturningHome ? 'rgba(22,119,255,0.03)' : 'rgba(82,196,26,0.03)'
}}
>
{activeDroneTask?.device_sn === selectedDevice?.device_sn ? (
<Space direction="vertical" size={6} style={{ width: '100%' }}>
<Space wrap>
<Tag color={droneReturningHome ? 'blue' : droneTaskPaused ? 'orange' : 'green'} style={{ fontSize: 12, padding: '2px 8px' }}>
{droneReturningHome ? t('devices.returnHome') : droneTaskPaused ? t('devices.taskStatusPause') : t('devices.taskStatusExecuting')}
</Tag>
<strong style={{ fontSize: 14 }}>{activeDroneTask.name || t('devices.unnamedTask')}</strong>
</Space>
<Row gutter={8} style={{ fontSize: 12, color: '#666' }}>
<Col span={12}>
<FileTextOutlined style={{ marginRight: 4 }} />
{t('devices.planId')}: {activeDroneTask.taskId || '-'}
</Col>
<Col span={12}>
<ClockCircleOutlined style={{ marginRight: 4 }} />
{t('common.createTime')}: {activeDroneTask.createTime || '-'}
</Col>
</Row>
</Space>
) : (
<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={t('devices.noCurrentTask')} style={{ padding: '8px 0' }} />
)}
</Card>
<Card
size="small"
title={<span style={{ fontWeight: 600, fontSize: 13 }}>{t('devices.waylineList')}</span>}
extra={<Button size="small" icon={<SyncOutlined />} onClick={fetchWaylineList}>{t('common.refresh')}</Button>}
>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
<Text strong>{selectedDevice?.deviceAlias || selectedDevice?.drone_callsign || selectedDevice?.name || selectedDevice?.device_sn || t('devices.drone')}</Text>
<Tag color={selectedDevice?.onlineStatus === 1 ? 'green' : 'default'}>{selectedDevice?.onlineStatus === 1 ? t('devices.idle') : t('devices.offline')}</Tag>
</div>
<div style={{ display: 'flex', flexWrap: 'wrap', gap: '2px 16px', fontSize: 12, color: '#666', marginBottom: 8 }}>
<span>{t('devices.batteryCapacity')}: <strong>{selectedDroneRealtime.capacity_percent ?? '-'}%</strong></span>
<span>高度: <strong>{selectedDroneRealtime.height ?? '-'} m</strong></span>
<span>{t('devices.horizontalSpeed')}: <strong>{selectedDroneRealtime.horizontal_speed ?? '-'} m/s</strong></span>
<span>RTK: <strong>{selectedDroneRealtime.position_state?.is_fixed === 'fixing_successful' ? t('devices.fixed2') : t('devices.notFixed2')}</strong></span>
</div>
<Search
placeholder={t('devices.searchWaylinePlaceholder')}
allowClear
size="small"
style={{ marginBottom: 8, width: '100%' }}
value={waylineSearch}
onChange={(e) => setWaylineSearch(e.target.value)}
/>
<div style={{ maxHeight: 460, overflow: 'auto', paddingRight: 4 }}>
{(waylineList || []).filter(item => !waylineSearch || String(item.name || '').toLowerCase().includes(waylineSearch.toLowerCase())).length === 0 ? (
<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={t('devices.noWaylineData')} style={{ padding: '16px 0' }} />
) : (
(waylineList || []).filter(item => !waylineSearch || String(item.name || '').toLowerCase().includes(waylineSearch.toLowerCase())).map(wayline => (
<div key={wayline.id || wayline.uuid}
onClick={() => handleWaylineClick(wayline)}
style={{ padding: '8px 10px', marginBottom: 8, border: '1px solid #f0f0f0', borderRadius: 8, cursor: 'pointer', background: (selectedWayline && (selectedWayline.id === wayline.id)) ? '#e6f4ff' : '#fff' }}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 8 }}>
<span style={{ fontSize: 13, fontWeight: 600 }}>{wayline.name}</span>
<Button type="text" size="small" icon={<SendOutlined />}
disabled={!selectedDevice?.gateway_sn || waylineLoading}
onClick={(e) => { e.stopPropagation(); handleDroneExecuteClick(wayline); }} />
</div>
</div>
))
)}
</div>
</Card>
</Space>
) : (
<Space direction="vertical" size={12} style={{ width: '100%' }}>
{/* ============== 【顶部】当前任务卡片 + 控制按钮 ============== */}
<Card
size="small"
title={
<span style={{ fontWeight: 600, fontSize: 13 }}>
<RocketOutlined style={{ color: '#1677ff', marginRight: 6 }} />
{t('devices.currentTask')}
</span>
}
extra={
<Space size={4}>
<Tooltip title={t('devices.pause')}>
<Button
size="small"
type={excuteStatus === 'pause' ? 'default' : 'text'}
icon={<PauseCircleOutlined />}
disabled={!runningPoolTask || excuteStatus !== 'running'}
onClick={() => handlePauseTask()}
danger={excuteStatus === 'running'}
/>
</Tooltip>
<Tooltip title={t('devices.resume')}>
<Button
size="small"
type="primary"
ghost={excuteStatus !== 'pause'}
icon={<PlayCircleOutlined />}
disabled={!runningPoolTask || excuteStatus !== 'pause'}
onClick={() => handleRecoverTask()}
/>
</Tooltip>
<Tooltip title={t('devices.stop')}>
<Button
size="small"
danger
icon={<StopOutlined />}
onClick={() => handleCancelTask()}
/>
</Tooltip>
</Space>
}
style={{
borderRadius: 10,
border: `1px solid ${runningPoolTask ? (excuteStatus === 'running' ? 'rgba(82,196,26,0.3)' : 'rgba(250,173,20,0.3)') : '#f0f0f0'}`,
background: runningPoolTask ? (excuteStatus === 'running' ? 'rgba(82,196,26,0.03)' : 'rgba(250,173,20,0.03)') : '#fff'
}}
>
{(runningPoolTask || deviceTasks.current) ? (
(() => {
const task = runningPoolTask || deviceTasks.current;
return (
<Space direction="vertical" size={6} style={{ width: '100%' }}>
<Space wrap>
<Tag color={taskStatusColor(task.taskStaus)} style={{ fontSize: 12, padding: '2px 8px' }}>
{task.taskStaus === 'NEW' ? t('devices.taskStatusNew') :
task.taskStaus === 'EXECUTING' ? t('devices.taskStatusExecuting') :
task.taskStaus === 'PAUSE' ? t('devices.taskStatusPause') :
task.taskStaus === 'FINISH' ? t('devices.taskStatusFinish') :
task.taskStaus === 'CANCEL' ? t('devices.taskStatusCancel') : task.taskStaus}
</Tag>
<strong style={{ fontSize: 14 }}>
{task.planName || task.planId || t('devices.unnamedTask')}
</strong>
</Space>
<Row gutter={8} style={{ fontSize: 12, color: '#666' }}>
<Col span={12}>
<FileTextOutlined style={{ marginRight: 4 }} />
{t('devices.planId')}: {task.id || '-'}
</Col>
<Col span={12}>
<ClockCircleOutlined style={{ marginRight: 4 }} />
{t('common.createTime')}: {task.createTime?.slice?.(0, 16) || '-'}
</Col>
{task.finishTime && (
<Col span={12} style={{ marginTop: 4 }}>
<ClockCircleOutlined style={{ marginRight: 4 }} />
{t('devices.expectedComplete')}: {task.finishTime?.slice?.(0, 16) || '-'}
</Col>
)}
</Row>
</Space>
);
})()
) : (
<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={t('devices.noCurrentTask')} style={{ padding: '8px 0' }} />
)}
</Card>
{/* ============== 【中部】预设路径列表 ============== */}
<Card
size="small"
title={
<span style={{ fontWeight: 600, fontSize: 13 }}>
<NodeIndexOutlined style={{ color: '#722ED1', marginRight: 6 }} />
{t('devices.presetRoutes')}
<Tag color="purple" style={{ marginLeft: 6 }}>{filteredRoutes.length}</Tag>
</span>
}
extra={
<Search
placeholder={t('devices.searchRoute')}
prefix={<SearchOutlined />}
allowClear
size="small"
style={{ width: 180 }}
value={routeSearch}
onChange={e => setRouteSearch(e.target.value)}
/>
}
style={{ borderRadius: 10 }}
styles={{ body: { padding: '8px 12px' } }}
>
{filteredRoutes.length === 0 ? (
<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={t('devices.noRouteTip')} style={{ padding: '16px 0' }} />
) : (
<div
style={{
maxHeight: 500,
overflow: 'auto',
paddingRight: 4
}}
className="custom-scrollbar"
>
{filteredRoutes.map(route => (
<div
key={route.id || route.workName}
onClick={() => {
setExecute(true);
fetchRouteDetailAndShow(route.id, route);
}}
style={{
padding: '10px 12px',
marginBottom: 6,
borderRadius: 8,
border: '1px solid #f0f0f0',
cursor: 'pointer',
transition: 'all 0.2s',
background: '#fafafa'
}}
onMouseEnter={e => {
e.currentTarget.style.background = '#fff';
e.currentTarget.style.borderColor = '#1677ff';
e.currentTarget.style.boxShadow = '0 2px 8px rgba(22,119,255,0.08)';
}}
onMouseLeave={e => {
e.currentTarget.style.background = '#fafafa';
e.currentTarget.style.borderColor = '#f0f0f0';
e.currentTarget.style.boxShadow = 'none';
}}
>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12 }}>
<Space direction="vertical" size={2} style={{ flex: 1, minWidth: 0 }}>
<Space size={6}>
<div style={{
width: 22, height: 22, background: 'rgba(114,46,209,0.1)',
borderRadius: 6, display: 'flex', alignItems: 'center', justifyContent: 'center',
color: '#722ED1', fontSize: 12
}}>
<NodeIndexOutlined />
</div>
<span style={{ fontWeight: 600, fontSize: 13, maxWidth: 280, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{route.workName || route.name || t('devices.unnamedRoute')}
</span>
</Space>
</Space>
<Button
type="text"
size="small"
icon={<SendOutlined />}
//disabled={!selectedDevice || selectedDevice.onlineStatus !== 1}
onClick={(e) => {
e.stopPropagation();
handleRouteExecute(route);
}}
style={{ flexShrink: 0 }}
>
</Button>
</div>
</div>
))}
</div>
)}
</Card>
</Space>
)
) : (
<Empty />
)}
<Modal
title={t('devices.executeWaylineTask')}
open={rthModalVisible}
onOk={confirmExecuteWayline}
onCancel={() => setRthModalVisible(false)}
confirmLoading={waylineLoading}
okText={t('devices.executeNow')}
cancelText={t('common.cancel')}
centered
width={420}
>
<div style={{ padding: '8px 0' }}>
<div style={{ marginBottom: 16 }}>
<Text strong>{t('devices.selectedWaylineColon')}</Text> <Text>{selectedWayline?.name}</Text>
</div>
<div style={{ marginBottom: 16 }}>
<Text strong>{t('devices.executeDeviceColon')}</Text> <Text>{selectedDevice?.deviceAlias || selectedDevice?.drone_callsign || selectedDevice?.name || selectedDevice?.device_sn || t('devices.noDeviceSelected')}</Text>
</div>
<div>
<div style={{ marginBottom: 8 }}><Text strong>{t('devices.returnHomeAltitudeColon')}</Text></div>
<InputNumber min={10} max={500} value={tempRthAltitude} onChange={(val) => setTempRthAltitude(val || 20)} style={{ width: '100%' }} />
</div>
</div>
</Modal>
</Drawer>
</div >
);
};
export default RealTimeMonitorPage;