Files
web-Iot/src/components/devices/DeviceOverviewPage.tsx

1543 lines
62 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, useMemo, useCallback } from 'react';
import {
Layout, Card, Row, Col, Statistic, Tag, Button, Table,
Typography, Space, Progress, Badge, Timeline, message,
Select, Modal, Space as AntSpace,
Input, Tooltip,
Empty
} from 'antd';
import {
EnvironmentOutlined, RobotOutlined, BranchesOutlined,
ThunderboltOutlined, CheckCircleOutlined, PauseOutlined,
RocketOutlined, SyncOutlined, WarningOutlined,
CloudOutlined, ClockCircleOutlined, ReloadOutlined,
AimOutlined, ApiOutlined, SettingOutlined,
PlusOutlined, ArrowRightOutlined,
EditOutlined, FullscreenOutlined, InfoCircleOutlined,
CarOutlined
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import DroneLivePlayer from '../VolcRtcPlayer.jsx';
import DroneVideoPlayer from './DroneVideoPlayer';
import AgoraTextTest from '../AgoraRtc.tsx';
import { useWebRTCPlayer } from '../useWebRTCStream.tsx';
import VideoPlayer from '../VideoPlayer.tsx';
import DeviceController from './DeviceController';
import AgrtcRoomRobot from '../AgrtcRoomRobot';
import CesiumMap from '../Map.jsx';
import DeviceParamModal from './DeviceParamModal';
import { getUAVState, getSiteDevice, getSiteUAVList, getsinglePlan, getRobotTaskList, getDeviceTotalData, updateDeviceAliasApi, hasPermission } from '@/api/device.ts';
import { getAlarmList, handleAlarm } from '@/api/alarmApi.js';
import dayjs from 'dayjs';
import { useMqtt } from '@/hooks/useMqtt';
import { useSelector } from 'react-redux';
import { RootState } from '@/store';
import envConfig from '../../../env';
import utils from '@/lib/utils.ts';
import { useUnitFormatter } from '@/lib/units';
import { useTranslation } from 'react-i18next';
import { sendEmergencyStop, subscribeEmergencyStop, syncEmergencyStop } from './emergencyStopControl';
import AlarmLevelTag from '../AlarmLevelTag.tsx';
import { getDeviceTastPool } from '@/api/device.ts';
import { backToRestPointCommand } from '@/api/mapEdit';
import './DeviceOverviewPage.css';
const { Content } = Layout;
const { Text, Title } = Typography;
// 告警时间兼容:Java LocalDateTime 数组 / ISO 字符串 / 时间戳
const formatAlarmTime = (value: any, fmt = 'YYYY-MM-DD HH:mm:ss') => {
if (value === null || value === undefined || value === '') return '';
if (Array.isArray(value)) {
const [y, mo, d, h = 0, mi = 0, se = 0] = value;
if (!y) return '';
const dt = dayjs(new Date(y, mo - 1, d, h, mi, se));
return dt.isValid() ? dt.format(fmt) : '';
}
const dt = dayjs(value);
return dt.isValid() ? dt.format(fmt) : String(value);
};
// 告警标题:alarmTitle 是编码时改用 alarmContent 中文描述
const isAlarmCode = (value: any) => typeof value === 'string' && /^[A-Z][A-Z0-9_]*$/.test(value);
const getAlarmTitleText = (record: any) => {
const title = record?.alarmTitle;
return (isAlarmCode(title) ? record?.alarmContent : (title || record?.alarmContent)) || record?.alarmNo || '';
};
// 告警级别:兼容数字 1-4 / CRITICAL 等别名
const ALARM_LEVEL_ALIAS: Record<string, string> = {
'1': 'ERROR', '2': 'WARNING', '3': 'INFO', '4': 'INFO',
CRITICAL: 'ERROR', MAJOR: 'WARNING', MINOR: 'INFO',
};
const resolveAlarmLevel = (record: any) => {
const raw = String(record?.alertLevel ?? record?.alarmLevel ?? 'INFO').toUpperCase();
return ALARM_LEVEL_ALIAS[raw] || raw;
};
export default function DeviceOverviewPage() {
const { t } = useTranslation();
const { userInfo } = useSelector((state: RootState) => state.user);
const { stationId, currentStation } = useSelector((state: RootState) => state.station);
const { formatTemperature } = useUnitFormatter();
const [zoomedVideo, setZoomedVideo] = useState(null);
const [mowerView, setMowerView] = useState('front');
const [videoSource, setVideoSource] = useState('drone');
const [uavState, setUavState] = useState(null);
const [persistentDroneData, setPersistentDroneData] = useState(null);
const [persistentHostData, setPersistentHostData] = useState(null);
const [devices, setDevices] = useState([]);
const [planedevices, setPlaneDevices] = useState([]);
const [devicesAll, setDevicesAll] = useState([]);
const [taskStats, setTaskStats] = useState({ completed: 12, total: 15 });
const [deviceStatistics, setDeviceStatistics] = useState(null);
const [currentSelectedRobot, setCurrentSelectedRobot] = useState(null);
const [realtimeMap, setRealtimeMap] = useState<any>({});
// 急停锁存状态:与 DPadControl / XboxController 共享同一份状态
const [eStopActive, setEStopActive] = useState(false);
useEffect(() => subscribeEmergencyStop(setEStopActive), []);
const controllerRef = useRef<DeviceController | null>(null);
const [messageApi, contextHolder] = message.useMessage();
const [taskList, setTaskList] = useState<any[]>([]);
const [alarmList, setAlarmList] = useState<any[]>([]);
// 编辑机器人弹窗相关
const [editRobotModalOpen, setEditRobotModalOpen] = useState(false);
const [currentEditRobot, setCurrentEditRobot] = useState(null);
const [editAliasInput, setEditAliasInput] = useState('');
const [editLoading, setEditLoading] = useState(false);
// 设备参数弹窗相关
const [paramModalOpen, setParamModalOpen] = useState(false);
const [currentParamDevice, setCurrentParamDevice] = useState<any>(null);
const navigate = useNavigate();
const [robotPlayActive, setRobotPlayActive] = useState<boolean>(false);
const [taskPoolList, setTaskPoolList] = useState<any[]>([]);
const taskTimeline = [
{ time: '10:24:18', color: 'blue', text: t('devices.uavC01ExecuteFixed2CleaningC05'), status: '任务开始' },
{ time: '10:21:35', color: 'orange', text: t('devices.rbt01ExecuteFixed2InspectionP02'), status: '任务开始' },
{ time: '10:18:02', color: 'green', text: t('devices.gr02G01'), status: '任务开始' },
{ time: '10:15:47', color: 'gray', text: t('devices.uavC02TaskSuspended2'), status: '待命就绪' },
{ time: '10:12:33', color: 'blue', text: t('devices.uavC01'), status: '返机补给' },
{ time: '09:58:10', color: 'green', text: t('devices.rbt02CompleteFixed2InspectionP01'), status: '任务完成' },
];
const fetchTaskPoolList = async () => {
if (!stationId) return;
try {
const params = {
userId: userInfo?.userId,
siteId: stationId,
orgId: currentStation?.orgId,
pageNum: 1,
pageSize: 10
};
const res = await getDeviceTastPool(params);
if (res.code === 200) {
const list = res.rows || [];
list.map(item => {
return {
time: dayjs(item.createTime).format('HH:mm:ss'),
color: item.taskStaus === 'EXECUTING' ? 'green' : 'blue',
text: item.workName || t('devices.unnamedTask'),
status: item.taskStaus === 'EXECUTING' ? t('devices.executing') : item.taskStaus === 'FAILED' ? t('devices.executeFail') : item.taskStaus === 'COMPLETED' ? t('devices.statusFinished') : item.taskStaus === 'CANCELED' ? t('devices.taskCanceled') : t('devices.taskStatusNew')
}
})
setTaskPoolList(list);
}
} catch (err) {
console.error('获取任务池失败:', err);
}
};
// 获取数据
const fetchAllData = async () => {
if (!stationId) return;
try {
// 1. 同时发请求
const [deviceRes, planeRes] = await Promise.all([
getSiteDevice({ siteId: stationId, pageSize: 9999, pageNum: 1, orgId: currentStation?.orgId }),
getSiteUAVList(stationId),
]);
// 2. 处理普通设备
const devData = deviceRes?.code === 200 ? (deviceRes.rows || []) : [];
// 3. 处理无人机 + 自动补全地图需要的字段(关键改动)
let planeData = planeRes?.code === 200 ? (planeRes?.rows || []) : [];
planeData = planeData.map(item => ({
...item,
type: 'plane',
lastRunningStatus: {
longitude: item.longitude || 0,
latitude: item.latitude || 0,
},
deviceAlias: item.drone_callsign || item.device_sn
|| t('constants.uav'),
}));
setDevices(devData);
setPlaneDevices(planeData);
// 合并所有设备
const all = [...devData, ...planeData];
setDevicesAll(all);
} catch (err) {
console.error('数据请求失败', err);
}
};
const onViewStatus = (sn) => {
navigate(`/devices/status?sn=${sn}`);
}
const getRealtimeColor = (status: any) => {
const s = Number(status);
if (s === 1) return 'green';
if (s === 2) return 'blue';
return 'red';
};
const mapDevices = useMemo(() => {
const base = [...devices];
const knownKeys = new Set();
base.forEach((d: any) => {
const k = d?.serialNumber ?? d?.device_sn ?? d?.id;
if (k != null && k !== '') knownKeys.add(String(k));
});
// mapPush 推的是 { [设备id]: 实时记录 },同时兼容数组结构
const rtList: any[] = Array.isArray(realtimeMap) ? realtimeMap : Object.values(realtimeMap || {});
const extras = rtList
.filter((rt: any) =>
Number.isFinite(Number(rt.lng)) &&
Number.isFinite(Number(rt.lat)) &&
!(Number(rt.lng) === 0 && Number(rt.lat) === 0) &&
!knownKeys.has(String(rt.id))
)
.map((rt: any) => ({
id: rt?.id,
name: rt?.name || rt?.alias || `设备-${String(rt?.id).slice(-4)}`,
serialNumber: rt?.id,
status: rt?.status,
color: getRealtimeColor(rt?.status),
longitude: rt?.lng,
latitude: rt?.lat,
heading: rt?.yaw,
batteryLevel: rt?.battery,
updateTime: rt?.updateTime,
feStatus: rt?.feStatus,
taskId: rt?.t,
isRealtimeOnly: true,
emergencyStop: rt?.emergencyStop,
// 同步写入 locationMessage / lastRunningStatus,确保 Map.jsx 设备渲染 useEffect 能读到实时坐标
locationMessage: { longitude: rt?.lng, latitude: rt?.lat, heading: rt?.yaw, batteryLevel: rt?.battery },
lastRunningStatus: { longitude: rt?.lng, latitude: rt?.lat, heading: rt?.yaw, batteryLevel: rt?.battery },
raw: { ...rt },
}));
// 关键:把静态列表中已有设备的位置/状态用实时数据覆盖,
// 否则 base 里的设备永远只有接口返回的旧坐标,地图实体不会实时动
const rtMapDict: any = Array.isArray(realtimeMap)
? realtimeMap.reduce((acc: any, r: any, i: number) => { acc[String(r?.id ?? i)] = r; return acc; }, {})
: (realtimeMap || {});
const baseOverridden = base.map((d) => {
const k = String(d?.serialNumber ?? d?.device_sn ?? d?.id ?? "");
const rt = rtMapDict[k];
if (!rt) return { ...d, color: 'red' };
return {
...d,
longitude: rt.lng ?? d.longitude,
latitude: rt.lat ?? d.latitude,
heading: rt.yaw ?? d.heading,
batteryLevel: rt.battery ?? d.batteryLevel,
feStatus: rt.feStatus ?? d.feStatus,
status: rt.status ?? d.status,
color: getRealtimeColor(rt.status),
hasAlarm: !!rt.hasAlarm,
taskId: rt.t ?? rt.taskId ?? d.taskId,
updateTime: rt.updateTime ?? d.updateTime,
locationMessage: {
longitude: rt.lng ?? d.locationMessage?.longitude,
latitude: rt.lat ?? d.locationMessage?.latitude,
heading: rt.yaw ?? d.locationMessage?.heading,
batteryLevel: rt.battery ?? d.locationMessage?.batteryLevel,
},
lastRunningStatus: {
longitude: rt.lng ?? d.lastRunningStatus?.longitude,
latitude: rt.lat ?? d.lastRunningStatus?.latitude,
heading: rt.yaw ?? d.lastRunningStatus?.heading,
batteryLevel: rt.battery ?? d.lastRunningStatus?.batteryLevel,
},
};
});
const all = [...baseOverridden, ...extras];
return all.filter((d: any) =>
(d?.lastRunningStatus?.latitude && d?.lastRunningStatus?.longitude) ||
(d?.locationMessage?.latitude && d?.locationMessage?.longitude) ||
(d?.longitude && d?.latitude)
);
}, [devices, realtimeMap]);
const formatTime = (seconds) => {
const time = Number(seconds || 0);
if (time >= 86400) {
return `${(time / 86400).toFixed(2)} d`;
}
return `${(time / 3600).toFixed(2)} h`;
};
// 打开编辑弹窗
const openEditRobotModal = (record) => {
// 仅机器人允许编辑,无人机直接提示
const isRobot = !record.gateway_sn && !record.drone_callsign;
if (!isRobot) {
message.info(t('devices.editFixed2RobotFixed2Device'));
return;
}
setCurrentEditRobot(record);
setEditAliasInput(record.deviceAlias || record.deviceName || '');
setEditRobotModalOpen(true);
};
// 确认保存别名
const handleSaveRobotAlias = async () => {
if (!currentEditRobot || !editAliasInput.trim()) {
utils.message.warning(t('devices.fixed2Device'));
return;
}
setEditLoading(true);
try {
const data = {
deviceId: currentEditRobot.serialNumber,
deviceAlias: editAliasInput.trim()
}
const sn = currentEditRobot.device_sn || currentEditRobot.serialNumber;
const res = await updateDeviceAliasApi(data);
if (res.code === 200 && res.data == true) {
fetchAllData();
utils.message.success(t('devices.modifiedSuccessfullyFixed2'));
setEditRobotModalOpen(false);
} else {
utils.message.error(t('devices.fixed2ModificationFailed'));
}
} catch (err) {
console.error('修改别名报错', err);
utils.message.error(t('devices.fixed2Fixed2AbnormalModificationFailedFixed2'));
} finally {
setEditLoading(false);
}
};
useEffect(() => {
if (!userInfo || !stationId) return;
const controller = new DeviceController(userInfo, messageApi, stationId);
controller.initMapPush((rtMap: any) => setRealtimeMap(rtMap || {}));
// 全局推送的新告警:合并到列表顶部(按 id 去重),只显示最近 5 条
controller.onDeviceErrorPush = (payload: any) => {
const incoming: any[] = Array.isArray(payload?.alarms) ? payload.alarms : [];
setAlarmList(incoming);
};
controllerRef.current = controller;
return () => {
if (controllerRef.current) controllerRef.current.closeMapPush();
};
}, [userInfo, stationId]);
useEffect(() => {
fetchAllData();
fetchAlarmList();
fetchTaskPoolList();
}, [stationId]);
useEffect(() => {
fetchTaskStats();
}, [devicesAll.length]);
// 获取今日任务统计
const fetchTaskStats = async () => {
if (!stationId) return;
try {
const todayStart = dayjs().startOf('day').unix();
const todayEnd = dayjs().endOf('day').unix();
let completedCount = 0;
let totalCount = 0;
// 1. 获取无人机今日任务
if (planedevices?.length > 0) {
try {
const sns = planedevices.map(item => item.gateway_sn);
const droneRes = await getsinglePlan({ sns, beginAt: todayStart, endAt: todayEnd });
if (droneRes?.code === 200 && droneRes.data) {
let droneTasks = [];
Object.values(droneRes.data).forEach((item: any) => {
if (item.list) droneTasks = droneTasks.concat(item.list);
});
totalCount += droneTasks.length;
// 计算无人机完成的任务
completedCount += droneTasks.filter(t =>
['success', 'completed', 'executed', 'FINISH', 'COMPLETED'].includes(t.status)
).length;
}
} catch (err) {
console.error('获取无人机任务统计失败', err);
}
}
// 2. 获取机器人今日任务
try {
const robotRes = await getRobotTaskList({ siteId: String(stationId) });
if (robotRes?.code == 200 && robotRes.data) {
setTaskList(robotRes?.data?.slice(0, 5) ?? []);
const todayRobotTasks = robotRes.data.filter((t: any) => {
// 简单判断是今日的任务
if (t.createTime) {
const taskTime = dayjs(t.createTime);
return taskTime.isAfter(dayjs().startOf('day')) && taskTime.isBefore(dayjs().endOf('day'));
}
return true; // 默认都算
});
totalCount += todayRobotTasks.length;
// 计算机器人完成的任务
completedCount += todayRobotTasks.filter((t: any) =>
['FINISH', 'FINISHED', 'COMPLETED', 'completed'].includes(t.taskStaus)
).length;
}
} catch (err) {
console.error('获取机器人任务统计失败', err);
}
setTaskStats({ completed: completedCount, total: totalCount });
} catch (err) {
console.error('获取任务统计失败', err);
setTaskStats({ completed: 12, total: 15 });
}
};
// 当前选中设备(切换时才变)
const selectedDevice = useMemo(() => {
const sn = currentSelectedRobot || (devicesAll?.[0]?.device_sn || devicesAll?.[0]?.serialNumber);
return devicesAll?.find(item => (item.device_sn || item.serialNumber) === sn) || null;
}, [devicesAll, currentSelectedRobot]);
const isUAV = !!selectedDevice?.gateway_sn;
useEffect(() => {
if (isUAV || !selectedDevice?.serialNumber) return;
const params = {
deviceId: selectedDevice?.serialNumber,
}
getDeviceTotalData(params).then((res) => {
if (res.code == 200) {
setDeviceStatistics(res.data || {})
}
})
}, [selectedDevice])
// ======================== 核心优化:视频用设备对象(绝不随MQTT刷新)========================
const videoDevice = useMemo(() => {
if (!selectedDevice) return null;
return { ...selectedDevice };
}, [selectedDevice]); // 只有切设备才变 → 视频不闪
// ======================== UI显示用(MQTT/WS实时更新)========================
const realtimeDevice = useMemo(() => {
if (!selectedDevice) return null;
const sn = selectedDevice.device_sn || selectedDevice.serialNumber;
const wsData = realtimeMap[sn] || {};
//setDeviceStatistics(wsData || {})
return {
...selectedDevice,
...uavState,
...persistentHostData,
...persistentDroneData,
...wsData,
// 统一字段名
capacity_percent: wsData.battery_level ?? wsData.battery ?? wsData.capacity_percent ?? persistentDroneData?.capacity_percent ?? selectedDevice.capacity_percent ?? 100
};
}, [selectedDevice, uavState, persistentHostData, persistentDroneData, realtimeMap]);
// 实时数据里的急停状态同步到共享锁存状态:true=已急停,false=未急停
useEffect(() => {
syncEmergencyStop(realtimeDevice?.emergencyStop);
}, [realtimeDevice?.emergencyStop]);
// MQTT消息处理
const handleMqttMessage = useCallback((topic, message) => {
try {
const parsed = JSON.parse(message);
if (parsed.data?.host) {
const { host } = parsed.data;
// 判断是无人机数据还是机场数据:无人机数据有 battery 字段
const isDroneData = host.battery !== undefined;
if (isDroneData) {
// 处理无人机数据
setPersistentDroneData(prevData => {
const newData = { ...prevData };
// 无人机特有字段
if (host.battery?.capacity_percent !== undefined) {
newData.capacity_percent = host.battery.capacity_percent;
}
if (host.attitude_head !== undefined) {
newData.heading = host.attitude_head;
}
if (host.horizontal_speed !== undefined) {
newData.horizontal_speed = host.horizontal_speed;
}
if (host.vertical_speed !== undefined) {
newData.vertical_speed = host.vertical_speed;
}
if (host.total_flight_time !== undefined) {
newData.total_flight_time = host.total_flight_time;
}
if (host.total_flight_sorties !== undefined) {
newData.total_flight_sorties = host.total_flight_sorties;
}
if (host.mode_code !== undefined) {
newData.mode_code = host.mode_code;
}
// 通用字段
if (host.height !== undefined) {
newData.height = host.height;
}
if (host.wind_speed !== undefined) {
newData.wind_speed = host.wind_speed;
}
if (host.position_state !== undefined) {
newData.position_state = host.position_state;
}
if (host.longitude !== undefined) {
newData.longitude = host.longitude;
}
if (host.latitude !== undefined) {
newData.latitude = host.latitude;
}
return newData;
});
} else {
// 处理机场数据
setPersistentHostData(prevData => {
const newData = { ...prevData };
// 机场特有字段
if (host.drone_charge_state?.capacity_percent !== undefined) {
newData.capacity_percent = host.drone_charge_state.capacity_percent;
}
if (host.air_conditioner?.air_conditioner_state !== undefined) {
newData.air_conditioner_state = host.air_conditioner.air_conditioner_state;
}
if (host.air_conditioner_state !== undefined) {
newData.air_conditioner_state = host.air_conditioner_state;
}
// 通用字段
if (host.environment_temperature !== undefined) {
newData.environment_temperature = host.environment_temperature;
}
if (host.wind_speed !== undefined) {
newData.wind_speed = host.wind_speed;
}
if (host.rainfall !== undefined) {
newData.rainfall = host.rainfall === 0 ? 'no_rain' : 'rain';
}
if (host.humidity !== undefined) {
newData.humidity = host.humidity;
}
if (host.drone_in_dock !== undefined) {
newData.drone_in_dock = host.drone_in_dock;
}
if (host.cover_state !== undefined) {
newData.cover_state = host.cover_state;
}
if (host.temperature !== undefined) {
newData.temperature = host.temperature;
}
if (host.home_distance !== undefined) {
newData.home_distance = host.home_distance;
}
return newData;
});
}
}
} catch (err) {
console.error('MQTT解析失败', err);
}
}, []);
// MQTT订阅
const mqttTopics = useMemo(() => {
if (!isUAV || !selectedDevice) return [];
const topics = [];
if (selectedDevice.device_sn) {
topics.push(`thing/product/${selectedDevice.device_sn}/osd`);
}
if (selectedDevice.gateway_sn && selectedDevice.gateway_sn !== selectedDevice.device_sn) {
topics.push(`thing/product/${selectedDevice.gateway_sn}/osd`);
}
return topics;
}, [selectedDevice]);
useMqtt({
url: envConfig.mqtt_url,
topic: mqttTopics,
onMessage: handleMqttMessage,
enabled: mqttTopics.length > 0,
});
// 机器人视频
// 机器人视频:只有 robotPlayActive = true 才真正拉流
const { video: robotVideo, error, ready } = useWebRTCPlayer(
(!isUAV && robotPlayActive && !selectedDevice?.hasHost) ? (selectedDevice?.serialNumber || '') : '',
(!isUAV && robotPlayActive)
? `webrtc://1.95.137.212/live/livestream/${selectedDevice?.serialNumber}`
: ''
);
const getDevivePermisstion = (data) => {
const params = {
deviceId: data.serialNumber,
}
setCurrentParamDevice(data);
setParamModalOpen(true);
return;
hasPermission(params).then(res => {
if (res.code == 200) {
if (res.data) {
} else {
utils.message.error(t('devices.noPermission'));
}
}
})
}
// 手动处理告警:handleStatus=2 表示已关闭
const handleAlarmItem = async (record: any) => {
const alarmId = record?.id;
if (!alarmId) return;
try {
const res = await handleAlarm({ alarmId, handleStatus: 2 });
if (res?.code === 200) {
messageApi.success(t('alerts.handleSuccess'));
setAlarmList((prev) => prev.filter((a) => a.id !== alarmId));
} else {
messageApi.error(res?.msg || t('alerts.handleFail'));
}
} catch (err) {
console.error('处理告警失败', err);
messageApi.error(t('alerts.handleFail'));
}
};
const fetchAlarmList = async () => {
try {
const res = await getAlarmList({ pageNum: 1, pageSize: 5, siteId: stationId });
if (res.code === 200) {
setAlarmList(res.rows?.slice(0, 5) ?? []);
}
} catch (err) {
messageApi.error(t('common.loadFailed'));
} finally {
}
};
// 顶部统计卡片
//feStatus; 1任务中 / 2空闲
const dynamicTopCards = useMemo(() => {
const totalDrones = planedevices?.length || 0;
const onlineDrones = planedevices?.filter(d => {
const rt = realtimeMap[d.device_sn];
return rt ? rt.status !== 'OFFLINE' : d.onlineStatus === 1;
}).length || 0;
const totalRobots = devices?.filter(d => !d.gateway_sn).length || 0;
const onlineRobots = devices?.filter(d => {
if (d.gateway_sn) return false;
const rt = realtimeMap[d.serialNumber];
return rt ? rt.status !== 'OFFLINE' : d.onlineStatus === 1;
}).length || 0;
const activeMowers = devices?.filter(d => {
const rt = realtimeMap[d.serialNumber];
return rt ? rt.status === 'EXECUTING' : d.feStatus == 1;
}).length || 0;
const washDroneStandby = planedevices?.filter(d => {
const rt = realtimeMap[d.device_sn];
return rt ? rt.status === 'IDLE' : true; // 简化逻辑
}).length || 0;
// 今日任务执行统计
const completedTasks = taskStats.completed;
const totalTasks = taskStats.total;
const completionRate = totalTasks > 0 ? Math.round((completedTasks / totalTasks) * 100) : 0;
return [
{
title: t('devices.fixed2DroneAirportFixed2StatusFixed2'),
icon: <EnvironmentOutlined className="device-overview-top-icon-blue" />,
value: `${onlineDrones} / ${totalDrones}`,
sub: `${t('devices.distributable')} ${onlineDrones} ${t('devices.UnitsDrone')}`,
color: '#165DFF',
iconBg: '#E8F3FF'
},
{
title: t('home.inspectionRobot'),
icon: <RobotOutlined className="device-overview-top-icon-cyan" />,
value: `${onlineRobots} / ${totalRobots}`,
sub: `${t('devices.online')} ${onlineRobots}`,
color: '#13c2c2',
iconBg: '#E6FFFA'
},
{
title: t('devices.mowingRobot'),
icon: <CarOutlined className="device-overview-top-icon-purple" />,
value: `${totalRobots} ${t('devices.UnitsRobot')}`,
sub: `${t('devices.executing')} ${activeMowers}`,
color: '#722ED1',
iconBg: '#F9F0FF'
},
{
title: t('devices.washDrone'),
icon: <CloudOutlined className="device-overview-top-icon-pink" />,
value: `${totalDrones} ${t('devices.UnitsDrone')}`,
sub: `${t('devices.waiting')} ${washDroneStandby}`,
color: '#eb2f96',
iconBg: '#FFF1F3'
},
{
title: t('devices.todayTaskExecute'),
icon: <CheckCircleOutlined className="device-overview-top-icon-indigo" />,
value: `${completedTasks} / ${totalTasks}`,
sub: `${t('devices.completionRate')} ${completionRate}%`,
color: '#2f54eb',
iconBg: '#E8F3FF'
},
];
}, [devices, planedevices, realtimeMap, taskStats]);
const handleAutoBack = () => {
const payload = {
deviceId: selectedDevice?.serialNumber,
orgId: currentStation?.orgId,
siteId: stationId,
}
backToRestPointCommand(payload).then(res => {
if (res.code == 200) {
message.success(t('devices.fixed2ReturnHomeFixed2CommandIssuedFixed2'));
} else {
message.error(t('devices.fixed2ReturnHomeFixed2CommandIssuedFixed2Failed'));
}
}).catch(err => {
console.error('返回休息点失败', err);
})
}
// 设备调度列表
const dynamicScheduleList = useMemo(() => {
return devicesAll?.map((d, index) => {
const sn = d.serialNumber || d.device_sn;
const rt = realtimeMap[sn] || {};
const online = rt.status !== undefined ? (rt.status !== 'OFFLINE' ? 1 : 0) : d.onlineStatus;
// 状态 / 电量优先取实时消息
const rtFeStatus = rt?.status;
const rtBattery = rt.battery ?? rt.battery_level ?? rt.capacity_percent ?? undefined;
return {
...d,
id: d.deviceId || index,
name: d.deviceAlias || d.deviceName || d.callsign || '未知设备',
type: d.deviceType || "割草机",
status: online === 1 ? t('devices.online') : t('devices.offline'),
onlineStatus: online,
mode: rt.status === 'EXECUTING' ? '作业中' : rt.status === 'IDLE' ? t('devices.idle') : (d.feStatus == 1 ? '作业中' : d.feStatus == 2 ? t('devices.idle') : '离线'),
feStatus: rtFeStatus,
capacity_percent: rtBattery ?? d.capacity_percent ?? 100,
lastRunningStatus: {
...(d.lastRunningStatus || {}),
battery: rtBattery ?? d.lastRunningStatus?.battery ?? d?.vehicleMessage?.battery
},
position: rt.position || d.position || '站内',
task: rt.currentTaskName || d.task || (d.status === 4 ? '待命' : '作业中'),
comm: rt.rssi ? `${rt.rssi}dBm` : (d.rssi ? `${d.rssi}dBm` : '良好'),
work_area: rt.work_area || 0
};
}) || [];
}, [devicesAll, realtimeMap]);
const handleStart = () => message.success(t('devices.fixed2TaskSuspended22'));
const handlePause = () => message.info(t('devices.taskPaused'));
const handleReturn = () => message.info(t('devices.fixed2ReturnHomeFixed2CommandIssuedFixed2'));
const handleRecharge = () => message.info(t('devices.commandIssuedFixed2'));
// 急停:点击时直接下发 button7(绕过控制权限校验),并提示已触发
const handleEmergencyStop = async () => {
const next = await sendEmergencyStop(selectedDevice?.serialNumber || "");
if (next) message.error(t('devices.estopTriggered'));
else message.success(t('devices.estopNormal'));
};
const fix2 = (val) => {
if (val === null || val === undefined || isNaN(val)) return '-';
return Number(val).toFixed(2);
};
const getVal = (val) => val == "no_rain" ? "无" : (val || '-');
const handleDeviceChange = (id) => {
setCurrentSelectedRobot(id);
setRobotPlayActive(false);
};
// 获取无人机状态
useEffect(() => {
const fetchUavState = async () => {
if (isUAV && selectedDevice?.gateway_sn && selectedDevice?.device_sn) {
try {
const res = await getUAVState({
sn: selectedDevice.gateway_sn,
droneSn: selectedDevice.device_sn
});
if (res.code === 200) setUavState(res.data);
} catch (err) {
console.error('获取无人机状态失败', err);
}
} else {
setUavState(null);
}
};
fetchUavState();
}, [selectedDevice]);
return (
<div className="device-overview-page">
<div className="device-overview-title-wrap">
<Typography.Title level={4} className="device-overview-title">{t('devices.fixed2Equipment')}</Typography.Title>
</div>
<Content className="device-overview-content">
<Row gutter={[12, 12]} className="device-overview-top-row">
{dynamicTopCards.map((card, idx) => (
<Col key={idx} className="device-overview-top-col">
<Card
variant="borderless"
className="device-overview-stat-card"
>
{/* 左侧文字区域 */}
<div className="device-overview-stat-info">
<div className="device-overview-stat-title">
{card.title}
</div>
<div className="device-overview-stat-value" style={{ '--card-color': card.color } as React.CSSProperties}>
{card.value}
</div>
{/* 底部环比/备注 */}
{card.sub && <div className="device-overview-stat-sub">
{card.sub}
</div>}
</div>
{/* 右侧圆形图标区域 */}
<div
className="device-overview-stat-icon" style={{ '--icon-bg': card.iconBg || '#f0f7ff' } as React.CSSProperties}
>
{card.icon}
</div>
</Card>
</Col>
))}
</Row>
<Row gutter={[8, 8]}>
<Col xs={24} lg={14}>
<Card title={<><EnvironmentOutlined />{t('devices.fixed2Equipment')}</>} extra={<Button type="text" icon={<SettingOutlined />} />} variant="borderless" className="device-overview-card device-overview-map-card">
<div className="device-overview-map-container">
{/*<div style={{ position: 'absolute', zIndex: 11, top: 12, left: 12, background: 'rgba(255,255,255,0.95)', borderRadius: 6, padding: 8 }}>
<div style={{ fontSize: 11, fontWeight: 60, marginBottom: 4 }}>{t('devices.s22')}</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 4, fontSize: 10 }}>
<div><span style={{ color: '#1890ff' }}>———</span>{t('devices.fixed2Inspection')}</div>
<div><span style={{ color: '#fa8c16' }}>———</span>{t('devices.robotPath')}</div>
<div><span style={{ color: '#52c41a' }}>———</span>{t('devices.cleaningPath')}</div>
<div>{t('devices.locationFixed2')}</div>
<div>{t('devices.dronePositionFixed2')}</div>
<div><span style={{ color: '#1890ff' }}>●</span>{t('devices.chargePointFixed2')}</div>
<div><span style={{ color: '#ff4d4f' }}>■</span>{t('devices.s9')}</div>
</div>
</div>*/}
<CesiumMap devices={mapDevices} mapLayer={currentStation?.siteMapName} />
</div>
</Card>
<Card title={<><SettingOutlined />{t('devices.fixed2EquipmentListFixed2')}</>} extra={<Button type="text" icon={<ReloadOutlined />} onClick={fetchAllData} />} variant="borderless" className="device-overview-card">
<Table rowKey={(record) => record.id || record.serialNumber || record.device_sn} size="small" pagination={false}
columns={[
{ title: t('devices.fixed2EquipmentFixed2NameFixed2'), dataIndex: 'name', width: 180 },
{
title: t('common.type'), dataIndex: 'deviceType',
render: (text, record) => {
if (record.deviceType == "U") return t('devices.uav');
if (record.deviceType == "M") return t("devices.mower");
if (record.deviceType == "I") return t("devices.robot");
return record.deviceType || record.type || t('devices.robot');
}
},
//{
// title: t('workOrder.currentStatus'),
// dataIndex: 'onlineStatus',
// width: 70,
// render: (s) => {
// const text = s === 1 ? t('devices.online') : t('devices.offline');
// const color = s === 1 ? 'success' : 'default';
// return <Tag color={color} style={{ margin: 0 }}>{text}</Tag>;
// }
//},
{
title: t('workOrder.currentStatus'), dataIndex: 'feStatus', width: 70, render: (text) => {
let color;
if (text == '1') color = 'processing';
if (text == '2') color = 'success';
if (text == '3') color = 'default'; // default 就是灰色标签
return <Tag color={color} className="device-overview-tag-flat">
{text == '1' ? "工作中" : text == '2' ? "空闲中" : "离线"}
</Tag>;
}
},
{
title: t('devices.batteryLevel'),
dataIndex: 'lastRunningStatus',
width: 70,
render: (lastRunningStatus) => {
const v = lastRunningStatus?.battery ?? "--";
return <Progress
percent={v}
size="small"
status={v < 40 ? 'exception' : 'active'}
/>;
}
},
// { title: t('aiAnalysis.location'), dataIndex: 'position', width: 90 },
//{ title: '累计作业面积', dataIndex: 'work_area', width: 110, render: v => `${Number(v || 0).toFixed(2)} ㎡` },
//{ title: t('devices.fixed2CurrentFixed2TaskSuspended2Fixed2'), dataIndex: 'task', width: 100 },
//{ title: t('devices.statusFixed2'), dataIndex: 'comm', width: 100, render: v => <Badge status={v && v.includes('-') ? 'warning' : 'success'} text={v} /> },
{
title: t('roles.actions'),
key: 'action',
width: 150,
//fixed: 'right',
render: (_, record) => (
<Space size={4}>
<Button
size="small"
type="text"
icon={<EditOutlined />}
onClick={() => openEditRobotModal(record)}
title={t('roles.edit')}
/>
<Tooltip title={t('devices.deviceParamSetting')}>
<Button
size="small"
type="text"
icon={<SettingOutlined />}
onClick={() => {
getDevivePermisstion(record);
}}
/>
</Tooltip>
</Space>
)
}]}
dataSource={dynamicScheduleList}
scroll={{ x: 'max-content', y: 280 }}
/>
</Card>
<Row wrap={false} gutter={16} className="device-overview-panels-row">
<Col flex="1 1 0">
<Card
title={<>
<SettingOutlined /> <span>{t('devices.TaskLog')}</span>
</>}
variant="borderless"
className="device-overview-panel-card"
>
<Table
rowKey={(record) => record?.id ?? record?.alarmNo ?? record?.alarmTime}
size="small"
pagination={false}
dataSource={taskList}
scroll={{ x: 'max-content' }}
columns={[
{ title: t('common.createTime'), dataIndex: 'startTime', width: 90, render: (v) => <span className="device-overview-text-13">{v}</span> },
{ title: t('devices.deviceId'), dataIndex: 'deviceId', width: 100, render: (v) => <span className="device-overview-text-13">{v}</span> },
{
title: t('devices.executionPlan'),
width: 280,
render: (_, record) => {
const rule = record.deviceTaskPlanRules || {};
const { type, startDate, dayTime, days, dayOfMonth } = rule;
// 周映射
const weekMap = {
SUNDAY: t('devices.sun'),
MONDAY: t('devices.mon'),
TUESDAY: t('devices.tue'),
WEDNESDAY: t('devices.wed'),
THURSDAY: t('devices.thu'),
FRIDAY: t('devices.fri'),
SATURDAY: t('devices.sat')
};
switch (type) {
case 'DAY':
return t('devices.planByDay', { startDate: startDate || '', dayTime: dayTime || '' });
case 'WEEK':
const weekText = (days || []).map(d => weekMap[d]).join('、');
return t('devices.planByWeek', { weekText, dayTime: dayTime || '' });
case 'MONTH':
const monthText = (dayOfMonth || []).map(d => t('devices.daySuffix', { day: d })).join('、');
return t('devices.planByMonth', { monthText, dayTime: dayTime || '' });
default:
return t('devices.unknownPlan');
}
}
},
{
title: t('devices.executionCycle'),
width: 320,
render: (_, record) => {
return `${record.startTime || ''} - ${record.finishTime || ''}`;
}
},
{
title: t('roles.status'),
dataIndex: 'taskStaus',
width: 100,
render: (status, record) => {
console.log('status', status, record);
const statusMap = {
'NEW': { color: 'default', text: t('devices.statusNew') },
'EXECUTING': { color: 'processing', text: t('workOrder.inProgress') },
'PAUSE': { color: 'warning', text: t('devices.statusPaused') },
'FINISH': { color: 'success', text: t('devices.statusFinished') },
'FAILED': { color: 'error', text: t('devices.statusFailed') },
"CANCELING": { color: 'warning', text: t('devices.statusCanceling') },
};
const item = statusMap[status] || { color: 'default', text: record.taskStausTranslate || t('constants.locationUnknown') };
return <Tag color={item.color}>{record.taskStausTranslate}</Tag>;
}
},
{ title: t('devices.taskName'), dataIndex: 'planName' },
]}
/>
<div className="device-overview-more">
<Button type="link" size="small" className="device-overview-more-btn" onClick={() => navigate('/devices/robotTask')}>
{t('devices.viewMoreLogs')}
</Button>
</div>
</Card>
</Col>
<Col flex="1 1 0">
<Card
title={<>
<SettingOutlined /> <span>{t('devices.AlertRecord')}</span>
</>}
variant="borderless"
className="device-overview-panel-card"
>
<Table
rowKey={(record) => record?.id ?? record?.alarmNo ?? record?.alarmTitle}
size="small"
pagination={false}
dataSource={alarmList}
scroll={{ x: 'max-content' }}
columns={[
{
title: t('common.time'),
dataIndex: 'alarmTime',
width: 145,
render: (v) => <span className="device-overview-time-nowrap">{formatAlarmTime(v) || '-'}</span>
},
{
title: t('devices.device'),
dataIndex: 'deviceName',
width: 110,
ellipsis: true,
render: (v, record) => <span className="device-overview-text-12">{record?.deviceAlias || record?.deviceId || v || '-'}</span>
},
{
title: t('alerts.alarmTitle'),
dataIndex: 'alarmContent',
width: 220,
render: (_, record) => {
const text = getAlarmTitleText(record);
return (
<Tooltip title={text}>
<span className="device-overview-text-12">{text || '-'}</span>
</Tooltip>
);
}
},
{
title: t('alerts.alertLevel'),
width: 70,
render: (_, record) => <AlarmLevelTag level={resolveAlarmLevel(record)} size="small" />
},
{
title: t('alerts.handle'),
width: 70,
render: (_, record) => record?.handleStatus === 2
? <Tag className="device-overview-handled-tag">{t('alerts.handled')}</Tag>
: (
<Button type="link" size="small" className="device-overview-handle-btn" onClick={() => handleAlarmItem(record)}>
{t('alerts.handle')}
</Button>
)
},
]}
/>
<div className="device-overview-more">
<Button type="link" size="small" className="device-overview-more-btn" onClick={() => navigate('/alerts/all')}>
{t('devices.viewMoreLogs')}
</Button>
</div>
</Card>
</Col>
</Row>
</Col>
<Col xs={24} lg={10}>
<Card title={<><SettingOutlined className="device-overview-control-title-icon" />{t('devices.deviceControlPanel')}</>} variant="borderless" className="device-overview-card device-overview-control-card">
<Select
className="device-overview-device-select"
placeholder={t('workOrder.selectDeviceFixed2')}
value={selectedDevice?.device_sn || selectedDevice?.serialNumber}
onChange={handleDeviceChange}
size="small"
showSearch
allowClear
optionFilterProp="label"
filterOption={(input, option) =>
String(option?.label || "").toLowerCase().includes(input.toLowerCase())
}
options={[
{ label: <span>{t('devices.robot')}</span>, options: devices.map(item => ({ value: item.device_sn || item.serialNumber, label: item.deviceAlias || item.deviceName || '未知设备' })) },
{ label: <span>{t('constants.uav')}</span>, options: planedevices.map(item => ({ value: item.device_sn, label: item.drone_callsign || item.callsign || '未知设备' })) },
]}
/>
{selectedDevice && (
<Row gutter={8}>
<Col span={12}>
<div className="device-overview-block-12">
<div className="device-overview-device-head">
{String(selectedDevice.deviceType || '').toUpperCase() === 'U' || selectedDevice.deviceName?.includes(t('constants.uav')) || selectedDevice.drone_callsign ? (
<span className="device-overview-device-type-icon"><RocketOutlined /></span>
) : (
<span className="device-overview-device-type-icon"><CarOutlined /></span>
)}
<span className="device-overview-device-name">{selectedDevice.deviceAlias || selectedDevice.drone_callsign || selectedDevice.callsign || selectedDevice.deviceName}</span>
<Tag color={realtimeDevice.status == 1 || realtimeDevice.status == 2 ? "success" : "default"} size="small" className="device-overview-tag-flat">
{realtimeDevice.status == 1 || realtimeDevice.status == 2 ? t('devices.online') : t('devices.offline')}
</Tag>
<Button
type="primary" size="small" ghost icon={<InfoCircleOutlined />}
className="device-overview-detail-btn"
onClick={() => onViewStatus(selectedDevice.device_sn || selectedDevice.serialNumber)}
>{t('common.detail')}</Button>
</div>
<div className="device-overview-stats-row">
<div className="device-overview-stat-cell">
<span className="device-overview-battery-icon"><ThunderboltOutlined /></span>
<span className="device-overview-text-12">{t('devices.batteryLevel')}: {fix2(realtimeDevice?.battery)}%</span>
</div>
{realtimeDevice?.environment_temperature && (
<div className="device-overview-temp-cell">
<span className="device-overview-text-12">{t('home.temperature')}</span>
<span className="device-overview-temp-value">{formatTemperature(Number(realtimeDevice.environment_temperature || 25), 1).label}</span>
</div>
)}
</div>
<div className="device-overview-detail-list">
{selectedDevice.productName && (
<div className="device-overview-detail-row">
<span className="device-overview-label-12">{t('devices.productType')}</span>
<span className="device-overview-text-12">{getVal(selectedDevice.productName)}</span>
</div>
)}
<div className="device-overview-detail-row-top">
<span className="device-overview-label-nowrap">{t('systemSetting.fixed2DeviceSn')}</span>
<span className="device-overview-sn-value">
{getVal(selectedDevice.device_sn || selectedDevice.serialNumber)}
</span>
</div>
{selectedDevice.activeTime && (
<div className="device-overview-detail-row">
<span className="device-overview-label-12">{t('devices.timeFixed2')}</span>
<span className="device-overview-text-12">{selectedDevice.activeTime}</span>
</div>
)}
{selectedDevice.firmwareVersion && (
<div className="device-overview-detail-row">
<span className="device-overview-label-12">{t('devices.firmwareVersion')}</span>
<span className="device-overview-text-12">v{selectedDevice.firmwareVersion}</span>
</div>
)}
{selectedDevice.deviceType && (
<div className="device-overview-detail-row">
<span className="device-overview-label-12">{t('devices.deviceType')}</span>
<span className="device-overview-text-12">{selectedDevice.deviceType}</span>
</div>
)}
{(selectedDevice.productName?.includes(t('constants.uav')) || selectedDevice.device_sn) && (
<>
<div className="device-overview-detail-row">
<span className="device-overview-label-12">{t('devices.flightAltitude')}</span>
<span className="device-overview-text-12">{fix2(realtimeDevice?.height)} m</span>
</div>
<div className="device-overview-detail-row">
<span className="device-overview-label-12">{t('devices.s21')}</span>
<span className="device-overview-text-12">{fix2(realtimeDevice?.wind_speed)} m/s</span>
</div>
<div className="device-overview-detail-row">
<span className="device-overview-label-12">{t('devices.rtkQuantityFixed2')}</span>
<span className="device-overview-text-12">
<Badge
showZero={true}
count={realtimeDevice?.position_state?.rtk_number || 0}
className="device-overview-rtk-badge"
/>
</span>
</div>
</>
)}
</div>
<div className="device-overview-action-row">
{/*<Button type="primary" style={{ borderRadius: 8, flex: 1 }} onClick={handleStart}>{t('devices.s23')}</Button>*/}
{/*<Button style={{ borderRadius: 8, flex: 1 }} onClick={handlePause}>{t('video.pause')}</Button>*/}
<Button type="primary" className="device-overview-action-btn" onClick={handleAutoBack}>{t('devices.returnHome')}</Button>
{/*<Button style={{ flex: 1, background: '#52c41a', borderColor: '#52c41a', color: "#fff", borderRadius: 8, }} onClick={handleRecharge}>{t('devices.s24')}</Button>*/}
<Button danger={!eStopActive} type={eStopActive ? 'primary' : 'default'} style={{ flex: 1, borderRadius: 8, background: eStopActive ? '#cf1322' : undefined, borderColor: eStopActive ? '#cf1322' : undefined, color: eStopActive ? '#fff' : undefined }} onClick={handleEmergencyStop}>{eStopActive ? t('devices.estopTriggered') : t('devices.s29')}</Button>
</div>
</div>
</Col>
<Col span={12}>
<div className="device-overview-block-8">
<div className="device-overview-video-head">
<span className="device-overview-video-title">{t('devices.s25')}</span>
{!isUAV && robotPlayActive && (
<div className="device-overview-video-stop">
<Button
size="small"
danger
onClick={() => {
setRobotPlayActive(false);
}}
>{t('devices.fixed2StopFixed2VideoFixed2')}</Button>
</div>
)}
{isUAV && (
<Select
size="small"
className="device-overview-video-source-select"
value={videoSource}
onChange={setVideoSource}
options={[
{ label: t('devices.videoFixed2'), value: 'station' },
{ label: t('devices.droneVideo'), value: 'drone' },
]}
/>
)}
</div>
{/* ✅ 关键:videoDevice 绝不随MQTT更新,视频永不闪烁 */}
<div className="device-overview-video-box">
{isUAV ? (
<DroneVideoPlayer
device={videoDevice}
height={160}
showSourceSelect={false}
videoSource={videoSource}
onSourceChange={setVideoSource}
/>
) : (
robotPlayActive ? (
selectedDevice?.hasHost ? (
<div className="device-overview-video-inner">
<AgrtcRoomRobot CHANNEL={selectedDevice?.serialNumber || ''} />
</div>
) : robotVideo ? (
<VideoPlayer
deviceId={selectedDevice?.device_sn || selectedDevice?.serialNumber}
idx={mowerView === 'front' ? 1 : mowerView === 'back' ? 2 : mowerView === 'left' ? 3 : 4}
className="w-full h-full object-contain"
video={robotVideo}
error={error}
ready={ready}
/>
) : (
<div className="device-overview-video-loading">{t('video.videoLoading')}</div>
)
) : (
// ========== 未点击播放时:显示播放大按钮 ==========
<div
onClick={() => setRobotPlayActive(true)}
className="device-overview-play-overlay"
>
<div
className="device-overview-play-btn"
>
▶
</div>
</div>
)
)}
</div>
</div>
<div className="device-overview-manual-row">
{/*<Button size="large" style={{ flex: 1, borderRadius: 8 }}>{t('devices.switchManual')}</Button>*/}
</div>
</Col>
</Row>
)}
</Card>
{/*<Card title={<><ApiOutlined />{t('devices.fixed2AiActions')}</>} variant="borderless" style={{ borderRadius: 12, marginBottom: 8 }}>
<Row gutter={16} style={{ marginBottom: 8 }}>
<Col span={6}><div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '6px 12px 4px', borderRadius: 12, border: '1px solid #e8e8e8' }}><div style={{ width: 30, height: 30, borderRadius: '50%', background: 'rgba(255,77,79,0.15)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#ff4d4f', fontSize: 20 }}><span role="img" aria-label="hotspot">🔥</span></div><div><div style={{ fontSize: 11, color: '#666' }}>{t('devices.hotspotSuspect')}</div><div style={{ fontSize: 22, fontWeight: 700, color: '#222' }}>2 <span style={{ fontSize: 12 }}>{t('devices.s32')}</span></div></div></div></Col>
<Col span={6}><div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '6px 12px 4px', borderRadius: 12, border: '1px solid #e8e8e8' }}><div style={{ width: 30, height: 30, borderRadius: '50%', background: 'rgba(82,196,26,0.15)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#52c41a', fontSize: 16 }}><BranchesOutlined /></div><div><div style={{ fontSize: 11, color: '#666' }}>{t('devices.s33')}</div><div style={{ fontSize: 22, fontWeight: 700, color: '#222' }}>3 <span style={{ fontSize: 12 }}>{t('devices.s34')}</span></div></div></div></Col>
<Col span={6}><div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '6px 12px 4px', borderRadius: 12, border: '1px solid #e8e8e8' }}><div style={{ width: 30, height: 30, borderRadius: '50%', background: 'rgba(24,144,255,0.15)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#1890ff', fontSize: 16 }}><CloudOutlined /></div><div><div style={{ fontSize: 11, color: '#666' }}>{t('devices.s35')}</div><div style={{ fontSize: 22, fontWeight: 700, color: '#222' }}>4 <span style={{ fontSize: 12 }}>{t('devices.s34')}</span></div></div></div></Col>
<Col span={6}><div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '6px 12px 4px', borderRadius: 12, border: '1px solid #e8e8e8' }}><div style={{ width: 30, height: 30, borderRadius: '50%', background: 'rgba(255,77,79,0.15)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#ff4d4f', fontSize: 16 }}><WarningOutlined /></div><div><div style={{ fontSize: 11, color: '#666' }}>{t('devices.fenceAbnormal')}</div><div style={{ fontSize: 22, fontWeight: 700, color: '#ff4d4f' }}>1 <span style={{ fontSize: 12 }}>{t('devices.s32')}</span></div></div></div></Col>
</Row>
<Row gutter={16}>
<Col span={14}>
<div style={{ marginBottom: 12 }}>
<div style={{ fontSize: 16, fontWeight: 600, color: '#1890ff', marginBottom: 8 }}>{t('devices.suggestAction')}</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 2, padding: '4px', borderRadius: 12, border: '1px solid #e8e8e8' }}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}><div style={{ display: 'flex', alignItems: 'center', gap: 8 }}><span style={{ color: '#1890ff' }}>⦿</span><span style={{ fontSize: 16 }}>{t('devices.executeFixed2InspectionP03')}</span></div><ArrowRightOutlined style={{ color: '#666' }} /></div>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}><div style={{ display: 'flex', alignItems: 'center', gap: 8 }}><span style={{ color: '#1890ff' }}>⦿</span><span style={{ fontSize: 16 }}>{t('devices.taskSuspended2G02')}</span></div><ArrowRightOutlined style={{ color: '#666' }} /></div>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}><div style={{ display: 'flex', alignItems: 'center', gap: 8 }}><span style={{ color: '#1890ff' }}>⦿</span><span style={{ fontSize: 16 }}>{t('devices.generateCleaningOrderFixed2')}</span></div><ArrowRightOutlined style={{ color: '#666' }} /></div>
</div>
</div>
</Col>
<Col span={10}>
<div style={{ display: 'flex', flexDirection: 'column', paddingBottom: "12px", gap: 16, height: '100%', justifyContent: "end" }}>
<div style={{ display: 'flex', gap: 12, flexWrap: "wrap" }}>
<Button type="primary" size="middle" style={{ flex: 1, borderRadius: 8, fontSize: 14 }}>{t('devices.generateTask')}</Button>
<Button size="middle" style={{ flex: 1, borderRadius: 8, fontSize: 14, border: '1px solid #1890ff', color: '#1890ff' }}>{t('devices.aiOptimizePath')}</Button>
</div>
<Button type="primary" size="middle" style={{ borderRadius: 8, fontSize: 14 }}>{t('devices.s43')}</Button>
</div>
</Col>
</Row>
</Card>*/}
{(selectedDevice?.productName?.includes(t('constants.uav')) || selectedDevice?.device_sn) && (
<Card title={t('devices.s60')} variant="borderless" className="device-overview-weather-card">
<div className="device-overview-weather-body">
<div className="device-overview-weather-grid">
<div className="device-overview-weather-cell"><div className="device-overview-weather-cell-label">{t('devices.s44')}</div><div className="device-overview-weather-cell-value">{fix2(realtimeDevice?.wind_speed)} m/s</div></div>
<div className="device-overview-weather-cell"><div className="device-overview-weather-cell-label">{t('home.temperature')}</div><div className="device-overview-weather-cell-value">{formatTemperature(Number(realtimeDevice?.environment_temperature || 0), 1).label}</div></div>
<div className="device-overview-weather-cell"><div className="device-overview-weather-cell-label">{t('devices.rainfall')}</div><div className="device-overview-weather-cell-value">{getVal(realtimeDevice?.rainfall)}</div></div>
<div className="device-overview-weather-cell-last"><div className="device-overview-weather-cell-label">RTK</div><div className="device-overview-weather-cell-value-good">{realtimeDevice?.position_state?.is_fixed === 'fixing_successful' ? '固定' : '未固定'}</div></div>
</div>
<div className="device-overview-weather-good">
<div className="flex items-center gap-1">
<div className="device-overview-weather-good-title">{t('devices.suitableExec')}</div>
<div className="device-overview-weather-good-icon"><CheckCircleOutlined className="device-overview-weather-good-icon-mark" /></div>
</div>
<div className="device-overview-weather-good-sub">{t('devices.normal')}</div>
</div>
</div>
</Card>
)}
{(!selectedDevice?.productName?.includes(t('constants.uav')) && !selectedDevice?.device_sn) && (
<Card title={<div className="device-overview-robot-title"><RobotOutlined className="device-overview-robot-title-icon" />{t('devices.fixed2RobotStatusFixed2')}</div>} variant="borderless" className="device-overview-robot-card">
<Row gutter={16} className="device-overview-robot-stats">
<Col span={8}>
<div className="device-overview-robot-stat"
onMouseEnter={e => {
e.currentTarget.style.background = '#E8F3FF';
e.currentTarget.style.borderColor = '#165DFF';
}}
onMouseLeave={e => {
e.currentTarget.style.background = '#F7F8FA';
e.currentTarget.style.borderColor = 'transparent';
}}
>
<Statistic className="device-overview-robot-statistic"
title={<span className="device-overview-robot-stat-title">{t('devices.statTotalDistance')}(m)</span>}
value={deviceStatistics?.distance ? Number(deviceStatistics.distance).toFixed(2) : Number(deviceStatistics?.workArea / 0.7 || 0).toFixed(2)}
suffix=""
/>
</div>
</Col>
<Col span={8}>
<div className="device-overview-robot-stat"
onMouseEnter={e => {
e.currentTarget.style.background = '#E8F3FF';
e.currentTarget.style.borderColor = '#165DFF';
}}
onMouseLeave={e => {
e.currentTarget.style.background = '#F7F8FA';
e.currentTarget.style.borderColor = 'transparent';
}}
>
<Statistic className="device-overview-robot-statistic"
title={<span className="device-overview-robot-stat-title">{t('devices.s50')}(㎡)</span>}
value={Number(deviceStatistics?.workArea || 0).toFixed(2)}
suffix=""
/>
</div>
</Col>
<Col span={8}>
<div className="device-overview-robot-stat"
onMouseEnter={e => {
e.currentTarget.style.background = '#E8F3FF';
e.currentTarget.style.borderColor = '#165DFF';
}}
onMouseLeave={e => {
e.currentTarget.style.background = '#F7F8FA';
e.currentTarget.style.borderColor = 'transparent';
}}
>
<Statistic
className="device-overview-robot-statistic"
title={
<span className="device-overview-robot-stat-title">
{t('devices.s51')}
</span>
}
value={formatTime(deviceStatistics?.time)}
suffix=""
/>
</div>
</Col>
</Row>
</Card>
)}
<Card title={<><ClockCircleOutlined />{t('devices.fixed2TaskSuspended2Fixed2ExecutionTime')}</>} variant="borderless" className="device-overview-schedule-card" extra={<div className="device-overview-schedule-extra"></div>}>
{taskPoolList.length > 0 ? (
<Timeline mode="left">
{taskPoolList.map((item, idx) => (
<Timeline.Item key={idx} color={item.color} label={<div className="device-overview-timeline-label">{item.time}</div>}>
<div className="device-overview-text-13">{item.text}</div>
<div className="device-overview-timeline-label">{item.status}</div>
</Timeline.Item>
))}
</Timeline>
) : (
<Empty description={t('common.noData')} className="device-overview-empty" />
)}
<div className="device-overview-more-12"><Button type="link" onClick={() => navigate('/devices/robotTask')}>{t('devices.viewMore')}</Button></div>
</Card>
</Col>
</Row>
{/* 机器人编辑别名弹窗 */}
<Modal
title={t('devices.fixed2EditFixed2RobotFixed2DeviceFixed2InfoFixed2')}
open={editRobotModalOpen}
onCancel={() => setEditRobotModalOpen(false)}
confirmLoading={editLoading}
onOk={handleSaveRobotAlias}
maskClosable={false}
>
{currentEditRobot && (
<div className="device-overview-edit-body">
<div className="device-overview-edit-row">
<Typography.Text strong>{t('devices.fixed2Fixed2DeviceSn')}</Typography.Text>
<Typography.Text copyable>
{currentEditRobot.device_sn || currentEditRobot.serialNumber}
</Typography.Text>
</div>
<div className="device-overview-edit-row">
<Typography.Text strong>{t('devices.fixed2DeviceType')}</Typography.Text>
<Typography.Text>{currentEditRobot.productName || t('constants.locationUnknown')}</Typography.Text>
</div>
<div className="device-overview-block-8">
<Typography.Text strong>{t('devices.fixed2Device')}<span className="device-overview-required-mark">*</span></Typography.Text>
</div>
<Input
value={editAliasInput}
onChange={e => setEditAliasInput(e.target.value)}
placeholder={t('devices.fixed2PleaseEnterDevice')}
maxLength={30}
allowClear
/>
<div className="device-overview-edit-hint">{t('devices.deviceListControlDeviceFixed2')}</div>
</div>
)}
</Modal>
{/* 设备参数查看与修改弹窗(通用组件) */}
<DeviceParamModal
open={paramModalOpen}
device={currentParamDevice}
onCancel={() => {
setParamModalOpen(false);
setCurrentParamDevice(null);
}}
onSuccess={() => {
fetchAllData();
}}
/>
</Content>
</div>
);
}