Compare commits

...

10 Commits

18 changed files with 1127 additions and 184 deletions

View File

@@ -1,15 +0,0 @@
services:
influxdb:
image: influxdb:2.7
container_name: influxdb
environment:
DOCKER_INFLUXDB_INIT_MODE: setup
DOCKER_INFLUXDB_INIT_USERNAME: tjwater
DOCKER_INFLUXDB_INIT_PASSWORD: Tjwater@123456
DOCKER_INFLUXDB_INIT_ORG: TJWATERORG
DOCKER_INFLUXDB_INIT_BUCKET: TJWATERBUCKET
DOCKER_INFLUXDB_INIT_ADMIN_TOKEN: kMPX2V5HsbzPpUT2B9HPBu1sTG1Emf-lPlT2UjxYnGAuocpXq_f_0lK4HHs-TbbKyjsZpICkMsyXG_V2D7P7yQ==
ports:
- "8086:8086"
volumes:
- C:\Users\admin\Documents\docker\influxdb\data:/var/lib/influxdb2

View File

@@ -1,47 +0,0 @@
services:
postgres:
image: postgis/postgis:14-3.5
container_name: keycloakDB
environment:
POSTGRES_DB: keycloak
POSTGRES_USER: keycloak
POSTGRES_PASSWORD: keycloak
ports:
- "5434:5432"
volumes:
- C:\Users\admin\Documents\docker\keycloakDB\data:/var/lib/postgresql/data
networks:
- keycloak
keycloak:
image: keycloak/keycloak:latest
container_name: keycloak
environment:
environment:
KC_HOSTNAME: localhost
KC_HOSTNAME_STRICT_BACKCHANNEL: "true"
KEYCLOAK_ADMIN: admin
KEYCLOAK_ADMIN_PASSWORD: admin
KC_HEALTH_ENABLED: "true"
KC_LOG_LEVEL: info
KC_DB: postgres
KC_DB_URL: jdbc:postgresql://postgres:5432/keycloak
KC_DB_USERNAME: keycloak
KC_DB_PASSWORD: keycloak
volumes:
- C:\Users\admin\Documents\docker\keycloak\themes:/opt/keycloak/themes
healthcheck:
test: [ "CMD", "curl", "-f", "http://localhost:8080/health/ready" ]
interval: 15s
timeout: 2s
retries: 15
command: [ "start-dev" ]
ports:
- "8088:8080"
depends_on:
- postgres
networks:
- keycloak
networks:
keycloak:
driver: bridge

View File

@@ -1,37 +0,0 @@
services:
postgis:
image: postgis/postgis:14-3.5
container_name: postgis
environment:
POSTGRES_DB: TJWater
POSTGRES_USER: tjwater
POSTGRES_PASSWORD: Tjwater@123456
ports:
- "5432:5432"
volumes:
- C:\Users\admin\Documents\docker\PostgreSQL\data:/var/lib/postgresql/data
networks:
- MapService
geoserver:
image: docker.osgeo.org/geoserver:2.27.1
container_name: geoserver
ports:
- "8080:8080"
depends_on:
- postgis
environment:
- GEOSERVER_ADMIN_USER=admin
- GEOSERVER_ADMIN_PASSWORD=geoserver
- INSTALL_EXTENSIONS=true
- STABLE_EXTENSIONS=css,vectortiles
- CORS_ENABLED=true
- CORS_ALLOWED_ORIGINS=*
volumes:
- C:\Users\admin\Documents\docker\GeoServer\data:/opt/geoserver_data
networks:
- MapService
networks:
MapService:
driver: bridge

View File

@@ -1,10 +0,0 @@
services:
redis:
image: redis:8.2
container_name: redis
# environment:
# REDIS_PASSWORD: Tjwater@123456
ports:
- "6379:6379"
volumes:
- C:\Users\admin\Documents\docker\redis\data:/data

View File

@@ -1,25 +0,0 @@
services:
timescaledb:
image: timescale/timescaledb:latest-pg15
container_name: timescaledb
environment:
POSTGRES_DB: TJWater
POSTGRES_USER: tjwater
POSTGRES_PASSWORD: Tjwater@123456
ports:
- "5435:5432"
volumes:
- C:\Users\admin\Documents\docker\serverdb\Timescaledb\data:/var/lib/postgresql/data
grafana:
image: grafana/grafana:latest
container_name: grafana
ports:
- "3035:3000"
depends_on:
- timescaledb
volumes:
- C:\Users\admin\Documents\docker\serverdb\Grafana\data:/var/lib/grafana
environment:
- GF_SECURITY_ADMIN_USER=tjwater # 设置管理员用户名
- GF_SECURITY_ADMIN_PASSWORD=Tjwater@123456 # 设置管理员密码

