前端项目结构调整

This commit is contained in:
JIANG
2026-03-10 11:04:30 +08:00
parent 7f25bd34d5
commit 520e1cb3f1
52 changed files with 242 additions and 345 deletions
@@ -0,0 +1,494 @@
"use client";
import React, { useState, useRef, useEffect, useCallback } from "react";
import {
Box,
TextField,
Button,
Typography,
IconButton,
Stack,
} from "@mui/material";
import { Close as CloseIcon } from "@mui/icons-material";
import { DateTimePicker } from "@mui/x-date-pickers/DateTimePicker";
import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
import { zhCN as pickerZhCN } from "@mui/x-date-pickers/locales";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import "dayjs/locale/zh-cn"; // 引入中文包
import dayjs, { Dayjs } from "dayjs";
import { useMap } from "@components/olmap/core/MapComponent";
import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
import { Style, Stroke, Icon } from "ol/style";
import { handleMapClickSelectFeatures as mapClickSelectFeatures } from "@/utils/mapQueryService";
import Feature, { FeatureLike } from "ol/Feature";
import { useNotification } from "@refinedev/core";
import { api } from "@/lib/api";
import { config, NETWORK_NAME } from "@/config/config";
import { along, lineString, length, toMercator } from "@turf/turf";
import { Point } from "ol/geom";
import { toLonLat } from "ol/proj";
interface PipePoint {
id: string;
diameter: number;
area: number;
feature?: any; // 存储管道要素用于高亮
}
const AnalysisParameters: React.FC = () => {
const map = useMap();
const { open } = useNotification();
const [pipePoints, setPipePoints] = useState<PipePoint[]>([]);
const [startTime, setStartTime] = useState<Dayjs | null>(dayjs(new Date()));
const [duration, setDuration] = useState<number>(3600);
const [schemeName, setSchemeName] = useState<string>(
"FANGAN" + new Date().getTime(),
);
const [network, setNetwork] = useState<string>(NETWORK_NAME);
const [isSelecting, setIsSelecting] = useState<boolean>(false);
const [highlightLayer, setHighlightLayer] =
useState<VectorLayer<VectorSource> | null>(null);
const [highlightFeatures, setHighlightFeatures] = useState<Feature[]>([]);
const [analyzing, setAnalyzing] = useState<boolean>(false);
// 检查是否所有必要参数都已填写
const isFormValid =
pipePoints.length > 0 &&
startTime !== null &&
duration > 0 &&
schemeName.trim() !== "";
// 初始化管道图层和高亮图层
useEffect(() => {
if (!map) return;
const burstPipeStyle = function (feature: FeatureLike) {
const styles = [];
// 线条样式(底层发光,主线条,内层高亮线)
styles.push(
new Style({
stroke: new Stroke({
color: "rgba(255, 0, 0, 0.3)",
width: 12,
}),
}),
new Style({
stroke: new Stroke({
color: "rgba(255, 0, 0, 1)",
width: 6,
lineDash: [15, 10],
}),
}),
new Style({
stroke: new Stroke({
color: "rgba(255, 102, 102, 1)",
width: 3,
lineDash: [15, 10],
}),
}),
);
const geometry = feature.getGeometry();
const lineCoords =
geometry?.getType() === "LineString"
? (geometry as any).getCoordinates()
: null;
if (geometry) {
const lineCoordsWGS84 = lineCoords.map((coord: []) => {
const [lon, lat] = toLonLat(coord);
return [lon, lat];
});
// 计算中点
const lineStringFeature = lineString(lineCoordsWGS84);
const lineLength = length(lineStringFeature);
const midPoint = along(lineStringFeature, lineLength / 2).geometry
.coordinates;
// 在中点添加 icon 样式
const midPointMercator = toMercator(midPoint);
styles.push(
new Style({
geometry: new Point(midPointMercator),
image: new Icon({
src: "/icons/burst_pipe.svg",
scale: 0.2,
anchor: [0.5, 1],
}),
}),
);
}
return styles;
};
// 创建高亮图层
const highlightLayer = new VectorLayer({
source: new VectorSource(),
style: burstPipeStyle,
properties: {
name: "高亮管道",
value: "highlight_pipeline",
},
});
map.addLayer(highlightLayer);
setHighlightLayer(highlightLayer);
return () => {
map.removeLayer(highlightLayer);
map.un("click", handleMapClickSelectFeatures);
};
}, [map]);
// 高亮要素的函数
useEffect(() => {
if (!highlightLayer) {
return;
}
const source = highlightLayer.getSource();
if (!source) {
return;
}
// 清除之前的高亮
source.clear();
// 添加新的高亮要素
highlightFeatures.forEach((feature) => {
if (feature instanceof Feature) {
source.addFeature(feature);
}
});
}, [highlightFeatures]);
// 同步高亮要素和爆管点信息
useEffect(() => {
setPipePoints((prevPipes) => {
// 移除不在highlightFeatures中的
const filtered = prevPipes.filter((pipe) =>
highlightFeatures.some(
(feature) => feature.getProperties().id === pipe.id,
),
);
// 添加新的
const newPipes = highlightFeatures
.filter(
(feature) =>
!filtered.some((p) => p.id === feature.getProperties().id),
)
.map((feature) => {
const properties = feature.getProperties();
return {
id: properties.id,
diameter: properties.diameter || 0,
area: 15,
feature: feature,
};
});
return [...filtered, ...newPipes];
});
}, [highlightFeatures]);
// 地图点击选择要素事件处理函数
const handleMapClickSelectFeatures = useCallback(
async (event: { coordinate: number[] }) => {
if (!map) return;
const feature = await mapClickSelectFeatures(event, map);
const layer = feature?.getId()?.toString().split(".")[0];
if (!feature) return;
if (
feature.getGeometry()?.getType() === "Point" ||
(layer !== "geo_pipes_mat" && layer !== "geo_pipes")
) {
// 点类型几何不处理
open?.({
type: "error",
message: "请选择线类型管道要素。",
});
return;
}
const featureId = feature.getProperties().id;
setHighlightFeatures((prev) => {
const existingIndex = prev.findIndex(
(f) => f.getProperties().id === featureId,
);
if (existingIndex !== -1) {
// 如果已存在,移除
return prev.filter((_, i) => i !== existingIndex);
} else {
// 如果不存在,添加
return [...prev, feature];
}
});
},
[map],
);
// 开始选择管道
const handleStartSelection = () => {
if (!map) return;
setIsSelecting(true);
// 注册点击事件
map.on("click", handleMapClickSelectFeatures);
};
// 结束选择管道
const handleEndSelection = () => {
if (!map) return;
setIsSelecting(false);
// 移除点击事件
map.un("click", handleMapClickSelectFeatures);
};
const handleRemovePipe = (id: string) => {
// 从高亮features中移除
setHighlightFeatures((prev) =>
prev.filter((f) => f.getProperties().id !== id),
);
};
const handleAreaChange = (id: string, value: string) => {
const numValue = parseFloat(value) || 0;
setPipePoints((prev) =>
prev.map((pipe) => (pipe.id === id ? { ...pipe, area: numValue } : pipe)),
);
};
const handleAnalyze = async () => {
setAnalyzing(true);
// 显示处理中的通知
open?.({
key: "burst-analysis",
type: "progress",
message: "方案提交分析中",
undoableTimeout: 3,
});
const burst_ID = pipePoints.map((pipe) => pipe.id);
const burst_size = pipePoints.map((pipe) =>
parseInt(pipe.area.toString(), 10),
);
// 格式化开始时间,去除秒部分
const modify_pattern_start_time = startTime
? startTime.format("YYYY-MM-DDTHH:mm:00Z")
: "";
const modify_total_duration = duration;
const params = {
network: network,
modify_pattern_start_time: modify_pattern_start_time,
burst_ID: burst_ID,
burst_size: burst_size,
modify_total_duration: modify_total_duration,
scheme_name: schemeName,
};
try {
await api.get(`${config.BACKEND_URL}/api/v1/burst_analysis/`, {
params,
paramsSerializer: {
indexes: null, // 移除数组索引,即由 burst_ID[] 变为 burst_ID
},
});
// 更新弹窗为成功状态
open?.({
key: "burst-analysis",
type: "success",
message: "方案分析成功",
description: "方案分析完成,请在方案查询中查看结果。",
});
} catch (error) {
console.error("分析请求失败:", error);
// 更新弹窗为失败状态
open?.({
key: "burst-analysis",
type: "error",
message: "提交分析失败",
description:
error instanceof Error ? error.message : "请检查网络连接或稍后重试",
});
} finally {
setAnalyzing(false);
}
};
return (
<Box className="flex flex-col h-full">
{/* 选择爆管点 */}
<Box className="mb-4">
<Box className="flex items-center justify-between mb-2">
<Typography variant="subtitle2" className="font-medium">
</Typography>
{/* 开始/结束选择按钮 */}
{!isSelecting ? (
<Button
variant="outlined"
size="small"
onClick={handleStartSelection}
className="border-blue-500 text-blue-600 hover:bg-blue-50"
startIcon={
<svg
className="w-4 h-4"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M15 15l-2 5L9 9l11 4-5 2zm0 0l5 5M7.188 2.239l.777 2.897M5.136 7.965l-2.898-.777M13.95 4.05l-2.122 2.122m-5.657 5.656l-2.12 2.122"
/>
</svg>
}
>
</Button>
) : (
<Button
variant="contained"
size="small"
onClick={handleEndSelection}
className="bg-red-500 hover:bg-red-600"
startIcon={
<svg
className="w-4 h-4"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M6 18L18 6M6 6l12 12"
/>
</svg>
}
>
</Button>
)}
</Box>
{isSelecting && (
<Box className="mb-2 p-2 bg-blue-50 border border-blue-200 rounded text-xs text-blue-700">
💡
</Box>
)}
<Stack spacing={2}>
{pipePoints.map((pipe) => (
<Box
key={pipe.id}
className="flex items-center gap-2 p-2 bg-gray-50 rounded"
>
<Typography className="flex-shrink-0 text-sm pl-1">
{pipe.id}
</Typography>
<Typography className="flex-shrink-0 text-sm text-gray-600">
: {pipe.diameter} mm
</Typography>
<Typography className="flex-shrink-0 text-sm text-gray-600 mr-2">
</Typography>
<TextField
size="small"
value={pipe.area}
onChange={(e) => handleAreaChange(pipe.id, e.target.value)}
type="number"
className="w-25"
slotProps={{
input: {
endAdornment: (
<span className="text-xs text-gray-500">cm²</span>
),
},
}}
/>
<IconButton
size="small"
onClick={() => handleRemovePipe(pipe.id)}
className="ml-auto"
>
<CloseIcon fontSize="small" />
</IconButton>
</Box>
))}
</Stack>
</Box>
{/* 选择开始时间 */}
<Box className="mb-4">
<Typography variant="subtitle2" className="mb-2 font-medium">
</Typography>
<LocalizationProvider dateAdapter={AdapterDayjs} adapterLocale="zh-cn">
<DateTimePicker
value={startTime}
onChange={(value) =>
value && dayjs.isDayjs(value) && setStartTime(value)
}
format="YYYY-MM-DD HH:mm"
slotProps={{
textField: {
size: "small",
fullWidth: true,
},
}}
localeText={
pickerZhCN.components.MuiLocalizationProvider.defaultProps
.localeText
}
/>
</LocalizationProvider>
</Box>
{/* 持续时长 */}
<Box className="mb-4">
<Typography variant="subtitle2" className="mb-2 font-medium">
()
</Typography>
<TextField
fullWidth
size="small"
type="number"
value={duration}
onChange={(e) => setDuration(parseInt(e.target.value) || 0)}
placeholder="输入持续时长"
/>
</Box>
{/* 方案名称 */}
<Box className="mb-4">
<Typography variant="subtitle2" className="mb-2 font-medium">
</Typography>
<TextField
fullWidth
size="small"
value={schemeName}
onChange={(e) => setSchemeName(e.target.value)}
placeholder="输入方案名称"
/>
</Box>
{/* 方案分析按钮 */}
<Box className="mt-auto">
<Button
fullWidth
variant="contained"
size="large"
onClick={handleAnalyze}
disabled={analyzing || !isFormValid}
className="bg-blue-600 hover:bg-blue-700"
>
{analyzing ? "方案提交分析中..." : "方案分析"}
</Button>
</Box>
</Box>
);
};
export default AnalysisParameters;
@@ -0,0 +1,258 @@
"use client";
import React, { useState } from "react";
import {
Box,
Drawer,
Tabs,
Tab,
Typography,
IconButton,
Tooltip,
} from "@mui/material";
import {
ChevronRight,
ChevronLeft,
Analytics as AnalyticsIcon,
Search as SearchIcon,
MyLocation as MyLocationIcon,
Handyman as HandymanIcon,
} from "@mui/icons-material";
import AnalysisParameters from "./AnalysisParameters";
import SchemeQuery from "./SchemeQuery";
import LocationResults from "./LocationResults";
import ValveIsolation from "./ValveIsolation";
import { api } from "@/lib/api";
import { config } from "@config/config";
import { useNotification } from "@refinedev/core";
import { LocationResult, SchemeRecord, ValveIsolationResult } from "./types";
interface TabPanelProps {
children?: React.ReactNode;
index: number;
value: number;
}
const TabPanel: React.FC<TabPanelProps> = ({ children, value, index }) => {
return (
<div
role="tabpanel"
hidden={value !== index}
className="flex-1 overflow-hidden flex flex-col"
>
{value === index && (
<Box className="flex-1 overflow-auto p-4">{children}</Box>
)}
</div>
);
};
interface BurstPipeAnalysisPanelProps {
open?: boolean;
onToggle?: () => void;
}
const BurstPipeAnalysisPanel: React.FC<BurstPipeAnalysisPanelProps> = ({
open: controlledOpen,
onToggle,
}) => {
const [internalOpen, setInternalOpen] = useState(true);
const [currentTab, setCurrentTab] = useState(0);
// 持久化方案查询结果
const [schemes, setSchemes] = useState<SchemeRecord[]>([]);
// 定位结果数据
const [locationResults, setLocationResults] = useState<LocationResult[]>([]);
// 关阀分析结果和加载状态
const [valveAnalysisLoading, setValveAnalysisLoading] = useState(false);
const [valveAnalysisResult, setValveAnalysisResult] = useState<ValveIsolationResult | null>(null);
const { open } = useNotification();
// 使用受控或非受控状态
const isOpen = controlledOpen !== undefined ? controlledOpen : internalOpen;
const handleToggle = () => {
if (onToggle) {
onToggle();
} else {
setInternalOpen(!internalOpen);
}
};
const handleTabChange = (_event: React.SyntheticEvent, newValue: number) => {
setCurrentTab(newValue);
};
const handleLocateScheme = async (scheme: SchemeRecord) => {
try {
const response = await api.get(
`${config.BACKEND_URL}/api/v1/burst-locate-result/${scheme.schemeName}`,
);
setLocationResults(response.data);
setCurrentTab(2); // 切换到定位结果标签页
} catch (error) {
console.error("获取定位结果失败:", error);
open?.({
type: "error",
message: "获取定位结果失败",
description: "无法从服务器获取该方案的定位结果",
});
}
};
const drawerWidth = 520;
const panelTitle = "爆管分析";
return (
<>
{/* 收起时的触发按钮 */}
{!isOpen && (
<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={handleToggle}
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={isOpen}
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={handleToggle}
sx={{ color: "primary.contrastText" }}
>
<ChevronRight fontSize="small" />
</IconButton>
</Tooltip>
</Box>
<Box className="border-b border-gray-200 bg-white">
<Tabs
value={currentTab}
onChange={handleTabChange}
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={<MyLocationIcon fontSize="small" />}
iconPosition="start"
label="定位结果"
/>
<Tab
icon={<HandymanIcon fontSize="small" />}
iconPosition="start"
label="关阀分析"
/>
</Tabs>
</Box>
{/* Tab 内容 */}
<TabPanel value={currentTab} index={0}>
<AnalysisParameters />
</TabPanel>
<TabPanel value={currentTab} index={1}>
<SchemeQuery
schemes={schemes}
onSchemesChange={setSchemes}
onLocate={handleLocateScheme}
/>
</TabPanel>
<TabPanel value={currentTab} index={2}>
<LocationResults
results={locationResults}
/>
</TabPanel>
<TabPanel value={currentTab} index={3}>
<ValveIsolation
loading={valveAnalysisLoading}
result={valveAnalysisResult}
onLoadingChange={setValveAnalysisLoading}
onResultChange={setValveAnalysisResult}
/>
</TabPanel>
</Box>
</Drawer>
</>
);
};
export default BurstPipeAnalysisPanel;
@@ -0,0 +1,418 @@
"use client";
import React, { useState, useEffect } from "react";
import {
Box,
Typography,
Chip,
IconButton,
Tooltip,
Link,
} from "@mui/material";
import {
LocationOn as LocationIcon,
} from "@mui/icons-material";
import { queryFeaturesByIds } from "@/utils/mapQueryService";
import { useMap } from "@components/olmap/core/MapComponent";
import { GeoJSON } from "ol/format";
import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
import { Stroke, Style, Icon } from "ol/style";
import Feature, { FeatureLike } from "ol/Feature";
import {
along,
lineString,
length,
toMercator,
bbox,
featureCollection,
} from "@turf/turf";
import { Point } from "ol/geom";
import { toLonLat } from "ol/proj";
import moment from "moment";
import "moment-timezone";
import { LocationResult } from "./types";
import { FLOW_DISPLAY_UNIT } from "@utils/units";
interface LocationResultsProps {
results?: LocationResult[];
}
const LocationResults: React.FC<LocationResultsProps> = ({
results = [],
}) => {
const [highlightLayer, setHighlightLayer] =
useState<VectorLayer<VectorSource> | null>(null);
const [highlightFeatures, setHighlightFeatures] = useState<Feature[]>([]);
const map = useMap();
// 格式化时间为 UTC+8
const formatTime = (timeStr: string) => {
return moment(timeStr).utcOffset(8).format("YYYY-MM-DD HH:mm:ss");
};
const handleLocatePipes = (pipeIds: string[]) => {
if (pipeIds.length > 0) {
queryFeaturesByIds(pipeIds, "geo_pipes_mat").then((features) => {
if (features.length > 0) {
// 设置高亮要素
setHighlightFeatures(features);
// 将 OpenLayers Feature 转换为 GeoJSON Feature
const geojsonFormat = new GeoJSON();
const geojsonFeatures = features.map((feature) =>
geojsonFormat.writeFeatureObject(feature),
);
const extent = bbox(featureCollection(geojsonFeatures as any));
if (extent) {
map?.getView().fit(extent, { maxZoom: 18, duration: 1000 });
}
}
});
}
};
// 初始化管道图层和高亮图层
useEffect(() => {
if (!map) return;
const burstPipeStyle = function (feature: FeatureLike) {
const styles = [];
// 线条样式(底层发光,主线条,内层高亮线)
styles.push(
new Style({
stroke: new Stroke({
color: "rgba(255, 0, 0, 0.3)",
width: 12,
}),
}),
new Style({
stroke: new Stroke({
color: "rgba(255, 0, 0, 1)",
width: 6,
lineDash: [15, 10],
}),
}),
new Style({
stroke: new Stroke({
color: "rgba(255, 102, 102, 1)",
width: 3,
lineDash: [15, 10],
}),
}),
);
const geometry = feature.getGeometry();
const lineCoords =
geometry?.getType() === "LineString"
? (geometry as any).getCoordinates()
: null;
if (geometry && lineCoords) {
const lineCoordsWGS84 = lineCoords.map((coord: []) => {
const [lon, lat] = toLonLat(coord);
return [lon, lat];
});
// 计算中点
const lineStringFeature = lineString(lineCoordsWGS84);
const lineLength = length(lineStringFeature);
const midPoint = along(lineStringFeature, lineLength / 2).geometry
.coordinates;
// 在中点添加 icon 样式
const midPointMercator = toMercator(midPoint);
styles.push(
new Style({
geometry: new Point(midPointMercator),
image: new Icon({
src: "/icons/burst_pipe.svg",
scale: 0.2,
anchor: [0.5, 1],
}),
}),
);
}
return styles;
};
// 创建高亮图层
const highlightLayer = new VectorLayer({
source: new VectorSource(),
style: burstPipeStyle,
maxZoom: 24,
minZoom: 12,
properties: {
name: "爆管管段高亮",
value: "burst_pipe_highlight",
},
});
map.addLayer(highlightLayer);
setHighlightLayer(highlightLayer);
return () => {
map.removeLayer(highlightLayer);
};
}, [map]);
// 高亮要素的函数
useEffect(() => {
if (!highlightLayer) {
return;
}
const source = highlightLayer.getSource();
if (!source) {
return;
}
// 清除之前的高亮
source.clear();
// 添加新的高亮要素
highlightFeatures.forEach((feature) => {
if (feature instanceof Feature) {
source.addFeature(feature);
}
});
}, [highlightFeatures, highlightLayer]);
// 取第一条记录或空对象
const result = results.length > 0 ? results[0] : null;
return (
<Box className="flex flex-col h-full">
{/* 结果展示 */}
<Box className="flex-1 overflow-auto bg-white rounded border border-gray-200">
{!result ? (
<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"
>
<circle
cx="40"
cy="40"
r="25"
stroke="currentColor"
strokeWidth="2"
/>
<circle cx="40" cy="40" r="5" fill="currentColor" />
<line
x1="40"
y1="15"
x2="40"
y2="25"
stroke="currentColor"
strokeWidth="2"
/>
<line
x1="40"
y1="55"
x2="40"
y2="65"
stroke="currentColor"
strokeWidth="2"
/>
<line
x1="15"
y1="40"
x2="25"
y2="40"
stroke="currentColor"
strokeWidth="2"
/>
<line
x1="55"
y1="40"
x2="65"
y2="40"
stroke="currentColor"
strokeWidth="2"
/>
</svg>
</Box>
<Typography variant="body2"></Typography>
<Typography variant="body2" className="mt-1">
</Typography>
</Box>
) : (
<Box className="p-5 h-full overflow-auto">
{/* 头部:标识信息 */}
<Box className="mb-5">
<Box className="flex items-center gap-2 mb-1">
<Typography
variant="h6"
className="font-bold text-gray-900"
title={result.burst_incident}
>
{result.burst_incident}
</Typography>
<Chip
label={
result.type === "burst_analysis" ? "爆管模拟" : result.type
}
size="small"
color="primary"
variant="outlined"
sx={{
fontWeight: 600,
fontSize: "0.75rem",
height: "24px",
}}
/>
</Box>
<Typography variant="caption" className="text-gray-500">
ID: {result.id}
</Typography>
</Box>
{/* 主要信息:三栏卡片布局 */}
<Box className="grid grid-cols-3 gap-3 mb-5">
{/* 检测时间卡片 */}
<Box className="bg-gradient-to-br from-blue-50 to-blue-100 rounded-lg p-3 border border-blue-200 shadow-sm hover:shadow-md transition-shadow">
<Box className="flex items-center gap-1.5 mb-2">
<Box className="w-1.5 h-1.5 rounded-full bg-blue-600"></Box>
<Typography
variant="caption"
className="text-blue-700 font-semibold uppercase tracking-wide"
sx={{ fontSize: "0.7rem" }}
>
</Typography>
</Box>
<Typography
variant="body2"
className="font-bold text-blue-900 leading-tight"
sx={{ fontSize: "0.875rem" }}
>
{formatTime(result.detect_time)}
</Typography>
</Box>
{/* 漏损量卡片 */}
<Box className="bg-gradient-to-br from-orange-50 to-orange-100 rounded-lg p-3 border border-orange-200 shadow-sm hover:shadow-md transition-shadow">
<Box className="flex items-center gap-1.5 mb-2">
<Box className="w-1.5 h-1.5 rounded-full bg-orange-600"></Box>
<Typography
variant="caption"
className="text-orange-700 font-semibold uppercase tracking-wide"
sx={{ fontSize: "0.7rem" }}
>
</Typography>
</Box>
<Typography
variant="body2"
className="font-bold text-orange-900"
sx={{ fontSize: "0.875rem" }}
>
{result.leakage !== null
? `${result.leakage.toFixed(2)} ${FLOW_DISPLAY_UNIT}`
: "N/A"}
</Typography>
</Box>
{/* 定位管段数量卡片 */}
<Box className="bg-gradient-to-br from-green-50 to-green-100 rounded-lg p-3 border border-green-200 shadow-sm hover:shadow-md transition-shadow">
<Box className="flex items-center gap-1.5 mb-2">
<Box className="w-1.5 h-1.5 rounded-full bg-green-600"></Box>
<Typography
variant="caption"
className="text-green-700 font-semibold uppercase tracking-wide"
sx={{ fontSize: "0.7rem" }}
>
</Typography>
</Box>
<Typography
variant="body2"
className="font-bold text-green-900"
sx={{ fontSize: "0.875rem" }}
>
{result.locate_result ? result.locate_result.length : 0}{" "}
</Typography>
</Box>
</Box>
{/* 定位管段详细列表 */}
{result.locate_result && result.locate_result.length > 0 && (
<Box className="bg-white rounded-lg p-4 border-2 border-blue-200 shadow-sm">
<Box className="flex items-center justify-between mb-3">
<Typography
variant="body1"
className="text-gray-900 font-bold"
sx={{ fontSize: "0.95rem" }}
>
</Typography>
<Box className="flex items-center gap-2">
<Tooltip title="定位所有管道">
<IconButton
size="small"
onClick={() => handleLocatePipes(result.locate_result!)}
color="primary"
sx={{
backgroundColor: "rgba(37, 125, 212, 0.1)",
"&:hover": {
backgroundColor: "rgba(37, 125, 212, 0.2)",
},
}}
>
<LocationIcon sx={{ fontSize: "1.2rem" }} />
</IconButton>
</Tooltip>
</Box>
</Box>
<Box className="grid grid-cols-2 gap-2">
{result.locate_result.map((pipeId, idx) => (
<Box
key={idx}
className="bg-gradient-to-r from-blue-50 to-white rounded-lg px-3 py-2 border border-blue-200 hover:border-blue-400 hover:shadow-md transition-all cursor-pointer group"
onClick={() => handleLocatePipes([pipeId])}
sx={{
"&:active": {
transform: "scale(0.98)",
boxShadow: "0 1px 2px rgba(25, 118, 210, 0.2)",
},
}}
>
<Box className="flex items-center justify-between">
<Typography
variant="body2"
className="font-semibold text-blue-700 group-hover:text-blue-900"
>
{pipeId}
</Typography>
<Box className="flex items-center gap-1">
{/* <Tooltip title="定位管段">
<IconButton
size="small"
onClick={(e) => {
e.stopPropagation();
handleLocatePipes([pipeId]);
}}
sx={{
"&:hover": {
backgroundColor: "rgba(37, 125, 212, 0.1)",
},
}}
>
<LocationIcon sx={{ fontSize: "1rem" }} />
</IconButton>
</Tooltip> */}
</Box>
</Box>
</Box>
))}
</Box>
</Box>
)}
</Box>
)}
</Box>
</Box>
);
};
export default LocationResults;
@@ -0,0 +1,673 @@
"use client";
import React, { useEffect, useMemo, useState } from "react";
import ReactDOM from "react-dom"; // 添加这行
import {
Box,
Button,
Typography,
Checkbox,
FormControlLabel,
IconButton,
Card,
CardContent,
Chip,
Tooltip,
Collapse,
Link,
} from "@mui/material";
import {
Info as InfoIcon,
LocationOn as LocationIcon,
} 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 { api } from "@/lib/api";
import moment from "moment";
import { config, NETWORK_NAME } from "@config/config";
import { useNotification } from "@refinedev/core";
import { queryFeaturesByIds } from "@/utils/mapQueryService";
import { useData, useMap } from "@components/olmap/core/MapComponent";
import { GeoJSON } from "ol/format";
import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
import { Stroke, Style, Icon } from "ol/style";
import Feature, { FeatureLike } from "ol/Feature";
import {
along,
lineString,
length,
toMercator,
bbox,
featureCollection,
} from "@turf/turf";
import { Point } from "ol/geom";
import { toLonLat } from "ol/proj";
import Timeline from "@components/olmap/core/Controls/Timeline";
import { SchemaItem, SchemeRecord } from "./types";
interface SchemeQueryProps {
schemes?: SchemeRecord[];
onSchemesChange?: (schemes: SchemeRecord[]) => void;
onLocate?: (scheme: SchemeRecord) => void;
network?: string;
}
const SCHEME_TYPE = "burst_analysis";
const SchemeQuery: React.FC<SchemeQueryProps> = ({
schemes: externalSchemes,
onSchemesChange,
onLocate,
network = NETWORK_NAME,
}) => {
const [queryAll, setQueryAll] = useState<boolean>(true);
const [queryDate, setQueryDate] = useState<Dayjs | null>(dayjs(new Date()));
const [highlightLayer, setHighlightLayer] =
useState<VectorLayer<VectorSource> | null>(null);
const [highlightFeatures, setHighlightFeatures] = useState<Feature[]>([]);
// 时间轴相关状态
const [showTimeline, setShowTimeline] = useState(false);
const [selectedDate, setSelectedDate] = useState<Date | undefined>(undefined);
const [timeRange, setTimeRange] = useState<
{ start: Date; end: Date } | undefined
>();
const [internalSchemes, setInternalSchemes] = useState<SchemeRecord[]>([]);
const [loading, setLoading] = useState<boolean>(false);
const [expandedId, setExpandedId] = useState<number | null>(null);
const [mapContainer, setMapContainer] = useState<HTMLElement | null>(null); // 地图容器元素
const { open } = useNotification();
const map = useMap();
const data = useData();
const { schemeName, setSchemeName } = data || {};
// 使用外部提供的 schemes 或内部状态
const schemes =
externalSchemes !== undefined ? externalSchemes : internalSchemes;
const setSchemes = onSchemesChange || setInternalSchemes;
// 格式化日期为简短格式
const formatTime = (timeStr: string) => {
const time = moment(timeStr);
return time.format("MM-DD");
};
const filteredSchemes = useMemo(() => {
return schemes.filter((scheme) => scheme.type === SCHEME_TYPE);
}, [schemes]);
const handleQuery = async () => {
if (!queryAll && !queryDate) return;
setLoading(true);
try {
const response = await api.get(
`${config.BACKEND_URL}/api/v1/getallschemes/?network=${network}`,
);
let filteredResults = response.data;
if (!queryAll) {
const formattedDate = queryDate!.format("YYYY-MM-DD");
filteredResults = response.data.filter((item: SchemaItem) => {
const itemDate = moment(item.create_time).format("YYYY-MM-DD");
return itemDate === formattedDate;
});
}
setSchemes(
filteredResults.map((item: SchemaItem) => ({
id: item.scheme_id,
schemeName: item.scheme_name,
type: item.scheme_type,
user: item.username,
create_time: item.create_time,
startTime: item.scheme_start_time,
schemeDetail: item.scheme_detail,
})),
);
if (filteredResults.length === 0) {
open?.({
type: "error",
message: "查询结果",
description: queryAll
? "没有找到任何方案"
: `${queryDate!.format("YYYY-MM-DD")} 没有找到相关方案`,
});
}
} catch (error) {
console.error("查询请求失败:", error);
open?.({
type: "error",
message: "查询失败",
description: "获取方案列表失败,请稍后重试",
});
} finally {
setLoading(false);
}
};
const handleLocatePipes = (pipeIds: string[]) => {
if (pipeIds.length > 0) {
queryFeaturesByIds(pipeIds, "geo_pipes_mat").then((features) => {
if (features.length > 0) {
// 设置高亮要素
setHighlightFeatures(features);
// 将 OpenLayers Feature 转换为 GeoJSON Feature
const geojsonFormat = new GeoJSON();
const geojsonFeatures = features.map((feature) =>
geojsonFormat.writeFeatureObject(feature),
);
const extent = bbox(featureCollection(geojsonFeatures as any));
if (extent) {
map?.getView().fit(extent, { maxZoom: 18, duration: 1000 });
}
}
});
}
};
// 内部的方案查询函数
const handleViewDetails = (id: number) => {
const scheme = filteredSchemes.find((s) => s.id === id);
if (!scheme) return;
setShowTimeline(true);
// 计算时间范围
const schemeDate = scheme.startTime
? new Date(scheme.startTime)
: undefined;
if (scheme.startTime && scheme.schemeDetail?.modify_total_duration) {
const start = new Date(scheme.startTime);
const end = new Date(
start.getTime() + scheme.schemeDetail.modify_total_duration * 1000,
);
setSelectedDate(schemeDate);
setTimeRange({ start, end });
}
setSchemeName?.(scheme.schemeName);
handleLocatePipes(scheme.schemeDetail?.burst_ID || []);
};
// 初始化管道图层和高亮图层
useEffect(() => {
if (!map) return;
// 获取地图的目标容器
const target = map.getTargetElement();
if (target) {
setMapContainer(target);
}
const burstPipeStyle = function (feature: FeatureLike) {
const styles = [];
// 线条样式(底层发光,主线条,内层高亮线)
styles.push(
new Style({
stroke: new Stroke({
color: "rgba(255, 0, 0, 0.3)",
width: 12,
}),
}),
new Style({
stroke: new Stroke({
color: "rgba(255, 0, 0, 1)",
width: 6,
lineDash: [15, 10],
}),
}),
new Style({
stroke: new Stroke({
color: "rgba(255, 102, 102, 1)",
width: 3,
lineDash: [15, 10],
}),
}),
);
const geometry = feature.getGeometry();
const lineCoords =
geometry?.getType() === "LineString"
? (geometry as any).getCoordinates()
: null;
if (geometry) {
const lineCoordsWGS84 = lineCoords.map((coord: []) => {
const [lon, lat] = toLonLat(coord);
return [lon, lat];
});
// 计算中点
const lineStringFeature = lineString(lineCoordsWGS84);
const lineLength = length(lineStringFeature);
const midPoint = along(lineStringFeature, lineLength / 2).geometry
.coordinates;
// 在中点添加 icon 样式
const midPointMercator = toMercator(midPoint);
styles.push(
new Style({
geometry: new Point(midPointMercator),
image: new Icon({
src: "/icons/burst_pipe.svg",
scale: 0.2,
anchor: [0.5, 1],
}),
}),
);
}
return styles;
};
// 创建高亮图层
const highlightLayer = new VectorLayer({
source: new VectorSource(),
style: burstPipeStyle,
maxZoom: 24,
minZoom: 12,
properties: {
name: "爆管管段高亮",
value: "burst_pipe_highlight",
},
});
map.addLayer(highlightLayer);
setHighlightLayer(highlightLayer);
return () => {
map.removeLayer(highlightLayer);
};
}, [map]);
// 高亮要素的函数
useEffect(() => {
if (!highlightLayer) {
return;
}
const source = highlightLayer.getSource();
if (!source) {
return;
}
// 清除之前的高亮
source.clear();
// 添加新的高亮要素
highlightFeatures.forEach((feature) => {
if (feature instanceof Feature) {
source.addFeature(feature);
}
});
}, [highlightFeatures]);
return (
<>
{/* 将时间轴渲染到地图容器中 */}
{showTimeline &&
mapContainer &&
ReactDOM.createPortal(
<Timeline
schemeDate={selectedDate}
timeRange={timeRange}
disableDateSelection={!!timeRange}
schemeName={schemeName}
schemeType={SCHEME_TYPE}
/>,
mapContainer, // 渲染到地图容器中,而不是 body
)}
<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
checked={queryAll}
onChange={(e) => setQueryAll(e.target.checked)}
size="small"
/>
}
label={<Typography variant="body2"></Typography>}
className="m-0"
/>
<LocalizationProvider
dateAdapter={AdapterDayjs}
adapterLocale="zh-cn"
>
<DatePicker
value={queryDate}
onChange={(value) =>
value && dayjs.isDayjs(value) && setQueryDate(value)
}
format="YYYY-MM-DD"
disabled={queryAll}
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">
{filteredSchemes.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">
{filteredSchemes.length}
</Typography>
{filteredSchemes.map((scheme) => (
<Card
key={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 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.schemeName}
>
{scheme.schemeName}
</Typography>
<Chip
label={
scheme.type === "burst_analysis"
? "爆管模拟"
: scheme.type
}
size="small"
className="h-5"
color="primary"
variant="outlined"
/>
</Box>
<Typography
variant="caption"
className="text-gray-500 block"
>
ID: {scheme.id} · :{" "}
{formatTime(scheme.create_time)}
</Typography>
</Box>
{/* 操作按钮 */}
<Box className="flex gap-1 ml-2">
<Tooltip
title={
expandedId === scheme.id ? "收起详情" : "查看详情"
}
>
<IconButton
size="small"
onClick={() =>
setExpandedId(
expandedId === scheme.id ? null : scheme.id,
)
}
color="primary"
className="p-1"
>
<InfoIcon fontSize="small" />
</IconButton>
</Tooltip>
<Tooltip title="查看定位结果">
<IconButton
size="small"
onClick={() => onLocate?.(scheme)}
color="primary"
className="p-1"
>
<LocationIcon fontSize="small" />
</IconButton>
</Tooltip>
</Box>
</Box>
{/* 可折叠的详细信息 */}
<Collapse in={expandedId === scheme.id}>
<Box className="mt-2 pt-3 border-t border-gray-200">
{/* 信息网格布局 */}
<Box className="grid grid-cols-2 gap-x-4 gap-y-3 mb-3">
{/* 爆管详情列 */}
<Box className="space-y-2">
<Box className="space-y-1.5 pl-2">
<Box className="flex items-start gap-2">
<Typography
variant="caption"
className="text-gray-600 min-w-[70px] mt-0.5"
>
ID:
</Typography>
<Box className="flex-1 flex flex-wrap gap-1">
{scheme.schemeDetail?.burst_ID?.length ? (
scheme.schemeDetail.burst_ID.map(
(pipeId, index) => (
<Link
key={index}
component="button"
variant="caption"
className="font-medium text-blue-600 hover:text-blue-800 underline cursor-pointer"
onClick={(e) => {
e.preventDefault();
handleLocatePipes?.([pipeId]);
}}
>
{pipeId}
</Link>
),
)
) : (
<Typography
variant="caption"
className="font-medium text-gray-900"
>
N/A
</Typography>
)}
</Box>
</Box>
<Box className="flex items-center gap-2">
<Typography
variant="caption"
className="text-gray-600 min-w-[70px]"
>
:
</Typography>
<Typography
variant="caption"
className="font-medium text-gray-900"
>
560 mm
</Typography>
</Box>
<Box className="flex items-center gap-2">
<Typography
variant="caption"
className="text-gray-600 min-w-[70px]"
>
:
</Typography>
<Typography
variant="caption"
className="font-medium text-gray-900"
>
{scheme.schemeDetail?.burst_size?.[0] ||
"N/A"}{" "}
cm²
</Typography>
</Box>
<Box className="flex items-center gap-2">
<Typography
variant="caption"
className="text-gray-600 min-w-[70px]"
>
:
</Typography>
<Typography
variant="caption"
className="font-medium text-gray-900"
>
{scheme.schemeDetail?.modify_total_duration ||
"N/A"}{" "}
</Typography>
</Box>
</Box>
</Box>
{/* 方案信息列 */}
<Box className="space-y-2">
<Box className="space-y-1.5 pl-2">
<Box className="flex items-center gap-2">
<Typography
variant="caption"
className="text-gray-600 min-w-[70px]"
>
:
</Typography>
<Typography
variant="caption"
className="font-medium text-gray-900"
>
{scheme.user}
</Typography>
</Box>
<Box className="flex items-center gap-2">
<Typography
variant="caption"
className="text-gray-600 min-w-[70px]"
>
:
</Typography>
<Typography
variant="caption"
className="font-medium text-gray-900"
>
{moment(scheme.create_time).format(
"YYYY-MM-DD HH:mm",
)}
</Typography>
</Box>
<Box className="flex items-center gap-2">
<Typography
variant="caption"
className="text-gray-600 min-w-[70px]"
>
:
</Typography>
<Typography
variant="caption"
className="font-medium text-gray-900"
>
{moment(scheme.startTime).format(
"YYYY-MM-DD HH:mm",
)}
</Typography>
</Box>
</Box>
</Box>
</Box>
{/* 操作按钮区域 */}
<Box className="pt-2 border-t border-gray-100 flex gap-5">
{scheme.schemeDetail?.burst_ID?.length ? (
<Button
variant="outlined"
fullWidth
size="small"
className="border-blue-600 text-blue-600 hover:bg-blue-50"
onClick={() =>
handleLocatePipes?.(
scheme.schemeDetail!.burst_ID,
)
}
sx={{
textTransform: "none",
fontWeight: 500,
}}
>
</Button>
) : null}
<Button
variant="contained"
fullWidth
size="small"
className="bg-blue-600 hover:bg-blue-700"
onClick={() => handleViewDetails(scheme.id)}
sx={{
textTransform: "none",
fontWeight: 500,
}}
>
</Button>
</Box>
</Box>
</Collapse>
</CardContent>
</Card>
))}
</Box>
)}
</Box>
</Box>
</>
);
};
export default SchemeQuery;
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,46 @@
export interface SchemeDetail {
burst_ID: string[];
burst_size: number[];
modify_total_duration: number;
modify_fixed_pump_pattern: any;
modify_valve_opening: any;
modify_variable_pump_pattern: any;
}
export interface SchemeRecord {
id: number;
schemeName: string;
type: string;
user: string;
create_time: string;
startTime: string;
// 详情信息
schemeDetail?: SchemeDetail;
}
export interface SchemaItem {
scheme_id: number;
scheme_name: string;
scheme_type: string;
username: string;
create_time: string;
scheme_start_time: string;
scheme_detail?: SchemeDetail;
}
export interface LocationResult {
id: number;
type: string;
burst_incident: string;
leakage: number | null;
detect_time: string;
locate_result: string[] | null;
}
export interface ValveIsolationResult {
accident_elements: string[];
affected_nodes: string[];
must_close_valves: string[];
optional_valves: string[];
isolatable: boolean;
}