import React, { useState, useEffect, useRef } from 'react';
import {
Row, Col, Card, Button, Space, Table, Tag, Typography, Progress, Badge,
Tabs, Input, Switch, Divider, Tooltip, Timeline, Select, message, DatePicker,
Modal, InputNumber
} from 'antd';
import {
PlusOutlined, ImportOutlined, NodeIndexOutlined,
SaveOutlined, FullscreenOutlined, EnvironmentOutlined,
BranchesOutlined, CloudOutlined, ThunderboltOutlined, CheckCircleOutlined,
InfoCircleOutlined, ClockCircleOutlined,
SettingOutlined, WarningOutlined, ArrowRightOutlined,
SearchOutlined, MoreOutlined, AimOutlined, PlayCircleOutlined
} from '@ant-design/icons';
import {
Plane, Navigation, Wind, Thermometer, Droplets, Satellite,
LayoutGrid, Clock, CheckCircle2, AlertCircle, Zap, Waves,
Calendar, User, TrendingUp, Maximize2, Play, Square, X, MapPin, RotateCw
} from 'lucide-react';
import {
getsinglePlan, getsinglePlanTrack, updateFlightTaskStatus, postFlightCommmand, getWayLine, createWaylineTask, getFlightTaskDetail, getSiteUAVList
} from '@/api/device';
import dayjs from 'dayjs';
import utils from '@/lib/utils';
import CesiumMap from '../Map';
import { getUAVState } from '@/api/device';
import { fix2, getVal } from '@/lib/utils';
import { useMqtt } from '@/hooks/useMqtt';
import envConfig from '../../../env';
import { useSelector } from 'react-redux';
import { RootState } from '@/store';
const { Text, Title } = Typography;
const { RangePicker } = DatePicker;
export default function WayLinePage({ onRefresh }) {
const { userInfo } = useSelector((state: RootState) => state.user);
const { stationId } = useSelector((state: RootState) => state.station);
const fontSmall = 'clamp(10px, 0.7vw, 11px)';
const fontNormal = 'clamp(12px, 0.75vw, 13px)';
const fontTitle = 'clamp(14px, 0.85vw, 16px)';
const fontLarge = 'clamp(18px, 1.1vw, 24px)';
const cardStyle = { borderRadius: 12, border: 'none', boxShadow: '0 2px 12px rgba(0,0,0,0.04)' };
// 任务列表 独立筛选状态
const [planedevices, setPlaneDevices] = useState([]);
const [listDrone, setListDrone] = useState(null);
const [listDroneRealtime, setListDroneRealtime] = useState(null);
const [listDateRange, setListDateRange] = useState(null);
const [taskList, setTaskList] = useState([]);
const [persistentDroneData, setPersistentDroneData] = useState(null); // 持久化无人机数据
const [persistentHostData, setPersistentHostData] = useState(null); // 持久化机场数据
// 获取数据
const fetchAllData = async () => {
if (!stationId) return;
try {
const planeRes = await getSiteUAVList(stationId);
// 处理无人机 + 自动补全地图需要的字段
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
|| '无人机',
}));
setPlaneDevices(planeData);
} catch (err) {
console.error('数据请求失败', err);
}
};
useEffect(() => {
fetchAllData();
}, [userInfo, stationId]);
// 当MQTT数据更新时,更新持久化数据(只在有新数据时更新)
const handleMqttMessage = (topic, message) => {
try {
const parsedMessage = JSON.parse(message);
if (parsedMessage.data && parsedMessage.data.host) {
const { host } = parsedMessage.data;
if (host?.job_number) { return; }
// 判断是无人机数据还是机场数据:无人机数据有 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('WayLinePage MQTT 消息解析失败:', err);
}
};
// 根据选中设备动态构建MQTT主题
const mqttTopics = React.useMemo(() => {
if (!listDrone) {
return [];
}
const topics = [];
if (listDrone.device_sn) {
topics.push(`thing/product/${listDrone.device_sn}/osd`);
}
if (listDrone.gateway_sn && listDrone.gateway_sn !== listDrone.device_sn) {
topics.push(`thing/product/${listDrone.gateway_sn}/osd`);
}
return topics;
}, [listDrone]);
// 订阅MQTT消息
useMqtt({
url: envConfig.mqtt_url,
topic: mqttTopics,
onMessage: handleMqttMessage,
});
// 优先使用持久化数据,保持显示稳定
const mqttDerivedData = React.useMemo(() => {
return { ...persistentHostData, ...persistentDroneData };
}, [persistentDroneData, persistentHostData]);
// 定时获取任务列表所选无人机的实时状态
useEffect(() => {
const fetchRealtime = async () => {
if (listDrone?.gateway_sn && listDrone?.device_sn) {
try {
const res = await getUAVState({
sn: listDrone.gateway_sn,
droneSn: listDrone.device_sn
});
if (res.code === 200) {
setListDroneRealtime(res.data);
}
} catch (err) {
console.error('获取列表无人机实时状态失败', err);
}
} else {
setListDroneRealtime(null);
}
};
fetchRealtime();
}, [listDrone]);
// 工作看板 独立筛选状态
const [boardDrone, setBoardDrone] = useState(null);
const [boardDateRange, setBoardDateRange] = useState(null);
const [boardTaskList, setBoardTaskList] = useState([]);
// ✅ 航线列表 独立无人机筛选(新增)
const [waylineDrone, setWaylineDrone] = useState(null);
const [focusLocation, setFocusLocation] = useState(null);
const [points, setPoints] = useState([]);
const fetchAndFocusDrone = async (drone) => {
if (!drone?.gateway_sn || !drone?.device_sn) return;
try {
const res = await getUAVState({
sn: drone.gateway_sn,
droneSn: drone.device_sn
});
if (res.code === 200 && res.data) {
setFocusLocation({
lon: res.data.longitude,
lat: res.data.latitude,
type: drone.type || 'plane',
name: drone.drone_callsign || drone.name || drone.device_sn
});
}
} catch (err) {
console.error('获取无人机位置失败', err);
}
};
// 航线列表相关状态
const [selectedWayline, setSelectedWayline] = useState(null);
const [rthModalVisible, setRthModalVisible] = useState(false);
const [tempRthAltitude, setTempRthAltitude] = useState(20);
const [waylineSearch, setWaylineSearch] = useState('');
// 任务控制相关状态
const [selectedTask, setSelectedTask] = useState(null);
const [taskstatus, setTaskStatus] = useState('suspended');
const [isReturningHome, setIsReturningHome] = useState(false);
const [isTaskPaused, setIsTaskPaused] = useState(false);
const [flightCommandLoading, setFlightCommandLoading] = useState(false);
const [loading, setLoading] = useState(false);
// ==============================================
// ✅ 创建任务弹窗相关状态(已完整整合)
// ==============================================
const [createTaskModal, setCreateTaskModal] = useState(false);
const [taskDetail, setTaskDetail] = useState(null);
const [waylineUuid, setWaylineUuid] = useState('');
const [waylineList, setWaylineList] = useState([]); // 航线列表
const [taskForm, setTaskForm] = useState({
name: '',
sn: '',
landing_dock_sn: '',
rth_altitude: 10,
rth_mode: 'optimal',
wayline_precision_type: 'gps',
resumable_status: 'auto',
min_battery_capacity: 50,
task_type: 'immediate',
repeat_type: 'nonrepeating',
repeat_option: {
interval: 1,
days_of_week: [],
days_of_month: [],
week_of_month: 1,
},
time_zone: Intl.DateTimeFormat().resolvedOptions().timeZone,
recurring_task_start_time_list: [],
});
// 根据 repeat_type 自动构建接口需要的 repeat_option
const buildRepeatOption = () => {
const { repeat_type, repeat_option } = taskForm;
const { interval, days_of_week, days_of_month, week_of_month } = repeat_option;
if (repeat_type === 'nonrepeating') return undefined;
switch (repeat_type) {
case 'daily':
return { interval: Math.max(1, interval) };
case 'weekly':
return { interval, days_of_week };
case 'absolute_monthly':
return { interval, days_of_month };
case 'relative_monthly':
return { interval, week_of_month, days_of_week };
default:
return undefined;
}
};
const fetchWaylineList = async () => {
try {
const res = await getWayLine();
if (res?.code == 200 || res?.code == 0) {
const _list = res?.data?.list.map(item => {
return {
...item,
label: item.name || `航线_${item.id || '未知'}`,
value: item.id
}
})
setWaylineList(_list || []);
}
} catch (err) {
message.error('获取航线列表失败');
}
};
// 关闭弹窗重置
const resetModals = () => {
setCreateTaskModal(false);
setWaylineUuid('');
setTaskForm({
name: '',
sn: waylineDrone?.gateway_sn || '',
landing_dock_sn: '',
rth_altitude: 10,
rth_mode: 'optimal',
wayline_precision_type: 'gps',
resumable_status: 'auto',
min_battery_capacity: 50,
task_type: 'immediate',
repeat_type: 'nonrepeating',
repeat_option: { interval: 1 },
time_zone: Intl.DateTimeFormat().resolvedOptions().timeZone,
begin_at: null,
end_at: null,
recurring_task_start_time_list: [],
});
};
// 创建任务提交
const createFlightTask = async () => {
if (!taskForm.name || !waylineUuid || !taskForm.sn) {
utils.message.warning('请完善必填项');
return;
}
setLoading(true);
try {
const payload = {
...taskForm,
wayline_uuid: waylineUuid,
repeat_type: taskForm.repeat_type,
repeat_option: buildRepeatOption(),
recurring_task_start_time_list: taskForm.recurring_task_start_time_list.map(t => dayjs(t).unix()),
};
const res: any = await createWaylineTask(payload);
if (res.code === 200 || res.code === 0) {
utils.message.success('创建任务成功');
resetModals();
getListTask();
if (onRefresh) onRefresh();
} else {
utils.message.error(res.msg || '创建失败');
}
} catch (err) {
utils.message.error('创建异常');
} finally {
setLoading(false);
}
};
// 航线列表无人机变更时同步到表单
useEffect(() => {
if (waylineDrone) {
setTaskForm(prev => ({
...prev,
sn: waylineDrone.gateway_sn || ''
}));
}
}, [waylineDrone]);
// 顶部统计
const [todayCount, setTodayCount] = useState(0);
const [yesterdayCount, setYesterdayCount] = useState(0);
const [trend, setTrend] = useState('');
const [trendColor, setTrendColor] = useState('');
// 计算今日/昨日任务数量
const calcTodayTaskCount = () => {
if (!taskList?.length) return;
const todayStart = dayjs().startOf('day').valueOf();
const todayEnd = dayjs().endOf('day').valueOf();
const yesterdayStart = dayjs().subtract(1, 'day').startOf('day').valueOf();
const yesterdayEnd = dayjs().subtract(1, 'day').endOf('day').valueOf();
const todayTotal = taskList.filter(t => {
const time = dayjs(t.begin_at).valueOf();
return time >= todayStart && time <= todayEnd;
}).length;
const yesterdayTotal = taskList.filter(t => {
const time = dayjs(t.begin_at).valueOf();
return time >= yesterdayStart && time <= yesterdayEnd;
}).length;
const diff = todayTotal - yesterdayTotal;
let trendText = '';
let color = '#00B42A';
if (diff > 0) {
trendText = `较昨日 +${diff}`;
color = '#00B42A';
} else if (diff < 0) {
trendText = `较昨日 ${diff}`;
color = '#F53F3F';
} else {
trendText = '较昨日 持平';
color = '#86909C';
}
setTodayCount(todayTotal);
setYesterdayCount(yesterdayTotal);
setTrend(trendText);
setTrendColor(color);
};
useEffect(() => {
calcTodayTaskCount();
}, [taskList]);
// 获取任务列表数据
const getListTask = async () => {
if (!planedevices?.length) return;
try {
const defaultStart = dayjs().startOf('day').unix();
const defaultEnd = dayjs().endOf('day').unix();
const [beginAt, endAt] = listDateRange?.length === 2
? [dayjs(listDateRange[0]).unix(), dayjs(listDateRange[1]).unix()]
: [defaultStart, defaultEnd];
const sns = listDrone ? [listDrone.gateway_sn] : planedevices.map(item => item.gateway_sn);
const res = await getsinglePlan({ sns, beginAt, endAt });
if (res?.code === 200) {
let combinedList = [];
if (res.data) {
Object.values(res.data).forEach((item: any) => {
if (item.list) combinedList = combinedList.concat(item.list);
});
}
setTaskList(combinedList);
}
} catch (err) {
message.error('任务列表数据获取失败');
}
};
// 获取看板任务数据
const getBoardTask = async () => {
if (!planedevices?.length) return;
try {
const defaultStart = dayjs().startOf('day').unix();
const defaultEnd = dayjs().endOf('day').unix();
const [beginAt, endAt] = boardDateRange?.length === 2
? [dayjs(boardDateRange[0]).unix(), dayjs(boardDateRange[1]).unix()]
: [defaultStart, defaultEnd];
const sns = boardDrone ? [boardDrone.gateway_sn] : planedevices.map(item => item.gateway_sn);
const res = await getsinglePlan({ sns, beginAt, endAt });
if (res?.code === 200) {
let combinedList = [];
if (res.data) {
Object.values(res.data).forEach((item: any) => {
if (item.list) combinedList = combinedList.concat(item.list);
});
}
setBoardTaskList(combinedList);
}
} catch (err) {
message.error('任务看板数据获取失败');
}
};
useEffect(() => {
fetchWaylineList();
}, [])
// 初始化默认设备
useEffect(() => {
if (planedevices?.length) {
setListDrone(planedevices[0]);
setWaylineDrone(planedevices[0]); // 航线列表默认选中第一个
setBoardDrone(null);
}
}, [planedevices]);
useEffect(() => {
getListTask();
}, [listDrone, listDateRange]);
useEffect(() => {
getBoardTask();
}, [boardDrone, boardDateRange, planedevices?.length]);
const realtimePosition = React.useMemo(() => {
if (persistentDroneData?.longitude && persistentDroneData?.latitude) {
return {
lon: persistentDroneData.longitude,
lat: persistentDroneData.latitude,
heading: persistentDroneData.heading || 0,
};
}
}, [persistentDroneData]);
// 任务状态标签
const getStatusTag = (status) => {
const statusMap = {
success: { color: 'success', text: '执行成功' },
preparing: { color: 'blue', text: '准备中' },
running: { color: 'processing', text: '执行中' },
failed: { color: 'error', text: '执行失败' },
waiting: { color: 'default', text: '待开始' },
starting_failure: { color: 'error', text: '启动失败' },
executing: { color: 'processing', text: '执行中' },
suspended: { color: 'warning', text: '已挂起' },
restored: { color: 'processing', text: '恢复执行' },
terminated: { color: 'default', text: '已终止' },
timeout: { color: 'error', text: '执行超时' },
};
const item = statusMap[status] || { color: 'default', text: status };
return