View File

@@ -776,7 +776,7 @@ const SCADADataPanel: React.FC<SCADADataPanelProps> = ({
return (
<>
{/* 主面板 */}
<Draggable nodeRef={draggableRef}>
<Draggable nodeRef={draggableRef} handle=".drag-handle">
<Box
ref={draggableRef}
sx={{
@@ -811,12 +811,14 @@ const SCADADataPanel: React.FC<SCADADataPanelProps> = ({
>
{/* Header */}
<Box
className="drag-handle"
sx={{
p: 2,
borderBottom: 1,
borderColor: "divider",
backgroundColor: "primary.main",
color: "primary.contrastText",
cursor: "move",
}}
>
<Stack

View File

@@ -201,6 +201,8 @@ const StyleEditorPanel: React.FC<StyleEditorPanelProps> = ({
elevationRange,
} = data;
const unitHeadlossRange = [0, 5];
const { open } = useNotification();
const [applyJunctionStyle, setApplyJunctionStyle] = useState(false);
@@ -406,6 +408,8 @@ const StyleEditorPanel: React.FC<StyleEditorPanelProps> = ({
layerType === "junctions" && styleConfig.property === "elevation";
const isDiameter =
layerType === "pipes" && styleConfig.property === "diameter";
const isUnitHeadloss =
layerType === "pipes" && styleConfig.property === "unit_headloss";
if (
layerType === "junctions" &&
@@ -479,7 +483,8 @@ const StyleEditorPanel: React.FC<StyleEditorPanelProps> = ({
} else if (
layerType === "pipes" &&
((currentPipeCalData && currentPipeCalData.length > 0) ||
(isDiameter && diameterRange))
(isDiameter && diameterRange) ||
isUnitHeadloss)
) {
// 应用管道样式
let pipeStyleConfigState = layerStyleStates.find(
@@ -492,6 +497,8 @@ const StyleEditorPanel: React.FC<StyleEditorPanelProps> = ({
const dataValues =
isDiameter && diameterRange
? [diameterRange[0], diameterRange[1]]
: isUnitHeadloss
? [unitHeadlossRange[0], unitHeadlossRange[1]]
: currentPipeCalData?.map((d: any) => d.value) || [];
if (dataValues.length === 0) return;
@@ -617,7 +624,15 @@ const StyleEditorPanel: React.FC<StyleEditorPanelProps> = ({
const conditions: any[] = ["case"];
for (let i = 1; i < breaks.length; i++) {
// 添加条件:属性值 <= 当前断点
conditions.push(["<=", ["get", property], breaks[i]]);
if (property === "unit_headloss") {
conditions.push([
"<=",
["/", ["get", "unit_headloss"], ["/", ["get", "length"], 1000]],
breaks[i],
]);
} else {
conditions.push(["<=", ["get", property], breaks[i]]);
}
// 添加对应的颜色值
const colorObj = parseColor(colors[i - 1]);
const color = `rgba(${colorObj.r}, ${colorObj.g}, ${colorObj.b}, ${styleConfig.opacity})`;
@@ -633,7 +648,16 @@ const StyleEditorPanel: React.FC<StyleEditorPanelProps> = ({
const generateDimensionConditions = (property: string): any[] => {
const conditions: any[] = ["case"];
for (let i = 0; i < breaks.length; i++) {
conditions.push(["<=", ["get", property], breaks[i]]);
// 单独处理 unit_headloss 属性
if (property === "unit_headloss") {
conditions.push([
"<=",
["/", ["get", "headloss"], ["get", "length"]],
breaks[i],
]);
} else {
conditions.push(["<=", ["get", property], breaks[i]]);
}
conditions.push(dimensions[i]);
}
conditions.push(dimensions[dimensions.length - 1]);
@@ -679,7 +703,7 @@ const StyleEditorPanel: React.FC<StyleEditorPanelProps> = ({
);
dynamicStyle["circle-stroke-width"] = 2;
}
// 应用样式到图层
renderLayer.setStyle(dynamicStyle);
// 用初始化时的样式配置更新图例配置,避免覆盖已有的图例名称和属性
const layerId = renderLayer.get("value");

View File

@@ -36,6 +36,7 @@ interface TimelineProps {
timeRange?: { start: Date; end: Date };
disableDateSelection?: boolean;
schemeName?: string;
schemeType?: string;
}
const Timeline: React.FC<TimelineProps> = ({
@@ -43,6 +44,7 @@ const Timeline: React.FC<TimelineProps> = ({
timeRange,
disableDateSelection = false,
schemeName = "",
schemeType = "burst_Analysis",
}) => {
const data = useData();
if (!data) {
@@ -100,7 +102,8 @@ const Timeline: React.FC<TimelineProps> = ({
queryTime: Date,
junctionProperties: string,
pipeProperties: string,
schemeName: string
schemeName: string,
schemeType: string
) => {
const query_time = queryTime.toISOString();
let nodeRecords: any = { results: [] };
@@ -110,14 +113,14 @@ const Timeline: React.FC<TimelineProps> = ({
let linkPromise: Promise<any> | null = null;
// 检查node缓存
if (junctionProperties !== "" && junctionProperties !== "elevation") {
const nodeCacheKey = `${query_time}_${junctionProperties}_${schemeName}`;
const nodeCacheKey = `${query_time}_${junctionProperties}_${schemeName}_${schemeType}`;
if (nodeCacheRef.current.has(nodeCacheKey)) {
nodeRecords = nodeCacheRef.current.get(nodeCacheKey)!;
} else {
disableDateSelection && schemeName
? (nodePromise = fetch(
// `${backendUrl}/queryallschemerecordsbytimeproperty/?querytime=${query_time}&type=node&property=${junctionProperties}&schemename=${schemeName}`
`${backendUrl}/timescaledb/scheme/query/by-scheme-time-property?scheme_type=burst_Analysis&scheme_name=${schemeName}&query_time=${query_time}&type=node&property=${junctionProperties}`
`${backendUrl}/timescaledb/scheme/query/by-scheme-time-property?scheme_type=${schemeType}&scheme_name=${schemeName}&query_time=${query_time}&type=node&property=${junctionProperties}`
))
: (nodePromise = fetch(
// `${backendUrl}/queryallrecordsbytimeproperty/?querytime=${query_time}&type=node&property=${junctionProperties}`
@@ -126,17 +129,19 @@ const Timeline: React.FC<TimelineProps> = ({
requests.push(nodePromise);
}
}
// 处理特殊属性名称
if (pipeProperties === "unit_headloss") pipeProperties = "headloss";
// 检查link缓存
if (pipeProperties !== "" && pipeProperties !== "diameter") {
const linkCacheKey = `${query_time}_${pipeProperties}_${schemeName}`;
const linkCacheKey = `${query_time}_${pipeProperties}_${schemeName}_${schemeType}`;
if (linkCacheRef.current.has(linkCacheKey)) {
linkRecords = linkCacheRef.current.get(linkCacheKey)!;
} else {
disableDateSelection && schemeName
? (linkPromise = fetch(
// `${backendUrl}/queryallschemerecordsbytimeproperty/?querytime=${query_time}&type=link&property=${pipeProperties}&schemename=${schemeName}`
`${backendUrl}/timescaledb/scheme/query/by-scheme-time-property?scheme_type=burst_Analysis&scheme_name=${schemeName}&query_time=${query_time}&type=link&property=${pipeProperties}`
`${backendUrl}/timescaledb/scheme/query/by-scheme-time-property?scheme_type=${schemeType}&scheme_name=${schemeName}&query_time=${query_time}&type=link&property=${pipeProperties}`
))
: (linkPromise = fetch(
// `${backendUrl}/queryallrecordsbytimeproperty/?querytime=${query_time}&type=link&property=${pipeProperties}`
@@ -156,7 +161,7 @@ const Timeline: React.FC<TimelineProps> = ({
nodeRecords = await nodeResponse.json();
// 缓存数据(修复键以包含 schemeName
nodeCacheRef.current.set(
`${query_time}_${junctionProperties}_${schemeName}`,
`${query_time}_${junctionProperties}_${schemeName}_${schemeType}`,
nodeRecords || []
);
}
@@ -167,7 +172,7 @@ const Timeline: React.FC<TimelineProps> = ({
linkRecords = await linkResponse.json();
// 缓存数据(修复键以包含 schemeName
linkCacheRef.current.set(
`${query_time}_${pipeProperties}_${schemeName}`,
`${query_time}_${pipeProperties}_${schemeName}_${schemeType}`,
linkRecords || []
);
}
@@ -374,8 +379,8 @@ const Timeline: React.FC<TimelineProps> = ({
// 首次加载时,如果 selectedDate 或 currentTime 未定义,则跳过执行,避免报错
if (selectedDate && currentTime !== undefined && currentTime !== -1) {
// 检查至少一个属性有值
const junctionProperties = junctionText;
const pipeProperties = pipeText;
// const junctionProperties = junctionText;
// const pipeProperties = pipeText;
// if (junctionProperties === "" && pipeProperties === "") {
// open?.({
// type: "error",
@@ -387,10 +392,11 @@ const Timeline: React.FC<TimelineProps> = ({
currentTimeToDate(selectedDate, currentTime),
junctionText,
pipeText,
schemeName
schemeName,
schemeType
);
}
}, [junctionText, pipeText, currentTime, selectedDate]);
}, [junctionText, pipeText, currentTime, selectedDate, schemeName, schemeType]);
// 组件卸载时清理定时器和防抖
useEffect(() => {
@@ -467,7 +473,8 @@ const Timeline: React.FC<TimelineProps> = ({
currentTimeToDate(selectedDate, currentTime),
junctionText,
pipeText,
schemeName
schemeName,
schemeType
);
};
@@ -536,7 +543,7 @@ const Timeline: React.FC<TimelineProps> = ({
};
return (
<Draggable nodeRef={draggableRef}>
<Draggable nodeRef={draggableRef} handle=".drag-handle">
<div
ref={draggableRef}
className="absolute bottom-4 left-1/2 -translate-x-1/2 z-10 w-[920px] opacity-90 hover:opacity-100 transition-opacity duration-300"
@@ -551,10 +558,37 @@ const Timeline: React.FC<TimelineProps> = ({
right: 0,
zIndex: 1000,
p: 2,
pt: 1, // 减小顶部内边距,为拖拽柄留出空间
backgroundColor: "rgba(255, 255, 255, 0.95)",
backdropFilter: "blur(10px)",
}}
>
{/* 拖拽柄区域 */}
<Box
className="drag-handle"
sx={{
width: "100%",
height: "16px",
display: "flex",
justifyContent: "center",
alignItems: "center",
cursor: "move",
mb: 1,
borderRadius: "4px 4px 0 0",
"&:hover": {
backgroundColor: "rgba(0, 0, 0, 0.05)",
},
}}
>
<Box
sx={{
width: "40px",
height: "4px",
backgroundColor: "grey.400",
borderRadius: "2px",
}}
/>
</Box>
<Box sx={{ width: "100%" }}>
{/* 控制按钮栏 */}
<Stack

View File

@@ -196,13 +196,20 @@ const Toolbar: React.FC<ToolbarProps> = ({
async (event: { coordinate: number[] }) => {
if (!map) return;
const feature = await mapClickSelectFeatures(event, map); // 调用导入的函数
if (!feature || !(feature instanceof Feature)) return;
if (!feature || !(feature instanceof Feature)) {
// 如果没有点击到要素,且当前是 info 模式,则清除高亮
if (activeTools.includes("info")) {
setHighlightFeatures([]);
}
return;
}
if (activeTools.includes("history")) {
// 历史查询模式:支持同类型多选
const featureId = feature.getProperties().id;
const layerId = feature.getId()?.toString().split(".")[0] || "";
console.log("点击选择要素", feature, "图层:", layerId);
// 简单的类型检查函数
const getBaseType = (lid: string) => {
if (lid.includes("pipe")) return "pipe";

View File

@@ -566,6 +566,7 @@ const MapComponent: React.FC<MapComponentProps> = ({ children }) => {
data.set(featureId, {
id: featureId,
diameter: props.diameter || 0,
length: props.length || 0,
path: lineCoordsWGS84, // 使用重建后的坐标
position: midPoint,
angle: lineAngle,
@@ -833,13 +834,21 @@ const MapComponent: React.FC<MapComponentProps> = ({ children }) => {
let idPart = showPipeId ? d.id : "";
let propPart = "";
if (showPipeTextLayer && d[pipeText] !== undefined) {
const value = Math.abs(d[pipeText] as number).toFixed(3);
let value;
if (pipeText === "unit_headloss") {
value = (
(d["unit_headloss"] / (d["length"] / 1000)) as number
).toFixed(3);
} else {
value = Math.abs(d[pipeText] as number).toFixed(3);
}
// 根据属性类型添加符号前缀
const prefix =
{
flow: "F:",
velocity: "V:",
headloss: "HL:",
unit_headloss: "UHL:",
diameter: "D:",
friction: "FR:",
}[pipeText] || "";

View File

@@ -1,6 +1,6 @@
"use client";
import React, { useState } from "react";
import React, { useEffect, useRef, useState } from "react";
import {
Box,
Drawer,
@@ -20,9 +20,13 @@ import {
import AnalysisParameters from "./AnalysisParameters";
import SchemeQuery from "./SchemeQuery";
import LocationResults, { LocationResult } from "./LocationResults";
import ContaminantAnalysisParameters from "../ContaminantSimulation/AnalysisParameters";
import ContaminantSchemeQuery from "../ContaminantSimulation/SchemeQuery";
import ContaminantResultsPanel from "../ContaminantSimulation/ResultsPanel";
import axios from "axios";
import { config } from "@config/config";
import { useNotification } from "@refinedev/core";
import { useData } from "@app/OlMap/MapComponent";
interface SchemeDetail {
burst_ID: string[];
burst_size: number[];
@@ -68,12 +72,20 @@ interface BurstPipeAnalysisPanelProps {
onToggle?: () => void;
}
type PanelMode = "burst" | "contaminant";
const BurstPipeAnalysisPanel: React.FC<BurstPipeAnalysisPanelProps> = ({
open: controlledOpen,
onToggle,
}) => {
const [internalOpen, setInternalOpen] = useState(true);
const [currentTab, setCurrentTab] = useState(0);
const [panelMode, setPanelMode] = useState<PanelMode>("burst");
const previousMapText = useRef<{ junction?: string; pipe?: string } | null>(
null
);
const data = useData();
// 持久化方案查询结果
const [schemes, setSchemes] = useState<SchemeRecord[]>([]);
@@ -96,6 +108,24 @@ const BurstPipeAnalysisPanel: React.FC<BurstPipeAnalysisPanelProps> = ({
setCurrentTab(newValue);
};
useEffect(() => {
if (!data) return;
if (panelMode === "contaminant") {
if (!previousMapText.current) {
previousMapText.current = {
junction: data.junctionText,
pipe: data.pipeText,
};
}
data.setJunctionText?.("quality");
data.setPipeText?.("quality");
} else if (panelMode === "burst" && previousMapText.current) {
data.setJunctionText?.(previousMapText.current.junction || "pressure");
data.setPipeText?.(previousMapText.current.pipe || "flow");
previousMapText.current = null;
}
}, [panelMode, data]);
const handleLocateScheme = async (scheme: SchemeRecord) => {
try {
const response = await axios.get(
@@ -114,6 +144,8 @@ const BurstPipeAnalysisPanel: React.FC<BurstPipeAnalysisPanelProps> = ({
};
const drawerWidth = 520;
const isBurstMode = panelMode === "burst";
const panelTitle = isBurstMode ? "爆管分析" : "水质模拟";
return (
<>
@@ -131,7 +163,7 @@ const BurstPipeAnalysisPanel: React.FC<BurstPipeAnalysisPanelProps> = ({
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>
@@ -175,7 +207,7 @@ const BurstPipeAnalysisPanel: React.FC<BurstPipeAnalysisPanelProps> = ({
<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="收起">
@@ -190,6 +222,31 @@ const BurstPipeAnalysisPanel: React.FC<BurstPipeAnalysisPanelProps> = ({
</Box>
{/* Tabs 导航 */}
<Box className="border-b border-gray-200 bg-white">
<Tabs
value={panelMode}
onChange={(_event, value: PanelMode) => setPanelMode(value)}
variant="fullWidth"
sx={{
minHeight: 46,
"& .MuiTab-root": {
minHeight: 46,
textTransform: "none",
fontSize: "0.8rem",
fontWeight: 600,
},
"& .Mui-selected": {
color: "#257DD4",
},
"& .MuiTabs-indicator": {
backgroundColor: "#257DD4",
},
}}
>
<Tab value="burst" label="爆管分析" />
<Tab value="contaminant" label="水质模拟" />
</Tabs>
</Box>
<Box className="border-b border-gray-200 bg-white">
<Tabs
value={currentTab}
@@ -225,40 +282,38 @@ const BurstPipeAnalysisPanel: React.FC<BurstPipeAnalysisPanelProps> = ({
<Tab
icon={<MyLocationIcon fontSize="small" />}
iconPosition="start"
label="定位结果"
label={isBurstMode ? "定位结果" : "模拟结果"}
/>
</Tabs>
</Box>
{/* Tab 内容 */}
<TabPanel value={currentTab} index={0}>
<AnalysisParameters />
{isBurstMode ? (
<AnalysisParameters />
) : (
<ContaminantAnalysisParameters />
)}
</TabPanel>
<TabPanel value={currentTab} index={1}>
<SchemeQuery
schemes={schemes}
onSchemesChange={setSchemes}
onLocate={handleLocateScheme}
/>
{isBurstMode ? (
<SchemeQuery
schemes={schemes}
onSchemesChange={setSchemes}
onLocate={handleLocateScheme}
/>
) : (
<ContaminantSchemeQuery />
)}
</TabPanel>
<TabPanel value={currentTab} index={2}>
<LocationResults
results={locationResults}
onLocate={(result) => {
console.log("定位到:", result.locate_result);
// TODO: 地图定位到指定坐标
}}
onLocateAll={(results) => {
console.log("定位全部结果:", results);
// TODO: 地图定位到所有结果坐标
}}
onViewDetail={(id) => {
console.log("查看节点详情:", id);
// TODO: 显示节点详细信息
}}
/>
{isBurstMode ? (
<LocationResults results={locationResults} />
) : (
<ContaminantResultsPanel schemeName={data?.schemeName} />
)}
</TabPanel>
</Box>
</Drawer>

View File

@@ -336,6 +336,7 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
timeRange={timeRange}
disableDateSelection={!!timeRange}
schemeName={schemeName}
schemeType="burst_Analysis"
/>,
mapContainer // 渲染到地图容器中,而不是 body
)}

View File

@@ -0,0 +1,367 @@
"use client";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import {
Box,
Button,
IconButton,
Stack,
TextField,
Typography,
} 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 { useNotification } from "@refinedev/core";
import axios from "axios";
import { config, NETWORK_NAME } from "@/config/config";
import { useMap } from "@app/OlMap/MapComponent";
import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
import { Style, Stroke, Fill, Circle as CircleStyle } from "ol/style";
import Feature from "ol/Feature";
import { handleMapClickSelectFeatures as mapClickSelectFeatures } from "@/utils/mapQueryService";
const AnalysisParameters: React.FC = () => {
const map = useMap();
const { open } = useNotification();
const network = NETWORK_NAME;
const [startTime, setStartTime] = useState<Dayjs | null>(dayjs(new Date()));
const [sourceNode, setSourceNode] = useState<string>("");
const [concentration, setConcentration] = useState<number>(1);
const [duration, setDuration] = useState<number>(900);
const [pattern, setPattern] = useState<string>("");
const [isSelecting, setIsSelecting] = useState<boolean>(false);
const [submitting, setSubmitting] = useState<boolean>(false);
const [highlightLayer, setHighlightLayer] =
useState<VectorLayer<VectorSource> | null>(null);
const [highlightFeature, setHighlightFeature] = useState<Feature | null>(
null
);
const isFormValid = useMemo(() => {
return (
Boolean(network) &&
Boolean(startTime) &&
Boolean(sourceNode) &&
concentration > 0 &&
duration > 0
);
}, [network, startTime, sourceNode, concentration, duration]);
useEffect(() => {
if (!map) return;
const sourceStyle = new Style({
image: new CircleStyle({
radius: 10,
fill: new Fill({ color: "rgba(37, 125, 212, 0.35)" }),
stroke: new Stroke({ color: "rgba(37, 125, 212, 1)", width: 3 }),
}),
});
const layer = new VectorLayer({
source: new VectorSource(),
style: sourceStyle,
properties: {
name: "污染源节点",
value: "contaminant_source_highlight",
},
});
map.addLayer(layer);
setHighlightLayer(layer);
return () => {
map.removeLayer(layer);
map.un("click", handleMapClickSelectFeatures);
};
}, [map]);
useEffect(() => {
if (!highlightLayer) return;
const source = highlightLayer.getSource();
if (!source) return;
source.clear();
if (highlightFeature) {
source.addFeature(highlightFeature);
}
}, [highlightFeature, highlightLayer]);
const handleMapClickSelectFeatures = useCallback(
async (event: { coordinate: number[] }) => {
if (!map) return;
const feature = await mapClickSelectFeatures(event, map);
if (!feature) return;
const layerId = feature.getId()?.toString().split(".")[0] || "";
const isJunction = layerId.includes("junction");
if (!isJunction) {
open?.({
type: "error",
message: "请选择节点类型要素作为污染源。",
});
return;
}
const id = feature.getProperties().id;
if (!id) return;
setSourceNode(id);
setHighlightFeature(feature);
setIsSelecting(false);
map.un("click", handleMapClickSelectFeatures);
},
[map, open]
);
const handleStartSelection = () => {
if (!map) return;
setIsSelecting(true);
map.on("click", handleMapClickSelectFeatures);
};
const handleEndSelection = () => {
if (!map) return;
setIsSelecting(false);
map.un("click", handleMapClickSelectFeatures);
};
const handleClearSource = () => {
setSourceNode("");
setHighlightFeature(null);
};
const handleAnalyze = async () => {
if (!startTime) return;
setSubmitting(true);
open?.({
key: "contaminant-analysis",
type: "progress",
message: "方案提交分析中",
undoableTimeout: 3,
});
try {
const params = {
network,
start_time: startTime.toISOString(),
source: sourceNode,
concentration,
duration,
pattern: pattern || undefined,
};
await axios.get(`${config.BACKEND_URL}/contaminant_simulation/`, {
params,
});
open?.({
key: "contaminant-analysis",
type: "success",
message: "方案分析成功",
description: "水质模拟完成,请在方案查询中查看结果。",
});
} catch (error) {
console.error("水质模拟请求失败:", error);
open?.({
key: "contaminant-analysis",
type: "error",
message: "提交分析失败",
description:
error instanceof Error ? error.message : "请检查网络连接或稍后重试",
});
} finally {
setSubmitting(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}>
{sourceNode ? (
<Box className="flex items-center gap-2 p-2 bg-gray-50 rounded">
<Typography className="flex-shrink-0 text-sm">
{sourceNode}
</Typography>
<Typography className="flex-shrink-0 text-sm text-gray-600">
</Typography>
<IconButton
size="small"
onClick={handleClearSource}
className="ml-auto"
>
<CloseIcon fontSize="small" />
</IconButton>
</Box>
) : (
<Box className="p-3 rounded border border-dashed border-gray-200 text-sm text-gray-400">
</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"
value={network}
disabled
/>
</Box>
<Box className="mb-4">
<Typography variant="subtitle2" className="mb-2 font-medium">
(mg/L)
</Typography>
<TextField
fullWidth
size="small"
type="number"
value={concentration}
onChange={(e) => setConcentration(parseFloat(e.target.value) || 0)}
placeholder="输入浓度"
/>
</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, 10) || 0)}
placeholder="输入持续时长"
/>
</Box>
<Box className="mb-4">
<Typography variant="subtitle2" className="mb-2 font-medium">
</Typography>
<TextField
fullWidth
size="small"
value={pattern}
onChange={(e) => setPattern(e.target.value)}
placeholder="可选,输入 pattern 名称"
/>
</Box>
<Box className="mt-auto">
<Button
fullWidth
variant="contained"
size="large"
onClick={handleAnalyze}
disabled={submitting || !isFormValid}
className="bg-blue-600 hover:bg-blue-700"
>
{submitting ? "方案提交分析中..." : "水质模拟"}
</Button>
</Box>
</Box>
);
};
export default AnalysisParameters;

View File

@@ -0,0 +1,30 @@
"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;

View File

@@ -0,0 +1,511 @@
"use client";
import React, { useEffect, useMemo, useState } from "react";
import ReactDOM from "react-dom";
import {
Box,
Button,
Card,
CardContent,
Checkbox,
Chip,
Collapse,
FormControlLabel,
IconButton,
Link,
Tooltip,
Typography,
} 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 axios from "axios";
import moment from "moment";
import { useNotification } from "@refinedev/core";
import { config, NETWORK_NAME } from "@config/config";
import { queryFeaturesByIds } from "@/utils/mapQueryService";
import { useData, useMap } from "@app/OlMap/MapComponent";
import Timeline from "@app/OlMap/Controls/Timeline";
import { ContaminantSchemaItem, ContaminantSchemeRecord } from "./types";
interface SchemeQueryProps {
schemes?: ContaminantSchemeRecord[];
onSchemesChange?: (schemes: ContaminantSchemeRecord[]) => void;
network?: string;
}
const SCHEME_TYPE = "contaminant_simulation";
const SchemeQuery: React.FC<SchemeQueryProps> = ({
schemes: externalSchemes,
onSchemesChange,
network = NETWORK_NAME,
}) => {
const [queryAll, setQueryAll] = useState<boolean>(true);
const [queryDate, setQueryDate] = useState<Dayjs | null>(dayjs(new Date()));
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<
ContaminantSchemeRecord[]
>([]);
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, setJunctionText, setPipeText } =
data || {};
const schemes =
externalSchemes !== undefined ? externalSchemes : internalSchemes;
const setSchemes = onSchemesChange || setInternalSchemes;
useEffect(() => {
if (!map) return;
const target = map.getTargetElement();
if (target) {
setMapContainer(target);
}
}, [map]);
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 axios.get(
`${config.BACKEND_URL}/getallschemes/?network=${network}`
);
let filteredResults = response.data;
if (!queryAll) {
const formattedDate = queryDate!.format("YYYY-MM-DD");
filteredResults = response.data.filter((item: ContaminantSchemaItem) => {
const itemDate = moment(item.create_time).format("YYYY-MM-DD");
return itemDate === formattedDate;
});
}
setSchemes(
filteredResults.map((item: ContaminantSchemaItem) => ({
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 handleLocateSource = (sourceId?: string) => {
if (!sourceId) return;
queryFeaturesByIds([sourceId], "geo_junctions_mat").then((features) => {
if (features.length > 0) {
const extent = features[0].getGeometry()?.getExtent();
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?.duration) {
const start = new Date(scheme.startTime);
const end = new Date(start.getTime() + scheme.schemeDetail.duration * 1000);
setSelectedDate(schemeDate);
setTimeRange({ start, end });
}
setSchemeName?.(scheme.schemeName);
setJunctionText?.("quality");
setPipeText?.("quality");
handleLocateSource(scheme.schemeDetail?.source);
};
return (
<>
{showTimeline &&
mapContainer &&
ReactDOM.createPortal(
<Timeline
schemeDate={selectedDate}
timeRange={timeRange}
disableDateSelection={!!timeRange}
schemeName={schemeName}
schemeType={SCHEME_TYPE}
/>,
mapContainer
)}
<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}
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={() => handleLocateSource(scheme.schemeDetail?.source)}
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"
>
:
</Typography>
<Box className="flex-1 flex flex-wrap gap-1">
{scheme.schemeDetail?.source ? (
<Link
component="button"
variant="caption"
className="font-medium text-blue-600 hover:text-blue-800 underline cursor-pointer"
onClick={(e) => {
e.preventDefault();
handleLocateSource(scheme.schemeDetail?.source);
}}
>
{scheme.schemeDetail.source}
</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"
>
{scheme.schemeDetail?.concentration ?? "N/A"} mg/L
</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?.duration ?? "N/A"}
</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?.pattern || "无"}
</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">
<Button
variant="outlined"
fullWidth
size="small"
className="border-blue-600 text-blue-600 hover:bg-blue-50"
onClick={() => handleLocateSource(scheme.schemeDetail?.source)}
sx={{
textTransform: "none",
fontWeight: 500,
}}
>
</Button>
<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;

View File

@@ -0,0 +1,27 @@
export interface ContaminantSchemeDetail {
source: string;
concentration: number;
duration: number;
pattern?: string | null;
start_time?: string;
}
export interface ContaminantSchemeRecord {
id: number;
schemeName: string;
type: string;
user: string;
create_time: string;
startTime: string;
schemeDetail?: ContaminantSchemeDetail;
}
export interface ContaminantSchemaItem {
scheme_id: number;
scheme_name: string;
scheme_type: string;
username: string;
create_time: string;
scheme_start_time: string;
scheme_detail?: ContaminantSchemeDetail;
}

View File

@@ -160,7 +160,7 @@ const PredictDataPanel: React.FC<PredictDataPanelProps> = ({
};
return (
<Draggable nodeRef={draggableRef}>
<Draggable nodeRef={draggableRef} handle=".drag-handle">
<Box
ref={draggableRef}
sx={{
@@ -195,12 +195,14 @@ const PredictDataPanel: React.FC<PredictDataPanelProps> = ({
>
{/* Header */}
<Box
className="drag-handle"
sx={{
p: 2,
borderBottom: 1,
borderColor: "divider",
backgroundColor: "primary.main",
color: "primary.contrastText",
cursor: "move",
}}
>
<Stack

View File

@@ -45,7 +45,7 @@ interface MapClickEvent {
const GEOSERVER_CONFIG = {
url: config.MAP_URL,
workspace: config.MAP_WORKSPACE,
layers: ["geo_pipes_mat", "geo_junctions_mat"],
layers: ["geo_pipes_mat", "geo_junctions_mat", "geo_valves"],
wfsVersion: "1.0.0",
outputFormat: "application/json",
} as const;
@@ -460,7 +460,11 @@ const handleMapClickSelectFeatures = async (
// 按几何类型优先级排序:点 > 线 > 其他
const { points, lines, others } =
classifyFeaturesByGeometry(allSelectedFeatures);
const prioritizedFeatures = [...points, ...lines, ...others];
const prioritizedFeatures = [
...points.reverse(),
...lines.reverse(),
...others.reverse(),
];
// 获取第一个要素
const firstFeature = prioritizedFeatures[0];
@@ -475,12 +479,16 @@ const handleMapClickSelectFeatures = async (
// 如果要素来自 VectorTileSource需要通过 WFS 查询完整信息
const queryId = firstFeature.getProperties().id;
const layerName = firstFeature.getProperties().layer;
if (layerName === "geo_pipes" || layerName === "geo_junctions") {
layerName.concat("_mat");
}
if (!queryId) {
return null;
}
try {
const features = await queryFeaturesByIds([queryId]);
const features = await queryFeaturesByIds([queryId], layerName);
return features[0] || null;
} catch (error) {
console.error("查询要素详情失败:", error);