Files
gofly-platform-services/zlt-web/yingyan/src/pages/dashboard/index.tsx
T

507 lines
18 KiB
TypeScript

import React, { useState, useEffect, useCallback, useMemo } from 'react';
import { Card, Button, List, Tag, Spin, message, DatePicker, Segmented, Space } from 'antd';
import {
DesktopOutlined,
WarningOutlined,
RocketOutlined,
EnvironmentOutlined,
PieChartOutlined,
FieldTimeOutlined
} from '@ant-design/icons';
import { Line, Pie, Column, Area, Rose } from '@ant-design/plots';
import { history } from 'umi';
import dayjs from 'dayjs';
import {
getDeviceStats,
getTaskStats,
getTrendData,
getMockAlerts,
DeviceStats,
TaskStats,
TrendItem,
AlertItem,
} from '@/services/dashboard';
import './index.less';
const Dashboard: React.FC = () => {
const [loading, setLoading] = useState(true);
const [deviceStats, setDeviceStats] = useState<DeviceStats | null>(null);
const [taskStats, setTaskStats] = useState<TaskStats | null>(null);
const [taskTrend, setTaskTrend] = useState<TrendItem[]>([]);
const [alerts, setAlerts] = useState<AlertItem[]>([]);
const [annualData, setAnnualData] = useState<any[]>([]);
const [failureAnalysisData, setFailureAnalysisData] = useState<any[]>([]);
const [taskTypeData, setTaskTypeData] = useState<any[]>([]);
const [taskStatType, setTaskStatType] = useState<'day' | 'month' | 'year'>('day');
const [taskStatDate, setTaskStatDate] = useState(dayjs());
const [tenantId, setTenantId] = useState<string | undefined>();
const [includeChildren, setIncludeChildren] = useState<boolean>(true);
useEffect(() => {
// 模拟年度数据
const mockAnnual: any[] = [];
for (let i = 1; i <= 12; i++) {
mockAnnual.push({
month: `${i}月`,
value: Math.floor(Math.random() * 500) + 100,
type: '任务总数',
});
mockAnnual.push({
month: `${i}月`,
value: Math.floor(Math.random() * 450) + 80,
type: '成功任务',
});
}
setAnnualData(mockAnnual);
// 模拟失败原因数据
setFailureAnalysisData([
{ type: '信号丢失', value: 27 },
{ type: '电池不足', value: 25 },
{ type: '天气原因', value: 18 },
{ type: '机械故障', value: 15 },
{ type: '人为取消', value: 10 },
{ type: '其他', value: 5 },
]);
// 任务类型分布数据
setTaskTypeData([
{ type: '航线任务', value: 156 },
{ type: '一键起飞', value: 89 },
{ type: '手动控制', value: 45 },
]);
}, []);
useEffect(() => {
const handler = (e: any) => {
const nextTenantId = e?.detail?.tenantId as string | undefined;
const nextIncludeChildren = !!e?.detail?.includeChildren;
setTenantId(nextTenantId);
setIncludeChildren(nextIncludeChildren);
};
window.addEventListener('tenant-change', handler as any);
return () => window.removeEventListener('tenant-change', handler as any);
}, []);
const fetchData = useCallback(async () => {
setLoading(true);
try {
const [deviceRes, taskRes, trendRes] = await Promise.all([
getDeviceStats({ tenantId, includeChildren }),
getTaskStats({
tenantId,
includeChildren,
statType: taskStatType,
date:
taskStatType === 'day'
? taskStatDate.format('YYYY-MM-DD')
: taskStatType === 'month'
? taskStatDate.format('YYYY-MM')
: taskStatDate.format('YYYY'),
}),
getTrendData(7),
]);
setDeviceStats(deviceRes);
setTaskStats(taskRes);
setTaskTrend(trendRes.taskTrend);
setAlerts(getMockAlerts());
} catch (error) {
console.error('获取数据失败:', error);
message.error('数据加载异常');
} finally {
setLoading(false);
}
}, [includeChildren, taskStatDate, taskStatType, tenantId]);
useEffect(() => {
if (!tenantId) return;
fetchData();
}, [fetchData]);
// 定时刷新和时间更新
useEffect(() => {
const dataTimer = setInterval(fetchData, 30000);
return () => {
clearInterval(dataTimer);
};
}, [fetchData]);
const goTo3D = () => {
// 传递来源页面,以便从map3d返回时能回到正确的大屏
history.push('/map3d?from=dashboard');
};
// --- 图表配置 ---
const taskTrendSeriesData = useMemo(() => {
return taskTrend.flatMap((t) => [
{ date: t.date, type: '创建', value: t.created || 0 },
{ date: t.date, type: '完成', value: t.completed || 0 },
{ date: t.date, type: '失败', value: t.failed || 0 },
]);
}, [taskTrend]);
// 近7日任务完成数趋势数据
const taskCompleteTrendData = useMemo(() => {
return taskTrend.map((t) => ({
date: t.date,
value: t.completed || 0,
}));
}, [taskTrend]);
const taskTrendConfig: any = {
data: taskTrendSeriesData,
xField: 'date',
yField: 'value',
seriesField: 'type',
smooth: true,
color: ['#00d4ff', '#00ff88', '#ffb800'],
areaStyle: {
fill: 'l(270) 0:#ffffff 0.5:#7ec2f3 1:#1890ff',
fillOpacity: 0.1,
},
xAxis: { label: { style: { fill: 'rgba(255,255,255,0.65)' } }, grid: null },
yAxis: { label: { style: { fill: 'rgba(255,255,255,0.65)' } }, grid: { line: { style: { stroke: 'rgba(255,255,255,0.1)' } } } },
tooltip: { showMarkers: true },
height: 180,
};
const pieConfig: any = {
data: deviceStats?.byType || [],
angleField: 'count',
colorField: 'name',
radius: 0.7,
innerRadius: 0.5,
label: {
text: (datum: any) => {
const name = datum?.name || '';
const count = datum?.count ?? 0;
const data = (deviceStats?.byType || []) as { name: string; count: number }[];
const total = data.reduce((sum, d) => sum + (d.count || 0), 0);
const percent = total > 0 ? ((count / total) * 100).toFixed(1) : 0;
return `${name} ${percent}%`;
},
style: { fill: 'rgba(255,255,255,0.65)' },
},
legend: { position: 'bottom', itemValue: { style: { fill: 'rgba(255,255,255,0.65)' } }, itemName: { style: { fill: 'rgba(255,255,255,0.65)' } } },
height: 200,
};
const columnConfig: any = {
data: taskTypeData,
xField: 'type',
yField: 'value',
seriesField: 'type',
color: ({ type }: any) => {
if(type === '航线任务') return '#00d4ff';
if(type === '一键起飞') return '#00ff88';
return '#ffb800';
},
label: {
text: (datum: any) => datum?.value?.toString() || '0',
style: { fill: '#fff' },
},
xAxis: { label: { style: { fill: 'rgba(255,255,255,0.65)' } } },
yAxis: { label: { style: { fill: 'rgba(255,255,255,0.65)' } }, grid: { line: { style: { stroke: 'rgba(255,255,255,0.1)' } } } },
legend: false,
height: 180,
};
const taskCompleteTrendConfig: any = {
data: taskCompleteTrendData,
xField: 'date',
yField: 'value',
smooth: true,
color: '#00ff88',
areaStyle: { fillOpacity: 0.15 },
xAxis: { label: { style: { fill: 'rgba(255,255,255,0.65)' } }, grid: null },
yAxis: {
label: { style: { fill: 'rgba(255,255,255,0.65)' } },
grid: { line: { style: { stroke: 'rgba(255,255,255,0.08)' } } },
},
tooltip: { showMarkers: true },
height: 160,
};
const areaConfig: any = {
data: annualData,
xField: 'month',
yField: 'value',
seriesField: 'type',
color: ['#00d4ff', '#00ff88'],
areaStyle: { fillOpacity: 0.3 },
xAxis: { label: { style: { fill: 'rgba(255,255,255,0.65)' } } },
yAxis: { label: { style: { fill: 'rgba(255,255,255,0.65)' } }, grid: { line: { style: { stroke: 'rgba(255,255,255,0.1)' } } } },
legend: { position: 'top-right', itemName: { style: { fill: '#fff' } } },
smooth: true,
height: 220,
};
const roseConfig: any = {
data: failureAnalysisData,
xField: 'type',
yField: 'value',
seriesField: 'type',
radius: 0.9,
label: {
text: (datum: any) => datum?.type || '',
style: { fill: '#fff' },
},
legend: { position: 'bottom', itemName: { style: { fill: 'rgba(255,255,255,0.65)' } } },
height: 200,
};
const taskStatusPieConfig: any = {
data: [
{ name: '待执行', value: taskStats?.pending || 0 },
{ name: '执行中', value: taskStats?.running || 0 },
{ name: '已完成', value: taskStats?.completed || 0 },
{ name: '已失败', value: taskStats?.failed || 0 },
],
angleField: 'value',
colorField: 'name',
radius: 0.85,
innerRadius: 0.55,
label: {
text: (datum: any) => {
const name = datum?.name || '';
const value = datum?.value ?? 0;
const total = (taskStats?.pending || 0) + (taskStats?.running || 0) + (taskStats?.completed || 0) + (taskStats?.failed || 0);
const percent = total > 0 ? ((value / total) * 100).toFixed(1) : 0;
return `${name} ${percent}%`;
},
style: { fill: 'rgba(255,255,255,0.65)' },
},
legend: { position: 'bottom', itemValue: { style: { fill: 'rgba(255,255,255,0.65)' } }, itemName: { style: { fill: 'rgba(255,255,255,0.65)' } } },
height: 190,
};
const getAlertColor = (level: string) => {
switch (level) {
case 'critical': return 'red';
case 'error': return 'orange';
case 'warning': return 'gold';
default: return 'blue';
}
};
const taskPeriodText = useMemo(() => {
if (taskStatType === 'day') return '当日';
if (taskStatType === 'month') return '当月';
return '当年';
}, [taskStatType]);
const taskNewLabel = useMemo(() => {
if (taskStatType === 'day') return '当日任务';
if (taskStatType === 'month') return '当月任务';
return '当年任务';
}, [taskStatType]);
const datePickerFormat = useMemo(() => {
if (taskStatType === 'day') return 'YYYY-MM-DD';
if (taskStatType === 'month') return 'YYYY-MM';
return 'YYYY';
}, [taskStatType]);
return (
<div className="dashboard-page">
<div className="dashboard-bg-animation"></div>
<Spin spinning={loading} wrapperClassName="dashboard-spin">
<div className="dashboard-content">
<div className="dashboard-grid">
{/* 左侧栏:设备态势 */}
<div className="grid-col left-col">
<Card title="设备类型分布" className="panel-card glass-panel" size="small">
<div className="chart-wrapper">
<Pie {...pieConfig} />
</div>
</Card>
<Card title="任务类型统计" className="panel-card glass-panel" size="small">
<div className="chart-wrapper">
<Column {...columnConfig} />
</div>
</Card>
<Card title="近7日任务完成趋势" className="panel-card glass-panel" size="small">
<div className="chart-wrapper">
<Area {...taskCompleteTrendConfig} />
</div>
</Card>
<Card
title={<span><WarningOutlined className="icon-warning" /> 实时告警</span>}
className="panel-card glass-panel flex-grow"
size="small"
extra={<Tag color="#f50">Live</Tag>}
>
<div className="alert-list-container">
<List
dataSource={alerts}
split={false}
renderItem={(item) => (
<List.Item className="alert-item">
<div className="alert-row">
<div className="alert-badge">
<Tag color={getAlertColor(item.level)}>{item.level.toUpperCase().slice(0,1)}</Tag>
</div>
<div className="alert-content">
<div className="alert-head">
<span className="alert-name">{item.deviceName || item.taskName}</span>
<span className="alert-time">{dayjs(item.timestamp).format('HH:mm')}</span>
</div>
<div className="alert-msg">{item.message}</div>
</div>
</div>
</List.Item>
)}
/>
</div>
</Card>
</div>
{/* 中间栏:核心监控 */}
<div className="grid-col center-col">
{/* 顶部KPI */}
<div className="kpi-row">
<div className="kpi-card">
<div className="kpi-icon blue"><DesktopOutlined /></div>
<div className="kpi-info">
<div className="label">设备总数</div>
<div className="value">{deviceStats?.total || 0}</div>
</div>
</div>
<div className="kpi-card">
<div className="kpi-icon green"><EnvironmentOutlined /></div>
<div className="kpi-info">
<div className="label">景区总数</div>
<div className="value">{deviceStats?.tourismCount || 0}</div>
</div>
</div>
<div className="kpi-card">
<div className="kpi-icon yellow"><RocketOutlined /></div>
<div className="kpi-info">
<div className="label">{taskNewLabel}</div>
<div className="value">{taskStats?.todayNew || 0}</div>
</div>
</div>
<div className="kpi-card">
<div className="kpi-icon purple"><PieChartOutlined /></div>
<div className="kpi-info">
<div className="label">执行成功率</div>
<div className="value">{taskStats?.successRate || 0}<small>%</small></div>
</div>
</div>
</div>
{/* 地图/3D入口 */}
<div className="map-portal-wrapper">
<div className="map-bg-grid"></div>
<div className="radar-sweep"></div>
<div className="map-content">
<div className="portal-center">
<EnvironmentOutlined style={{ fontSize: 56, color: '#00d4ff', marginBottom: 20 }} />
<h2 className="portal-title">全域数字孪生监控中心</h2>
<Button type="primary" shape="round" size="large" onClick={goTo3D} className="portal-btn">
立即进入监控视图
</Button>
</div>
</div>
</div>
{/* 底部年度统计 */}
<Card title="年度任务执行趋势分析" className="panel-card glass-panel fill-bottom" size="small">
<div className="chart-wrapper">
<Area {...areaConfig} />
</div>
</Card>
</div>
{/* 右侧栏:任务与运维 */}
<div className="grid-col right-col">
<Card
title={`${taskPeriodText}任务统计`}
className="panel-card glass-panel"
size="small"
extra={
<Space size={8} className="task-filter">
<Segmented
size="small"
options={[
{ label: '日', value: 'day' },
{ label: '月', value: 'month' },
{ label: '年', value: 'year' },
]}
value={taskStatType}
onChange={(v) => setTaskStatType(v as any)}
/>
<DatePicker
size="small"
value={taskStatDate}
onChange={(v) => v && setTaskStatDate(v)}
picker={taskStatType === 'day' ? 'date' : taskStatType}
allowClear={false}
format={datePickerFormat}
disabledDate={(d) => !!d && d.isAfter(dayjs(), 'day')}
/>
</Space>
}
>
<div className="task-overview-grid">
<div className="task-stat-box">
<div className="val pending">{taskStats?.pending || 0}</div>
<div className="lbl">待执行</div>
</div>
<div className="task-stat-box">
<div className="val running">{taskStats?.running || 0}</div>
<div className="lbl">执行中</div>
</div>
<div className="task-stat-box">
<div className="val completed">{taskStats?.completed || 0}</div>
<div className="lbl">已完成</div>
</div>
<div className="task-stat-box">
<div className="val failed">{taskStats?.failed || 0}</div>
<div className="lbl">已失败</div>
</div>
</div>
<div style={{ marginTop: 16, textAlign: 'center' }}>
<div style={{ fontSize: '32px', fontWeight: 'bold', color: '#00ff88' }}>
{taskStats?.successRate || 0}%
</div>
<div style={{ fontSize: '14px', color: '#fff', marginTop: 4 }}>
{taskPeriodText}成功率
</div>
</div>
</Card>
<Card title="任务状态占比" className="panel-card glass-panel" size="small">
<div className="chart-wrapper">
<Pie {...taskStatusPieConfig} />
</div>
</Card>
<Card title="近7日任务趋势" className="panel-card glass-panel" size="small">
<div className="chart-wrapper">
<Line {...taskTrendConfig} />
</div>
</Card>
<Card title="异常原因分析" className="panel-card glass-panel flex-grow" size="small">
<div className="chart-wrapper">
<Rose {...roseConfig} />
</div>
</Card>
</div>
</div>
</div>
</Spin>
</div>
);
};
export default Dashboard;