import React, { useState, useEffect } 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 } 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 } from '@/api/device'; import dayjs from 'dayjs'; import utils from '@/lib/utils'; import CesiumMap from '../Map'; const { Text, Title } = Typography; const { RangePicker } = DatePicker; export default function WayLinePage({ planedevices }) { 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 [listDrone, setListDrone] = useState(null); const [listDateRange, setListDateRange] = useState(null); const [taskList, setTaskList] = useState([]); // 工作看板 独立筛选状态 const [boardDrone, setBoardDrone] = useState(null); const [boardDateRange, setBoardDateRange] = useState(null); const [boardTaskList, setBoardTaskList] = useState([]); const [points, setPoints] = 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: 100, 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 || []); // 取list数组 } } catch (err) { message.error('获取航线列表失败'); } }; // 关闭弹窗重置 const resetModals = () => { setCreateTaskModal(false); setWaylineUuid(''); setTaskForm({ name: '', sn: listDrone?.gateway_sn || '', landing_dock_sn: '', rth_altitude: 100, 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, //task_type: 'recurring', 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(); // 刷新列表 } else { utils.message.error(res.msg || '创建失败'); } } catch (err) { utils.message.error('创建异常'); } finally { setLoading(false); } }; // 选中无人机时自动填充机场SN useEffect(() => { if (listDrone) { setTaskForm(prev => ({ ...prev, sn: listDrone.gateway_sn || '' })); } }, [listDrone]); // 顶部统计 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) { // 处理嵌套数据结构:data: { [sn]: { list: [] } } 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]); // 默认显示第一个无人机 setBoardDrone(null); // 默认显示所有 } }, [planedevices]); // 各自筛选变更独立请求 useEffect(() => { getListTask(); }, [listDrone, listDateRange]); useEffect(() => { getBoardTask(); }, [boardDrone, boardDateRange]); // 任务状态标签 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 {item.text}; }; // 列表表格列 const taskColumns = [ { title: '任务名称', dataIndex: 'name', width: 260, ellipsis: true, fixed: "left" }, //{ title: '任务UUID', dataIndex: 'uuid', width: 260, ellipsis: true }, { title: '设备SN', dataIndex: 'sn', width: 140 }, { title: '状态', dataIndex: 'status', width: 80, render: getStatusTag }, { title: '开始时间', dataIndex: 'begin_at', width: 170, render: t => t ? dayjs(t).format('YYYY-MM-DD HH:mm:ss') : '-' }, { title: '结束时间', dataIndex: 'end_at', width: 170, render: t => t ? dayjs(t).format('YYYY-MM-DD HH:mm:ss') : '-' }, ]; // 表格行点击查看轨迹 const handleRowClick = async (record) => { setSelectedTask(record); // 记录当前选中的任务 try { getTaskDetail(record.uuid); // 获取任务详情 const res = await getsinglePlanTrack(record); if (res.code === 0 && res.data.track?.points?.length) { const points = res.data.track.points.map(item => ({ lon: item.longitude || item.lon, lat: item.latitude || item.lat })); setPoints(points); } else { utils.message.warning("暂无航线数据"); setPoints([]); } } catch (err) { message.error('请求失败'); console.error(err); } }; // 看板数据分组处理 const groupBoardData = () => { // 待执行 = 准备中 + 待开始 + 已挂起 + 已终止 const waitList = boardTaskList.filter(item => ['preparing', 'waiting', 'suspended', 'terminated'].includes(item.status) ); // 执行中 = 运行中 + 执行中 + 恢复执行 const runList = boardTaskList.filter(item => ['running', 'executing', 'restored'].includes(item.status) ); // 已完成 = 执行成功 const finishList = boardTaskList.filter(item => ['success'].includes(item.status) ); return { waitList, runList, finishList }; }; const { waitList, runList, finishList } = groupBoardData(); const topCards = [ { title: '今日航线计划', value: todayCount, unit: '条', trend: trend, trendColor: trendColor, icon: , color: '#165DFF' }, { title: '执行中任务', value: runList.length, unit: '个', desc: '进行中', icon: , color: '#165DFF' }, { title: '待审批任务', value: '4', unit: '个', trend: '较昨日 -1', trendColor: '#F53F3F', icon: , color: '#FF7D00' }, { title: '任务完成率', value: finishList.length ? Math.round((finishList.length / taskList.length) * 100) : 0, unit: '%', trend: '较昨日 +6%', trendColor: '#00B42A', icon: , color: '#00B42A' }, { title: 'AI 优化收益', value: '+7.8', unit: '%', trend: '较昨日 +1.2%', trendColor: '#00B42A', icon: , color: '#722ED1' }, { title: '覆盖装备', value: '4 类 / 9 台', unit: '', desc: '全部在线', icon: , color: '#165DFF' }, ]; // 指令下发逻辑 const sendFlightCommand = async (command: 'return_home' | 'return_home_cancel' | 'flighttask_pause' | 'flighttask_recovery') => { if (!listDrone?.device_sn) { utils.message.warning('未选中无人机或无人机SN不存在'); return; } setFlightCommandLoading(true); const data = { command, deviceSn: listDrone.device_sn, } try { const res: any = await postFlightCommmand(data); if (res.code === 200 || res.code === 0) { utils.message.success('指令下发成功'); // 切换状态 if (command === 'return_home') setIsReturningHome(true); if (command === 'return_home_cancel') setIsReturningHome(false); if (command === 'flighttask_pause') setIsTaskPaused(true); if (command === 'flighttask_recovery') setIsTaskPaused(false); } else { utils.message.error(res.msg || '指令下发失败'); } } catch (err) { utils.message.error('接口请求异常'); } finally { setFlightCommandLoading(false); } }; const getTaskDetail = async (taskId) => { console.log('获取任务详情,taskId=', taskId); if (!taskId) return; setTaskDetail(null); setLoading(true); try { const res = await getFlightTaskDetail(taskId); if (res.code === 0) { setTaskDetail(res.data); } else { setTaskDetail(null); utils.message.error('暂无详情'); } } catch (err) { setTaskDetail(null); utils.message.error('获取详情接口异常'); } finally { setLoading(false); } }; // 任务状态更新逻辑 const updateTaskStatus = async (taskId: string, status: string) => { if (!taskId) { utils.message.warning('请先选择航线任务'); return; } setLoading(true); try { const res: any = await updateFlightTaskStatus(taskId, status); if (res.code === 200 || res.code === 0) { const statusText = { executing: '任务执行成功', suspended: '任务已挂起', restored: '任务已继续', return_home: '任务已返航' }[status] || '状态更新成功'; if (status === "suspended") { setTaskStatus('suspended'); } else { setTaskStatus('restored'); } utils.message.success(statusText); // 刷新任务列表 getListTask(); } else { utils.message.error(res.msg || '操作失败'); } } catch (err) { utils.message.error('操作接口异常'); } finally { setLoading(false); } }; return (
{topCards.map((item, index) => (
{React.cloneElement(item.icon, { size: 18 })}
{item.title}
{item.value} {item.unit}
{item.trend || item.desc}
))}
{/* 地图卡片 */} 航线编辑与路径规划} size="small" extra={
} bordered={false} bodyStyle={{ padding: 16 }} style={{ ...cardStyle, height: '100%', maxHeight: 480, overflow: "auto" }} > {[ { title: '待执行', count: waitList.length, color: '#4E5969', bg: '#F7F8FA', list: waitList.map(item => ({ id: item.sn?.slice(-5) || '', name: item.name, device: item.sn, begin_at: '' })) }, { title: '执行中', count: runList.length, color: '#165DFF', bg: '#E8F3FF', list: runList.map(item => ({ id: item.sn?.slice(-5) || '', name: item.name, device: item.sn, begin_at: '' })) }, { title: '已完成', count: finishList.length, color: '#00B42A', bg: '#E8FFEA', list: finishList.map(item => ({ id: item.sn?.slice(-5) || '', name: item.name, device: item.sn, begin_at: item.begin_at, completed_at: item.completed_at })) }, ].map((col, idx) => (
{col.title} ({col.count})
{col.list.map((task, tidx) => (
{task.name}
装备: {task.device || 'UAV-A01'}
{task.begin_at &&
开始时间: {task.begin_at}
} {task.completed_at &&
完成时间: {task.completed_at}
}
))}
))}
{/*
*/} {/* ============================================== */}
{/* 基础信息 */}
setTaskForm({ ...taskForm, name: e.target.value })} placeholder="请输入" />
setTaskForm({ ...taskForm, landing_dock_sn: e.target.value })} />
{/* 飞行参数 */}
setTaskForm({ ...taskForm, rth_altitude: v })} style={{ width: '100%' }} />
setTaskForm({ ...taskForm, wayline_precision_type: v })} options={[{ label: 'GPS', value: 'gps' }, { label: 'RTK', value: 'rtk' }]} style={{ width: '100%' }} />
setTaskForm({ ...taskForm, task_type: v })} options={[ { label: '立即', value: 'immediate' }, //{ label: '单次定时', value: 'timed' }, //{ label: '重复', value: 'recurring' }, //{ label: '连续', value: 'continuous' }, ]} style={{ width: '100%' }} />
{/* 时间选择 */} {(taskForm.task_type === 'timed' || taskForm.task_type === 'recurring' || taskForm.task_type === 'continuous') && (
setTaskForm({ ...taskForm, begin_at: v })} style={{ width: '100%' }} />
{(taskForm.task_type === 'recurring' || taskForm.task_type === 'continuous') && (
setTaskForm({ ...taskForm, end_at: v })} style={{ width: '100%' }} />
)}
)} {/* 重复任务配置 repeat_option 对象绑定 */} {taskForm.task_type === 'recurring' && ( <>
setTaskForm({ ...taskForm, repeat_option: { ...taskForm.repeat_option, days_of_week: v } })} options={[ { label: '周日', value: 0 }, { label: '周一', value: 1 }, { label: '周二', value: 2 }, { label: '周三', value: 3 }, { label: '周四', value: 4 }, { label: '周五', value: 5 }, { label: '周六', value: 6 } ]} style={{ width: '100%' }} />
)} {/* 按月日期 */} {taskForm.repeat_type === 'absolute_monthly' && (
setTaskForm({ ...taskForm, repeat_option: { ...taskForm.repeat_option, week_of_month: v } })} options={[1, 2, 3, 4].map(w => ({ label: `第${w}周`, value: w }))} style={{ width: '100%' }} />
setTaskForm({ ...taskForm, recurring_task_start_time_list: v })} placeholder="输入时间戳" style={{ width: '100%' }} />
)} {/* 按钮 */}
); }