实现DMA漏损识别面板整体设计

This commit is contained in:
JIANG
2026-03-06 09:59:06 +08:00
parent b73481d604
commit 377fc32f4c
10 changed files with 1096 additions and 68 deletions
@@ -0,0 +1,5 @@
import { MapSkeleton } from "@components/loading/MapSkeleton";
export default function Loading() {
return <MapSkeleton />;
}
@@ -0,0 +1,20 @@
"use client";
import MapComponent from "@app/OlMap/MapComponent";
import MapToolbar from "@app/OlMap/Controls/Toolbar";
import DMALeakDetectionPanel from "@/components/olmap/DMALeakDetection/DMALeakDetectionPanel";
export default function Home() {
return (
<div className="relative w-full h-full overflow-hidden">
<MapComponent>
<MapToolbar
queryType="scheme"
schemeType="dma_leak_identification"
hiddenButtons={["style"]}
/>
<DMALeakDetectionPanel />
</MapComponent>
</div>
);
}
+58 -33
View File
@@ -10,6 +10,9 @@ interface LegendStyleConfig {
type: string; // 图例类型
dimensions: number[]; // 尺寸大小
breaks: number[]; // 分段值
labels?: string[]; // 可选标签(用于离散分类)
columns?: number;
itemsPerColumn?: number;
}
// 图例组件
// 该组件用于显示图层样式的图例,包含属性名称、颜色、尺寸和分段值等信息
@@ -24,6 +27,9 @@ const StyleLegend: React.FC<LegendStyleConfig> = ({
type, // 图例类型
dimensions,
breaks,
labels,
columns = 1,
itemsPerColumn,
}) => {
return (
<Box
@@ -33,9 +39,26 @@ const StyleLegend: React.FC<LegendStyleConfig> = ({
<Typography variant="subtitle2" gutterBottom>
{layerName} - {property}
</Typography>
{[...Array(breaks.length)].map((_, index) => {
const color = colors[index]; // 默认颜色为黑色
const dimension = dimensions[index]; // 默认尺寸为16
<Box
sx={{
display: "grid",
gridTemplateColumns:
itemsPerColumn && itemsPerColumn > 0
? undefined
: `repeat(${Math.max(1, columns)}, minmax(0, 1fr))`,
gridTemplateRows:
itemsPerColumn && itemsPerColumn > 0
? `repeat(${itemsPerColumn}, minmax(0, auto))`
: undefined,
gridAutoFlow:
itemsPerColumn && itemsPerColumn > 0 ? "column" : undefined,
columnGap: 1.5,
rowGap: 0.5,
}}
>
{[...Array(breaks.length)].map((_, index) => {
const color = colors[index]; // 默认颜色为黑色
const dimension = dimensions[index]; // 默认尺寸为16
// // 处理第一个区间(小于 breaks[0])
// if (index === 0) {
@@ -66,37 +89,39 @@ const StyleLegend: React.FC<LegendStyleConfig> = ({
// }
// 处理中间区间(breaks[index] - breaks[index + 1]
if (index + 1 < breaks.length) {
const prevValue = breaks[index];
const currentValue = breaks[index + 1];
return (
<Box key={index} className="flex items-center gap-2 mb-1">
<Box
sx={
type === "point"
? {
width: dimension,
height: dimension,
borderRadius: "50%",
backgroundColor: color,
}
: {
width: 16,
height: dimension,
backgroundColor: color,
border: `1px solid ${color}`,
}
}
/>
<Typography variant="caption" className="text-xs">
{prevValue?.toFixed(1)} - {currentValue?.toFixed(1)}
</Typography>
</Box>
);
}
if (index + 1 < breaks.length) {
const prevValue = breaks[index];
const currentValue = breaks[index + 1];
return (
<Box key={index} className="flex items-center gap-2">
<Box
sx={
type === "point"
? {
width: dimension,
height: dimension,
borderRadius: "50%",
backgroundColor: color,
}
: {
width: 16,
height: dimension,
backgroundColor: color,
border: `1px solid ${color}`,
}
}
/>
<Typography variant="caption" className="text-xs">
{labels?.[index] ??
`${prevValue?.toFixed(1)} - ${currentValue?.toFixed(1)}`}
</Typography>
</Box>
);
}
return null;
})}
return null;
})}
</Box>
</Box>
);
};
+9
View File
@@ -180,6 +180,15 @@ const App = (props: React.PropsWithChildren<AppProps>) => {
label: "爆管分析定位",
},
},
{
name: "DMA漏损识别",
list: "/hydraulic-simulation/dma-leak-detection",
meta: {
parent: "Hydraulic Simulation",
icon: <TbLocationPin className="w-6 h-6" />,
label: "DMA漏损识别",
},
},
{
name: "水质模拟",
list: "/hydraulic-simulation/water-quality-simulation",
@@ -1,30 +0,0 @@
"use client";
import React from "react";
import { Box, Typography } from "@mui/material";
interface ResultsPanelProps {
schemeName?: string;
}
const ResultsPanel: React.FC<ResultsPanelProps> = ({ schemeName }) => {
return (
<Box className="flex flex-col h-full">
<Box className="flex-1 overflow-auto bg-white rounded border border-gray-200 p-5">
<Typography variant="h6" className="font-semibold text-gray-900">
</Typography>
<Typography variant="body2" className="text-gray-600 mt-2">
</Typography>
{schemeName && (
<Typography variant="caption" className="text-gray-500 mt-4 block">
{schemeName}
</Typography>
)}
</Box>
</Box>
);
};
export default ResultsPanel;
@@ -19,7 +19,6 @@ import {
} from "@mui/icons-material";
import ContaminantAnalysisParameters from "./AnalysisParameters";
import ContaminantSchemeQuery from "./SchemeQuery";
import ContaminantResultsPanel from "./ResultsPanel";
import { useData } from "@app/OlMap/MapComponent";
interface WaterQualityPanelProps {
@@ -175,10 +174,6 @@ const WaterQualityPanel: React.FC<WaterQualityPanelProps> = ({
<TabPanel value={currentTab} index={1}>
<ContaminantSchemeQuery onViewResults={() => setCurrentTab(2)} />
</TabPanel>
<TabPanel value={currentTab} index={2}>
<ContaminantResultsPanel schemeName={data?.schemeName} />
</TabPanel>
</Box>
</Drawer>
</>
@@ -0,0 +1,260 @@
"use client";
import React, { useMemo, useState } from "react";
import {
Alert,
Box,
Button,
Collapse,
TextField,
Typography,
} from "@mui/material";
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
import { DateTimePicker } from "@mui/x-date-pickers/DateTimePicker";
import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import { zhCN as pickerZhCN } from "@mui/x-date-pickers/locales";
import dayjs, { Dayjs } from "dayjs";
import "dayjs/locale/zh-cn";
import { useNotification } from "@refinedev/core";
import { api } from "@/lib/api";
import { NETWORK_NAME, config } from "@config/config";
import { LeakageResultDetail } from "./types";
interface Props {
onResult: (result: LeakageResultDetail) => void;
}
const AnalysisParameters: React.FC<Props> = ({ onResult }) => {
const { open } = useNotification();
const [schemeName, setSchemeName] = useState(`DMA_Leak_${Date.now()}`);
const [dmaCount, setDmaCount] = useState<number>(5);
const [startTime, setStartTime] = useState<Dayjs | null>(
dayjs().subtract(2, "hour"),
);
const [endTime, setEndTime] = useState<Dayjs | null>(dayjs());
const [popSize, setPopSize] = useState<number>(50);
const [maxGen, setMaxGen] = useState<number>(100);
const [qSum, setQSum] = useState<number>(0.4);
const [advancedOpen, setAdvancedOpen] = useState(false);
const [running, setRunning] = useState(false);
const isValid = useMemo(() => {
if (!schemeName.trim() || !startTime || !endTime) return false;
return startTime.isBefore(endTime) && qSum >= 0.1;
}, [schemeName, startTime, endTime, qSum]);
const handleRun = async () => {
if (!isValid || !startTime || !endTime) {
open?.({ type: "error", message: "请完善参数并确认时间范围合法" });
return;
}
setRunning(true);
open?.({
key: "dma-leak-analysis",
type: "progress",
message: "方案提交分析中",
undoableTimeout: 3,
});
try {
const response = await api.post(
`${config.BACKEND_URL}/api/v1/leakage/identify/`,
{
network: NETWORK_NAME,
scheme_name: schemeName.trim(),
dma_count: dmaCount,
scada_start: startTime.toISOString(),
scada_end: endTime.toISOString(),
pop_size: popSize,
max_gen: maxGen,
q_sum: qSum,
q_sum_unit: "m3/s",
output_flow_unit: "m3/s",
},
);
onResult(response.data as LeakageResultDetail);
open?.({
key: "dma-leak-analysis",
type: "success",
message: "方案分析成功",
description: "DMA漏损识别完成,请在方案查询中查看结果。",
});
} catch (error: any) {
open?.({
key: "dma-leak-analysis",
type: "error",
message: "提交分析失败",
description: error?.response?.data?.detail ?? "请求失败",
});
} finally {
setRunning(false);
}
};
return (
<Box className="flex flex-col flex-1 min-h-0">
<Box className="flex flex-col gap-3">
<Alert severity="info">
DMA DMA
</Alert>
<Box>
<Typography variant="subtitle2" className="mb-1 font-medium">
</Typography>
<TextField
value={schemeName}
onChange={(e) => setSchemeName(e.target.value)}
placeholder="请输入方案名称"
fullWidth
size="small"
/>
</Box>
<Box>
<Typography variant="subtitle2" className="mb-1 font-medium">
DMA
</Typography>
<TextField
type="number"
value={dmaCount}
onChange={(e) => {
const value = Number.parseInt(e.target.value, 10);
setDmaCount(Number.isNaN(value) ? 5 : Math.max(3, value));
}}
fullWidth
size="small"
inputProps={{ min: 3, step: 1 }}
/>
</Box>
<LocalizationProvider
dateAdapter={AdapterDayjs}
adapterLocale="zh-cn"
localeText={
pickerZhCN.components.MuiLocalizationProvider.defaultProps.localeText
}
>
<Box>
<Typography variant="subtitle2" className="mb-1 font-medium">
SCADA
</Typography>
<DateTimePicker
value={startTime}
onChange={setStartTime}
maxDateTime={endTime ?? undefined}
format="YYYY-MM-DD HH:mm"
slotProps={{ textField: { size: "small", fullWidth: true } }}
/>
</Box>
<Box>
<Typography variant="subtitle2" className="mb-1 font-medium">
SCADA
</Typography>
<DateTimePicker
value={endTime}
onChange={setEndTime}
minDateTime={startTime ?? undefined}
format="YYYY-MM-DD HH:mm"
slotProps={{ textField: { size: "small", fullWidth: true } }}
/>
</Box>
</LocalizationProvider>
<Box className="flex flex-col gap-2">
<Typography variant="subtitle2" className="mb-1 font-medium">
(m3/s)
</Typography>
<TextField
type="number"
size="small"
value={qSum}
onChange={(e) => {
const value = Number(e.target.value);
setQSum(Number.isNaN(value) ? 0.4 : Math.max(0.1, value));
}}
inputProps={{ min: 0.1, step: 0.1 }}
/>
<Box
sx={{
border: "1px solid",
borderColor: "grey.200",
borderRadius: 1,
overflow: "hidden",
}}
>
<Box
role="button"
tabIndex={0}
onClick={() => setAdvancedOpen((prev) => !prev)}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") setAdvancedOpen((prev) => !prev);
}}
sx={{
display: "flex",
alignItems: "center",
justifyContent: "space-between",
px: 1.25,
py: 0.75,
cursor: "pointer",
backgroundColor: "transparent",
"&:hover": { backgroundColor: "action.hover" },
}}
>
<Typography variant="body2" color="text.secondary">
</Typography>
<ExpandMoreIcon
sx={{
transform: advancedOpen ? "rotate(180deg)" : "rotate(0deg)",
transition: "transform 0.2s ease",
}}
/>
</Box>
<Collapse in={advancedOpen} timeout="auto" unmountOnExit>
<Box
sx={{
px: 1.25,
pt: 1.25,
pb: 1.25,
backgroundColor: "transparent",
}}
>
<Box className="grid grid-cols-2 gap-2">
<TextField
type="number"
label="种群规模"
size="small"
value={popSize}
onChange={(e) => setPopSize(Number(e.target.value))}
/>
<TextField
type="number"
label="最大代数"
size="small"
value={maxGen}
onChange={(e) => setMaxGen(Number(e.target.value))}
/>
</Box>
</Box>
</Collapse>
</Box>
</Box>
</Box>
<Box className="mt-auto pt-3">
<Button
fullWidth
variant="contained"
onClick={handleRun}
disabled={!isValid || running}
className="bg-blue-600 hover:bg-blue-700"
>
{running ? "识别中..." : "开始识别"}
</Button>
</Box>
</Box>
);
};
export default AnalysisParameters;
@@ -0,0 +1,432 @@
"use client";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import {
Box,
Drawer,
Tabs,
Tab,
Typography,
IconButton,
Tooltip,
Table,
TableBody,
TableCell,
TableHead,
TableRow,
Chip,
} from "@mui/material";
import {
Analytics as AnalyticsIcon,
Search as SearchIcon,
ChevronLeft,
ChevronRight,
FormatListBulleted,
} from "@mui/icons-material";
import dayjs from "dayjs";
import { Circle as CircleStyle, Fill, Stroke, Style } from "ol/style";
import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
import Feature from "ol/Feature";
import { queryFeaturesByIds } from "@/utils/mapQueryService";
import { useMap } from "@app/OlMap/MapComponent";
import StyleLegend from "@app/OlMap/Controls/StyleLegend";
import AnalysisParameters from "./AnalysisParameters";
import SchemeQuery from "./SchemeQuery";
import { LeakageResultDetail } from "./types";
const TabPanel = ({
value,
index,
children,
}: {
value: number;
index: number;
children: React.ReactNode;
}) => (
<div role="tabpanel" hidden={value !== index} className="flex-1 overflow-hidden flex flex-col">
{value === index ? <Box className="flex-1 overflow-auto p-4 flex flex-col">{children}</Box> : null}
</div>
);
const AREA_COLORS = [
"#2563eb",
"#7c3aed",
"#0891b2",
"#16a34a",
"#ca8a04",
"#dc2626",
"#ea580c",
"#0f766e",
"#4338ca",
"#be123c",
];
const getAreaColor = (areaId: string | number | undefined) => {
const text = String(areaId ?? "");
let hash = 0;
for (let i = 0; i < text.length; i += 1) {
hash = (hash * 31 + text.charCodeAt(i)) >>> 0;
}
return AREA_COLORS[hash % AREA_COLORS.length];
};
const DMALeakDetectionPanel: React.FC = () => {
const map = useMap();
const [open, setOpen] = useState(true);
const [tab, setTab] = useState(0);
const [result, setResult] = useState<LeakageResultDetail | null>(null);
const [loadedResult, setLoadedResult] = useState<LeakageResultDetail | null>(null);
const [nodeLayer, setNodeLayer] = useState<VectorLayer<VectorSource> | null>(null);
const sortedRows = useMemo(() => {
if (!result?.rows) return [];
return [...result.rows].sort(
(a, b) => b.LeakageFlow_m3_per_s - a.LeakageFlow_m3_per_s,
);
}, [result]);
const drawerWidth = 450;
const panelTitle = "DMA漏损识别";
const activeAreas = loadedResult?.areas ?? [];
const legendColors = useMemo(
() => activeAreas.map((area) => getAreaColor(area.area_id)),
[activeAreas],
);
const legendLabels = useMemo(
() => activeAreas.map((area) => `区域 ${area.area_id}`),
[activeAreas],
);
const legendBreaks = useMemo(
() => Array.from({ length: activeAreas.length + 1 }, (_, i) => i + 1),
[activeAreas.length],
);
useEffect(() => {
if (!map) return;
const layer = new VectorLayer({
source: new VectorSource(),
maxZoom: 24,
minZoom: 12,
properties: {
name: "DMA漏损节点着色",
value: "dma_leak_nodes",
},
style: (feature) => {
const areaId = feature.get("__areaId");
return new Style({
image: new CircleStyle({
radius: 4.5,
fill: new Fill({ color: getAreaColor(areaId) }),
stroke: new Stroke({ color: "#ffffff", width: 1.2 }),
}),
});
},
});
map.addLayer(layer);
setNodeLayer(layer);
return () => {
map.removeLayer(layer);
};
}, [map]);
useEffect(() => {
if (!nodeLayer) return;
const source = nodeLayer.getSource();
if (!source) return;
source.clear();
if (!loadedResult) return;
const nodeAreaMap = loadedResult.node_area_map || {};
const nodeIds = Object.keys(nodeAreaMap);
if (nodeIds.length === 0) return;
queryFeaturesByIds(nodeIds, "geo_junctions_mat").then((features) => {
if (!features?.length) return;
features.forEach((feature) => {
const nodeId = String(feature.get("id") ?? "");
feature.set("__areaId", nodeAreaMap[nodeId] ?? "");
});
source.addFeatures(features as Feature[]);
});
}, [loadedResult, nodeLayer]);
const handleAnalysisResult = useCallback((res: LeakageResultDetail) => {
setResult(res);
}, []);
const handleViewResult = useCallback((res: LeakageResultDetail) => {
setResult(res);
setLoadedResult(res);
setTab(2);
}, []);
return (
<>
{!open && (
<Box
className="absolute top-4 right-4 bg-white shadow-2xl rounded-lg cursor-pointer hover:shadow-xl transition-all duration-300 opacity-95 hover:opacity-100"
onClick={() => setOpen(true)}
sx={{ zIndex: 1300 }}
>
<Box className="flex flex-col items-center py-3 px-3 gap-1">
<AnalyticsIcon className="text-[#257DD4] w-5 h-5" />
<Typography
variant="caption"
className="text-gray-700 font-semibold my-1 text-xs"
style={{ writingMode: "vertical-rl" }}
>
{panelTitle}
</Typography>
<ChevronLeft className="text-gray-600 w-4 h-4" />
</Box>
</Box>
)}
<Drawer
anchor="right"
open={open}
variant="persistent"
hideBackdrop
sx={{
width: 0,
flexShrink: 0,
"& .MuiDrawer-paper": {
width: drawerWidth,
boxSizing: "border-box",
position: "absolute",
top: 16,
right: 16,
height: "calc(100vh - 32px)",
maxHeight: "850px",
borderRadius: "12px",
boxShadow:
"0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04)",
backdropFilter: "blur(8px)",
opacity: 0.95,
transition: "transform 0.3s ease-in-out, opacity 0.3s ease-in-out",
border: "none",
"&:hover": {
opacity: 1,
},
},
}}
>
<Box className="flex flex-col h-full bg-white rounded-xl overflow-hidden">
<Box className="flex items-center justify-between px-5 py-4 bg-[#257DD4] text-white">
<Box className="flex items-center gap-2">
<AnalyticsIcon className="w-5 h-5" />
<Typography variant="h6" className="text-lg font-semibold">
{panelTitle}
</Typography>
</Box>
<Tooltip title="收起">
<IconButton
size="small"
onClick={() => setOpen(false)}
sx={{ color: "primary.contrastText" }}
>
<ChevronRight fontSize="small" />
</IconButton>
</Tooltip>
</Box>
<Box className="border-b border-gray-200 bg-white">
<Tabs
value={tab}
onChange={(_, v) => setTab(v)}
variant="fullWidth"
sx={{
minHeight: 48,
"& .MuiTab-root": {
minHeight: 48,
textTransform: "none",
fontSize: "0.875rem",
fontWeight: 500,
transition: "all 0.2s",
},
"& .Mui-selected": {
color: "#257DD4",
},
"& .MuiTabs-indicator": {
backgroundColor: "#257DD4",
},
}}
>
<Tab icon={<AnalyticsIcon fontSize="small" />} iconPosition="start" label="识别参数" />
<Tab icon={<SearchIcon fontSize="small" />} iconPosition="start" label="方案查询" />
<Tab icon={<FormatListBulleted fontSize="small" />} iconPosition="start" label="识别结果" />
</Tabs>
</Box>
<TabPanel value={tab} index={0}>
<AnalysisParameters onResult={handleAnalysisResult} />
</TabPanel>
<TabPanel value={tab} index={1}>
<SchemeQuery onViewResult={handleViewResult} />
</TabPanel>
<TabPanel value={tab} index={2}>
{!result || !sortedRows.length ? (
<Box className="flex flex-col items-center justify-center h-full text-gray-400 p-4">
<Box className="mb-4">
<svg width="80" height="80" viewBox="0 0 80 80" fill="none" className="opacity-40">
<rect x="10" y="20" width="60" height="45" rx="2" stroke="currentColor" strokeWidth="2" />
<line x1="10" y1="30" x2="70" y2="30" stroke="currentColor" strokeWidth="2" />
</svg>
</Box>
<Typography variant="body2"></Typography>
<Typography variant="body2" className="mt-1">
</Typography>
</Box>
) : (
<Box className="h-full overflow-auto p-1">
{/* 方案详情卡片 */}
<Box className="mb-4 space-y-3">
<Box className="flex items-center justify-between px-1">
<Box className="flex items-center gap-2">
<Box className="w-1 h-4 bg-blue-600 rounded-full" />
<Typography
variant="h6"
className="font-bold text-gray-900 truncate"
sx={{ fontSize: "1.1rem" }}
title={result.scheme_name || ""}
>
{result.scheme_name || "漏损识别结果"}
</Typography>
</Box>
{result.username && (
<Chip
label={result.username}
size="small"
sx={{
height: 24,
backgroundColor: "#f3f4f6",
color: "#4b5563",
border: "none",
fontWeight: 500
}}
/>
)}
</Box>
<Box className="grid grid-cols-2 gap-3">
{/* 方案时间 */}
<Box className="bg-gradient-to-br from-blue-50 to-blue-100 rounded-lg p-3 border border-blue-200 shadow-sm">
<Typography variant="caption" className="text-blue-700 font-semibold block mb-1 text-xs uppercase tracking-wide">
</Typography>
<Typography variant="body2" className="font-bold text-blue-900">
{dayjs(result.scheme_start_time || result.create_time).format("MM-DD HH:mm")}
</Typography>
</Box>
{/* 总漏损流量 */}
<Box className="bg-gradient-to-br from-orange-50 to-orange-100 rounded-lg p-3 border border-orange-200 shadow-sm">
<Typography variant="caption" className="text-orange-700 font-semibold block mb-1 text-xs uppercase tracking-wide">
</Typography>
<Typography variant="body2" className="font-bold text-orange-900">
{(() => {
const val = (result.scheme_detail as any)?.algorithm_params?.q_sum;
const unit = (result.scheme_detail as any)?.algorithm_params?.q_sum_unit || "m3/s";
return val !== undefined ? `${Number(val).toFixed(3)} ${unit}` : "-";
})()}
</Typography>
</Box>
{/* 分区数量 */}
<Box className="bg-gradient-to-br from-green-50 to-green-100 rounded-lg p-3 border border-green-200 shadow-sm">
<Typography variant="caption" className="text-green-700 font-semibold block mb-1 text-xs uppercase tracking-wide">
</Typography>
<Typography variant="body2" className="font-bold text-green-900">
{(result.scheme_detail as any)?.result_summary?.area_count ?? result.areas?.length ?? 0}
</Typography>
</Box>
{/* 最大漏损 */}
<Box className="bg-gradient-to-br from-purple-50 to-purple-100 rounded-lg p-3 border border-purple-200 shadow-sm">
<Typography variant="caption" className="text-purple-700 font-semibold block mb-1 text-xs uppercase tracking-wide">
</Typography>
<Typography variant="body2" className="font-bold text-purple-900">
{(() => {
const maxL = (result.scheme_detail as any)?.result_summary?.max_leakage;
return maxL !== undefined ? `${Number(maxL).toFixed(3)} m3/s` : "-";
})()}
</Typography>
</Box>
</Box>
</Box>
{/* 漏损列表 */}
<Box className="rounded-xl border border-gray-100 bg-white shadow-sm overflow-hidden">
<Box className="px-4 py-3 border-b border-gray-100 flex items-center justify-between bg-white">
<Box className="flex items-center gap-2">
<FormatListBulleted className="text-blue-600 w-5 h-5" />
<Typography variant="subtitle1" className="font-bold text-gray-800">
</Typography>
</Box>
<Chip
size="small"
label={`${sortedRows.length}`}
sx={{
height: 22,
backgroundColor: "rgba(37, 99, 235, 0.08)",
color: "#2563eb",
fontWeight: 600,
fontSize: "0.75rem",
border: "none"
}}
/>
</Box>
<Table size="small">
<TableHead>
<TableRow sx={{ backgroundColor: "#f8fafc" }}>
<TableCell sx={{ fontWeight: 600, color: "#64748b", py: 1.5, pl: 3 }}></TableCell>
<TableCell align="right" sx={{ fontWeight: 600, color: "#64748b", py: 1.5 }}> (%)</TableCell>
<TableCell align="right" sx={{ fontWeight: 600, color: "#64748b", py: 1.5, pr: 3 }}> (m3/s)</TableCell>
</TableRow>
</TableHead>
<TableBody>
{sortedRows.map((row) => (
<TableRow key={row.Area} hover sx={{ "&:last-child td, &:last-child th": { border: 0 } }}>
<TableCell sx={{ pl: 3, py: 1.2 }}>
<Box className="flex items-center gap-2">
<Box className="w-2 h-2 rounded-full" sx={{ backgroundColor: getAreaColor(row.Area) }} />
<Typography variant="body2" className="font-medium text-gray-700">
{row.Area}
</Typography>
</Box>
</TableCell>
<TableCell align="right" sx={{ py: 1.2, color: "#475569" }}>{(row.LeakageRatio * 100).toFixed(3)}</TableCell>
<TableCell align="right" sx={{ pr: 3, py: 1.2, fontWeight: 500, color: "#334155" }}>{row.LeakageFlow_m3_per_s.toFixed(3)}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</Box>
</Box>
)}
</TabPanel>
</Box>
</Drawer>
{loadedResult && activeAreas.length > 0 && (
<Box className="absolute bottom-40 right-4 drop-shadow-xl flex flex-row items-end max-w-screen-lg overflow-x-auto z-10">
<StyleLegend
layerName="节点"
layerId="dma-leakage"
property="区域"
colors={legendColors}
type="point"
dimensions={Array(legendColors.length).fill(10)}
breaks={legendBreaks}
labels={legendLabels}
itemsPerColumn={5}
/>
</Box>
)}
</>
);
};
export default DMALeakDetectionPanel;
@@ -0,0 +1,259 @@
"use client";
import React, { useState } from "react";
import {
Box,
Button,
Card,
CardContent,
Chip,
Collapse,
FormControlLabel,
Checkbox,
IconButton,
Tooltip,
Typography,
} from "@mui/material";
import { Info as InfoIcon } from "@mui/icons-material";
import { DatePicker } from "@mui/x-date-pickers/DatePicker";
import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import "dayjs/locale/zh-cn";
import dayjs, { Dayjs } from "dayjs";
import { useNotification } from "@refinedev/core";
import { api } from "@/lib/api";
import { NETWORK_NAME, config } from "@config/config";
import { LeakageResultDetail, LeakageSchemeRecord } from "./types";
interface Props {
onViewResult: (result: LeakageResultDetail) => void;
}
const SchemeQuery: React.FC<Props> = ({ onViewResult }) => {
const { open } = useNotification();
const [queryAll, setQueryAll] = useState(true);
const [queryDate, setQueryDate] = useState<Dayjs | null>(dayjs());
const [schemes, setSchemes] = useState<LeakageSchemeRecord[]>([]);
const [loading, setLoading] = useState(false);
const [expandedId, setExpandedId] = useState<number | null>(null);
const handleQuery = async () => {
setLoading(true);
try {
const params: Record<string, string> = { network: NETWORK_NAME };
if (!queryAll && queryDate) {
params.query_date = queryDate.startOf("day").toISOString();
}
const response = await api.get(`${config.BACKEND_URL}/api/v1/leakage/schemes/`, {
params,
});
setSchemes(response.data);
} catch (error: any) {
open?.({
type: "error",
message: "查询失败",
description: error?.response?.data?.detail ?? "无法获取方案列表",
});
} finally {
setLoading(false);
}
};
const handleViewSchemeResult = async (schemeName: string) => {
try {
const response = await api.get(
`${config.BACKEND_URL}/api/v1/leakage/schemes/${encodeURIComponent(schemeName)}`,
{ params: { network: NETWORK_NAME } },
);
onViewResult(response.data as LeakageResultDetail);
} catch (error: any) {
open?.({
type: "error",
message: "查看详情失败",
description: error?.response?.data?.detail ?? "无法获取方案详情",
});
}
};
return (
<Box className="flex flex-col h-full">
<Box className="mb-2 p-2 bg-gray-50 rounded">
<Box className="flex items-center gap-2 justify-between">
<Box className="flex items-center gap-2">
<FormControlLabel
control={
<Checkbox
size="small"
checked={queryAll}
onChange={(e) => setQueryAll(e.target.checked)}
/>
}
label={<Typography variant="body2"></Typography>}
className="m-0"
/>
<LocalizationProvider dateAdapter={AdapterDayjs} adapterLocale="zh-cn">
<DatePicker
value={queryDate}
onChange={setQueryDate}
disabled={queryAll}
format="YYYY-MM-DD"
slotProps={{ textField: { size: "small", sx: { width: 200 } } }}
/>
</LocalizationProvider>
</Box>
<Button
variant="contained"
onClick={handleQuery}
disabled={loading}
size="small"
className="bg-blue-600 hover:bg-blue-700"
sx={{ minWidth: 80 }}
>
{loading ? "查询中..." : "查询"}
</Button>
</Box>
</Box>
<Box className="flex-1 overflow-auto">
{schemes.length === 0 ? (
<Box className="flex flex-col items-center justify-center h-full text-gray-400">
<Box className="mb-4">
<svg
width="80"
height="80"
viewBox="0 0 80 80"
fill="none"
className="opacity-40"
>
<rect
x="10"
y="20"
width="60"
height="45"
rx="2"
stroke="currentColor"
strokeWidth="2"
/>
<line
x1="10"
y1="30"
x2="70"
y2="30"
stroke="currentColor"
strokeWidth="2"
/>
</svg>
</Box>
<Typography variant="body2"> 0 </Typography>
<Typography variant="body2" className="mt-1">
No data
</Typography>
</Box>
) : (
<Box className="space-y-2 p-2">
<Typography variant="caption" className="text-gray-500 px-2">
{schemes.length}
</Typography>
{schemes.map((scheme) => (
<Card key={scheme.scheme_id} variant="outlined" className="hover:shadow-md transition-shadow">
<CardContent className="p-3 pb-2 last:pb-3">
<Box className="flex items-start justify-between gap-2 mb-2">
<Box className="flex-1 min-w-0">
<Box className="flex items-center gap-2 mb-1">
<Typography variant="body2" className="font-medium truncate" title={scheme.scheme_name}>
{scheme.scheme_name}
</Typography>
<Chip size="small" variant="outlined" color="primary" label="DMA漏损" className="h-5" />
</Box>
<Typography variant="caption" className="text-gray-500 block">
ID: {scheme.scheme_id} · : {dayjs(scheme.create_time).format("MM-DD")}
</Typography>
</Box>
<Box className="flex gap-1 ml-2">
<Tooltip title={expandedId === scheme.scheme_id ? "收起详情" : "查看详情"}>
<IconButton
size="small"
onClick={() => setExpandedId(expandedId === scheme.scheme_id ? null : scheme.scheme_id)}
color="primary"
className="p-1"
>
<InfoIcon fontSize="small" />
</IconButton>
</Tooltip>
</Box>
</Box>
<Collapse in={expandedId === scheme.scheme_id}>
<Box className="mt-2 pt-3 border-t border-gray-200">
<Box className="mb-3 rounded-md bg-gray-50 px-3 py-2 space-y-2">
<Box className="grid grid-cols-[78px_1fr] items-center gap-x-2">
<Typography variant="caption" className="text-gray-600">
:
</Typography>
<Typography variant="caption" className="font-medium text-gray-900">
{String((scheme.scheme_detail as any)?.result_summary?.area_count ?? "-")}
</Typography>
</Box>
<Box className="grid grid-cols-[78px_1fr] items-center gap-x-2">
<Typography variant="caption" className="text-gray-600">
:
</Typography>
<Typography variant="caption" className="font-medium text-gray-900">
{scheme.username || "-"}
</Typography>
</Box>
<Box className="grid grid-cols-[78px_1fr] items-center gap-x-2">
<Typography variant="caption" className="text-gray-600">
:
</Typography>
<Typography variant="caption" className="font-medium text-gray-900">
{(() => {
const value = Number((scheme.scheme_detail as any)?.result_summary?.max_leakage);
return Number.isFinite(value) ? `${value.toFixed(3)} m3/s` : "-";
})()}
</Typography>
</Box>
<Box className="grid grid-cols-[78px_1fr] items-center gap-x-2">
<Typography variant="caption" className="text-gray-600">
:
</Typography>
<Typography variant="caption" className="font-medium text-gray-900">
{(() => {
const value = Number((scheme.scheme_detail as any)?.algorithm_params?.q_sum);
const unit = String((scheme.scheme_detail as any)?.algorithm_params?.q_sum_unit || "m3/s");
return Number.isFinite(value) ? `${value.toFixed(3)} ${unit}` : "-";
})()}
</Typography>
</Box>
<Box className="grid grid-cols-[78px_1fr] items-center gap-x-2">
<Typography variant="caption" className="text-gray-600">
:
</Typography>
<Typography variant="caption" className="font-medium text-gray-900">
{dayjs(scheme.scheme_start_time || scheme.create_time).format("YYYY-MM-DD HH:mm")}
</Typography>
</Box>
</Box>
<Box className="pt-2 border-t border-gray-100">
<Button
variant="contained"
fullWidth
size="small"
className="bg-blue-600 hover:bg-blue-700"
sx={{ textTransform: "none", fontWeight: 500 }}
onClick={() => handleViewSchemeResult(scheme.scheme_name)}
>
</Button>
</Box>
</Box>
</Collapse>
</CardContent>
</Card>
))}
</Box>
)}
</Box>
</Box>
);
};
export default SchemeQuery;
@@ -0,0 +1,53 @@
export interface LeakageRow {
Area: string;
LeakageRatioRaw: number;
LeakageRatio: number;
LeakageFlow_m3_per_s: number;
}
export interface LeakageSchemeRecord {
scheme_id: number;
scheme_name: string;
scheme_type: string;
username: string;
create_time: string;
scheme_start_time: string;
scheme_detail: Record<string, unknown>;
}
export interface LeakageResultDetail {
scheme_name?: string;
network?: string;
sensor_nodes: string[];
rows: LeakageRow[];
node_area_map: Record<string, string>;
areas: Array<{
area_id: string;
node_count: number;
node_ids: string[];
sensor_nodes: string[];
}>;
drawing_payload: {
type: "FeatureCollection";
features: Array<Record<string, unknown>>;
};
node_visual_payload?: {
type: "FeatureCollection";
features: Array<Record<string, unknown>>;
};
scheme_detail?: {
algorithm_params?: {
q_sum?: number;
q_sum_unit?: string;
[key: string]: unknown;
};
result_summary?: {
area_count?: number;
max_leakage?: number;
};
[key: string]: unknown;
};
scheme_start_time?: string;
create_time?: string;
username?: string;
}