实现 SCADA 设备列表数据对接;监测点优化,实现传感器定位;爆管分析,属性面板新增计算属性的获取;更新部分图标;爆管分析定位,更改时间轴样式。

This commit is contained in:
JIANG
2025-10-29 16:39:23 +08:00
parent 86e7349c85
commit a5954624a0
22 changed files with 474 additions and 170 deletions

View File

@@ -110,7 +110,7 @@ const AnalysisParameters: React.FC = () => {
new Style({
geometry: new Point(midPointMercator),
image: new Icon({
src: "/icons/burst_pipe_icon.svg",
src: "/icons/burst_pipe.svg",
scale: 0.2,
anchor: [0.5, 1],
}),

View File

@@ -32,14 +32,20 @@ import { config, NETWORK_NAME } from "@config/config";
import { useNotification } from "@refinedev/core";
import { queryFeaturesByIds } from "@/utils/mapQueryService";
import { useMap } from "@app/OlMap/MapComponent";
import * as turf from "@turf/turf";
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 { Stroke, Style, Icon } from "ol/style";
import Feature, { FeatureLike } from "ol/Feature";
import { along, lineString, length, toMercator } from "@turf/turf";
import {
along,
lineString,
length,
toMercator,
bbox,
featureCollection,
} from "@turf/turf";
import { Point } from "ol/geom";
import { toLonLat } from "ol/proj";
import Timeline from "@app/OlMap/Controls/Timeline";
@@ -100,7 +106,6 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
{ start: Date; end: Date } | undefined
>();
const [internalSchemes, setInternalSchemes] = useState<SchemeRecord[]>([]);
const [schemeName, setSchemeName] = useState<string>("");
const [loading, setLoading] = useState<boolean>(false);
const [expandedId, setExpandedId] = useState<number | null>(null);
const [mapContainer, setMapContainer] = useState<HTMLElement | null>(null); // 地图容器元素
@@ -108,7 +113,9 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
const { open } = useNotification();
const map = useMap();
const data = useData();
if (!data) return null;
const { schemeName, setSchemeName } = data;
// 使用外部提供的 schemes 或内部状态
const schemes =
externalSchemes !== undefined ? externalSchemes : internalSchemes;
@@ -183,9 +190,7 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
geojsonFormat.writeFeatureObject(feature)
);
const extent = turf.bbox(
turf.featureCollection(geojsonFeatures as any)
);
const extent = bbox(featureCollection(geojsonFeatures as any));
if (extent) {
map?.getView().fit(extent, { maxZoom: 18, duration: 1000 });
@@ -211,7 +216,9 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
);
setSelectedDate(schemeDate);
setTimeRange({ start, end });
setSchemeName(scheme.schemeName);
if (setSchemeName) {
setSchemeName(scheme.schemeName);
}
handleLocatePipes(burstPipeIds);
}
};
@@ -270,7 +277,7 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
new Style({
geometry: new Point(midPointMercator),
image: new Icon({
src: "/icons/burst_pipe_icon.svg",
src: "/icons/burst_pipe.svg",
scale: 0.2,
anchor: [0.5, 1],
}),
@@ -283,6 +290,8 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
const highlightLayer = new VectorLayer({
source: new VectorSource(),
style: burstPipeStyle,
maxZoom: 24,
minZoom: 12,
properties: {
name: "爆管管段高亮",
value: "burst_pipe_highlight",

View File

@@ -1,6 +1,6 @@
"use client";
import React, { useState } from "react";
import React, { useEffect, useState } from "react";
import {
Box,
Button,
@@ -30,7 +30,12 @@ import { config, NETWORK_NAME } from "@config/config";
import { useNotification } from "@refinedev/core";
import { useMap } from "@app/OlMap/MapComponent";
import { queryFeaturesByIds } from "@/utils/mapQueryService";
import * as turf from "@turf/turf";
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, { FeatureLike } from "ol/Feature";
import { bbox, featureCollection } from "@turf/turf";
interface SchemeRecord {
id: number;
@@ -74,23 +79,68 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
const { open } = useNotification();
const map = useMap();
const [highlightLayer, setHighlightLayer] =
useState<VectorLayer<VectorSource> | null>(null);
const [highlightFeatures, setHighlightFeatures] = useState<Feature[]>([]);
// 使用外部提供的 schemes 或内部状态
const schemes =
externalSchemes !== undefined ? externalSchemes : internalSchemes;
const setSchemes = onSchemesChange || setInternalSchemes;
// 格式化日期
const formatTime = (timeStr: string) => {
const time = moment(timeStr);
return time.format("YYYY-MM-DD HH:mm:ss");
};
// 格式化简短日期
const formatShortDate = (timeStr: string) => {
const time = moment(timeStr);
return time.format("MM-DD");
};
// 初始化管道图层和高亮图层
useEffect(() => {
if (!map) return;
// 定义传感器样式
const sensorStyle = new Style({
image: new Icon({
src: "/icons/sensor.svg",
scale: 0.2,
anchor: [0.5, 1],
}),
});
// 创建高亮图层 - 爆管管段标识样式
const highlightLayer = new VectorLayer({
source: new VectorSource(),
style: sensorStyle,
maxZoom: 24,
minZoom: 12,
properties: {
name: "传感器高亮",
value: "sensor_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]);
// 查询方案
const handleQuery = async () => {
if (!queryAll && !queryDate) return;
@@ -158,29 +208,19 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
if (sensorIds.length > 0) {
queryFeaturesByIds(sensorIds).then((features) => {
if (features.length > 0) {
// 计算范围并缩放
const geojsonFormat = new (window as any).ol.format.GeoJSON();
// 设置高亮要素
setHighlightFeatures(features);
// 将 OpenLayers Feature 转换为 GeoJSON Feature
const geojsonFormat = new GeoJSON();
const geojsonFeatures = features.map((feature) =>
geojsonFormat.writeFeatureObject(feature)
);
const extent = turf.bbox(
turf.featureCollection(geojsonFeatures as any)
);
const extent = bbox(featureCollection(geojsonFeatures as any));
if (extent) {
map.getView().fit(extent, { maxZoom: 18, duration: 1000 });
map?.getView().fit(extent, { maxZoom: 18, duration: 1000 });
}
open?.({
type: "success",
message: `已定位 ${features.length} 个传感器位置`,
});
} else {
open?.({
type: "error",
message: "未找到传感器位置",
});
}
});
}
@@ -321,7 +361,8 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
variant="caption"
className="text-gray-500 block"
>
: {scheme.minDiameter} · : {scheme.user} · : {formatShortDate(scheme.create_time)}
: {scheme.minDiameter} · : {scheme.user} ·
: {formatShortDate(scheme.create_time)}
</Typography>
</Box>
{/* 操作按钮 */}
@@ -434,54 +475,58 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
</Box>
{/* 传感器位置列表 */}
{scheme.sensorLocation && scheme.sensorLocation.length > 0 && (
<Box className="mb-3">
<Typography
variant="caption"
className="text-gray-600 block mb-2"
>
({scheme.sensorLocation.length}):
</Typography>
<Box className="max-h-40 overflow-auto bg-gray-50 rounded p-2">
<Box className="flex flex-wrap gap-2">
{scheme.sensorLocation.map((sensorId, index) => (
<Link
key={index}
component="button"
variant="caption"
className="font-medium text-blue-600 hover:text-blue-800 underline cursor-pointer"
onClick={(e) => {
e.preventDefault();
handleLocateSensors([sensorId]);
}}
>
{sensorId}
</Link>
))}
{scheme.sensorLocation &&
scheme.sensorLocation.length > 0 && (
<Box className="mb-3">
<Typography
variant="caption"
className="text-gray-600 block mb-2"
>
({scheme.sensorLocation.length}):
</Typography>
<Box className="max-h-40 overflow-auto bg-gray-50 rounded p-2">
<Box className="flex flex-wrap gap-2">
{scheme.sensorLocation.map(
(sensorId, index) => (
<Link
key={index}
component="button"
variant="caption"
className="font-medium text-blue-600 hover:text-blue-800 underline cursor-pointer"
onClick={(e) => {
e.preventDefault();
handleLocateSensors([sensorId]);
}}
>
{sensorId}
</Link>
)
)}
</Box>
</Box>
</Box>
</Box>
)}
)}
{/* 操作按钮区域 */}
<Box className="pt-2 border-t border-gray-100 flex gap-2">
{scheme.sensorLocation && scheme.sensorLocation.length > 0 && (
<Button
variant="outlined"
fullWidth
size="small"
className="border-blue-600 text-blue-600 hover:bg-blue-50"
onClick={() =>
handleLocateSensors(scheme.sensorLocation!)
}
sx={{
textTransform: "none",
fontWeight: 500,
}}
>
</Button>
)}
{scheme.sensorLocation &&
scheme.sensorLocation.length > 0 && (
<Button
variant="outlined"
fullWidth
size="small"
className="border-blue-600 text-blue-600 hover:bg-blue-50"
onClick={() =>
handleLocateSensors(scheme.sensorLocation!)
}
sx={{
textTransform: "none",
fontWeight: 500,
}}
>
</Button>
)}
<Button
variant="contained"
fullWidth

View File

@@ -349,7 +349,7 @@ const SCADADataPanel: React.FC<SCADADataPanelProps> = ({
rowsCount: rows.length,
columnsCount: columns.length,
sampleRow: rows[0],
columns: columns.map(c => c.field),
columns: columns.map((c) => c.field),
});
return (
@@ -373,7 +373,7 @@ const SCADADataPanel: React.FC<SCADADataPanelProps> = ({
<Paper
className={clsx(
"absolute right-4 top-20 w-4xl h-2xl bg-white rounded-xl shadow-lg overflow-hidden flex flex-col transition-opacity duration-300",
visible ? "opacity-95 hover:opacity-100" : "opacity-0 z-10"
visible ? "opacity-95 hover:opacity-100" : "opacity-0 -z-10"
)}
>
{/* Header */}

View File

@@ -1,10 +1,16 @@
"use client";
import React, { useState, useEffect, useMemo } from "react";
import React, {
useState,
useEffect,
useMemo,
useCallback,
useRef,
startTransition,
} from "react";
import {
Box,
Paper,
TextField,
Typography,
List,
ListItem,
@@ -14,7 +20,6 @@ import {
Chip,
IconButton,
Collapse,
InputAdornment,
FormControl,
InputLabel,
Select,
@@ -23,6 +28,7 @@ import {
Stack,
Divider,
InputBase,
CircularProgress,
} from "@mui/material";
import {
Search,
@@ -31,17 +37,19 @@ import {
ExpandLess,
FilterList,
Clear,
Visibility,
VisibilityOff,
DeviceHub,
} from "@mui/icons-material";
import { useMap } from "@app/OlMap/MapComponent";
import { GeoJSON } from "ol/format";
import { Point } from "ol/geom";
import config from "@/config/config";
interface SCADADevice {
id: string;
name: string;
type: string;
coordinates: [number, number];
status: "online" | "offline" | "warning" | "error";
status: "在线" | "离线" | "警告" | "错误";
properties?: Record<string, any>;
}
@@ -57,7 +65,6 @@ interface SCADADeviceListProps {
const SCADADeviceList: React.FC<SCADADeviceListProps> = ({
devices = [],
onDeviceClick,
onZoomToDevice,
multiSelect = true,
selectedDeviceIds,
onSelectionChange,
@@ -70,9 +77,28 @@ const SCADADeviceList: React.FC<SCADADeviceListProps> = ({
const [pendingSelection, setPendingSelection] = useState<string[] | null>(
null
);
const [internalDevices, setInternalDevices] = useState<SCADADevice[]>([]);
const [loading, setLoading] = useState<boolean>(true);
const [inputValue, setInputValue] = useState<string>("");
const debounceTimerRef = useRef<NodeJS.Timeout | null>(null);
// 防抖更新搜索查询
const debouncedSetSearchQuery = useCallback((value: string) => {
if (debounceTimerRef.current) {
clearTimeout(debounceTimerRef.current);
}
// 根据输入长度调整防抖延迟:短输入延迟更长,长输入响应更快
const delay = value.length <= 2 ? 200 : 100;
debounceTimerRef.current = setTimeout(() => {
setSearchQuery(value);
}, delay);
}, []);
const activeSelection = selectedDeviceIds ?? internalSelection;
const map = useMap(); // 移到此处,确保在条件检查前调用
useEffect(() => {
if (selectedDeviceIds) {
setInternalSelection(selectedDeviceIds);
@@ -87,28 +113,87 @@ const SCADADeviceList: React.FC<SCADADeviceListProps> = ({
}
}, [pendingSelection, onSelectionChange]);
// 初始化 SCADA 设备列表
useEffect(() => {
const fetchScadaDevices = async () => {
setLoading(true);
try {
const url = `${config.mapUrl}/TJWater/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=TJWater:geo_scada&outputFormat=application/json`;
const response = await fetch(url);
if (!response.ok) throw new Error("Failed to fetch SCADA devices");
const json = await response.json();
const features = new GeoJSON().readFeatures(json);
const data = features.map((feature) => ({
id: feature.get("id") || feature.getId(),
name: feature.get("id") || feature.getId(),
type: feature.get("type") === "pipe_flow" ? "流量" : "压力",
status: ["在线", "离线", "警告", "错误"][
Math.floor(Math.random() * 4)
] as "在线" | "离线" | "警告" | "错误",
coordinates: (feature.getGeometry() as Point)?.getCoordinates() as [
number,
number
],
properties: feature.getProperties(),
}));
setInternalDevices(data);
console.log("Fetched SCADA devices:", data);
} catch (error) {
console.error("Error fetching SCADA devices:", error);
} finally {
setLoading(false);
}
};
fetchScadaDevices();
}, []);
const effectiveDevices = devices.length > 0 ? devices : internalDevices;
// 获取设备类型列表
const deviceTypes = useMemo(() => {
const types = Array.from(new Set(devices.map((device) => device.type)));
const types = Array.from(
new Set(effectiveDevices.map((device) => device.type))
);
return types.sort();
}, [devices]);
}, [effectiveDevices]);
// 获取设备状态列表
const deviceStatuses = useMemo(() => {
const statuses = Array.from(
new Set(devices.map((device) => device.status))
new Set(effectiveDevices.map((device) => device.status))
);
return statuses.sort();
}, [devices]);
}, [effectiveDevices]);
// 创建设备索引 Map使用设备 ID 作为键
const deviceIndex = useMemo(() => {
const index = new Map<string, SCADADevice>();
effectiveDevices.forEach((device) => {
index.set(device.id, device);
});
return index;
}, [effectiveDevices]);
// 过滤设备列表
const filteredDevices = useMemo(() => {
return devices.filter((device) => {
if (
searchQuery === "" &&
selectedType === "all" &&
selectedStatus === "all"
) {
return effectiveDevices;
}
const searchLower = searchQuery.toLowerCase();
return effectiveDevices.filter((device) => {
if (searchQuery === "") return true;
const nameLower = device.name.toLowerCase();
const idLower = device.id.toLowerCase();
const matchesSearch =
searchQuery === "" ||
device.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
device.id.toLowerCase().includes(searchQuery.toLowerCase()) ||
device.type.toLowerCase().includes(searchQuery.toLowerCase());
nameLower.indexOf(searchLower) !== -1 ||
idLower.indexOf(searchLower) !== -1;
const matchesType =
selectedType === "all" || device.type === selectedType;
@@ -117,7 +202,7 @@ const SCADADeviceList: React.FC<SCADADeviceListProps> = ({
return matchesSearch && matchesType && matchesStatus;
});
}, [devices, searchQuery, selectedType, selectedStatus]);
}, [effectiveDevices, searchQuery, selectedType, selectedStatus]);
// 状态颜色映射
const getStatusColor = (status: string) => {
@@ -171,22 +256,38 @@ const SCADADeviceList: React.FC<SCADADeviceListProps> = ({
};
// 处理缩放到设备
const handleZoomToDevice = (device: SCADADevice, event: React.MouseEvent) => {
event.stopPropagation();
onZoomToDevice?.(device.coordinates);
const handleZoomToDevice = (device: SCADADevice) => {
map
?.getView()
.fit(new Point(device.coordinates), { maxZoom: 15, duration: 1000 });
};
// 清除搜索
const handleClearSearch = () => {
setSearchQuery("");
};
const handleClearSearch = useCallback(() => {
setInputValue("");
startTransition(() => {
setSearchQuery("");
});
}, []);
// 重置所有筛选条件
const handleResetFilters = () => {
setSearchQuery("");
setSelectedType("all");
setSelectedStatus("all");
};
const handleResetFilters = useCallback(() => {
setInputValue("");
startTransition(() => {
setSearchQuery("");
setSelectedType("all");
setSelectedStatus("all");
});
}, []);
// 清理定时器
useEffect(() => {
return () => {
if (debounceTimerRef.current) {
clearTimeout(debounceTimerRef.current);
}
};
}, []);
return (
<Paper className="absolute left-4 top-20 w-90 max-h-[calc(100vh-100px)] bg-white rounded-xl shadow-lg overflow-hidden flex flex-col opacity-95 transition-opacity duration-200 ease-in-out hover:opacity-100">
@@ -242,9 +343,12 @@ const SCADADeviceList: React.FC<SCADADeviceListProps> = ({
<Box className="h-10 flex items-center border border-gray-300 rounded-md p-0.5">
<InputBase
sx={{ ml: 1, flex: 1 }}
placeholder="搜索设备名称、ID 或类型..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
placeholder="搜索设备名称、ID..."
value={inputValue}
onChange={(e) => {
setInputValue(e.target.value);
debouncedSetSearchQuery(e.target.value);
}}
inputProps={{ "aria-label": "search devices" }}
/>
<IconButton type="button" sx={{ p: "6px" }} aria-label="search">
@@ -310,7 +414,7 @@ const SCADADeviceList: React.FC<SCADADeviceListProps> = ({
<Typography variant="caption" color="text.secondary">
{filteredDevices.length}
{devices.length !== filteredDevices.length &&
` (共 ${devices.length} 个设备)`}
` (共 ${effectiveDevices.length} 个设备)`}
</Typography>
</Stack>
</Box>
@@ -319,7 +423,18 @@ const SCADADeviceList: React.FC<SCADADeviceListProps> = ({
{/* 设备列表 */}
<Box sx={{ flex: 1, overflow: "auto", maxHeight: 400 }}>
{filteredDevices.length === 0 ? (
{loading ? (
<Box
sx={{
display: "flex",
justifyContent: "center",
alignItems: "center",
height: 200,
}}
>
<CircularProgress />
</Box>
) : filteredDevices.length === 0 ? (
<Box
sx={{
p: 4,
@@ -416,7 +531,10 @@ const SCADADeviceList: React.FC<SCADADeviceListProps> = ({
<Tooltip title="缩放到设备位置">
<IconButton
size="small"
onClick={(e) => handleZoomToDevice(device, e)}
onClick={(event) => {
event.stopPropagation();
handleZoomToDevice(device);
}}
sx={{
ml: 1,
color: "primary.main",