402 lines
15 KiB
TypeScript
402 lines
15 KiB
TypeScript
import dayjs from 'dayjs';
|
||
import type { AlertItem, DeviceStats, TaskStats, TrendItem } from '@/services/dashboard';
|
||
|
||
type Severity = 'normal' | 'warning' | 'critical';
|
||
|
||
export interface SmartCityKpiItem {
|
||
key: string;
|
||
label: string;
|
||
value: number | string;
|
||
unit?: string;
|
||
accent?: 'blue' | 'green' | 'yellow' | 'red' | 'purple';
|
||
sub?: string;
|
||
}
|
||
|
||
export interface SmartCityEventItem {
|
||
id: string;
|
||
title: string;
|
||
location: string;
|
||
source: '无人机' | '摄像头' | '机库' | '多源融合';
|
||
severity: Severity;
|
||
status: '待确认' | '已派单' | '处理中' | '已闭环';
|
||
timeText: string;
|
||
desc: string;
|
||
}
|
||
|
||
export interface SmartCityModels {
|
||
kpis: SmartCityKpiItem[];
|
||
fleet: {
|
||
droneTotal: number;
|
||
droneOnline: number;
|
||
droneInFlight: number;
|
||
droneStandby: number;
|
||
droneMaintenance: number;
|
||
dockTotal: number;
|
||
dockOnline: number;
|
||
cameraTotal: number;
|
||
cameraOnline: number;
|
||
lowBatteryAlerts: number;
|
||
avgBattery: number;
|
||
flightHoursToday: number;
|
||
flightMileageToday: number;
|
||
};
|
||
airspace: {
|
||
safetyIndex: number;
|
||
complianceIndex: number;
|
||
geofenceTriggers: number;
|
||
noFlyWarnings: number;
|
||
approvalsToday: number;
|
||
approvalsPassRate: number;
|
||
};
|
||
regionCoverage: Array<{
|
||
id: string;
|
||
name: string;
|
||
coverage: number;
|
||
pending: number;
|
||
risk: Severity;
|
||
updatedAt: string;
|
||
}>;
|
||
terminalPieData: { name: string; count: number }[];
|
||
onlineRate: number;
|
||
liquidRate: number;
|
||
gridRadarData: { item: string; score: number; type: '当前' }[];
|
||
envTrendData: { time: string; type: string; value: number }[];
|
||
trafficHeatmapData: { x: string; y: string; value: number }[];
|
||
eventTypeData: { type: string; value: number }[];
|
||
eventFunnelData: { stage: string; value: number }[];
|
||
eventList: SmartCityEventItem[];
|
||
aiSnapshots: Array<{
|
||
id: string;
|
||
title: string;
|
||
location: string;
|
||
tag: string;
|
||
confidence: number;
|
||
timeText: string;
|
||
severity: Severity;
|
||
}>;
|
||
}
|
||
|
||
function hashStringToSeed(text: string): number {
|
||
let hash = 2166136261;
|
||
for (let i = 0; i < text.length; i++) {
|
||
hash ^= text.charCodeAt(i);
|
||
hash = Math.imul(hash, 16777619);
|
||
}
|
||
return hash >>> 0;
|
||
}
|
||
|
||
function createRng(seedText: string) {
|
||
let seed = hashStringToSeed(seedText) || 1;
|
||
return () => {
|
||
seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0;
|
||
return seed / 4294967296;
|
||
};
|
||
}
|
||
|
||
function clampNumber(value: number, min: number, max: number) {
|
||
return Math.max(min, Math.min(max, value));
|
||
}
|
||
|
||
function pickOne<T>(rng: () => number, items: T[]): T {
|
||
return items[Math.floor(rng() * items.length)];
|
||
}
|
||
|
||
function mapAlertToEvent(alert: AlertItem): Omit<SmartCityEventItem, 'location' | 'source' | 'status'> & {
|
||
severity: Severity;
|
||
title: string;
|
||
} {
|
||
const severity: Severity =
|
||
alert.level === 'critical' ? 'critical' : alert.level === 'error' ? 'warning' : 'normal';
|
||
|
||
if (alert.type === 'device_offline') {
|
||
return {
|
||
id: alert.id,
|
||
title: '关键点位离线预警',
|
||
severity,
|
||
timeText: dayjs(alert.timestamp).format('HH:mm'),
|
||
desc: alert.message,
|
||
};
|
||
}
|
||
if (alert.type === 'low_battery') {
|
||
return {
|
||
id: alert.id,
|
||
title: '保障能力风险提示',
|
||
severity: severity === 'normal' ? 'warning' : severity,
|
||
timeText: dayjs(alert.timestamp).format('HH:mm'),
|
||
desc: alert.message,
|
||
};
|
||
}
|
||
if (alert.type === 'task_failed') {
|
||
return {
|
||
id: alert.id,
|
||
title: '巡检任务异常',
|
||
severity,
|
||
timeText: dayjs(alert.timestamp).format('HH:mm'),
|
||
desc: alert.message,
|
||
};
|
||
}
|
||
return {
|
||
id: alert.id,
|
||
title: '终端运行异常',
|
||
severity: severity === 'normal' ? 'warning' : severity,
|
||
timeText: dayjs(alert.timestamp).format('HH:mm'),
|
||
desc: alert.message,
|
||
};
|
||
}
|
||
|
||
function calcSafetyIndex(params: {
|
||
deviceStats?: DeviceStats | null;
|
||
taskStats?: TaskStats | null;
|
||
alerts?: AlertItem[];
|
||
baseSeed: string;
|
||
}) {
|
||
const rng = createRng(`${params.baseSeed}:safety`);
|
||
const onlineRate = params.deviceStats?.onlineRate ?? 0;
|
||
const successRate = params.taskStats?.successRate ?? 0;
|
||
const alerts = params.alerts || [];
|
||
|
||
const critical = alerts.filter((a) => a.level === 'critical').length;
|
||
const error = alerts.filter((a) => a.level === 'error').length;
|
||
const warning = alerts.filter((a) => a.level === 'warning').length;
|
||
|
||
const baseline = 90 + Math.round(rng() * 4);
|
||
const penalty = critical * 6 + error * 4 + warning * 2 + Math.round((100 - onlineRate) * 0.18);
|
||
const bonus = Math.round((successRate - 80) * 0.15);
|
||
|
||
return clampNumber(baseline - penalty + bonus, 60, 99);
|
||
}
|
||
|
||
export function buildSmartCityModels(params: {
|
||
tenantId?: string;
|
||
deviceStats?: DeviceStats | null;
|
||
taskStats?: TaskStats | null;
|
||
taskTrend?: TrendItem[];
|
||
alerts?: AlertItem[];
|
||
}): SmartCityModels {
|
||
const todayKey = dayjs().format('YYYY-MM-DD');
|
||
const baseSeed = `${params.tenantId || 'default'}:${todayKey}`;
|
||
const rng = createRng(baseSeed);
|
||
|
||
const deviceStats = params.deviceStats;
|
||
const taskStats = params.taskStats;
|
||
const taskTrend = params.taskTrend || [];
|
||
const alerts = params.alerts || [];
|
||
|
||
const onlineRate = deviceStats?.onlineRate ?? 0;
|
||
const safetyIndex = calcSafetyIndex({ deviceStats, taskStats, alerts, baseSeed });
|
||
|
||
const eventCount = alerts.length + 6 + Math.floor(rng() * 6);
|
||
const avgResponse = clampNumber(8 + Math.round((1 - (taskStats?.successRate ?? 0) / 100) * 12) + Math.round(rng() * 4), 6, 28);
|
||
const closedLoopRate = clampNumber(
|
||
taskStats?.total ? Math.round(((taskStats.completed || 0) / taskStats.total) * 100) : 70 + Math.round(rng() * 18),
|
||
40,
|
||
99,
|
||
);
|
||
|
||
const byType = deviceStats?.byType || [];
|
||
const droneTotal = byType.find((d) => d.type === 'drone')?.count || 0;
|
||
const dockTotal = byType.find((d) => d.type === 'dock')?.count || 0;
|
||
const cameraTotal = byType.find((d) => d.type === 'camera')?.count || 0;
|
||
|
||
const ratio = clampNumber((onlineRate || 0) / 100, 0, 1);
|
||
const droneOnline = clampNumber(Math.round(droneTotal * ratio * (0.94 + rng() * 0.12)), 0, droneTotal);
|
||
const dockOnline = clampNumber(Math.round(dockTotal * ratio * (0.92 + rng() * 0.14)), 0, dockTotal);
|
||
const cameraOnline = clampNumber(Math.round(cameraTotal * ratio * (0.90 + rng() * 0.16)), 0, cameraTotal);
|
||
|
||
const runningTasks = taskStats?.running || 0;
|
||
const droneInFlight = clampNumber(Math.min(droneOnline, Math.max(0, runningTasks) + Math.round(rng() * 2)), 0, droneOnline);
|
||
const droneMaintenance = clampNumber(Math.round(droneTotal * (0.06 + rng() * 0.09)), 0, droneTotal);
|
||
const droneStandby = clampNumber(droneOnline - droneInFlight - Math.min(droneMaintenance, droneOnline), 0, droneOnline);
|
||
|
||
const lowBatteryAlerts = alerts.filter((a) => a.type === 'low_battery').length;
|
||
const avgBattery = clampNumber(62 + Math.round(rng() * 28) - lowBatteryAlerts * 3, 18, 98);
|
||
const flightHoursToday = clampNumber(6 + Math.round((taskStats?.total || 0) * 0.55) + Math.round(rng() * 4), 0, 78);
|
||
const flightMileageToday = clampNumber(28 + Math.round((taskStats?.total || 0) * 2.2) + Math.round(rng() * 12), 0, 420);
|
||
|
||
const critical = alerts.filter((a) => a.level === 'critical').length;
|
||
const error = alerts.filter((a) => a.level === 'error').length;
|
||
const warning = alerts.filter((a) => a.level === 'warning').length;
|
||
|
||
const complianceIndex = clampNumber(95 - critical * 6 - error * 3 - warning * 1 - Math.round((100 - onlineRate) * 0.12) + Math.round(rng() * 2), 60, 99);
|
||
const geofenceTriggers = clampNumber(Math.round(rng() * 5) + critical + Math.floor(error / 2), 0, 12);
|
||
const noFlyWarnings = clampNumber(Math.round(rng() * 3) + Math.floor(warning / 2), 0, 10);
|
||
const approvalsToday = clampNumber(18 + Math.round(rng() * 28), 0, 120);
|
||
const approvalsPassRate = clampNumber(92 - critical * 2 - error + Math.round(rng() * 4), 70, 99);
|
||
|
||
const fleet = {
|
||
droneTotal,
|
||
droneOnline,
|
||
droneInFlight,
|
||
droneStandby,
|
||
droneMaintenance,
|
||
dockTotal,
|
||
dockOnline,
|
||
cameraTotal,
|
||
cameraOnline,
|
||
lowBatteryAlerts,
|
||
avgBattery,
|
||
flightHoursToday,
|
||
flightMileageToday,
|
||
};
|
||
|
||
const airspace = {
|
||
safetyIndex,
|
||
complianceIndex,
|
||
geofenceTriggers,
|
||
noFlyWarnings,
|
||
approvalsToday,
|
||
approvalsPassRate,
|
||
};
|
||
|
||
const kpis: SmartCityKpiItem[] = [
|
||
{ key: 'air', label: '空域合规指数', value: complianceIndex, unit: '', accent: complianceIndex >= 92 ? 'green' : complianceIndex >= 82 ? 'yellow' : 'red', sub: '围栏/禁飞/链路综合' },
|
||
{ key: 'flight', label: '在飞无人机', value: droneInFlight, unit: '架', accent: 'purple', sub: `在线 ${droneOnline}/${droneTotal}` },
|
||
{ key: 'sortie', label: '今日出动任务', value: taskStats?.todayNew ?? 0, unit: '次', accent: 'blue', sub: '巡检/应急/处置' },
|
||
{ key: 'closed', label: '问题闭环率', value: closedLoopRate, unit: '%', accent: closedLoopRate >= 85 ? 'green' : 'yellow', sub: '发现→处置→复核' },
|
||
{ key: 'online', label: '终端在线率', value: onlineRate, unit: '%', accent: onlineRate >= 90 ? 'green' : onlineRate >= 75 ? 'yellow' : 'red', sub: `低电 ${lowBatteryAlerts} 起` },
|
||
];
|
||
|
||
const terminalPieData = (deviceStats?.byType || []).map((d) => ({ name: d.name, count: d.count }));
|
||
|
||
const regionCoverage = (() => {
|
||
const regions = ['政务中心片区', '滨河公园带', '高新大道走廊', '老城商圈', '西站枢纽', '南湖片区', '工业园北区', '东门立交'];
|
||
const picked = regions.slice(0, 6);
|
||
return picked.map((name, idx) => {
|
||
const coverage = clampNumber(72 + Math.round(rng() * 26) - idx * 2, 45, 99);
|
||
const pending = clampNumber(Math.round(rng() * 8) + (idx % 2 === 0 ? 1 : 0), 0, 18);
|
||
const risk: Severity = coverage >= 88 ? 'normal' : coverage >= 76 ? 'warning' : 'critical';
|
||
const updatedAt = dayjs().subtract(5 + Math.round(rng() * 55), 'minute').format('HH:mm');
|
||
return { id: `region-${idx}`, name, coverage, pending, risk, updatedAt };
|
||
});
|
||
})();
|
||
|
||
const gridRadarData = [
|
||
{ item: '巡检覆盖', score: clampNumber(70 + Math.round(rng() * 24), 55, 98), type: '当前' as const },
|
||
{ item: '问题发现', score: clampNumber(62 + Math.round(rng() * 30), 50, 98), type: '当前' as const },
|
||
{ item: '处置效率', score: clampNumber(68 + Math.round(rng() * 22), 50, 98), type: '当前' as const },
|
||
{ item: '复核通过', score: clampNumber(72 + Math.round(rng() * 18), 55, 99), type: '当前' as const },
|
||
{ item: '重点关注', score: clampNumber(58 + Math.round(rng() * 34), 45, 98), type: '当前' as const },
|
||
];
|
||
|
||
const envTrendData: { time: string; type: string; value: number }[] = [];
|
||
const startHour = dayjs().startOf('day');
|
||
const pmBase = clampNumber(22 + Math.round(rng() * 26), 15, 60);
|
||
const noiseBase = clampNumber(52 + Math.round(rng() * 10), 45, 70);
|
||
for (let i = 0; i < 24; i++) {
|
||
const time = startHour.add(i, 'hour').format('HH:00');
|
||
const wave = Math.sin((i / 24) * Math.PI * 2);
|
||
const pm = clampNumber(pmBase + wave * 10 + (rng() - 0.5) * 6, 8, 85);
|
||
const noise = clampNumber(noiseBase + Math.abs(wave) * 9 + (rng() - 0.5) * 4, 35, 85);
|
||
envTrendData.push({ time, type: 'PM2.5', value: Number(pm.toFixed(1)) });
|
||
envTrendData.push({ time, type: '噪声(dB)', value: Number(noise.toFixed(1)) });
|
||
}
|
||
|
||
const trafficHeatmapData: { x: string; y: string; value: number }[] = [];
|
||
const cols = 10;
|
||
const rows = 6;
|
||
for (let y = 0; y < rows; y++) {
|
||
for (let x = 0; x < cols; x++) {
|
||
const centerBias = 1 - Math.abs(x - (cols - 1) / 2) / cols;
|
||
const value = clampNumber(12 + centerBias * 36 + rng() * 18 + (y % 2 === 0 ? 2 : -2), 0, 100);
|
||
trafficHeatmapData.push({ x: `${x + 1}`, y: `${rows - y}`, value: Math.round(value) });
|
||
}
|
||
}
|
||
|
||
const locations = ['政务中心', '滨河公园', '高新大道', '老城商圈', '西站枢纽', '南湖片区', '工业园北区', '东门立交'];
|
||
const sources: SmartCityEventItem['source'][] = ['无人机', '摄像头', '机库', '多源融合'];
|
||
const statuses: SmartCityEventItem['status'][] = ['待确认', '已派单', '处理中', '已闭环'];
|
||
|
||
const eventListFromAlerts: SmartCityEventItem[] = alerts.slice(0, 8).map((a, idx) => {
|
||
const base = mapAlertToEvent(a);
|
||
const status = idx === 0 ? '处理中' : idx === 1 ? '待确认' : pickOne(rng, statuses);
|
||
const source = idx % 2 === 0 ? '无人机' : '机库';
|
||
return {
|
||
...base,
|
||
location: pickOne(rng, locations),
|
||
source,
|
||
status,
|
||
};
|
||
});
|
||
|
||
const aiEventTypes = ['违停抓拍', '烟火识别', '占道经营', '河道漂浮物', '工地未戴帽', '夜间聚集'];
|
||
const aiSnapshots = new Array(10).fill(0).map((_, i) => {
|
||
const type = aiEventTypes[i % aiEventTypes.length];
|
||
const confidence = clampNumber(78 + Math.round(rng() * 20), 60, 99);
|
||
const severity: Severity = confidence >= 92 ? 'critical' : confidence >= 84 ? 'warning' : 'normal';
|
||
const timeText = dayjs().subtract(Math.round(rng() * 65), 'minute').format('HH:mm');
|
||
return {
|
||
id: `snap-${todayKey}-${i}`,
|
||
title: type,
|
||
location: pickOne(rng, locations),
|
||
tag: pickOne(rng, ['AI识别', '多源融合', '重点区域', '高频点位']),
|
||
confidence,
|
||
timeText,
|
||
severity,
|
||
};
|
||
});
|
||
|
||
const eventListGenerated: SmartCityEventItem[] = aiSnapshots.slice(0, 6).map((s, idx) => {
|
||
const severity: Severity = s.severity;
|
||
const status = idx < 2 ? '待确认' : idx < 4 ? '已派单' : pickOne(rng, statuses);
|
||
const source = idx % 3 === 0 ? '无人机' : idx % 3 === 1 ? '摄像头' : '多源融合';
|
||
return {
|
||
id: `evt-${s.id}`,
|
||
title: s.title,
|
||
location: s.location,
|
||
source,
|
||
severity,
|
||
status,
|
||
timeText: s.timeText,
|
||
desc: `疑似${s.title}(置信度 ${s.confidence}%)`,
|
||
};
|
||
});
|
||
|
||
const eventList = [...eventListGenerated, ...eventListFromAlerts].slice(0, 12);
|
||
|
||
const eventTypeCounts: Record<string, number> = {};
|
||
eventList.forEach((e) => {
|
||
const key = e.title;
|
||
eventTypeCounts[key] = (eventTypeCounts[key] || 0) + 1;
|
||
});
|
||
const eventTypeData = Object.entries(eventTypeCounts)
|
||
.map(([type, value]) => ({ type, value }))
|
||
.sort((a, b) => b.value - a.value)
|
||
.slice(0, 6);
|
||
|
||
const eventFunnelData = (() => {
|
||
const total = eventCount;
|
||
const confirmed = clampNumber(Math.round(total * (0.78 + rng() * 0.08)), 0, total);
|
||
const assigned = clampNumber(Math.round(confirmed * (0.75 + rng() * 0.1)), 0, confirmed);
|
||
const processing = clampNumber(Math.round(assigned * (0.72 + rng() * 0.12)), 0, assigned);
|
||
const closed = clampNumber(Math.round(processing * (0.78 + rng() * 0.12)), 0, processing);
|
||
return [
|
||
{ stage: '识别', value: total },
|
||
{ stage: '确认', value: confirmed },
|
||
{ stage: '派单', value: assigned },
|
||
{ stage: '处置', value: processing },
|
||
{ stage: '闭环', value: closed },
|
||
];
|
||
})();
|
||
|
||
const liquidRate = clampNumber((onlineRate || 0) / 100, 0, 1);
|
||
|
||
void taskTrend;
|
||
|
||
return {
|
||
kpis,
|
||
fleet,
|
||
airspace,
|
||
regionCoverage,
|
||
terminalPieData,
|
||
onlineRate,
|
||
liquidRate,
|
||
gridRadarData,
|
||
envTrendData,
|
||
trafficHeatmapData,
|
||
eventTypeData,
|
||
eventFunnelData,
|
||
eventList,
|
||
aiSnapshots,
|
||
};
|
||
}
|