Compare commits
19 Commits
fb35bcdf44
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b8d7974ce9 | ||
|
|
0690b0b804 | ||
|
|
6f0ef342e9 | ||
|
|
a3f4b477bc | ||
|
|
799eab03d0 | ||
|
|
133e812700 | ||
|
|
d584268acd | ||
|
|
c28325e997 | ||
|
|
5cb2d17be1 | ||
|
|
7122b0b2ac | ||
|
|
ffe42d0185 | ||
|
|
350eda4b10 | ||
|
|
f43abfc6c4 | ||
|
|
1e8ea08e9f | ||
|
|
3255108d96 | ||
|
|
f137883e4c | ||
|
|
4e24319dbb | ||
|
|
2d7fcc5e3a | ||
|
|
142a9b888d |
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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 # 设置管理员密码
|
||||
30
jest.config.js
Normal file
30
jest.config.js
Normal file
@@ -0,0 +1,30 @@
|
||||
const nextJest = require('next/jest')
|
||||
|
||||
const createJestConfig = nextJest({
|
||||
// Provide the path to your Next.js app to load next.config.js and .env files in your test environment
|
||||
dir: './',
|
||||
})
|
||||
|
||||
// Add any custom config to be passed to Jest
|
||||
const customJestConfig = {
|
||||
setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
|
||||
testEnvironment: 'jest-environment-jsdom',
|
||||
moduleNameMapper: {
|
||||
'^@pages/(.*)$': '<rootDir>/pages/$1',
|
||||
'^@/(.*)$': '<rootDir>/src/$1',
|
||||
'^@app/(.*)$': '<rootDir>/src/app/$1',
|
||||
'^@assets/(.*)$': '<rootDir>/src/assets/$1',
|
||||
'^@components/(.*)$': '<rootDir>/src/components/$1',
|
||||
'^@config/(.*)$': '<rootDir>/src/config/$1',
|
||||
'^@contexts/(.*)$': '<rootDir>/src/contexts/$1',
|
||||
'^@interfaces/(.*)$': '<rootDir>/src/interfaces/$1',
|
||||
'^@libs/(.*)$': '<rootDir>/src/libs/$1',
|
||||
'^@providers/(.*)$': '<rootDir>/src/providers/$1',
|
||||
'^@utils/(.*)$': '<rootDir>/src/utils/$1',
|
||||
// Handle specific aliases if generic one causes issues, but trying generic first matching tsconfig
|
||||
// '^@(.*)$': '<rootDir>/src/$1',
|
||||
},
|
||||
}
|
||||
|
||||
// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
|
||||
module.exports = createJestConfig(customJestConfig)
|
||||
1
jest.setup.js
Normal file
1
jest.setup.js
Normal file
@@ -0,0 +1 @@
|
||||
import '@testing-library/jest-dom'
|
||||
4142
package-lock.json
generated
4142
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
20
package.json
20
package.json
@@ -10,6 +10,9 @@
|
||||
"build": "refine build",
|
||||
"start": "refine start",
|
||||
"lint": "next lint",
|
||||
"test": "jest",
|
||||
"test:watch": "jest --watch",
|
||||
"test:coverage": "jest --coverage",
|
||||
"refine": "refine"
|
||||
},
|
||||
"dependencies": {
|
||||
@@ -22,12 +25,12 @@
|
||||
"@mui/x-data-grid": "^7.22.2",
|
||||
"@mui/x-date-pickers": "^8.12.0",
|
||||
"@refinedev/cli": "^2.16.50",
|
||||
"@refinedev/core": "^5.0.6",
|
||||
"@refinedev/core": "^5.0.8",
|
||||
"@refinedev/devtools": "^2.0.3",
|
||||
"@refinedev/kbar": "^2.0.1",
|
||||
"@refinedev/mui": "^7.0.1",
|
||||
"@refinedev/mui": "^8.0.0",
|
||||
"@refinedev/nextjs-router": "^7.0.4",
|
||||
"@refinedev/react-hook-form": "^5.0.3",
|
||||
"@refinedev/react-hook-form": "^5.0.4",
|
||||
"@refinedev/simple-rest": "^6.0.1",
|
||||
"@tailwindcss/postcss": "^4.1.13",
|
||||
"@turf/turf": "^7.2.0",
|
||||
@@ -37,7 +40,7 @@
|
||||
"echarts": "^6.0.0",
|
||||
"echarts-for-react": "^3.0.5",
|
||||
"js-cookie": "^3.0.5",
|
||||
"next": "15.5.9",
|
||||
"next": "^15.5.11",
|
||||
"next-auth": "^4.24.5",
|
||||
"ol": "^10.7.0",
|
||||
"postcss": "^8.5.6",
|
||||
@@ -50,14 +53,21 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@svgr/webpack": "^8.1.0",
|
||||
"@testing-library/dom": "^10.4.1",
|
||||
"@testing-library/jest-dom": "^6.9.1",
|
||||
"@testing-library/react": "^16.3.2",
|
||||
"@types/jest": "^30.0.0",
|
||||
"@types/js-cookie": "^3.0.6",
|
||||
"@types/node": "^20",
|
||||
"@types/react": "^19.1.0",
|
||||
"@types/react-dom": "^19.1.0",
|
||||
"@types/react-window": "^1.8.8",
|
||||
"cross-env": "^7.0.3",
|
||||
"eslint": "^8",
|
||||
"eslint": "^9.39.2",
|
||||
"eslint-config-next": "^15.0.3",
|
||||
"jest": "^30.2.0",
|
||||
"jest-environment-jsdom": "^30.2.0",
|
||||
"ts-jest": "^29.4.6",
|
||||
"typescript": "^5.8.3"
|
||||
},
|
||||
"refine": {
|
||||
|
||||
1
public/icons/contaminant_source.svg
Normal file
1
public/icons/contaminant_source.svg
Normal file
@@ -0,0 +1 @@
|
||||
<?xml version="1.0" standalone="no"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg t="1769741101058" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="6910" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200"><path d="M102.4 921.6a25.6 25.6 0 0 1 25.6-25.6h768a25.6 25.6 0 0 1 0 51.2h-768A25.6 25.6 0 0 1 102.4 921.6zM638.464 612.5056A177.664 177.664 0 0 1 512 665.6a177.664 177.664 0 0 1-126.464-53.0944A183.6544 183.6544 0 0 1 332.8 483.328c0-20.224 10.0352-54.6304 31.232-100.352 20.3264-43.8272 47.9232-91.8016 76.1344-136.8576 25.6512-40.96 51.4048-78.7456 71.8336-107.776 20.48 29.0304 46.1824 66.816 71.8336 107.776 28.2112 45.056 55.808 93.0304 76.1344 136.8576 21.1968 45.7216 31.232 80.128 31.232 100.352 0 48.64-19.0464 95.0272-52.736 129.1264zM480.3584 94.464C417.28 182.9376 281.6 384.512 281.6 483.328c0 61.952 24.2688 121.344 67.4816 165.12A228.864 228.864 0 0 0 512 716.8a228.864 228.864 0 0 0 162.9184-68.3008A234.8544 234.8544 0 0 0 742.4 483.328c0-98.8672-135.68-300.4416-198.8096-388.9152C524.544 67.584 512 51.2 512 51.2s-12.4928 16.384-31.6416 43.264z" fill="#03a86b" p-id="6911"></path><path d="M409.6 870.4a51.2 51.2 0 1 1-102.4 0 51.2 51.2 0 0 1 102.4 0z" fill="#03a86b" p-id="6912"></path><path d="M640 780.8a38.4 38.4 0 1 1-76.8 0 38.4 38.4 0 0 1 76.8 0zM778.24 675.84a30.72 30.72 0 1 1-61.44 0 30.72 30.72 0 0 1 61.44 0zM317.44 706.56a30.72 30.72 0 1 1-61.44 0 30.72 30.72 0 0 1 61.44 0zM419.7376 435.2a25.6 25.6 0 0 1 18.0736 31.3344 76.8 76.8 0 0 0 94.0544 94.0544 25.6 25.6 0 1 1 13.2608 49.4592 128 128 0 0 1-156.7744-156.7744 25.6 25.6 0 0 1 31.3856-18.0736z" fill="#03a86b" p-id="6913"></path></svg>
|
||||
|
After Width: | Height: | Size: 1.7 KiB |
@@ -91,13 +91,13 @@ const fetchFromBackend = async (
|
||||
.join(",");
|
||||
|
||||
// 监测值数据接口(use_cleaned=false)
|
||||
const rawDataUrl = `${config.BACKEND_URL}/timescaledb/composite/element-scada?element_id=${feature_ids}&start_time=${start_time}&end_time=${end_time}&use_cleaned=false`;
|
||||
const rawDataUrl = `${config.BACKEND_URL}/api/v1/composite/element-scada?element_id=${feature_ids}&start_time=${start_time}&end_time=${end_time}&use_cleaned=false`;
|
||||
// 清洗数据接口(use_cleaned=true)
|
||||
const cleanedDataUrl = `${config.BACKEND_URL}/timescaledb/composite/element-scada?element_id=${feature_ids}&start_time=${start_time}&end_time=${end_time}&use_cleaned=true`;
|
||||
const cleanedDataUrl = `${config.BACKEND_URL}/api/v1/composite/element-scada?element_id=${feature_ids}&start_time=${start_time}&end_time=${end_time}&use_cleaned=true`;
|
||||
// 模拟数据接口
|
||||
const simulationDataUrl = `${config.BACKEND_URL}/timescaledb/composite/element-simulation?feature_infos=${feature_infos}&start_time=${start_time}&end_time=${end_time}`;
|
||||
const simulationDataUrl = `${config.BACKEND_URL}/api/v1/composite/element-simulation?feature_infos=${feature_infos}&start_time=${start_time}&end_time=${end_time}`;
|
||||
// 策略模拟数据接口
|
||||
const schemeSimulationDataUrl = `${config.BACKEND_URL}/timescaledb/composite/element-simulation?feature_infos=${feature_infos}&start_time=${start_time}&end_time=${end_time}&scheme_type=${scheme_type}&scheme_name=${scheme_name}`;
|
||||
const schemeSimulationDataUrl = `${config.BACKEND_URL}/api/v1/composite/element-simulation?feature_infos=${feature_infos}&start_time=${start_time}&end_time=${end_time}&scheme_type=${scheme_type}&scheme_name=${scheme_name}`;
|
||||
|
||||
try {
|
||||
if (type === "none") {
|
||||
@@ -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
|
||||
|
||||
@@ -28,10 +28,21 @@ const LayerControl: React.FC = () => {
|
||||
} = data;
|
||||
const [layerItems, setLayerItems] = useState<LayerItem[]>([]);
|
||||
|
||||
const layerOrder = [
|
||||
"junctions",
|
||||
"reservoirs",
|
||||
"tanks",
|
||||
"pipes",
|
||||
"pumps",
|
||||
"valves",
|
||||
"scada",
|
||||
"waterflowLayer",
|
||||
"junctionContourLayer",
|
||||
];
|
||||
|
||||
// 更新图层列表
|
||||
const updateLayers = useCallback(() => {
|
||||
if (!map || !data) return;
|
||||
const { deckLayer } = data;
|
||||
|
||||
const items: LayerItem[] = [];
|
||||
|
||||
@@ -93,19 +104,6 @@ const LayerControl: React.FC = () => {
|
||||
});
|
||||
}
|
||||
|
||||
// 3. 定义图层显示顺序和过滤白名单
|
||||
const layerOrder = [
|
||||
"junctions",
|
||||
"reservoirs",
|
||||
"tanks",
|
||||
"pipes",
|
||||
"pumps",
|
||||
"valves",
|
||||
"scada",
|
||||
"waterflowLayer",
|
||||
"junctionContourLayer",
|
||||
];
|
||||
|
||||
// 过滤并排序
|
||||
const sortedItems = items
|
||||
.filter((item) => layerOrder.includes(item.id))
|
||||
@@ -116,7 +114,7 @@ const LayerControl: React.FC = () => {
|
||||
});
|
||||
|
||||
setLayerItems(sortedItems);
|
||||
}, [map, isWaterflowLayerAvailable, isContourLayerAvailable]);
|
||||
}, [map, deckLayer, isWaterflowLayerAvailable, isContourLayerAvailable]);
|
||||
|
||||
useEffect(() => {
|
||||
updateLayers();
|
||||
@@ -146,7 +144,7 @@ const LayerControl: React.FC = () => {
|
||||
}
|
||||
|
||||
setLayerItems((prev) =>
|
||||
prev.map((i) => (i.id === item.id ? { ...i, visible: checked } : i))
|
||||
prev.map((i) => (i.id === item.id ? { ...i, visible: checked } : i)),
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -29,13 +29,13 @@ import { FiSkipBack, FiSkipForward } from "react-icons/fi";
|
||||
import { useData } from "../MapComponent";
|
||||
import { config, NETWORK_NAME } from "@/config/config";
|
||||
import { useMap } from "../MapComponent";
|
||||
const backendUrl = config.BACKEND_URL;
|
||||
|
||||
interface TimelineProps {
|
||||
schemeDate?: Date;
|
||||
timeRange?: { start: Date; end: Date };
|
||||
disableDateSelection?: boolean;
|
||||
schemeName?: string;
|
||||
schemeType?: string;
|
||||
}
|
||||
|
||||
const Timeline: React.FC<TimelineProps> = ({
|
||||
@@ -43,6 +43,7 @@ const Timeline: React.FC<TimelineProps> = ({
|
||||
timeRange,
|
||||
disableDateSelection = false,
|
||||
schemeName = "",
|
||||
schemeType = "burst_Analysis",
|
||||
}) => {
|
||||
const data = useData();
|
||||
if (!data) {
|
||||
@@ -100,7 +101,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,37 +112,39 @@ 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}`
|
||||
// `${config.BACKEND_URL}/queryallschemerecordsbytimeproperty/?querytime=${query_time}&type=node&property=${junctionProperties}&schemename=${schemeName}`
|
||||
`${config.BACKEND_URL}/api/v1/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}`
|
||||
`${backendUrl}/timescaledb/realtime/query/by-time-property?query_time=${query_time}&type=node&property=${junctionProperties}`
|
||||
// `${config.BACKEND_URL}/queryallrecordsbytimeproperty/?querytime=${query_time}&type=node&property=${junctionProperties}`
|
||||
`${config.BACKEND_URL}/api/v1/realtime/query/by-time-property?query_time=${query_time}&type=node&property=${junctionProperties}`,
|
||||
));
|
||||
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}`
|
||||
// `${config.BACKEND_URL}/queryallschemerecordsbytimeproperty/?querytime=${query_time}&type=link&property=${pipeProperties}&schemename=${schemeName}`
|
||||
`${config.BACKEND_URL}/api/v1/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}`
|
||||
`${backendUrl}/timescaledb/realtime/query/by-time-property?query_time=${query_time}&type=link&property=${pipeProperties}`
|
||||
// `${config.BACKEND_URL}/queryallrecordsbytimeproperty/?querytime=${query_time}&type=link&property=${pipeProperties}`
|
||||
`${config.BACKEND_URL}/api/v1/realtime/query/by-time-property?query_time=${query_time}&type=link&property=${pipeProperties}`,
|
||||
));
|
||||
requests.push(linkPromise);
|
||||
}
|
||||
@@ -156,8 +160,8 @@ const Timeline: React.FC<TimelineProps> = ({
|
||||
nodeRecords = await nodeResponse.json();
|
||||
// 缓存数据(修复键以包含 schemeName)
|
||||
nodeCacheRef.current.set(
|
||||
`${query_time}_${junctionProperties}_${schemeName}`,
|
||||
nodeRecords || []
|
||||
`${query_time}_${junctionProperties}_${schemeName}_${schemeType}`,
|
||||
nodeRecords || [],
|
||||
);
|
||||
}
|
||||
if (linkPromise) {
|
||||
@@ -167,8 +171,8 @@ const Timeline: React.FC<TimelineProps> = ({
|
||||
linkRecords = await linkResponse.json();
|
||||
// 缓存数据(修复键以包含 schemeName)
|
||||
linkCacheRef.current.set(
|
||||
`${query_time}_${pipeProperties}_${schemeName}`,
|
||||
linkRecords || []
|
||||
`${query_time}_${pipeProperties}_${schemeName}_${schemeType}`,
|
||||
linkRecords || [],
|
||||
);
|
||||
}
|
||||
// 更新状态
|
||||
@@ -244,7 +248,7 @@ const Timeline: React.FC<TimelineProps> = ({
|
||||
setCurrentTime(value);
|
||||
}, 500); // 500ms 防抖延迟
|
||||
},
|
||||
[timeRange, minTime, maxTime]
|
||||
[timeRange, minTime, maxTime],
|
||||
);
|
||||
|
||||
// 播放控制
|
||||
@@ -361,7 +365,7 @@ const Timeline: React.FC<TimelineProps> = ({
|
||||
}, newInterval);
|
||||
}
|
||||
},
|
||||
[isPlaying]
|
||||
[isPlaying],
|
||||
);
|
||||
// 计算时间段改变处理
|
||||
const handleCalculatedIntervalChange = useCallback((event: any) => {
|
||||
@@ -374,8 +378,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 +391,18 @@ const Timeline: React.FC<TimelineProps> = ({
|
||||
currentTimeToDate(selectedDate, currentTime),
|
||||
junctionText,
|
||||
pipeText,
|
||||
schemeName
|
||||
schemeName,
|
||||
schemeType,
|
||||
);
|
||||
}
|
||||
}, [junctionText, pipeText, currentTime, selectedDate]);
|
||||
}, [
|
||||
junctionText,
|
||||
pipeText,
|
||||
currentTime,
|
||||
selectedDate,
|
||||
schemeName,
|
||||
schemeType,
|
||||
]);
|
||||
|
||||
// 组件卸载时清理定时器和防抖
|
||||
useEffect(() => {
|
||||
@@ -439,7 +451,7 @@ const Timeline: React.FC<TimelineProps> = ({
|
||||
const dateStr = date.toISOString().split("T")[0];
|
||||
|
||||
const clearCache = (
|
||||
cacheRef: ReturnType<typeof useRef<Map<string, any[]>>>
|
||||
cacheRef: ReturnType<typeof useRef<Map<string, any[]>>>,
|
||||
) => {
|
||||
if (!cacheRef.current) return;
|
||||
const cacheKeys = Array.from(cacheRef.current.keys());
|
||||
@@ -467,7 +479,8 @@ const Timeline: React.FC<TimelineProps> = ({
|
||||
currentTimeToDate(selectedDate, currentTime),
|
||||
junctionText,
|
||||
pipeText,
|
||||
schemeName
|
||||
schemeName,
|
||||
schemeType,
|
||||
);
|
||||
};
|
||||
|
||||
@@ -501,14 +514,14 @@ const Timeline: React.FC<TimelineProps> = ({
|
||||
};
|
||||
|
||||
const response = await fetch(
|
||||
`${backendUrl}/runsimulationmanuallybydate/`,
|
||||
`${config.BACKEND_URL}/api/v1/runsimulationmanuallybydate/`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
if (response.ok) {
|
||||
@@ -536,7 +549,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 +564,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
|
||||
|
||||
@@ -20,7 +20,6 @@ import { handleMapClickSelectFeatures as mapClickSelectFeatures } from "@/utils/
|
||||
import { useNotification } from "@refinedev/core";
|
||||
|
||||
import { config } from "@/config/config";
|
||||
const backendUrl = config.BACKEND_URL;
|
||||
|
||||
// 添加接口定义隐藏按钮的props
|
||||
interface ToolbarProps {
|
||||
@@ -196,13 +195,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";
|
||||
@@ -222,7 +228,7 @@ const Toolbar: React.FC<ToolbarProps> = ({
|
||||
if (getBaseType(layerId) !== getBaseType(firstLayerId)) {
|
||||
// 如果点击的是已选中的要素(为了取消选中),则不报错
|
||||
const isAlreadySelected = highlightFeatures.some(
|
||||
(f) => f.getProperties().id === featureId
|
||||
(f) => f.getProperties().id === featureId,
|
||||
);
|
||||
if (!isAlreadySelected) {
|
||||
open?.({
|
||||
@@ -236,7 +242,7 @@ const Toolbar: React.FC<ToolbarProps> = ({
|
||||
|
||||
setHighlightFeatures((prev) => {
|
||||
const existingIndex = prev.findIndex(
|
||||
(f) => f.getProperties().id === featureId
|
||||
(f) => f.getProperties().id === featureId,
|
||||
);
|
||||
|
||||
if (existingIndex !== -1) {
|
||||
@@ -252,7 +258,7 @@ const Toolbar: React.FC<ToolbarProps> = ({
|
||||
setHighlightFeatures([feature]);
|
||||
}
|
||||
},
|
||||
[map, activeTools, highlightFeatures, open]
|
||||
[map, activeTools, highlightFeatures, open],
|
||||
);
|
||||
// 添加矢量属性查询事件监听器
|
||||
useEffect(() => {
|
||||
@@ -381,13 +387,13 @@ const Toolbar: React.FC<ToolbarProps> = ({
|
||||
let response;
|
||||
if (queryType === "scheme") {
|
||||
response = await fetch(
|
||||
// `${backendUrl}/queryschemesimulationrecordsbyidtime/?scheme_name=${schemeName}&id=${id}&querytime=${querytime}&type=${type}`
|
||||
`${backendUrl}/timescaledb/scheme/query/by-id-time?scheme_name=${schemeName}&id=${id}&type=${type}&query_time=${querytime}`
|
||||
// `${config.BACKEND_URL}/queryschemesimulationrecordsbyidtime/?scheme_name=${schemeName}&id=${id}&querytime=${querytime}&type=${type}`
|
||||
`${config.BACKEND_URL}/api/v1/scheme/query/by-id-time?scheme_name=${schemeName}&id=${id}&type=${type}&query_time=${querytime}`,
|
||||
);
|
||||
} else {
|
||||
response = await fetch(
|
||||
// `${backendUrl}/querysimulationrecordsbyidtime/?id=${id}&querytime=${querytime}&type=${type}`
|
||||
`${backendUrl}/timescaledb/realtime/query/by-id-time?id=${id}&type=${type}&query_time=${querytime}`
|
||||
// `${config.BACKEND_URL}/querysimulationrecordsbyidtime/?id=${id}&querytime=${querytime}&type=${type}`
|
||||
`${config.BACKEND_URL}/api/v1/realtime/query/by-id-time?id=${id}&type=${type}&query_time=${querytime}`,
|
||||
);
|
||||
}
|
||||
if (!response.ok) {
|
||||
|
||||
@@ -111,7 +111,7 @@ const MapComponent: React.FC<MapComponentProps> = ({ children }) => {
|
||||
const [schemeName, setSchemeName] = useState<string>(""); // 当前方案名称
|
||||
// 记录 id、对应属性的计算值
|
||||
const [currentJunctionCalData, setCurrentJunctionCalData] = useState<any[]>(
|
||||
[]
|
||||
[],
|
||||
);
|
||||
const [currentPipeCalData, setCurrentPipeCalData] = useState<any[]>([]);
|
||||
// junctionData 和 pipeData 分别缓存瓦片解析后节点和管道的数据,用于 deck.gl 定位、标签渲染
|
||||
@@ -180,7 +180,7 @@ const MapComponent: React.FC<MapComponentProps> = ({ children }) => {
|
||||
setPipeData(tilePipeDataBuffer.current);
|
||||
tilePipeDataBuffer.current = [];
|
||||
}
|
||||
}, 100)
|
||||
}, 100),
|
||||
);
|
||||
|
||||
const setJunctionData = (newData: any[]) => {
|
||||
@@ -317,7 +317,7 @@ const MapComponent: React.FC<MapComponentProps> = ({ children }) => {
|
||||
scale: 0.12,
|
||||
anchor: [0.5, 0.5],
|
||||
}),
|
||||
})
|
||||
}),
|
||||
);
|
||||
}
|
||||
return styles;
|
||||
@@ -500,7 +500,7 @@ const MapComponent: React.FC<MapComponentProps> = ({ children }) => {
|
||||
const uniqueData = Array.from(data.values());
|
||||
if (uniqueData.length > 0) {
|
||||
uniqueData.forEach((item) =>
|
||||
tileJunctionDataBuffer.current.push(item)
|
||||
tileJunctionDataBuffer.current.push(item),
|
||||
);
|
||||
debouncedUpdateData.current();
|
||||
}
|
||||
@@ -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,
|
||||
@@ -708,7 +709,7 @@ const MapComponent: React.FC<MapComponentProps> = ({ children }) => {
|
||||
if (center && typeof zoom === "number") {
|
||||
localStorage.setItem(
|
||||
MAP_VIEW_STORAGE_KEY,
|
||||
JSON.stringify({ center, zoom })
|
||||
JSON.stringify({ center, zoom }),
|
||||
);
|
||||
}
|
||||
} catch (err) {
|
||||
@@ -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] || "";
|
||||
@@ -938,27 +947,12 @@ const MapComponent: React.FC<MapComponentProps> = ({ children }) => {
|
||||
|
||||
// 动画循环
|
||||
const animate = () => {
|
||||
if (!flowAnimation.current) {
|
||||
try {
|
||||
deckLayer.removeDeckLayer("waterflowLayer");
|
||||
} catch (error) {
|
||||
console.error("Error in animation loop:", error);
|
||||
}
|
||||
return;
|
||||
}
|
||||
// 动画总时长(秒)
|
||||
if (mergedPipeData.length === 0) {
|
||||
animationFrameId = requestAnimationFrame(animate);
|
||||
return;
|
||||
}
|
||||
const animationDuration = 10;
|
||||
// 缓冲时间(秒)
|
||||
const bufferTime = 2;
|
||||
// 完整循环周期
|
||||
const loopLength = animationDuration + bufferTime;
|
||||
// 确保时间范围与你的时间戳数据匹配
|
||||
const currentTime = (Date.now() / 1000) % loopLength; // (0,12) 之间循环
|
||||
// console.log("Current Time:", currentTime);
|
||||
const currentTime = (Date.now() / 1000) % loopLength;
|
||||
|
||||
const waterflowLayer = new TripsLayer({
|
||||
id: "waterflowLayer",
|
||||
name: "水流",
|
||||
@@ -972,7 +966,7 @@ const MapComponent: React.FC<MapComponentProps> = ({ children }) => {
|
||||
visible:
|
||||
isWaterflowLayerAvailable &&
|
||||
showWaterflowLayer &&
|
||||
flowAnimation.current &&
|
||||
flowAnimation.current && // 保持动画标志作为可见性的一部分
|
||||
currentZoom >= 12 &&
|
||||
currentZoom <= 24,
|
||||
widthMinPixels: 5,
|
||||
@@ -981,13 +975,17 @@ const MapComponent: React.FC<MapComponentProps> = ({ children }) => {
|
||||
trailLength: 2, // 水流尾迹淡出时间
|
||||
currentTime: currentTime,
|
||||
});
|
||||
|
||||
if (deckLayer.getDeckLayerById("waterflowLayer")) {
|
||||
deckLayer.updateDeckLayer("waterflowLayer", waterflowLayer);
|
||||
} else {
|
||||
deckLayer.addDeckLayer(waterflowLayer);
|
||||
}
|
||||
// 继续请求动画帧,每帧执行一次函数
|
||||
animationFrameId = requestAnimationFrame(animate);
|
||||
|
||||
// 只有在需要动画时才请求下一帧,但图层已经添加到了 deckLayer 中
|
||||
if (flowAnimation.current) {
|
||||
animationFrameId = requestAnimationFrame(animate);
|
||||
}
|
||||
};
|
||||
animate();
|
||||
|
||||
@@ -998,6 +996,7 @@ const MapComponent: React.FC<MapComponentProps> = ({ children }) => {
|
||||
}
|
||||
};
|
||||
}, [
|
||||
currentPipeCalData,
|
||||
currentZoom,
|
||||
mergedPipeData,
|
||||
pipeText,
|
||||
|
||||
@@ -154,11 +154,11 @@ const App = (props: React.PropsWithChildren<AppProps>) => {
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "爆管分析定位",
|
||||
list: "/burst-pipe-analysis",
|
||||
name: "风险分析定位",
|
||||
list: "/risk-analysis-location",
|
||||
meta: {
|
||||
icon: <TbLocationPin className="w-6 h-6" />,
|
||||
label: "爆管分析定位",
|
||||
label: "风险分析定位",
|
||||
},
|
||||
},
|
||||
{
|
||||
|
||||
@@ -44,7 +44,7 @@ const AnalysisParameters: React.FC = () => {
|
||||
const [startTime, setStartTime] = useState<Dayjs | null>(dayjs(new Date()));
|
||||
const [duration, setDuration] = useState<number>(3600);
|
||||
const [schemeName, setSchemeName] = useState<string>(
|
||||
"FANGAN" + new Date().getTime()
|
||||
"FANGAN" + new Date().getTime(),
|
||||
);
|
||||
const [network, setNetwork] = useState<string>(NETWORK_NAME);
|
||||
const [isSelecting, setIsSelecting] = useState<boolean>(false);
|
||||
@@ -88,7 +88,7 @@ const AnalysisParameters: React.FC = () => {
|
||||
width: 3,
|
||||
lineDash: [15, 10],
|
||||
}),
|
||||
})
|
||||
}),
|
||||
);
|
||||
const geometry = feature.getGeometry();
|
||||
const lineCoords =
|
||||
@@ -115,7 +115,7 @@ const AnalysisParameters: React.FC = () => {
|
||||
scale: 0.2,
|
||||
anchor: [0.5, 1],
|
||||
}),
|
||||
})
|
||||
}),
|
||||
);
|
||||
}
|
||||
return styles;
|
||||
@@ -163,14 +163,14 @@ const AnalysisParameters: React.FC = () => {
|
||||
// 移除不在highlightFeatures中的
|
||||
const filtered = prevPipes.filter((pipe) =>
|
||||
highlightFeatures.some(
|
||||
(feature) => feature.getProperties().id === pipe.id
|
||||
)
|
||||
(feature) => feature.getProperties().id === pipe.id,
|
||||
),
|
||||
);
|
||||
// 添加新的
|
||||
const newPipes = highlightFeatures
|
||||
.filter(
|
||||
(feature) =>
|
||||
!filtered.some((p) => p.id === feature.getProperties().id)
|
||||
!filtered.some((p) => p.id === feature.getProperties().id),
|
||||
)
|
||||
.map((feature) => {
|
||||
const properties = feature.getProperties();
|
||||
@@ -207,7 +207,7 @@ const AnalysisParameters: React.FC = () => {
|
||||
const featureId = feature.getProperties().id;
|
||||
setHighlightFeatures((prev) => {
|
||||
const existingIndex = prev.findIndex(
|
||||
(f) => f.getProperties().id === featureId
|
||||
(f) => f.getProperties().id === featureId,
|
||||
);
|
||||
if (existingIndex !== -1) {
|
||||
// 如果已存在,移除
|
||||
@@ -218,7 +218,7 @@ const AnalysisParameters: React.FC = () => {
|
||||
}
|
||||
});
|
||||
},
|
||||
[map]
|
||||
[map],
|
||||
);
|
||||
|
||||
// 开始选择管道
|
||||
@@ -242,14 +242,14 @@ const AnalysisParameters: React.FC = () => {
|
||||
const handleRemovePipe = (id: string) => {
|
||||
// 从高亮features中移除
|
||||
setHighlightFeatures((prev) =>
|
||||
prev.filter((f) => f.getProperties().id !== id)
|
||||
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))
|
||||
prev.map((pipe) => (pipe.id === id ? { ...pipe, area: numValue } : pipe)),
|
||||
);
|
||||
};
|
||||
|
||||
@@ -266,30 +266,26 @@ const AnalysisParameters: React.FC = () => {
|
||||
|
||||
const burst_ID = pipePoints.map((pipe) => pipe.id);
|
||||
const burst_size = pipePoints.map((pipe) =>
|
||||
parseInt(pipe.area.toString(), 10)
|
||||
parseInt(pipe.area.toString(), 10),
|
||||
);
|
||||
// 格式化开始时间,去除秒部分
|
||||
const modify_pattern_start_time = startTime
|
||||
? startTime.format("YYYY-MM-DDTHH:mm:00Z")
|
||||
: "";
|
||||
const modify_total_duration = duration;
|
||||
const body = {
|
||||
name: network,
|
||||
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,
|
||||
scheme_name: schemeName,
|
||||
};
|
||||
|
||||
try {
|
||||
await axios.post(`${config.BACKEND_URL}/burst_analysis/`, body, {
|
||||
headers: {
|
||||
"Accept-Encoding": "gzip",
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
await axios.get(`${config.BACKEND_URL}/api/v1/burst_analysis/`, {
|
||||
params,
|
||||
});
|
||||
|
||||
// 更新弹窗为成功状态
|
||||
open?.({
|
||||
key: "burst-analysis",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import React, { useState } from "react";
|
||||
import React, { useEffect, useRef, useState } from "react";
|
||||
import {
|
||||
Box,
|
||||
Drawer,
|
||||
@@ -16,32 +16,20 @@ import {
|
||||
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, { LocationResult } from "./LocationResults";
|
||||
import LocationResults from "./LocationResults";
|
||||
import ValveIsolation from "./ValveIsolation";
|
||||
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";
|
||||
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;
|
||||
}
|
||||
|
||||
interface SchemeRecord {
|
||||
id: number;
|
||||
schemeName: string;
|
||||
type: string;
|
||||
user: string;
|
||||
create_time: string;
|
||||
startTime: string;
|
||||
// 详情信息
|
||||
schemeDetail?: SchemeDetail;
|
||||
}
|
||||
import { useData } from "@app/OlMap/MapComponent";
|
||||
import { LocationResult, SchemeRecord, ValveIsolationResult } from "./types";
|
||||
|
||||
interface TabPanelProps {
|
||||
children?: React.ReactNode;
|
||||
@@ -68,17 +56,32 @@ 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[]>([]);
|
||||
// 定位结果数据
|
||||
const [locationResults, setLocationResults] = useState<LocationResult[]>([]);
|
||||
// 选中的管段ID数组
|
||||
const [selectedPipeIds, setSelectedPipeIds] = useState<string[]>([]);
|
||||
// 关阀分析状态提升到父组件
|
||||
const [valveAnalysisTriggered, setValveAnalysisTriggered] = useState(false);
|
||||
// 关阀分析结果和加载状态
|
||||
const [valveAnalysisLoading, setValveAnalysisLoading] = useState(false);
|
||||
const [valveAnalysisResult, setValveAnalysisResult] = useState<ValveIsolationResult | null>(null);
|
||||
|
||||
const { open } = useNotification();
|
||||
|
||||
@@ -96,10 +99,20 @@ const BurstPipeAnalysisPanel: React.FC<BurstPipeAnalysisPanelProps> = ({
|
||||
setCurrentTab(newValue);
|
||||
};
|
||||
|
||||
const handleModeChange = (_event: React.SyntheticEvent, newMode: PanelMode) => {
|
||||
setPanelMode(newMode);
|
||||
// 切换模式时,如果当前标签索引超出新模式的标签数量,重置为第一个标签
|
||||
// 爆管分析有4个标签(0-3),水质模拟有3个标签(0-2)
|
||||
const maxTabIndex = newMode === "burst" ? 3 : 2;
|
||||
if (currentTab > maxTabIndex) {
|
||||
setCurrentTab(0);
|
||||
}
|
||||
};
|
||||
|
||||
const handleLocateScheme = async (scheme: SchemeRecord) => {
|
||||
try {
|
||||
const response = await axios.get(
|
||||
`${config.BACKEND_URL}/postgresql/burst-locate-result/${scheme.schemeName}`
|
||||
`${config.BACKEND_URL}/api/v1/burst-locate-result/${scheme.schemeName}`,
|
||||
);
|
||||
setLocationResults(response.data);
|
||||
setCurrentTab(2); // 切换到定位结果标签页
|
||||
@@ -113,7 +126,15 @@ const BurstPipeAnalysisPanel: React.FC<BurstPipeAnalysisPanelProps> = ({
|
||||
}
|
||||
};
|
||||
|
||||
const handleAnalyzePipe = (pipeIds: string[]) => {
|
||||
setSelectedPipeIds(pipeIds);
|
||||
setValveAnalysisTriggered(true);
|
||||
setCurrentTab(3);
|
||||
};
|
||||
|
||||
const drawerWidth = 520;
|
||||
const isBurstMode = panelMode === "burst";
|
||||
const panelTitle = isBurstMode ? "爆管分析" : "水质模拟";
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -131,7 +152,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 +196,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 +211,31 @@ const BurstPipeAnalysisPanel: React.FC<BurstPipeAnalysisPanelProps> = ({
|
||||
</Box>
|
||||
|
||||
{/* Tabs 导航 */}
|
||||
<Box className="border-b border-gray-200 bg-white">
|
||||
<Tabs
|
||||
value={panelMode}
|
||||
onChange={handleModeChange}
|
||||
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,41 +271,63 @@ const BurstPipeAnalysisPanel: React.FC<BurstPipeAnalysisPanelProps> = ({
|
||||
<Tab
|
||||
icon={<MyLocationIcon fontSize="small" />}
|
||||
iconPosition="start"
|
||||
label="定位结果"
|
||||
label={isBurstMode ? "定位结果" : "模拟结果"}
|
||||
/>
|
||||
{isBurstMode && (
|
||||
<Tab
|
||||
icon={<HandymanIcon fontSize="small" />}
|
||||
iconPosition="start"
|
||||
label="关阀分析"
|
||||
/>
|
||||
)}
|
||||
</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 onViewResults={() => setCurrentTab(2)} />
|
||||
)}
|
||||
</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}
|
||||
onAnalyze={handleAnalyzePipe}
|
||||
/>
|
||||
) : (
|
||||
<ContaminantResultsPanel schemeName={data?.schemeName} />
|
||||
)}
|
||||
</TabPanel>
|
||||
|
||||
{isBurstMode && (
|
||||
<TabPanel value={currentTab} index={3}>
|
||||
<ValveIsolation
|
||||
initialPipeIds={selectedPipeIds}
|
||||
shouldFetch={valveAnalysisTriggered}
|
||||
onFetchComplete={() => setValveAnalysisTriggered(false)}
|
||||
loading={valveAnalysisLoading}
|
||||
result={valveAnalysisResult}
|
||||
onLoadingChange={setValveAnalysisLoading}
|
||||
onResultChange={setValveAnalysisResult}
|
||||
/>
|
||||
</TabPanel>
|
||||
)}
|
||||
</Box>
|
||||
</Drawer>
|
||||
</>
|
||||
|
||||
@@ -9,7 +9,10 @@ import {
|
||||
Tooltip,
|
||||
Link,
|
||||
} from "@mui/material";
|
||||
import { LocationOn as LocationIcon } from "@mui/icons-material";
|
||||
import {
|
||||
LocationOn as LocationIcon,
|
||||
Handyman as HandymanIcon,
|
||||
} from "@mui/icons-material";
|
||||
import { queryFeaturesByIds } from "@/utils/mapQueryService";
|
||||
import { useMap } from "@app/OlMap/MapComponent";
|
||||
import { GeoJSON } from "ol/format";
|
||||
@@ -29,21 +32,17 @@ import { Point } from "ol/geom";
|
||||
import { toLonLat } from "ol/proj";
|
||||
import moment from "moment";
|
||||
import "moment-timezone";
|
||||
|
||||
export interface LocationResult {
|
||||
id: number;
|
||||
type: string;
|
||||
burst_incident: string;
|
||||
leakage: number | null;
|
||||
detect_time: string;
|
||||
locate_result: string[] | null;
|
||||
}
|
||||
import { LocationResult } from "./types";
|
||||
|
||||
interface LocationResultsProps {
|
||||
results?: LocationResult[];
|
||||
onAnalyze?: (pipeIds: string[]) => void;
|
||||
}
|
||||
|
||||
const LocationResults: React.FC<LocationResultsProps> = ({ results = [] }) => {
|
||||
const LocationResults: React.FC<LocationResultsProps> = ({
|
||||
results = [],
|
||||
onAnalyze,
|
||||
}) => {
|
||||
const [highlightLayer, setHighlightLayer] =
|
||||
useState<VectorLayer<VectorSource> | null>(null);
|
||||
const [highlightFeatures, setHighlightFeatures] = useState<Feature[]>([]);
|
||||
@@ -56,14 +55,14 @@ const LocationResults: React.FC<LocationResultsProps> = ({ results = [] }) => {
|
||||
|
||||
const handleLocatePipes = (pipeIds: string[]) => {
|
||||
if (pipeIds.length > 0) {
|
||||
queryFeaturesByIds(pipeIds).then((features) => {
|
||||
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)
|
||||
geojsonFormat.writeFeatureObject(feature),
|
||||
);
|
||||
|
||||
const extent = bbox(featureCollection(geojsonFeatures as any));
|
||||
@@ -103,7 +102,7 @@ const LocationResults: React.FC<LocationResultsProps> = ({ results = [] }) => {
|
||||
width: 3,
|
||||
lineDash: [15, 10],
|
||||
}),
|
||||
})
|
||||
}),
|
||||
);
|
||||
const geometry = feature.getGeometry();
|
||||
const lineCoords =
|
||||
@@ -130,7 +129,7 @@ const LocationResults: React.FC<LocationResultsProps> = ({ results = [] }) => {
|
||||
scale: 0.2,
|
||||
anchor: [0.5, 1],
|
||||
}),
|
||||
})
|
||||
}),
|
||||
);
|
||||
}
|
||||
return styles;
|
||||
@@ -251,7 +250,9 @@ const LocationResults: React.FC<LocationResultsProps> = ({ results = [] }) => {
|
||||
{result.burst_incident}
|
||||
</Typography>
|
||||
<Chip
|
||||
label={result.type}
|
||||
label={
|
||||
result.type === "burst_analysis" ? "爆管模拟" : result.type
|
||||
}
|
||||
size="small"
|
||||
color="primary"
|
||||
variant="outlined"
|
||||
@@ -347,21 +348,40 @@ const LocationResults: React.FC<LocationResultsProps> = ({ results = [] }) => {
|
||||
>
|
||||
管段列表
|
||||
</Typography>
|
||||
<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 className="flex items-center gap-2">
|
||||
{onAnalyze && (
|
||||
<Tooltip title="关阀分析">
|
||||
<IconButton
|
||||
size="small"
|
||||
onClick={() => onAnalyze(result.locate_result!)}
|
||||
color="secondary"
|
||||
sx={{
|
||||
backgroundColor: "rgba(156, 39, 176, 0.1)",
|
||||
"&:hover": {
|
||||
backgroundColor: "rgba(156, 39, 176, 0.2)",
|
||||
},
|
||||
}}
|
||||
>
|
||||
<HandymanIcon sx={{ fontSize: "1.2rem" }} />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
)}
|
||||
<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) => (
|
||||
@@ -369,6 +389,12 @@ const LocationResults: React.FC<LocationResultsProps> = ({ results = [] }) => {
|
||||
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
|
||||
@@ -377,10 +403,43 @@ const LocationResults: React.FC<LocationResultsProps> = ({ results = [] }) => {
|
||||
>
|
||||
{pipeId}
|
||||
</Typography>
|
||||
<LocationIcon
|
||||
sx={{ fontSize: "1rem" }}
|
||||
className="text-blue-400 group-hover:text-blue-600 transition-colors"
|
||||
/>
|
||||
<Box className="flex items-center gap-1">
|
||||
{onAnalyze && (
|
||||
<Tooltip title="单管段关阀分析">
|
||||
<IconButton
|
||||
size="small"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onAnalyze([pipeId]);
|
||||
}}
|
||||
className="text-blue-400 hover:text-blue-600"
|
||||
sx={{
|
||||
"&:hover": {
|
||||
backgroundColor: "rgba(37, 125, 212, 0.1)",
|
||||
},
|
||||
}}
|
||||
>
|
||||
<HandymanIcon sx={{ fontSize: "1rem" }} />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
)}
|
||||
{/* <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>
|
||||
))}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import React, { useEffect, useState } from "react";
|
||||
import React, { useEffect, useMemo, useState } from "react";
|
||||
import ReactDOM from "react-dom"; // 添加这行
|
||||
|
||||
import {
|
||||
@@ -49,36 +49,7 @@ import {
|
||||
import { Point } from "ol/geom";
|
||||
import { toLonLat } from "ol/proj";
|
||||
import Timeline from "@app/OlMap/Controls/Timeline";
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
interface SchemeRecord {
|
||||
id: number;
|
||||
schemeName: string;
|
||||
type: string;
|
||||
user: string;
|
||||
create_time: string;
|
||||
startTime: string;
|
||||
// 详情信息
|
||||
schemeDetail?: SchemeDetail;
|
||||
}
|
||||
|
||||
interface SchemaItem {
|
||||
scheme_id: number;
|
||||
scheme_name: string;
|
||||
scheme_type: string;
|
||||
username: string;
|
||||
create_time: string;
|
||||
scheme_start_time: string;
|
||||
scheme_detail?: SchemeDetail;
|
||||
}
|
||||
import { SchemaItem, SchemeRecord } from "./types";
|
||||
|
||||
interface SchemeQueryProps {
|
||||
schemes?: SchemeRecord[];
|
||||
@@ -87,6 +58,8 @@ interface SchemeQueryProps {
|
||||
network?: string;
|
||||
}
|
||||
|
||||
const SCHEME_TYPE = "burst_analysis";
|
||||
|
||||
const SchemeQuery: React.FC<SchemeQueryProps> = ({
|
||||
schemes: externalSchemes,
|
||||
onSchemesChange,
|
||||
@@ -114,8 +87,8 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
|
||||
|
||||
const map = useMap();
|
||||
const data = useData();
|
||||
if (!data) return null;
|
||||
const { schemeName, setSchemeName } = data;
|
||||
const { schemeName, setSchemeName } = data || {};
|
||||
|
||||
// 使用外部提供的 schemes 或内部状态
|
||||
const schemes =
|
||||
externalSchemes !== undefined ? externalSchemes : internalSchemes;
|
||||
@@ -127,13 +100,17 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
|
||||
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}`
|
||||
`${config.BACKEND_URL}/api/v1/getallschemes/?network=${network}`,
|
||||
);
|
||||
let filteredResults = response.data;
|
||||
|
||||
@@ -154,7 +131,7 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
|
||||
create_time: item.create_time,
|
||||
startTime: item.scheme_start_time,
|
||||
schemeDetail: item.scheme_detail,
|
||||
}))
|
||||
})),
|
||||
);
|
||||
|
||||
if (filteredResults.length === 0) {
|
||||
@@ -180,14 +157,14 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
|
||||
|
||||
const handleLocatePipes = (pipeIds: string[]) => {
|
||||
if (pipeIds.length > 0) {
|
||||
queryFeaturesByIds(pipeIds).then((features) => {
|
||||
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)
|
||||
geojsonFormat.writeFeatureObject(feature),
|
||||
);
|
||||
|
||||
const extent = bbox(featureCollection(geojsonFeatures as any));
|
||||
@@ -202,25 +179,24 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
|
||||
|
||||
// 内部的方案查询函数
|
||||
const handleViewDetails = (id: number) => {
|
||||
const scheme = filteredSchemes.find((s) => s.id === id);
|
||||
if (!scheme) return;
|
||||
|
||||
setShowTimeline(true);
|
||||
// 计算时间范围
|
||||
const scheme = schemes.find((s) => s.id === id);
|
||||
const burstPipeIds = scheme?.schemeDetail?.burst_ID || [];
|
||||
const schemeDate = scheme?.startTime
|
||||
const schemeDate = scheme.startTime
|
||||
? new Date(scheme.startTime)
|
||||
: undefined;
|
||||
if (scheme?.startTime && scheme.schemeDetail?.modify_total_duration) {
|
||||
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
|
||||
start.getTime() + scheme.schemeDetail.modify_total_duration * 1000,
|
||||
);
|
||||
setSelectedDate(schemeDate);
|
||||
setTimeRange({ start, end });
|
||||
if (setSchemeName) {
|
||||
setSchemeName(scheme.schemeName);
|
||||
}
|
||||
handleLocatePipes(burstPipeIds);
|
||||
}
|
||||
setSchemeName?.(scheme.schemeName);
|
||||
handleLocatePipes(scheme.schemeDetail?.burst_ID || []);
|
||||
};
|
||||
|
||||
// 初始化管道图层和高亮图层
|
||||
@@ -254,7 +230,7 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
|
||||
width: 3,
|
||||
lineDash: [15, 10],
|
||||
}),
|
||||
})
|
||||
}),
|
||||
);
|
||||
const geometry = feature.getGeometry();
|
||||
const lineCoords =
|
||||
@@ -281,7 +257,7 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
|
||||
scale: 0.2,
|
||||
anchor: [0.5, 1],
|
||||
}),
|
||||
})
|
||||
}),
|
||||
);
|
||||
}
|
||||
return styles;
|
||||
@@ -336,8 +312,9 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
|
||||
timeRange={timeRange}
|
||||
disableDateSelection={!!timeRange}
|
||||
schemeName={schemeName}
|
||||
schemeType={SCHEME_TYPE}
|
||||
/>,
|
||||
mapContainer // 渲染到地图容器中,而不是 body
|
||||
mapContainer, // 渲染到地图容器中,而不是 body
|
||||
)}
|
||||
<Box className="flex flex-col h-full">
|
||||
{/* 查询条件 - 单行布局 */}
|
||||
@@ -390,7 +367,7 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
|
||||
|
||||
{/* 结果列表 */}
|
||||
<Box className="flex-1 overflow-auto">
|
||||
{schemes.length === 0 ? (
|
||||
{filteredSchemes.length === 0 ? (
|
||||
<Box className="flex flex-col items-center justify-center h-full text-gray-400">
|
||||
<Box className="mb-4">
|
||||
<svg
|
||||
@@ -427,9 +404,9 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
|
||||
) : (
|
||||
<Box className="space-y-2 p-2">
|
||||
<Typography variant="caption" className="text-gray-500 px-2">
|
||||
共 {schemes.length} 条记录
|
||||
共 {filteredSchemes.length} 条记录
|
||||
</Typography>
|
||||
{schemes.map((scheme) => (
|
||||
{filteredSchemes.map((scheme) => (
|
||||
<Card
|
||||
key={scheme.id}
|
||||
variant="outlined"
|
||||
@@ -448,7 +425,11 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
|
||||
{scheme.schemeName}
|
||||
</Typography>
|
||||
<Chip
|
||||
label={scheme.type}
|
||||
label={
|
||||
scheme.type === "burst_analysis"
|
||||
? "爆管模拟"
|
||||
: scheme.type
|
||||
}
|
||||
size="small"
|
||||
className="h-5"
|
||||
color="primary"
|
||||
@@ -474,7 +455,7 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
|
||||
size="small"
|
||||
onClick={() =>
|
||||
setExpandedId(
|
||||
expandedId === scheme.id ? null : scheme.id
|
||||
expandedId === scheme.id ? null : scheme.id,
|
||||
)
|
||||
}
|
||||
color="primary"
|
||||
@@ -483,7 +464,7 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
|
||||
<InfoIcon fontSize="small" />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
<Tooltip title="定位">
|
||||
<Tooltip title="查看定位结果">
|
||||
<IconButton
|
||||
size="small"
|
||||
onClick={() => onLocate?.(scheme)}
|
||||
@@ -527,7 +508,7 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
|
||||
>
|
||||
{pipeId}
|
||||
</Link>
|
||||
)
|
||||
),
|
||||
)
|
||||
) : (
|
||||
<Typography
|
||||
@@ -617,7 +598,7 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
|
||||
className="font-medium text-gray-900"
|
||||
>
|
||||
{moment(scheme.create_time).format(
|
||||
"YYYY-MM-DD HH:mm"
|
||||
"YYYY-MM-DD HH:mm",
|
||||
)}
|
||||
</Typography>
|
||||
</Box>
|
||||
@@ -633,7 +614,7 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
|
||||
className="font-medium text-gray-900"
|
||||
>
|
||||
{moment(scheme.startTime).format(
|
||||
"YYYY-MM-DD HH:mm"
|
||||
"YYYY-MM-DD HH:mm",
|
||||
)}
|
||||
</Typography>
|
||||
</Box>
|
||||
@@ -651,7 +632,7 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
|
||||
className="border-blue-600 text-blue-600 hover:bg-blue-50"
|
||||
onClick={() =>
|
||||
handleLocatePipes?.(
|
||||
scheme.schemeDetail!.burst_ID
|
||||
scheme.schemeDetail!.burst_ID,
|
||||
)
|
||||
}
|
||||
sx={{
|
||||
|
||||
733
src/components/olmap/BurstPipeAnalysis/ValveIsolation.tsx
Normal file
733
src/components/olmap/BurstPipeAnalysis/ValveIsolation.tsx
Normal file
@@ -0,0 +1,733 @@
|
||||
"use client";
|
||||
|
||||
import React, { useState, useEffect, useCallback, useRef } from "react";
|
||||
import {
|
||||
Box,
|
||||
Typography,
|
||||
Chip,
|
||||
CircularProgress,
|
||||
IconButton,
|
||||
Tooltip,
|
||||
} from "@mui/material";
|
||||
import { LocationOn as LocationIcon } from "@mui/icons-material";
|
||||
import axios from "axios";
|
||||
import { config, NETWORK_NAME } from "@config/config";
|
||||
import { ValveIsolationResult } from "./types";
|
||||
import { useNotification } from "@refinedev/core";
|
||||
import { queryFeaturesByIds } from "@/utils/mapQueryService";
|
||||
import { useMap } from "@app/OlMap/MapComponent";
|
||||
import { GeoJSON } from "ol/format";
|
||||
import VectorLayer from "ol/layer/Vector";
|
||||
import VectorSource from "ol/source/Vector";
|
||||
import { Circle as CircleStyle, Fill, Stroke, Style, Icon } from "ol/style";
|
||||
import Feature, { FeatureLike } from "ol/Feature";
|
||||
import {
|
||||
bbox,
|
||||
featureCollection,
|
||||
along,
|
||||
lineString,
|
||||
length,
|
||||
toMercator,
|
||||
} from "@turf/turf";
|
||||
import { Point } from "ol/geom";
|
||||
import { toLonLat } from "ol/proj";
|
||||
|
||||
interface ValveIsolationProps {
|
||||
initialPipeIds?: string[];
|
||||
shouldFetch?: boolean;
|
||||
onFetchComplete?: () => void;
|
||||
loading?: boolean;
|
||||
result?: ValveIsolationResult | null;
|
||||
onLoadingChange?: (loading: boolean) => void;
|
||||
onResultChange?: (result: ValveIsolationResult | null) => void;
|
||||
}
|
||||
|
||||
const ValveIsolation: React.FC<ValveIsolationProps> = ({
|
||||
initialPipeIds,
|
||||
shouldFetch = false,
|
||||
onFetchComplete,
|
||||
loading: externalLoading,
|
||||
result: externalResult,
|
||||
onLoadingChange,
|
||||
onResultChange,
|
||||
}) => {
|
||||
const [internalLoading, setInternalLoading] = useState(false);
|
||||
const [internalResult, setInternalResult] =
|
||||
useState<ValveIsolationResult | null>(null);
|
||||
|
||||
// 使用外部状态或内部状态
|
||||
const loading =
|
||||
externalLoading !== undefined ? externalLoading : internalLoading;
|
||||
const result = externalResult !== undefined ? externalResult : internalResult;
|
||||
const setLoading = onLoadingChange || setInternalLoading;
|
||||
const setResult = onResultChange || setInternalResult;
|
||||
const [highlightLayer, setHighlightLayer] =
|
||||
useState<VectorLayer<VectorSource> | null>(null);
|
||||
const [highlightFeatures, setHighlightFeatures] = useState<Feature[]>([]);
|
||||
const [highlightType, setHighlightType] = useState<
|
||||
"must_close" | "optional" | "affected_node" | "pipe"
|
||||
>("affected_node");
|
||||
const { open } = useNotification();
|
||||
const lastPipeIdsRef = useRef<string>("");
|
||||
const map = useMap();
|
||||
|
||||
const handleLocatePipes = (pipeIds: string[]) => {
|
||||
if (pipeIds.length > 0) {
|
||||
queryFeaturesByIds(pipeIds, "geo_pipes_mat").then((features) => {
|
||||
if (features.length > 0) {
|
||||
// 设置高亮类型为管段
|
||||
setHighlightType("pipe");
|
||||
// 设置高亮要素
|
||||
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 handleLocateNodes = (nodeIds: string[]) => {
|
||||
if (nodeIds.length > 0) {
|
||||
queryFeaturesByIds(nodeIds, "geo_junctions").then((features) => {
|
||||
if (features.length > 0) {
|
||||
// 设置高亮类型为受影响节点
|
||||
setHighlightType("affected_node");
|
||||
// 设置高亮要素
|
||||
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 handleLocateMustCloseValves = (valveIds: string[]) => {
|
||||
if (valveIds.length > 0) {
|
||||
queryFeaturesByIds(valveIds, "geo_valves").then((features) => {
|
||||
if (features.length > 0) {
|
||||
// 设置高亮类型为必关阀门
|
||||
setHighlightType("must_close");
|
||||
// 设置高亮要素
|
||||
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 handleLocateOptionalValves = (valveIds: string[]) => {
|
||||
if (valveIds.length > 0) {
|
||||
queryFeaturesByIds(valveIds, "geo_valves").then((features) => {
|
||||
if (features.length > 0) {
|
||||
// 设置高亮类型为可选阀门
|
||||
setHighlightType("optional");
|
||||
// 设置高亮要素
|
||||
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 fetchAnalysis = useCallback(
|
||||
async (ids: string[]) => {
|
||||
if (!ids || ids.length === 0) {
|
||||
open?.({ type: "error", message: "请提供管段ID" });
|
||||
return;
|
||||
}
|
||||
setLoading(true);
|
||||
setResult(null);
|
||||
try {
|
||||
const response = await axios.get(
|
||||
`${config.BACKEND_URL}/api/v1/valve_isolation_analysis/`,
|
||||
{
|
||||
params: {
|
||||
network: NETWORK_NAME,
|
||||
accident_element: ids,
|
||||
},
|
||||
paramsSerializer: {
|
||||
indexes: null, // 生成格式: accident_element=P1&accident_element=P2
|
||||
},
|
||||
},
|
||||
);
|
||||
setResult(response.data);
|
||||
open?.({ type: "success", message: "分析成功" });
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
open?.({
|
||||
type: "error",
|
||||
message: "分析失败",
|
||||
description: "无法获取关阀分析结果",
|
||||
});
|
||||
} finally {
|
||||
setLoading(false);
|
||||
onFetchComplete?.();
|
||||
}
|
||||
},
|
||||
[open, onFetchComplete],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
// 只有在明确要求获取数据时才调用 API
|
||||
if (shouldFetch && initialPipeIds && initialPipeIds.length > 0) {
|
||||
// 使用排序后的字符串作为唯一标识,避免数组引用变化导致重复调用
|
||||
const pipeIdsKey = [...initialPipeIds].sort().join(",");
|
||||
|
||||
// 只有当 pipeIds 真正改变时才调用 API
|
||||
if (pipeIdsKey !== lastPipeIdsRef.current) {
|
||||
lastPipeIdsRef.current = pipeIdsKey;
|
||||
fetchAnalysis(initialPipeIds);
|
||||
} else {
|
||||
// 如果 pipeIds 相同,直接调用完成回调
|
||||
onFetchComplete?.();
|
||||
}
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [shouldFetch, initialPipeIds]);
|
||||
|
||||
// 初始化高亮图层
|
||||
useEffect(() => {
|
||||
if (!map) return;
|
||||
|
||||
// 动态样式函数,根据 highlightType 返回不同的样式
|
||||
const getHighlightStyle = (feature: FeatureLike) => {
|
||||
if (highlightType === "pipe") {
|
||||
// 管段 - 多层红色线条样式 + 中点图标
|
||||
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;
|
||||
}
|
||||
|
||||
// 阀门和节点的样式
|
||||
let color: string;
|
||||
let strokeColor: string;
|
||||
let radius: number;
|
||||
|
||||
switch (highlightType) {
|
||||
case "must_close":
|
||||
// 必关阀门 - 深红色
|
||||
color = "rgba(211, 47, 47, 0.6)";
|
||||
strokeColor = "rgba(211, 47, 47, 1)";
|
||||
radius = 10;
|
||||
break;
|
||||
case "optional":
|
||||
// 可选阀门 - 橙色
|
||||
color = "rgba(237, 108, 2, 0.6)";
|
||||
strokeColor = "rgba(237, 108, 2, 1)";
|
||||
radius = 10;
|
||||
break;
|
||||
case "affected_node":
|
||||
default:
|
||||
// 受影响节点 - 蓝色
|
||||
color = "rgba(25, 118, 210, 0.6)";
|
||||
strokeColor = "rgba(25, 118, 210, 1)";
|
||||
radius = 8;
|
||||
break;
|
||||
}
|
||||
|
||||
return new Style({
|
||||
image: new CircleStyle({
|
||||
radius: radius,
|
||||
fill: new Fill({
|
||||
color: color,
|
||||
}),
|
||||
stroke: new Stroke({
|
||||
color: strokeColor,
|
||||
width: 3,
|
||||
}),
|
||||
}),
|
||||
});
|
||||
};
|
||||
|
||||
// 创建高亮图层
|
||||
const highlightLayer = new VectorLayer({
|
||||
source: new VectorSource(),
|
||||
style: getHighlightStyle,
|
||||
maxZoom: 24,
|
||||
minZoom: 12,
|
||||
properties: {
|
||||
name: "阀门节点高亮",
|
||||
value: "valve_node_highlight",
|
||||
},
|
||||
});
|
||||
|
||||
map.addLayer(highlightLayer);
|
||||
setHighlightLayer(highlightLayer);
|
||||
|
||||
return () => {
|
||||
map.removeLayer(highlightLayer);
|
||||
};
|
||||
}, [map, highlightType]);
|
||||
|
||||
// 高亮要素的函数
|
||||
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]);
|
||||
|
||||
return (
|
||||
<Box className="flex flex-col h-full">
|
||||
{/* Results Section */}
|
||||
<Box className="flex-1 overflow-auto bg-white rounded border border-gray-200">
|
||||
{loading ? (
|
||||
<Box className="flex flex-col items-center justify-center h-full text-gray-500">
|
||||
<CircularProgress size={40} className="mb-4" />
|
||||
<Typography variant="body2">正在分析...</Typography>
|
||||
</Box>
|
||||
) : result ? (
|
||||
<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">
|
||||
关阀分析结果
|
||||
</Typography>
|
||||
<Chip
|
||||
label={result.isolatable ? "可隔离" : "不可隔离"}
|
||||
size="small"
|
||||
color={result.isolatable ? "success" : "error"}
|
||||
variant="outlined"
|
||||
sx={{
|
||||
fontWeight: 600,
|
||||
fontSize: "0.75rem",
|
||||
height: "24px",
|
||||
}}
|
||||
/>
|
||||
</Box>
|
||||
<Box className="bg-gradient-to-r from-red-50 via-pink-50 to-red-50 rounded-lg p-3 border border-red-200 shadow-sm">
|
||||
<Box className="flex items-center justify-between mb-2">
|
||||
<Box className="flex items-center gap-2">
|
||||
<Box className="w-2 h-2 rounded-full bg-red-600 animate-pulse"></Box>
|
||||
<Typography
|
||||
variant="caption"
|
||||
className="text-red-700 font-semibold uppercase tracking-wide"
|
||||
sx={{ fontSize: "0.7rem" }}
|
||||
>
|
||||
爆管管段
|
||||
</Typography>
|
||||
</Box>
|
||||
{result.accident_elements &&
|
||||
result.accident_elements.length > 0 && (
|
||||
<Tooltip title="定位所有管段">
|
||||
<IconButton
|
||||
size="small"
|
||||
onClick={() =>
|
||||
handleLocatePipes(result.accident_elements!)
|
||||
}
|
||||
sx={{
|
||||
backgroundColor: "rgba(255, 0, 0, 0.1)",
|
||||
"&:hover": {
|
||||
backgroundColor: "rgba(255, 0, 0, 0.2)",
|
||||
},
|
||||
}}
|
||||
>
|
||||
<LocationIcon
|
||||
sx={{ fontSize: "1rem", color: "rgb(220, 38, 38)" }}
|
||||
/>
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
)}
|
||||
</Box>
|
||||
<Box className="flex flex-wrap gap-2">
|
||||
{result.accident_elements?.map(
|
||||
(pipeId: string, idx: number) => (
|
||||
<Chip
|
||||
key={idx}
|
||||
label={pipeId}
|
||||
size="small"
|
||||
onClick={() => handleLocatePipes([pipeId])}
|
||||
sx={{
|
||||
backgroundColor: "rgba(255, 255, 255, 0.9)",
|
||||
border: "1.5px solid rgb(248, 113, 113)",
|
||||
color: "rgb(185, 28, 28)",
|
||||
fontWeight: 600,
|
||||
fontSize: "0.8rem",
|
||||
cursor: "pointer",
|
||||
transition: "all 0.2s",
|
||||
"&:hover": {
|
||||
backgroundColor: "rgb(254, 226, 226)",
|
||||
borderColor: "rgb(220, 38, 38)",
|
||||
transform: "translateY(-1px)",
|
||||
boxShadow: "0 2px 4px rgba(220, 38, 38, 0.2)",
|
||||
},
|
||||
}}
|
||||
/>
|
||||
),
|
||||
)}
|
||||
</Box>
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
{/* 主要信息:三栏卡片布局 */}
|
||||
<Box className="grid grid-cols-3 gap-3 mb-5">
|
||||
{/* 必关阀门卡片 */}
|
||||
<Box className="bg-gradient-to-br from-red-50 to-red-100 rounded-lg p-3 border border-red-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-red-600"></Box>
|
||||
<Typography
|
||||
variant="caption"
|
||||
className="text-red-700 font-semibold uppercase tracking-wide"
|
||||
sx={{ fontSize: "0.7rem" }}
|
||||
>
|
||||
必关阀门
|
||||
</Typography>
|
||||
</Box>
|
||||
<Typography
|
||||
variant="body2"
|
||||
className="font-bold text-red-900"
|
||||
sx={{ fontSize: "0.875rem" }}
|
||||
>
|
||||
{result.must_close_valves?.length || 0} 个
|
||||
</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.optional_valves?.length || 0} 个
|
||||
</Typography>
|
||||
</Box>
|
||||
|
||||
{/* 受影响节点卡片 */}
|
||||
<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"
|
||||
sx={{ fontSize: "0.875rem" }}
|
||||
>
|
||||
{result.affected_nodes?.length || 0} 个
|
||||
</Typography>
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
{/* 必须关闭阀门详细列表 */}
|
||||
{result.must_close_valves &&
|
||||
result.must_close_valves.length > 0 && (
|
||||
<Box className="bg-white rounded-lg p-4 border-2 border-red-200 shadow-sm mb-4">
|
||||
<Box className="flex items-center justify-between mb-3">
|
||||
<Typography
|
||||
variant="body1"
|
||||
className="text-gray-900 font-bold"
|
||||
sx={{ fontSize: "0.95rem" }}
|
||||
>
|
||||
必须关闭阀门
|
||||
</Typography>
|
||||
<Tooltip title="定位所有阀门">
|
||||
<IconButton
|
||||
size="small"
|
||||
onClick={() =>
|
||||
handleLocateMustCloseValves(result.must_close_valves!)
|
||||
}
|
||||
color="error"
|
||||
sx={{
|
||||
backgroundColor: "rgba(211, 47, 47, 0.1)",
|
||||
"&:hover": {
|
||||
backgroundColor: "rgba(211, 47, 47, 0.2)",
|
||||
},
|
||||
}}
|
||||
>
|
||||
<LocationIcon sx={{ fontSize: "1.2rem" }} />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
</Box>
|
||||
<Box className="grid grid-cols-3 gap-2">
|
||||
{result.must_close_valves.map((valveId, idx) => (
|
||||
<Box
|
||||
key={idx}
|
||||
className="bg-gradient-to-r from-red-50 to-white rounded-lg px-3 py-2 border border-red-200 hover:border-red-400 hover:shadow-md transition-all cursor-pointer group"
|
||||
onClick={() => handleLocateMustCloseValves([valveId])}
|
||||
sx={{
|
||||
"&:active": {
|
||||
transform: "scale(0.98)",
|
||||
boxShadow: "0 1px 2px rgba(211, 47, 47, 0.2)",
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Typography
|
||||
variant="body2"
|
||||
className="font-semibold text-red-700 group-hover:text-red-900"
|
||||
>
|
||||
{valveId}
|
||||
</Typography>
|
||||
</Box>
|
||||
))}
|
||||
</Box>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
{/* 可选关闭阀门详细列表 */}
|
||||
{result.optional_valves && result.optional_valves.length > 0 && (
|
||||
<Box className="bg-white rounded-lg p-4 border-2 border-orange-200 shadow-sm mb-4">
|
||||
<Box className="flex items-center justify-between mb-3">
|
||||
<Typography
|
||||
variant="body1"
|
||||
className="text-gray-900 font-bold"
|
||||
sx={{ fontSize: "0.95rem" }}
|
||||
>
|
||||
可选关闭阀门
|
||||
</Typography>
|
||||
<Tooltip title="定位所有阀门">
|
||||
<IconButton
|
||||
size="small"
|
||||
onClick={() =>
|
||||
handleLocateOptionalValves(result.optional_valves!)
|
||||
}
|
||||
color="warning"
|
||||
sx={{
|
||||
backgroundColor: "rgba(237, 108, 2, 0.1)",
|
||||
"&:hover": {
|
||||
backgroundColor: "rgba(237, 108, 2, 0.2)",
|
||||
},
|
||||
}}
|
||||
>
|
||||
<LocationIcon sx={{ fontSize: "1.2rem" }} />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
</Box>
|
||||
<Box className="grid grid-cols-3 gap-2">
|
||||
{result.optional_valves.map((valveId, idx) => (
|
||||
<Box
|
||||
key={idx}
|
||||
className="bg-gradient-to-r from-orange-50 to-white rounded-lg px-3 py-2 border border-orange-200 hover:border-orange-400 hover:shadow-md transition-all cursor-pointer group"
|
||||
onClick={() => handleLocateOptionalValves([valveId])}
|
||||
sx={{
|
||||
"&:active": {
|
||||
transform: "scale(0.98)",
|
||||
boxShadow: "0 1px 2px rgba(237, 108, 2, 0.2)",
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Typography
|
||||
variant="body2"
|
||||
className="font-semibold text-orange-700 group-hover:text-orange-900"
|
||||
>
|
||||
{valveId}
|
||||
</Typography>
|
||||
</Box>
|
||||
))}
|
||||
</Box>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
{/* 受影响节点详细列表 */}
|
||||
{result.affected_nodes && result.affected_nodes.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>
|
||||
<Tooltip title="定位所有节点">
|
||||
<IconButton
|
||||
size="small"
|
||||
onClick={() => handleLocateNodes(result.affected_nodes!)}
|
||||
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 className="grid grid-cols-3 gap-2">
|
||||
{result.affected_nodes.map((nodeId, 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={() => handleLocateNodes([nodeId])}
|
||||
sx={{
|
||||
"&:active": {
|
||||
transform: "scale(0.98)",
|
||||
boxShadow: "0 1px 2px rgba(25, 118, 210, 0.2)",
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Typography
|
||||
variant="body2"
|
||||
className="font-semibold text-blue-700 group-hover:text-blue-900"
|
||||
>
|
||||
{nodeId}
|
||||
</Typography>
|
||||
</Box>
|
||||
))}
|
||||
</Box>
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
) : (
|
||||
<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"
|
||||
/>
|
||||
<path d="M40 25 L40 55" stroke="currentColor" strokeWidth="3" />
|
||||
<rect
|
||||
x="30"
|
||||
y="35"
|
||||
width="20"
|
||||
height="10"
|
||||
fill="currentColor"
|
||||
rx="2"
|
||||
/>
|
||||
<path
|
||||
d="M25 40 L30 40 M50 40 L55 40"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
/>
|
||||
</svg>
|
||||
</Box>
|
||||
<Typography variant="body2">暂无关阀分析结果</Typography>
|
||||
<Typography variant="body2" className="mt-1">
|
||||
请先查看定位结果
|
||||
</Typography>
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
export default ValveIsolation;
|
||||
46
src/components/olmap/BurstPipeAnalysis/types.ts
Normal file
46
src/components/olmap/BurstPipeAnalysis/types.ts
Normal file
@@ -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;
|
||||
}
|
||||
@@ -0,0 +1,396 @@
|
||||
"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, Icon } 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 [schemeName, setSchemeName] = useState<string>(
|
||||
"WQ_" + new Date().getTime(),
|
||||
);
|
||||
const [startTime, setStartTime] = useState<Dayjs | null>(dayjs(new Date()));
|
||||
const [sourceNode, setSourceNode] = useState<string>("");
|
||||
const [concentration, setConcentration] = useState<number>(100);
|
||||
const [duration, setDuration] = useState<number>(3600);
|
||||
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 &&
|
||||
schemeName.trim() !== ""
|
||||
);
|
||||
}, [network, startTime, sourceNode, concentration, duration, schemeName]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!map) return;
|
||||
|
||||
const themeColor = "rgba(3, 168, 107"; // #03a86b
|
||||
|
||||
const sourceStyle = [
|
||||
// 外层扩散光圈
|
||||
new Style({
|
||||
image: new CircleStyle({
|
||||
radius: 12,
|
||||
fill: new Fill({ color: `${themeColor}, 0.2)` }),
|
||||
}),
|
||||
}),
|
||||
// 中层扩散背景
|
||||
new Style({
|
||||
image: new CircleStyle({
|
||||
radius: 8,
|
||||
stroke: new Stroke({ color: `${themeColor}, 0.5)`, width: 2 }),
|
||||
fill: new Fill({ color: `${themeColor}, 0.3)` }),
|
||||
}),
|
||||
}),
|
||||
// 上层图标
|
||||
new Style({
|
||||
image: new Icon({
|
||||
src: "/icons/contaminant_source.svg",
|
||||
scale: 0.2,
|
||||
anchor: [0.5, 1],
|
||||
}),
|
||||
}),
|
||||
];
|
||||
|
||||
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,
|
||||
});
|
||||
// 格式化开始时间,去除秒部分
|
||||
const start_time = startTime
|
||||
? startTime.format("YYYY-MM-DDTHH:mm:00Z")
|
||||
: "";
|
||||
try {
|
||||
const params = {
|
||||
network,
|
||||
start_time: start_time,
|
||||
source: sourceNode,
|
||||
concentration,
|
||||
duration,
|
||||
pattern: pattern || undefined,
|
||||
scheme_name: schemeName,
|
||||
};
|
||||
|
||||
await axios.get(`${config.BACKEND_URL}/api/v1/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={schemeName}
|
||||
onChange={(e) => setSchemeName(e.target.value)}
|
||||
placeholder="输入方案名称"
|
||||
/>
|
||||
</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;
|
||||
30
src/components/olmap/ContaminantSimulation/ResultsPanel.tsx
Normal file
30
src/components/olmap/ContaminantSimulation/ResultsPanel.tsx
Normal 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;
|
||||
631
src/components/olmap/ContaminantSimulation/SchemeQuery.tsx
Normal file
631
src/components/olmap/ContaminantSimulation/SchemeQuery.tsx
Normal file
@@ -0,0 +1,631 @@
|
||||
"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 { GeoJSON } from "ol/format";
|
||||
import VectorLayer from "ol/layer/Vector";
|
||||
import VectorSource from "ol/source/Vector";
|
||||
import { Style, Icon, Circle, Fill, Stroke } from "ol/style";
|
||||
import Feature from "ol/Feature";
|
||||
import { bbox, featureCollection } from "@turf/turf";
|
||||
import Timeline from "@app/OlMap/Controls/Timeline";
|
||||
import { ContaminantSchemaItem, ContaminantSchemeRecord } from "./types";
|
||||
|
||||
interface SchemeQueryProps {
|
||||
schemes?: ContaminantSchemeRecord[];
|
||||
onSchemesChange?: (schemes: ContaminantSchemeRecord[]) => void;
|
||||
onViewResults?: () => void;
|
||||
network?: string;
|
||||
}
|
||||
|
||||
const SCHEME_TYPE = "contaminant_analysis";
|
||||
|
||||
const SchemeQuery: React.FC<SchemeQueryProps> = ({
|
||||
schemes: externalSchemes,
|
||||
onSchemesChange,
|
||||
onViewResults,
|
||||
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<
|
||||
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 } = data || {};
|
||||
|
||||
const schemes =
|
||||
externalSchemes !== undefined ? externalSchemes : internalSchemes;
|
||||
const setSchemes = onSchemesChange || setInternalSchemes;
|
||||
|
||||
useEffect(() => {
|
||||
if (!map) return;
|
||||
const target = map.getTargetElement();
|
||||
if (target) {
|
||||
setMapContainer(target);
|
||||
}
|
||||
}, [map]);
|
||||
|
||||
// 初始化高亮图层
|
||||
useEffect(() => {
|
||||
if (!map) return;
|
||||
|
||||
const themeColor = "rgba(3, 168, 107"; // #03a86b
|
||||
|
||||
const sourceStyle = [
|
||||
// 外层扩散光圈
|
||||
new Style({
|
||||
image: new Circle({
|
||||
radius: 12,
|
||||
fill: new Fill({
|
||||
color: `${themeColor}, 0.2)`,
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
// 中层扩散背景
|
||||
new Style({
|
||||
image: new Circle({
|
||||
radius: 8,
|
||||
stroke: new Stroke({
|
||||
color: `${themeColor}, 0.5)`,
|
||||
width: 2,
|
||||
}),
|
||||
fill: new Fill({
|
||||
color: `${themeColor}, 0.3)`,
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
// 上层图标
|
||||
new Style({
|
||||
image: new Icon({
|
||||
src: "/icons/contaminant_source.svg",
|
||||
scale: 0.2,
|
||||
anchor: [0.5, 1],
|
||||
}),
|
||||
}),
|
||||
];
|
||||
|
||||
const highlightLayer = new VectorLayer({
|
||||
source: new VectorSource(),
|
||||
style: sourceStyle,
|
||||
maxZoom: 24,
|
||||
minZoom: 12,
|
||||
properties: {
|
||||
name: "污染源高亮",
|
||||
value: "contaminant_source_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 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}/api/v1/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 = (sourceIds: string[]) => {
|
||||
if (sourceIds.length > 0) {
|
||||
queryFeaturesByIds(sourceIds, "geo_junctions_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?.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);
|
||||
if (scheme.schemeDetail?.source) {
|
||||
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 === "contaminant_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={() =>
|
||||
scheme.schemeDetail?.source &&
|
||||
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={() =>
|
||||
scheme.schemeDetail?.source &&
|
||||
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;
|
||||
26
src/components/olmap/ContaminantSimulation/types.ts
Normal file
26
src/components/olmap/ContaminantSimulation/types.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
export interface ContaminantSchemeDetail {
|
||||
source: string;
|
||||
concentration: number;
|
||||
duration: number;
|
||||
pattern?: string | null;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -38,8 +38,6 @@ import {
|
||||
RISK_BREAKS,
|
||||
} from "./types";
|
||||
|
||||
const backendUrl = config.BACKEND_URL;
|
||||
|
||||
// 辅助函数:将日期向下取整到最近的15分钟
|
||||
const getRoundedDate = (date: Date): Date => {
|
||||
const minutes = date.getHours() * 60 + date.getMinutes();
|
||||
@@ -49,7 +47,7 @@ const getRoundedDate = (date: Date): Date => {
|
||||
Math.floor(roundedMinutes / 60),
|
||||
roundedMinutes % 60,
|
||||
0,
|
||||
0
|
||||
0,
|
||||
);
|
||||
return roundedDate;
|
||||
};
|
||||
@@ -124,7 +122,7 @@ const Timeline: React.FC<TimelineProps> = ({
|
||||
setCurrentYear(value);
|
||||
}, 500); // 500ms 防抖延迟
|
||||
},
|
||||
[minTime, maxTime]
|
||||
[minTime, maxTime],
|
||||
);
|
||||
|
||||
// 播放控制
|
||||
@@ -152,7 +150,6 @@ const Timeline: React.FC<TimelineProps> = ({
|
||||
|
||||
const handleStop = useCallback(() => {
|
||||
setIsPlaying(false);
|
||||
setSelectedDateTime(getRoundedDate(new Date()));
|
||||
if (intervalRef.current) {
|
||||
clearInterval(intervalRef.current);
|
||||
intervalRef.current = null;
|
||||
@@ -215,7 +212,7 @@ const Timeline: React.FC<TimelineProps> = ({
|
||||
}, newInterval);
|
||||
}
|
||||
},
|
||||
[isPlaying]
|
||||
[isPlaying],
|
||||
);
|
||||
|
||||
// 组件加载时设置初始时间为当前时间的最近15分钟
|
||||
@@ -245,7 +242,7 @@ const Timeline: React.FC<TimelineProps> = ({
|
||||
const safeIndex = Math.max(0, Math.min(index, y.length - 1));
|
||||
return y[safeIndex];
|
||||
},
|
||||
[]
|
||||
[],
|
||||
);
|
||||
|
||||
// 更新管道图层中的 healthRisk 属性
|
||||
@@ -270,7 +267,7 @@ const Timeline: React.FC<TimelineProps> = ({
|
||||
});
|
||||
});
|
||||
},
|
||||
[pipeLayer]
|
||||
[pipeLayer],
|
||||
);
|
||||
|
||||
// 监听瓦片加载,为新瓦片设置 healthRisk 属性
|
||||
@@ -313,7 +310,7 @@ const Timeline: React.FC<TimelineProps> = ({
|
||||
predictionResults.forEach((result) => {
|
||||
const probability = getSurvivalProbabilityAtYear(
|
||||
result.survival_function,
|
||||
currentYear - 4 // 使用索引 (0-based)
|
||||
currentYear - 4, // 使用索引 (0-based)
|
||||
);
|
||||
pipeHealthData.set(result.link_id, probability);
|
||||
});
|
||||
@@ -346,11 +343,11 @@ const Timeline: React.FC<TimelineProps> = ({
|
||||
colorCases.push(["<=", ["get", "healthRisk"], breakValue], colorStr);
|
||||
widthCases.push(["<=", ["get", "healthRisk"], breakValue], width);
|
||||
});
|
||||
console.log(
|
||||
`应用健康风险样式,年份: ${currentYear}, 分段: ${breaks.length}`
|
||||
);
|
||||
console.log("颜色表达式:", colorCases);
|
||||
console.log("宽度表达式:", widthCases);
|
||||
// console.log(
|
||||
// `应用健康风险样式,年份: ${currentYear}, 分段: ${breaks.length}`,
|
||||
// );
|
||||
// console.log("颜色表达式:", colorCases);
|
||||
// console.log("宽度表达式:", widthCases);
|
||||
// 应用样式到图层
|
||||
pipeLayer.setStyle({
|
||||
"stroke-color": ["case", ...colorCases, "rgba(128, 128, 128, 1)"],
|
||||
@@ -371,7 +368,7 @@ const Timeline: React.FC<TimelineProps> = ({
|
||||
const layers = map.getLayers().getArray();
|
||||
const pipesLayer = layers.find(
|
||||
(layer) =>
|
||||
layer instanceof WebGLVectorTileLayer && layer.get("value") === "pipes"
|
||||
layer instanceof WebGLVectorTileLayer && layer.get("value") === "pipes",
|
||||
) as WebGLVectorTileLayer | undefined;
|
||||
|
||||
if (pipesLayer) {
|
||||
@@ -426,7 +423,7 @@ const Timeline: React.FC<TimelineProps> = ({
|
||||
});
|
||||
try {
|
||||
const response = await fetch(
|
||||
`${backendUrl}/timescaledb/composite/pipeline-health-prediction?query_time=${query_time}&network_name=${NETWORK_NAME}`
|
||||
`${config.BACKEND_URL}/api/v1/composite/pipeline-health-prediction?query_time=${query_time}&network_name=${NETWORK_NAME}`,
|
||||
);
|
||||
|
||||
if (response.ok) {
|
||||
@@ -437,16 +434,19 @@ const Timeline: React.FC<TimelineProps> = ({
|
||||
message: `模拟预测完成,获取到 ${results.length} 条管道数据`,
|
||||
});
|
||||
} else {
|
||||
// 读取后端 HTTPException 返回的 detail 信息
|
||||
const errorData = await response.json().catch(() => ({}));
|
||||
const errorMessage = errorData.detail || "模拟预测失败";
|
||||
open?.({
|
||||
type: "error",
|
||||
message: "模拟预测失败",
|
||||
message: errorMessage,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
} catch (error: any) {
|
||||
console.error("Simulation prediction failed:", error);
|
||||
open?.({
|
||||
type: "error",
|
||||
message: "模拟预测时发生错误",
|
||||
message: `模拟预测时发生错误: ${error.message || "未知错误"}`,
|
||||
});
|
||||
} finally {
|
||||
setIsPredicting(false);
|
||||
|
||||
@@ -94,7 +94,7 @@ const OptimizationParameters: React.FC = () => {
|
||||
try {
|
||||
// 发送优化请求
|
||||
const response = await axios.post(
|
||||
`${config.BACKEND_URL}/sensorplacementscheme/create`,
|
||||
`${config.BACKEND_URL}/api/v1/sensorplacementscheme/create`,
|
||||
null,
|
||||
{
|
||||
params: {
|
||||
|
||||
@@ -141,6 +141,7 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
|
||||
}
|
||||
});
|
||||
}, [highlightFeatures]);
|
||||
|
||||
// 查询方案
|
||||
const handleQuery = async () => {
|
||||
if (!queryAll && !queryDate) return;
|
||||
@@ -148,7 +149,7 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
|
||||
setLoading(true);
|
||||
try {
|
||||
const response = await axios.get(
|
||||
`${config.BACKEND_URL}/getallsensorplacements/?network=${network}`
|
||||
`${config.BACKEND_URL}/api/v1/getallsensorplacements/?network=${network}`,
|
||||
);
|
||||
|
||||
let filteredResults = response.data;
|
||||
@@ -171,7 +172,7 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
|
||||
user: item.username,
|
||||
create_time: item.create_time,
|
||||
sensorLocation: item.sensor_location,
|
||||
}))
|
||||
})),
|
||||
);
|
||||
|
||||
if (filteredResults.length === 0) {
|
||||
@@ -206,14 +207,14 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
|
||||
}
|
||||
|
||||
if (sensorIds.length > 0) {
|
||||
queryFeaturesByIds(sensorIds).then((features) => {
|
||||
queryFeaturesByIds(sensorIds, "geo_junctions_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)
|
||||
geojsonFormat.writeFeatureObject(feature),
|
||||
);
|
||||
|
||||
const extent = bbox(featureCollection(geojsonFeatures as any));
|
||||
@@ -376,7 +377,7 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
|
||||
size="small"
|
||||
onClick={() =>
|
||||
setExpandedId(
|
||||
expandedId === scheme.id ? null : scheme.id
|
||||
expandedId === scheme.id ? null : scheme.id,
|
||||
)
|
||||
}
|
||||
color="primary"
|
||||
@@ -385,7 +386,7 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
|
||||
<InfoIcon fontSize="small" />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
<Tooltip title="定位">
|
||||
{/* <Tooltip title="定位">
|
||||
<IconButton
|
||||
size="small"
|
||||
onClick={() => onLocate?.(scheme.id)}
|
||||
@@ -394,7 +395,7 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
|
||||
>
|
||||
<LocationIcon fontSize="small" />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
</Tooltip> */}
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
@@ -466,7 +467,7 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
|
||||
className="font-medium text-gray-900"
|
||||
>
|
||||
{moment(scheme.create_time).format(
|
||||
"YYYY-MM-DD HH:mm"
|
||||
"YYYY-MM-DD HH:mm",
|
||||
)}
|
||||
</Typography>
|
||||
</Box>
|
||||
@@ -500,7 +501,7 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
|
||||
>
|
||||
{sensorId}
|
||||
</Link>
|
||||
)
|
||||
),
|
||||
)}
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
@@ -78,7 +78,7 @@ type LoadingState = "idle" | "loading" | "success" | "error";
|
||||
*/
|
||||
const fetchFromBackend = async (
|
||||
deviceIds: string[],
|
||||
range: { from: Date; to: Date }
|
||||
range: { from: Date; to: Date },
|
||||
): Promise<TimeSeriesPoint[]> => {
|
||||
if (deviceIds.length === 0) {
|
||||
return [];
|
||||
@@ -88,12 +88,11 @@ const fetchFromBackend = async (
|
||||
const start_time = dayjs(range.from).toISOString();
|
||||
const end_time = dayjs(range.to).toISOString();
|
||||
// 清洗数据接口
|
||||
const cleaningDataUrl = `${config.BACKEND_URL}/timescaledb/scada/by-ids-field-time-range?device_ids=${device_ids}&field=cleaned_value&start_time=${start_time}&end_time=${end_time}`;
|
||||
const cleaningDataUrl = `${config.BACKEND_URL}/api/v1/scada/by-ids-field-time-range?device_ids=${device_ids}&field=cleaned_value&start_time=${start_time}&end_time=${end_time}`;
|
||||
// 原始数据
|
||||
const rawDataUrl = `${config.BACKEND_URL}/timescaledb/scada/by-ids-field-time-range?device_ids=${device_ids}&field=monitored_value&start_time=${start_time}&end_time=${end_time}`;
|
||||
const rawDataUrl = `${config.BACKEND_URL}/api/v1/scada/by-ids-field-time-range?device_ids=${device_ids}&field=monitored_value&start_time=${start_time}&end_time=${end_time}`;
|
||||
// 模拟数据接口
|
||||
const simulationDataUrl = `${config.BACKEND_URL}/timescaledb/composite/scada-simulation?device_ids=${device_ids}&start_time=${start_time}&end_time=${end_time}`;
|
||||
|
||||
const simulationDataUrl = `${config.BACKEND_URL}/api/v1/composite/scada-simulation?device_ids=${device_ids}&start_time=${start_time}&end_time=${end_time}`;
|
||||
try {
|
||||
// 优先查询清洗数据和模拟数据
|
||||
const [cleaningRes, simulationRes] = await Promise.all([
|
||||
@@ -115,7 +114,7 @@ const fetchFromBackend = async (
|
||||
simulationData,
|
||||
deviceIds,
|
||||
"clean",
|
||||
"sim"
|
||||
"sim",
|
||||
);
|
||||
} else {
|
||||
// 如果清洗数据没有数据,查询原始数据,返回模拟和原始数据
|
||||
@@ -128,7 +127,7 @@ const fetchFromBackend = async (
|
||||
rawData,
|
||||
deviceIds,
|
||||
"sim",
|
||||
"raw"
|
||||
"raw",
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
@@ -143,7 +142,7 @@ const fetchFromBackend = async (
|
||||
*/
|
||||
const transformBackendData = (
|
||||
backendData: any,
|
||||
deviceIds: string[]
|
||||
deviceIds: string[],
|
||||
): TimeSeriesPoint[] => {
|
||||
// 处理后端返回的对象格式: { deviceId: [{time: "...", value: ...}] }
|
||||
if (backendData && !Array.isArray(backendData)) {
|
||||
@@ -176,12 +175,12 @@ const transformBackendData = (
|
||||
([timestamp, values]) => ({
|
||||
timestamp,
|
||||
values,
|
||||
})
|
||||
}),
|
||||
);
|
||||
|
||||
result.sort(
|
||||
(a, b) =>
|
||||
new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime()
|
||||
new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime(),
|
||||
);
|
||||
|
||||
return result;
|
||||
@@ -200,7 +199,7 @@ const mergeTimeSeriesData = (
|
||||
data2: TimeSeriesPoint[],
|
||||
deviceIds: string[],
|
||||
suffix1: string,
|
||||
suffix2: string
|
||||
suffix2: string,
|
||||
): TimeSeriesPoint[] => {
|
||||
const timeMap = new Map<string, Record<string, number | null>>();
|
||||
|
||||
@@ -228,7 +227,7 @@ const mergeTimeSeriesData = (
|
||||
}));
|
||||
|
||||
result.sort(
|
||||
(a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime()
|
||||
(a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime(),
|
||||
);
|
||||
|
||||
return result;
|
||||
@@ -239,7 +238,7 @@ const formatTimestamp = (timestamp: string) =>
|
||||
|
||||
const ensureValidRange = (
|
||||
from: Dayjs,
|
||||
to: Dayjs
|
||||
to: Dayjs,
|
||||
): { from: Dayjs; to: Dayjs } => {
|
||||
if (from.isAfter(to)) {
|
||||
return { from: to, to: from };
|
||||
@@ -251,7 +250,7 @@ const buildDataset = (
|
||||
points: TimeSeriesPoint[],
|
||||
deviceIds: string[],
|
||||
fractionDigits: number,
|
||||
showCleaning: boolean
|
||||
showCleaning: boolean,
|
||||
) => {
|
||||
return points.map((point) => {
|
||||
const entry: Record<string, any> = {
|
||||
@@ -325,19 +324,18 @@ const SCADADataPanel: React.FC<SCADADataPanelProps> = ({
|
||||
|
||||
return async (
|
||||
deviceIds: string[],
|
||||
range: { from: Date; to: Date }
|
||||
range: { from: Date; to: Date },
|
||||
): Promise<TimeSeriesPoint[]> => {
|
||||
const device_ids = deviceIds.join(",");
|
||||
const start_time = dayjs(range.from).toISOString();
|
||||
const end_time = dayjs(range.to).toISOString();
|
||||
|
||||
// 清洗数据接口
|
||||
const cleaningDataUrl = `${config.BACKEND_URL}/timescaledb/scada/by-ids-field-time-range?device_ids=${device_ids}&field=cleaned_value&start_time=${start_time}&end_time=${end_time}`;
|
||||
const cleaningDataUrl = `${config.BACKEND_URL}/api/v1/scada/by-ids-field-time-range?device_ids=${device_ids}&field=cleaned_value&start_time=${start_time}&end_time=${end_time}`;
|
||||
// 原始数据
|
||||
const rawDataUrl = `${config.BACKEND_URL}/timescaledb/scada/by-ids-field-time-range?device_ids=${device_ids}&field=monitored_value&start_time=${start_time}&end_time=${end_time}`;
|
||||
const rawDataUrl = `${config.BACKEND_URL}/api/v1/scada/by-ids-field-time-range?device_ids=${device_ids}&field=monitored_value&start_time=${start_time}&end_time=${end_time}`;
|
||||
// 模拟数据接口
|
||||
const simulationDataUrl = `${config.BACKEND_URL}/timescaledb/composite/scada-simulation?device_ids=${device_ids}&start_time=${start_time}&end_time=${end_time}`;
|
||||
|
||||
const simulationDataUrl = `${config.BACKEND_URL}/api/v1/composite/scada-simulation?device_ids=${device_ids}&start_time=${start_time}&end_time=${end_time}`;
|
||||
try {
|
||||
const [cleanRes, rawRes, simRes] = await Promise.all([
|
||||
fetch(cleaningDataUrl)
|
||||
@@ -381,12 +379,12 @@ const SCADADataPanel: React.FC<SCADADataPanelProps> = ({
|
||||
([timestamp, values]) => ({
|
||||
timestamp,
|
||||
values,
|
||||
})
|
||||
}),
|
||||
);
|
||||
|
||||
result.sort(
|
||||
(a, b) =>
|
||||
new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime()
|
||||
new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime(),
|
||||
);
|
||||
|
||||
return result;
|
||||
@@ -420,7 +418,7 @@ const SCADADataPanel: React.FC<SCADADataPanelProps> = ({
|
||||
|
||||
const dataset = useMemo(
|
||||
() => buildDataset(timeSeries, deviceIds, fractionDigits, showCleaning),
|
||||
[timeSeries, deviceIds, fractionDigits, showCleaning]
|
||||
[timeSeries, deviceIds, fractionDigits, showCleaning],
|
||||
);
|
||||
|
||||
const handleFetch = useCallback(
|
||||
@@ -447,7 +445,7 @@ const SCADADataPanel: React.FC<SCADADataPanelProps> = ({
|
||||
setLoadingState("error");
|
||||
}
|
||||
},
|
||||
[deviceIds, customFetcher, hasDevices, normalizedRange]
|
||||
[deviceIds, customFetcher, hasDevices, normalizedRange],
|
||||
);
|
||||
|
||||
// 处理数据清洗
|
||||
@@ -479,9 +477,9 @@ const SCADADataPanel: React.FC<SCADADataPanelProps> = ({
|
||||
const response = await axios.post(
|
||||
`${
|
||||
config.BACKEND_URL
|
||||
}/timescaledb/composite/clean-scada?device_ids=${deviceIds.join(
|
||||
","
|
||||
)}&start_time=${startTime}&end_time=${endTime}`
|
||||
}/api/v1/composite/clean-scada?device_ids=${deviceIds.join(
|
||||
",",
|
||||
)}&start_time=${startTime}&end_time=${endTime}`,
|
||||
);
|
||||
|
||||
console.log("[SCADADataPanel] 清洗响应:", response.data);
|
||||
@@ -627,7 +625,7 @@ const SCADADataPanel: React.FC<SCADADataPanelProps> = ({
|
||||
const fieldKey = `${id}_${key}`;
|
||||
// 检查是否有该字段的数据
|
||||
const hasData = dataset.some(
|
||||
(item) => item[fieldKey] !== null && item[fieldKey] !== undefined
|
||||
(item) => item[fieldKey] !== null && item[fieldKey] !== undefined,
|
||||
);
|
||||
|
||||
if (hasData) {
|
||||
@@ -663,7 +661,7 @@ const SCADADataPanel: React.FC<SCADADataPanelProps> = ({
|
||||
}-${index}`,
|
||||
...item,
|
||||
})),
|
||||
[dataset]
|
||||
[dataset],
|
||||
);
|
||||
|
||||
const renderEmpty = () => {
|
||||
@@ -760,7 +758,7 @@ const SCADADataPanel: React.FC<SCADADataPanelProps> = ({
|
||||
["raw", "clean", "sim"].forEach((suffix, sIndex) => {
|
||||
const key = `${id}_${suffix}`;
|
||||
const hasData = dataset.some(
|
||||
(item) => item[key] !== null && item[key] !== undefined
|
||||
(item) => item[key] !== null && item[key] !== undefined,
|
||||
);
|
||||
if (hasData) {
|
||||
series.push({
|
||||
|
||||
@@ -124,7 +124,7 @@ const SCADADeviceList: React.FC<SCADADeviceListProps> = ({
|
||||
const [isSelecting, setIsSelecting] = useState<boolean>(false);
|
||||
const [internalSelection, setInternalSelection] = useState<string[]>([]);
|
||||
const [pendingSelection, setPendingSelection] = useState<string[] | null>(
|
||||
null
|
||||
null,
|
||||
);
|
||||
const [internalDevices, setInternalDevices] = useState<SCADADevice[]>([]);
|
||||
const [loading, setLoading] = useState<boolean>(true);
|
||||
@@ -142,7 +142,7 @@ const SCADADeviceList: React.FC<SCADADeviceListProps> = ({
|
||||
// 清洗对话框状态
|
||||
const [cleanDialogOpen, setCleanDialogOpen] = useState<boolean>(false);
|
||||
const [cleanStartTime, setCleanStartTime] = useState<Dayjs>(() =>
|
||||
dayjs().subtract(1, "week")
|
||||
dayjs().subtract(1, "week"),
|
||||
);
|
||||
const [cleanEndTime, setCleanEndTime] = useState<Dayjs>(() => dayjs());
|
||||
const [timeRangeError, setTimeRangeError] = useState<string>("");
|
||||
@@ -199,7 +199,7 @@ const SCADADeviceList: React.FC<SCADADeviceListProps> = ({
|
||||
status: STATUS_OPTIONS[Math.floor(Math.random() * 4)],
|
||||
coordinates: (feature.getGeometry() as Point)?.getCoordinates() as [
|
||||
number,
|
||||
number
|
||||
number,
|
||||
],
|
||||
properties: feature.getProperties(),
|
||||
}));
|
||||
@@ -218,7 +218,7 @@ const SCADADeviceList: React.FC<SCADADeviceListProps> = ({
|
||||
// 获取设备类型列表
|
||||
const deviceTypes = useMemo(() => {
|
||||
const types = Array.from(
|
||||
new Set(effectiveDevices.map((device) => device.type))
|
||||
new Set(effectiveDevices.map((device) => device.type)),
|
||||
);
|
||||
return types.sort();
|
||||
}, [effectiveDevices]);
|
||||
@@ -406,7 +406,7 @@ const SCADADeviceList: React.FC<SCADADeviceListProps> = ({
|
||||
color: `rgba(255, 255, 0, ${(opacity * 0.3).toFixed(3)})`,
|
||||
}),
|
||||
}),
|
||||
})
|
||||
}),
|
||||
);
|
||||
vectorContext.drawGeometry(flashGeom);
|
||||
|
||||
@@ -423,7 +423,7 @@ const SCADADeviceList: React.FC<SCADADeviceListProps> = ({
|
||||
width: 2,
|
||||
}),
|
||||
}),
|
||||
})
|
||||
}),
|
||||
);
|
||||
vectorContext.drawGeometry(flashGeom);
|
||||
|
||||
@@ -436,7 +436,7 @@ const SCADADeviceList: React.FC<SCADADeviceListProps> = ({
|
||||
color: `rgba(255, 255, 255, ${opacity.toFixed(3)})`,
|
||||
}),
|
||||
}),
|
||||
})
|
||||
}),
|
||||
);
|
||||
vectorContext.drawGeometry(flashGeom);
|
||||
|
||||
@@ -519,7 +519,7 @@ const SCADADeviceList: React.FC<SCADADeviceListProps> = ({
|
||||
// 更新高亮要素
|
||||
setHighlightFeatures((prev) => {
|
||||
const existingIndex = prev.findIndex(
|
||||
(f) => f.getProperties().id === featureId
|
||||
(f) => f.getProperties().id === featureId,
|
||||
);
|
||||
if (existingIndex !== -1) {
|
||||
// 如果已存在,移除
|
||||
@@ -530,7 +530,7 @@ const SCADADeviceList: React.FC<SCADADeviceListProps> = ({
|
||||
}
|
||||
});
|
||||
},
|
||||
[map, effectiveDevices, multiSelect, open]
|
||||
[map, effectiveDevices, multiSelect, open],
|
||||
);
|
||||
|
||||
// 处理清洗对话框关闭
|
||||
@@ -561,7 +561,7 @@ const SCADADeviceList: React.FC<SCADADeviceListProps> = ({
|
||||
setTimeRangeError(error);
|
||||
}
|
||||
},
|
||||
[cleanEndTime, validateTimeRange]
|
||||
[cleanEndTime, validateTimeRange],
|
||||
);
|
||||
|
||||
// 处理结束时间变化
|
||||
@@ -574,7 +574,7 @@ const SCADADeviceList: React.FC<SCADADeviceListProps> = ({
|
||||
setTimeRangeError(error);
|
||||
}
|
||||
},
|
||||
[cleanStartTime, validateTimeRange]
|
||||
[cleanStartTime, validateTimeRange],
|
||||
);
|
||||
|
||||
// 确认清洗
|
||||
@@ -608,7 +608,7 @@ const SCADADeviceList: React.FC<SCADADeviceListProps> = ({
|
||||
open?.({
|
||||
type: "progress",
|
||||
message: "正在清洗数据,请稍候...",
|
||||
undoableTimeout: 3000,
|
||||
undoableTimeout: 3,
|
||||
});
|
||||
|
||||
try {
|
||||
@@ -617,7 +617,7 @@ const SCADADeviceList: React.FC<SCADADeviceListProps> = ({
|
||||
|
||||
// 调用后端清洗接口
|
||||
const response = await axios.post(
|
||||
`${config.BACKEND_URL}/timescaledb/composite/clean-scada?device_ids=all&start_time=${startTime}&end_time=${endTime}`
|
||||
`${config.BACKEND_URL}/api/v1/composite/clean-scada?device_ids=all&start_time=${startTime}&end_time=${endTime}`,
|
||||
);
|
||||
|
||||
// 处理成功响应
|
||||
@@ -1103,7 +1103,7 @@ const SCADADeviceList: React.FC<SCADADeviceListProps> = ({
|
||||
variant="caption"
|
||||
sx={{
|
||||
color: `${getStatusColor(
|
||||
device.status.value
|
||||
device.status.value,
|
||||
)}.main`,
|
||||
fontWeight: "bold",
|
||||
fontSize: 16,
|
||||
@@ -1134,7 +1134,7 @@ const SCADADeviceList: React.FC<SCADADeviceListProps> = ({
|
||||
/>
|
||||
<Chip
|
||||
label={`可靠度: ${getReliability(
|
||||
device.reliability
|
||||
device.reliability,
|
||||
)}`}
|
||||
size="small"
|
||||
variant="outlined"
|
||||
@@ -1156,7 +1156,7 @@ const SCADADeviceList: React.FC<SCADADeviceListProps> = ({
|
||||
>
|
||||
传输频率:{" "}
|
||||
{getTransmissionFrequency(
|
||||
device.transmission_frequency
|
||||
device.transmission_frequency,
|
||||
)}{" "}
|
||||
分钟
|
||||
</Typography>
|
||||
|
||||
@@ -23,7 +23,7 @@ export const config = {
|
||||
},
|
||||
MAP_AVAILABLE_LAYERS: process.env.NEXT_PUBLIC_MAP_AVAILABLE_LAYERS
|
||||
? process.env.NEXT_PUBLIC_MAP_AVAILABLE_LAYERS.split(",").map((item) =>
|
||||
item.trim().toLowerCase()
|
||||
item.trim().toLowerCase(),
|
||||
)
|
||||
: ["junctions", "pipes", "valves", "reservoirs", "pumps", "tanks", "scada"],
|
||||
};
|
||||
|
||||
@@ -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);
|
||||
|
||||
21
src/utils/parseColor.test.js
Normal file
21
src/utils/parseColor.test.js
Normal file
@@ -0,0 +1,21 @@
|
||||
const { parseColor } = require('./parseColor');
|
||||
|
||||
describe('parseColor', () => {
|
||||
it('should parse hex color', () => {
|
||||
expect(parseColor('#FF0000')).toEqual({ r: 255, g: 0, b: 0 });
|
||||
expect(parseColor('00FF00')).toEqual({ r: 0, g: 255, b: 0 });
|
||||
});
|
||||
|
||||
it('should parse rgb color', () => {
|
||||
expect(parseColor('rgb(0, 0, 255)')).toEqual({ r: 0, g: 0, b: 255, a: 1 });
|
||||
});
|
||||
|
||||
it('should parse rgba color', () => {
|
||||
expect(parseColor('rgba(0, 0, 255, 0.5)')).toEqual({ r: 0, g: 0, b: 255, a: 0.5 });
|
||||
});
|
||||
|
||||
it('should default alpha to 1 if not provided in rgba-like pattern', () => {
|
||||
// The regex supports optional alpha
|
||||
expect(parseColor('rgba(0, 0, 255)')).toEqual({ r: 0, g: 0, b: 255, a: 1 });
|
||||
});
|
||||
});
|
||||
@@ -23,11 +23,38 @@
|
||||
}
|
||||
],
|
||||
"paths": {
|
||||
"@*": [
|
||||
"./src/*"
|
||||
],
|
||||
"@pages/*": [
|
||||
"./pages/*"
|
||||
],
|
||||
"@app/*": [
|
||||
"./src/app/*"
|
||||
],
|
||||
"@assets/*": [
|
||||
"./src/assets/*"
|
||||
],
|
||||
"@components/*": [
|
||||
"./src/components/*"
|
||||
],
|
||||
"@config/*": [
|
||||
"./src/config/*"
|
||||
],
|
||||
"@contexts/*": [
|
||||
"./src/contexts/*"
|
||||
],
|
||||
"@interfaces/*": [
|
||||
"./src/interfaces/*"
|
||||
],
|
||||
"@libs/*": [
|
||||
"./src/libs/*"
|
||||
],
|
||||
"@providers/*": [
|
||||
"./src/providers/*"
|
||||
],
|
||||
"@utils/*": [
|
||||
"./src/utils/*"
|
||||
],
|
||||
"@/*": [
|
||||
"./src/*"
|
||||
]
|
||||
},
|
||||
"incremental": true
|
||||
|
||||
Reference in New Issue
Block a user