新增水质模拟模块;移除docker配置文件,现放置到后端项目中

This commit is contained in:
JIANG
2026-01-21 17:03:31 +08:00
parent ffe42d0185
commit 7122b0b2ac
12 changed files with 1031 additions and 155 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:
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
- C:\Users\admin\Documents\docker\keycloak\import:/opt/keycloak/data/import
healthcheck:
test: [ "CMD", "curl", "-f", "http://localhost:8080/health/ready" ]
interval: 15s
timeout: 2s
retries: 15
command: [ "start-dev", "--import-realm" ]
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

@@ -36,6 +36,7 @@ interface TimelineProps {
timeRange?: { start: Date; end: Date }; timeRange?: { start: Date; end: Date };
disableDateSelection?: boolean; disableDateSelection?: boolean;
schemeName?: string; schemeName?: string;
schemeType?: string;
} }
const Timeline: React.FC<TimelineProps> = ({ const Timeline: React.FC<TimelineProps> = ({
@@ -43,6 +44,7 @@ const Timeline: React.FC<TimelineProps> = ({
timeRange, timeRange,
disableDateSelection = false, disableDateSelection = false,
schemeName = "", schemeName = "",
schemeType = "burst_Analysis",
}) => { }) => {
const data = useData(); const data = useData();
if (!data) { if (!data) {
@@ -100,7 +102,8 @@ const Timeline: React.FC<TimelineProps> = ({
queryTime: Date, queryTime: Date,
junctionProperties: string, junctionProperties: string,
pipeProperties: string, pipeProperties: string,
schemeName: string schemeName: string,
schemeType: string
) => { ) => {
const query_time = queryTime.toISOString(); const query_time = queryTime.toISOString();
let nodeRecords: any = { results: [] }; let nodeRecords: any = { results: [] };
@@ -110,14 +113,14 @@ const Timeline: React.FC<TimelineProps> = ({
let linkPromise: Promise<any> | null = null; let linkPromise: Promise<any> | null = null;
// 检查node缓存 // 检查node缓存
if (junctionProperties !== "" && junctionProperties !== "elevation") { if (junctionProperties !== "" && junctionProperties !== "elevation") {
const nodeCacheKey = `${query_time}_${junctionProperties}_${schemeName}`; const nodeCacheKey = `${query_time}_${junctionProperties}_${schemeName}_${schemeType}`;
if (nodeCacheRef.current.has(nodeCacheKey)) { if (nodeCacheRef.current.has(nodeCacheKey)) {
nodeRecords = nodeCacheRef.current.get(nodeCacheKey)!; nodeRecords = nodeCacheRef.current.get(nodeCacheKey)!;
} else { } else {
disableDateSelection && schemeName disableDateSelection && schemeName
? (nodePromise = fetch( ? (nodePromise = fetch(
// `${backendUrl}/queryallschemerecordsbytimeproperty/?querytime=${query_time}&type=node&property=${junctionProperties}&schemename=${schemeName}` // `${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( : (nodePromise = fetch(
// `${backendUrl}/queryallrecordsbytimeproperty/?querytime=${query_time}&type=node&property=${junctionProperties}` // `${backendUrl}/queryallrecordsbytimeproperty/?querytime=${query_time}&type=node&property=${junctionProperties}`
@@ -131,14 +134,14 @@ const Timeline: React.FC<TimelineProps> = ({
// 检查link缓存 // 检查link缓存
if (pipeProperties !== "" && pipeProperties !== "diameter") { if (pipeProperties !== "" && pipeProperties !== "diameter") {
const linkCacheKey = `${query_time}_${pipeProperties}_${schemeName}`; const linkCacheKey = `${query_time}_${pipeProperties}_${schemeName}_${schemeType}`;
if (linkCacheRef.current.has(linkCacheKey)) { if (linkCacheRef.current.has(linkCacheKey)) {
linkRecords = linkCacheRef.current.get(linkCacheKey)!; linkRecords = linkCacheRef.current.get(linkCacheKey)!;
} else { } else {
disableDateSelection && schemeName disableDateSelection && schemeName
? (linkPromise = fetch( ? (linkPromise = fetch(
// `${backendUrl}/queryallschemerecordsbytimeproperty/?querytime=${query_time}&type=link&property=${pipeProperties}&schemename=${schemeName}` // `${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( : (linkPromise = fetch(
// `${backendUrl}/queryallrecordsbytimeproperty/?querytime=${query_time}&type=link&property=${pipeProperties}` // `${backendUrl}/queryallrecordsbytimeproperty/?querytime=${query_time}&type=link&property=${pipeProperties}`
@@ -158,7 +161,7 @@ const Timeline: React.FC<TimelineProps> = ({
nodeRecords = await nodeResponse.json(); nodeRecords = await nodeResponse.json();
// 缓存数据(修复键以包含 schemeName // 缓存数据(修复键以包含 schemeName
nodeCacheRef.current.set( nodeCacheRef.current.set(
`${query_time}_${junctionProperties}_${schemeName}`, `${query_time}_${junctionProperties}_${schemeName}_${schemeType}`,
nodeRecords || [] nodeRecords || []
); );
} }
@@ -169,7 +172,7 @@ const Timeline: React.FC<TimelineProps> = ({
linkRecords = await linkResponse.json(); linkRecords = await linkResponse.json();
// 缓存数据(修复键以包含 schemeName // 缓存数据(修复键以包含 schemeName
linkCacheRef.current.set( linkCacheRef.current.set(
`${query_time}_${pipeProperties}_${schemeName}`, `${query_time}_${pipeProperties}_${schemeName}_${schemeType}`,
linkRecords || [] linkRecords || []
); );
} }
@@ -389,10 +392,11 @@ const Timeline: React.FC<TimelineProps> = ({
currentTimeToDate(selectedDate, currentTime), currentTimeToDate(selectedDate, currentTime),
junctionText, junctionText,
pipeText, pipeText,
schemeName schemeName,
schemeType
); );
} }
}, [junctionText, pipeText, currentTime, selectedDate]); }, [junctionText, pipeText, currentTime, selectedDate, schemeName, schemeType]);
// 组件卸载时清理定时器和防抖 // 组件卸载时清理定时器和防抖
useEffect(() => { useEffect(() => {
@@ -469,7 +473,8 @@ const Timeline: React.FC<TimelineProps> = ({
currentTimeToDate(selectedDate, currentTime), currentTimeToDate(selectedDate, currentTime),
junctionText, junctionText,
pipeText, pipeText,
schemeName schemeName,
schemeType
); );
}; };

View File

@@ -1,6 +1,6 @@
"use client"; "use client";
import React, { useState } from "react"; import React, { useEffect, useRef, useState } from "react";
import { import {
Box, Box,
Drawer, Drawer,
@@ -20,9 +20,13 @@ import {
import AnalysisParameters from "./AnalysisParameters"; import AnalysisParameters from "./AnalysisParameters";
import SchemeQuery from "./SchemeQuery"; import SchemeQuery from "./SchemeQuery";
import LocationResults, { LocationResult } from "./LocationResults"; 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 axios from "axios";
import { config } from "@config/config"; import { config } from "@config/config";
import { useNotification } from "@refinedev/core"; import { useNotification } from "@refinedev/core";
import { useData } from "@app/OlMap/MapComponent";
interface SchemeDetail { interface SchemeDetail {
burst_ID: string[]; burst_ID: string[];
burst_size: number[]; burst_size: number[];
@@ -68,12 +72,20 @@ interface BurstPipeAnalysisPanelProps {
onToggle?: () => void; onToggle?: () => void;
} }
type PanelMode = "burst" | "contaminant";
const BurstPipeAnalysisPanel: React.FC<BurstPipeAnalysisPanelProps> = ({ const BurstPipeAnalysisPanel: React.FC<BurstPipeAnalysisPanelProps> = ({
open: controlledOpen, open: controlledOpen,
onToggle, onToggle,
}) => { }) => {
const [internalOpen, setInternalOpen] = useState(true); const [internalOpen, setInternalOpen] = useState(true);
const [currentTab, setCurrentTab] = useState(0); 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[]>([]); const [schemes, setSchemes] = useState<SchemeRecord[]>([]);
@@ -96,6 +108,24 @@ const BurstPipeAnalysisPanel: React.FC<BurstPipeAnalysisPanelProps> = ({
setCurrentTab(newValue); 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) => { const handleLocateScheme = async (scheme: SchemeRecord) => {
try { try {
const response = await axios.get( const response = await axios.get(
@@ -114,6 +144,8 @@ const BurstPipeAnalysisPanel: React.FC<BurstPipeAnalysisPanelProps> = ({
}; };
const drawerWidth = 520; const drawerWidth = 520;
const isBurstMode = panelMode === "burst";
const panelTitle = isBurstMode ? "爆管分析" : "水质模拟";
return ( return (
<> <>
@@ -131,7 +163,7 @@ const BurstPipeAnalysisPanel: React.FC<BurstPipeAnalysisPanelProps> = ({
className="text-gray-700 font-semibold my-1 text-xs" className="text-gray-700 font-semibold my-1 text-xs"
style={{ writingMode: "vertical-rl" }} style={{ writingMode: "vertical-rl" }}
> >
{panelTitle}
</Typography> </Typography>
<ChevronLeft className="text-gray-600 w-4 h-4" /> <ChevronLeft className="text-gray-600 w-4 h-4" />
</Box> </Box>
@@ -175,7 +207,7 @@ const BurstPipeAnalysisPanel: React.FC<BurstPipeAnalysisPanelProps> = ({
<Box className="flex items-center gap-2"> <Box className="flex items-center gap-2">
<AnalyticsIcon className="w-5 h-5" /> <AnalyticsIcon className="w-5 h-5" />
<Typography variant="h6" className="text-lg font-semibold"> <Typography variant="h6" className="text-lg font-semibold">
{panelTitle}
</Typography> </Typography>
</Box> </Box>
<Tooltip title="收起"> <Tooltip title="收起">
@@ -190,6 +222,31 @@ const BurstPipeAnalysisPanel: React.FC<BurstPipeAnalysisPanelProps> = ({
</Box> </Box>
{/* Tabs 导航 */} {/* 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"> <Box className="border-b border-gray-200 bg-white">
<Tabs <Tabs
value={currentTab} value={currentTab}
@@ -225,26 +282,38 @@ const BurstPipeAnalysisPanel: React.FC<BurstPipeAnalysisPanelProps> = ({
<Tab <Tab
icon={<MyLocationIcon fontSize="small" />} icon={<MyLocationIcon fontSize="small" />}
iconPosition="start" iconPosition="start"
label="定位结果" label={isBurstMode ? "定位结果" : "模拟结果"}
/> />
</Tabs> </Tabs>
</Box> </Box>
{/* Tab 内容 */} {/* Tab 内容 */}
<TabPanel value={currentTab} index={0}> <TabPanel value={currentTab} index={0}>
<AnalysisParameters /> {isBurstMode ? (
<AnalysisParameters />
) : (
<ContaminantAnalysisParameters />
)}
</TabPanel> </TabPanel>
<TabPanel value={currentTab} index={1}> <TabPanel value={currentTab} index={1}>
<SchemeQuery {isBurstMode ? (
schemes={schemes} <SchemeQuery
onSchemesChange={setSchemes} schemes={schemes}
onLocate={handleLocateScheme} onSchemesChange={setSchemes}
/> onLocate={handleLocateScheme}
/>
) : (
<ContaminantSchemeQuery />
)}
</TabPanel> </TabPanel>
<TabPanel value={currentTab} index={2}> <TabPanel value={currentTab} index={2}>
<LocationResults results={locationResults} /> {isBurstMode ? (
<LocationResults results={locationResults} />
) : (
<ContaminantResultsPanel schemeName={data?.schemeName} />
)}
</TabPanel> </TabPanel>
</Box> </Box>
</Drawer> </Drawer>

View File

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