Просмотр исходного кода

feat(risk): 添加风险评估相关功能和统计计算,修复燃气数据大量时引起风险评估四色图的掉帧

刘昊林 1 день назад
Родитель
Сommit
4e699ce304

+ 107 - 0
src/utils/riskFourColorMapModel.js

@@ -0,0 +1,107 @@
+import { convertCoord } from './coordTransform.js'
+
+export const RISK_STYLES = {
+  major: { name: '重大风险', color: '#f56c6c', lineWidth: 6, priority: 0 },
+  larger: { name: '较大风险', color: '#e6a23c', lineWidth: 5, priority: 1 },
+  general: { name: '一般风险', color: '#f4d03f', lineWidth: 4, priority: 2 },
+  low: { name: '低风险', color: '#409eff', lineWidth: 3, priority: 3 }
+}
+
+export function getRiskLevel(score) {
+  if (score >= 75) return 'major'
+  if (score >= 55) return 'larger'
+  if (score >= 35) return 'general'
+  return 'low'
+}
+
+export function normalizeRiskPipeline(row, feature) {
+  const properties = feature?.properties || {}
+  const geometry = feature?.geometry
+  let path = geometry?.type === 'LineString' && Array.isArray(geometry.coordinates)
+    ? geometry.coordinates : []
+  if (geometry?.type === 'MultiLineString' && Array.isArray(geometry.coordinates)) {
+    path = geometry.coordinates.flat().filter(c => Array.isArray(c) && c.length >= 2)
+  }
+  const startLng = row.startLongitude ?? properties.startLongitude
+  const startLat = row.startLatitude ?? properties.startLatitude
+  const endLng = row.endLongitude ?? properties.endLongitude
+  const endLat = row.endLatitude ?? properties.endLatitude
+  if (path.length < 2 && [startLng, startLat, endLng, endLat].every(v => v != null)) {
+    path = [[Number(startLng), Number(startLat)], [Number(endLng), Number(endLat)]]
+  }
+  // Keep map-ready coordinates so render, fit, and locate do not convert them again.
+  path = (Array.isArray(row.path) && path.length < 2 ? row.path : path)
+    .map(c => [Number(c?.[0]), Number(c?.[1])])
+    .filter(c => Number.isFinite(c[0]) && Number.isFinite(c[1]))
+    .map(([lng, lat]) => convertCoord(lng, lat))
+    .filter(c => Number.isFinite(c[0]) && Number.isFinite(c[1]))
+
+  const riskScore = Number(row.riskScore) || 0
+  const riskLevel = getRiskLevel(riskScore)
+  const style = RISK_STYLES[riskLevel]
+  return {
+    ...row,
+    id: row.id || row.networkId || properties.networkId,
+    code: row.code || row.networkCode || properties.networkCode || row.networkId || '',
+    name: row.name || row.networkName || properties.networkName || row.networkId || '未命名管段',
+    riskScore,
+    riskLevel,
+    riskLevelName: style.name,
+    color: style.color,
+    lineWidth: style.lineWidth,
+    material: row.material || properties.material || '-',
+    pressureLevel: row.pressureLevel || row.networkLevel || '-',
+    diameter: Number(row.diameter) || 0,
+    length: Number(row.length) || 0,
+    path,
+    riskFactors: Array.isArray(row.riskFactors) ? row.riskFactors : []
+  }
+}
+
+export function calculateRiskStatistics(pipelines) {
+  const counts = { major: 0, larger: 0, general: 0, low: 0 }
+  let totalScore = 0
+  pipelines.forEach(pipeline => {
+    if (counts[pipeline.riskLevel] !== undefined) counts[pipeline.riskLevel] += 1
+    totalScore += Number(pipeline.riskScore) || 0
+  })
+
+  const total = pipelines.length
+  const percentages = {}
+  Object.keys(counts).forEach(level => {
+    percentages[level] = total ? ((counts[level] / total) * 100).toFixed(1) : '0.0'
+  })
+  return {
+    counts,
+    total,
+    average: total ? (totalScore / total).toFixed(1) : '0.0',
+    percentages
+  }
+}
+
+export function sortRiskLabelCandidates(pipelines) {
+  return pipelines
+    .filter(pipeline => Array.isArray(pipeline.path) && pipeline.path.length >= 2)
+    .slice()
+    .sort((a, b) => (RISK_STYLES[a.riskLevel]?.priority ?? 9) - (RISK_STYLES[b.riskLevel]?.priority ?? 9))
+}
+
+export function groupRiskLabelCandidates(candidates, visibleRisks, projectPoint, cellSize) {
+  const visible = new Set(visibleRisks)
+  const cells = new Map()
+  candidates.forEach(pipeline => {
+    if (!visible.has(pipeline.riskLevel)) return
+    const midpoint = pipeline.path[Math.floor(pipeline.path.length / 2)]
+    const pixel = projectPoint(pipeline, midpoint)
+    if (!Number.isFinite(pixel?.x) || !Number.isFinite(pixel?.y)) return
+
+    const key = `${Math.floor(pixel.x / cellSize.x)}_${Math.floor(pixel.y / cellSize.y)}`
+    const group = cells.get(key)
+    if (group) {
+      group.count += 1
+    } else {
+      cells.set(key, { pipeline, midpoint, count: 1 })
+    }
+  })
+  return [...cells.values()]
+}

+ 213 - 137
src/views/subSystem/gas/gasfxpg/gxfxpgsst.vue

@@ -169,12 +169,19 @@
 
 <script setup>
 import { ensureTdtMap } from '@/utils/mapApi'
-import { ref, computed, onMounted, onBeforeUnmount, nextTick } from 'vue'
+import { ref, shallowRef, computed, onMounted, onBeforeUnmount, nextTick } from 'vue'
 import { MapLocation, Search, Refresh, FullScreen, Location, ZoomIn, ZoomOut, InfoFilled } from '@element-plus/icons-vue'
 import { ElMessage } from 'element-plus'
 import { convertCoord } from '@/utils/coordTransform'
 import { getGisPipeLines } from '@/api/pipeNetwork/basic'
 import { getGasRiskAssessments } from '@/api/pipeNetwork/hazard'
+import {
+  calculateRiskStatistics,
+  groupRiskLabelCandidates,
+  normalizeRiskPipeline,
+  RISK_STYLES,
+  sortRiskLabelCandidates
+} from '@/utils/riskFourColorMapModel'
 
 // ==================== 天地图初始化 ====================
 const MAP_CENTER = { lng: 110.386, lat: 28.445 }
@@ -182,13 +189,23 @@ const MAP_DEFAULT_ZOOM = 14
 
 let mapInstance = null
 const mapError = ref('')
-const currentLng = ref(110.394)
-const currentLat = ref(28.469)
 
 const overlayStore = {
   major: [], larger: [], general: [], low: []
 }
 
+const LABEL_CELL = { x: 120, y: 44 }
+const LABEL_FONT = "'Microsoft YaHei', 'PingFang SC', 'Helvetica Neue', Arial, sans-serif"
+const PIPELINE_BATCH_SIZE = 30
+const pipelineLabels = []
+const pipelineMidpoints = new WeakMap()
+let labelTimer = null
+let pipelineRenderFrame = null
+let pipelineRenderVersion = 0
+let isRenderingPipelines = false
+let hoverPositionFrame = null
+let latestMousePosition = null
+let isUnmounted = false
 
 
 function initMap() {
@@ -199,73 +216,15 @@ function initMap() {
   const [clng, clat] = convertCoord(MAP_CENTER.lng, MAP_CENTER.lat)
   mapInstance.centerAndZoom(new TdtMap.Point(clng, clat), MAP_DEFAULT_ZOOM)
   mapInstance.enableScrollWheelZoom(true)
-  mapInstance.addEventListener('mousemove', (e) => {
-    currentLng.value = e.latlng.lng
-    currentLat.value = e.latlng.lat
-  })
+  mapInstance.addEventListener('zoomend', scheduleLabels)
+  mapInstance.addEventListener('moveend', scheduleLabels)
   renderAllOverlays()
   fitBounds()
 }
 
 // ==================== 沅陵县燃气管网四色风险数据 ====================
-function getRiskLevel(score) {
-  if (score >= 75) return 'major'
-  if (score >= 55) return 'larger'
-  if (score >= 35) return 'general'
-  return 'low'
-}
-
-function getRiskLevelName(level) {
-  const map = { major: '重大风险', larger: '较大风险', general: '一般风险', low: '低风险' }
-  return map[level]
-}
-
-function getRiskColor(level) {
-  const map = { major: '#f56c6c', larger: '#e6a23c', general: '#f4d03f', low: '#409eff' }
-  return map[level]
-}
-
 // 风险评估四色图使用真实风险评估及 GIS 管线接口,不保留静态示例数据。
-const pipelines = ref([])
-
-function normalizePipeline(row, feature) {
-  const properties = feature?.properties || {}
-  const geometry = feature?.geometry
-  let path = geometry?.type === 'LineString' && Array.isArray(geometry.coordinates)
-    ? geometry.coordinates : []
-  if (geometry?.type === 'MultiLineString' && Array.isArray(geometry.coordinates)) {
-    path = geometry.coordinates.flat().filter(c => Array.isArray(c) && c.length >= 2)
-  }
-  const startLng = row.startLongitude ?? properties.startLongitude
-  const startLat = row.startLatitude ?? properties.startLatitude
-  const endLng = row.endLongitude ?? properties.endLongitude
-  const endLat = row.endLatitude ?? properties.endLatitude
-  if (path.length < 2 && [startLng, startLat, endLng, endLat].every(v => v != null)) {
-    path = [[Number(startLng), Number(startLat)], [Number(endLng), Number(endLat)]]
-  }
-  path = (Array.isArray(row.path) && path.length < 2 ? row.path : path)
-    .map(c => [Number(c?.[0]), Number(c?.[1])])
-    .filter(c => Number.isFinite(c[0]) && Number.isFinite(c[1]))
-  const riskScore = Number(row.riskScore) || 0
-  const riskLevel = getRiskLevel(riskScore)
-  return {
-    ...row,
-    id: row.id || row.networkId || properties.networkId,
-    code: row.code || row.networkCode || properties.networkCode || row.networkId || '',
-    name: row.name || row.networkName || properties.networkName || row.networkId || '未命名管段',
-    riskScore,
-    riskLevel,
-    riskLevelName: getRiskLevelName(riskLevel),
-    color: getRiskColor(riskLevel),
-    lineWidth: riskLevel === 'major' ? 6 : riskLevel === 'larger' ? 5 : riskLevel === 'general' ? 4 : 3,
-    material: row.material || properties.material || '-',
-    pressureLevel: row.pressureLevel || row.networkLevel || '-',
-    diameter: Number(row.diameter) || 0,
-    length: Number(row.length) || 0,
-    path,
-    riskFactors: Array.isArray(row.riskFactors) ? row.riskFactors : []
-  }
-}
+const pipelines = shallowRef([])
 
 async function loadRiskData() {
   try {
@@ -273,6 +232,7 @@ async function loadRiskData() {
       getGasRiskAssessments(),
       getGisPipeLines({ networkType: 'gas' })
     ])
+    if (isUnmounted) return
     const features = Array.isArray(gisResponse?.data?.features) ? gisResponse.data.features : []
     const byKey = new Map()
     features.forEach(feature => {
@@ -284,32 +244,30 @@ async function loadRiskData() {
     pipelines.value = rows.map(row => {
       const keys = [row.networkId, row.id, row.code, row.networkCode, row.name, row.networkName]
         .filter(Boolean).map(key => String(key).trim().toLowerCase())
-      return normalizePipeline(row, keys.map(key => byKey.get(key)).find(Boolean))
+      return normalizeRiskPipeline(row, keys.map(key => byKey.get(key)).find(Boolean))
     })
     if (mapInstance) {
       renderAllOverlays()
       fitBounds()
     }
   } catch (e) {
+    if (isUnmounted) return
     pipelines.value = []
     ElMessage.error('燃气管线风险数据加载失败')
   }
 }
 
 // ==================== 统计数据 ====================
-const majorCount = computed(() => pipelines.value.filter(p => p.riskLevel === 'major').length)
-const largerCount = computed(() => pipelines.value.filter(p => p.riskLevel === 'larger').length)
-const generalCount = computed(() => pipelines.value.filter(p => p.riskLevel === 'general').length)
-const lowCount = computed(() => pipelines.value.filter(p => p.riskLevel === 'low').length)
-const totalCount = computed(() => pipelines.value.length)
-const majorPercent = computed(() => totalCount.value ? ((majorCount.value / totalCount.value) * 100).toFixed(1) : '0.0')
-const largerPercent = computed(() => totalCount.value ? ((largerCount.value / totalCount.value) * 100).toFixed(1) : '0.0')
-const generalPercent = computed(() => totalCount.value ? ((generalCount.value / totalCount.value) * 100).toFixed(1) : '0.0')
-const lowPercent = computed(() => totalCount.value ? ((lowCount.value / totalCount.value) * 100).toFixed(1) : '0.0')
-const riskIndex = computed(() => {
-  const totalScore = pipelines.value.reduce((sum, p) => sum + p.riskScore, 0)
-  return totalCount.value ? (totalScore / totalCount.value).toFixed(1) : '0.0'
-})
+const riskStatistics = computed(() => calculateRiskStatistics(pipelines.value))
+const majorCount = computed(() => riskStatistics.value.counts.major)
+const largerCount = computed(() => riskStatistics.value.counts.larger)
+const generalCount = computed(() => riskStatistics.value.counts.general)
+const lowCount = computed(() => riskStatistics.value.counts.low)
+const majorPercent = computed(() => riskStatistics.value.percentages.major)
+const largerPercent = computed(() => riskStatistics.value.percentages.larger)
+const generalPercent = computed(() => riskStatistics.value.percentages.general)
+const lowPercent = computed(() => riskStatistics.value.percentages.low)
+const riskIndex = computed(() => riskStatistics.value.average)
 const riskIndexClass = computed(() => {
   const score = parseFloat(riskIndex.value)
   if (score >= 70) return 'high'
@@ -319,6 +277,7 @@ const riskIndexClass = computed(() => {
 
 // ==================== 筛选 ====================
 const visibleRisks = ref(['major', 'larger', 'general', 'low'])
+let lastVisibleRisks = new Set(visibleRisks.value)
 const searchKeyword = ref('')
 
 const filteredPipelines = computed(() => {
@@ -329,16 +288,26 @@ const filteredPipelines = computed(() => {
   }
   return list.filter(p => visibleRisks.value.includes(p.riskLevel))
 })
+const labelCandidates = computed(() => sortRiskLabelCandidates(pipelines.value))
 
 // ==================== 交互状态 ====================
-const hoverPipeline = ref(null)
+const hoverPipeline = shallowRef(null)
 const hoverX = ref(0)
 const hoverY = ref(0)
-const currentPipeline = ref(null)
+const currentPipeline = shallowRef(null)
 const detailDrawerVisible = ref(false)
 
 // ==================== 地图覆盖物渲染 ====================
 function clearOverlays() {
+  pipelineRenderVersion += 1
+  isRenderingPipelines = false
+  if (pipelineRenderFrame !== null) {
+    cancelAnimationFrame(pipelineRenderFrame)
+    pipelineRenderFrame = null
+  }
+  clearTimeout(labelTimer)
+  labelTimer = null
+  clearPipelineLabels()
   Object.values(overlayStore).forEach(arr => {
     arr.forEach(o => { try { mapInstance.removeOverlay(o) } catch {} })
     arr.length = 0
@@ -351,48 +320,47 @@ function addToStore(layer, overlay) {
 
 function renderPipelines() {
   const TdtMap = window.TdtMap
-  pipelines.value.forEach(p => {
-    if (!visibleRisks.value.includes(p.riskLevel)) return
-    if (!Array.isArray(p.path) || p.path.length < 2) return
-    const points = p.path.map(c => { const [lng, lat] = convertCoord(c[0], c[1]); return new TdtMap.Point(lng, lat) })
-    const polyline = new TdtMap.Polyline(points, {
-      strokeColor: p.color, strokeWeight: p.lineWidth, strokeOpacity: 0.82
-    })
-    mapInstance.addOverlay(polyline)
-    addToStore(p.riskLevel, polyline)
-
-    polyline.addEventListener('click', () => {
-      currentPipeline.value = p
-      detailDrawerVisible.value = true
-    })
-    polyline.addEventListener('mouseover', () => { hoverPipeline.value = p })
-    polyline.addEventListener('mouseout', () => { hoverPipeline.value = null })
-
-    const mid = Math.floor(points.length / 2)
-    // 风险评分标签
-    const scoreLabel = new TdtMap.Label(p.riskScore + '分', {
-      position: points[mid],
-      offset: new TdtMap.Size(0, -16)
-    })
-    scoreLabel.setStyle({
-      color: '#fff', fontSize: '11px', fontWeight: 'bold', padding: '2px 8px',
-      backgroundColor: p.color, borderRadius: '10px', border: 'none', whiteSpace: 'nowrap'
-    })
-    mapInstance.addOverlay(scoreLabel)
-    addToStore(p.riskLevel, scoreLabel)
-
-    // 管线名称标签
-    const nameLabel = new TdtMap.Label(p.name, {
-      position: points[mid],
-      offset: new TdtMap.Size(0, 4)
-    })
-    nameLabel.setStyle({
-      color: '#333', fontSize: '10px', padding: '1px 4px',
-      backgroundColor: 'rgba(255,255,255,0.85)', borderRadius: '2px', border: 'none', whiteSpace: 'nowrap'
-    })
-    mapInstance.addOverlay(nameLabel)
-    addToStore(p.riskLevel, nameLabel)
-  })
+  const rows = pipelines.value
+  const renderVersion = pipelineRenderVersion
+  let index = 0
+  isRenderingPipelines = rows.length > 0
+  const renderBatch = () => {
+    pipelineRenderFrame = null
+    if (!mapInstance || renderVersion !== pipelineRenderVersion) return
+    const end = Math.min(index + PIPELINE_BATCH_SIZE, rows.length)
+    for (; index < end; index += 1) {
+      const pipeline = rows[index]
+      if (!Array.isArray(pipeline.path) || pipeline.path.length < 2) continue
+      const points = pipeline.path.map(([lng, lat]) => new TdtMap.Point(lng, lat))
+      const polyline = new TdtMap.Polyline(points, {
+        strokeColor: pipeline.color,
+        strokeWeight: pipeline.lineWidth,
+        strokeOpacity: 0.82
+      })
+      mapInstance.addOverlay(polyline)
+      addToStore(pipeline.riskLevel, polyline)
+      pipelineMidpoints.set(pipeline, points[Math.floor(points.length / 2)])
+      if (!visibleRisks.value.includes(pipeline.riskLevel)) polyline.hide()
+
+      polyline.addEventListener('click', () => {
+        currentPipeline.value = pipeline
+        detailDrawerVisible.value = true
+      })
+      polyline.addEventListener('mouseover', () => { hoverPipeline.value = pipeline })
+      polyline.addEventListener('mouseout', () => { hoverPipeline.value = null })
+    }
+    if (index < rows.length) {
+      pipelineRenderFrame = requestAnimationFrame(renderBatch)
+    } else {
+      isRenderingPipelines = false
+      scheduleLabels()
+    }
+  }
+  if (rows.length) {
+    pipelineRenderFrame = requestAnimationFrame(renderBatch)
+  } else {
+    scheduleLabels()
+  }
 }
 
 function renderAllOverlays() {
@@ -405,10 +373,84 @@ function renderAllOverlays() {
 function onLayerChange() {
   const set = new Set(visibleRisks.value)
   Object.entries(overlayStore).forEach(([layer, overlays]) => {
+    if (set.has(layer) === lastVisibleRisks.has(layer)) return
     overlays.forEach(o => {
       try { set.has(layer) ? o.show() : o.hide() } catch {}
     })
   })
+  lastVisibleRisks = set
+  scheduleLabels()
+}
+
+function clearPipelineLabels() {
+  pipelineLabels.forEach(label => { try { mapInstance.removeOverlay(label) } catch {} })
+  pipelineLabels.length = 0
+}
+
+function escapeLabel(value) {
+  return String(value ?? '').replace(/[&<>"']/g, ch => ({
+    '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;'
+  }[ch]))
+}
+
+function renderPipelineLabels() {
+  if (!mapInstance || !window.TdtMap) return
+  const TdtMap = window.TdtMap
+  const mapElement = document.getElementById('riskFourColorTdtMap')
+  if (!mapElement) return
+  clearPipelineLabels()
+  const groups = groupRiskLabelCandidates(
+    labelCandidates.value,
+    visibleRisks.value,
+    pipeline => {
+      const point = pipelineMidpoints.get(pipeline)
+      if (!point) return null
+      const pixel = mapInstance.pointToPixel(point)
+      return pixel?.x >= 0 && pixel.x <= mapElement.clientWidth
+        && pixel.y >= 0 && pixel.y <= mapElement.clientHeight
+        ? pixel
+        : null
+    },
+    LABEL_CELL
+  )
+  groups.forEach(({ pipeline, midpoint, count }) => {
+    const riskStyle = RISK_STYLES[pipeline.riskLevel]
+    const name = escapeLabel(pipeline.name || pipeline.code || '未命名管段')
+    const more = count > 1
+      ? `<span style="margin-left:6px;padding:0 5px;border-radius:8px;background:#e2e8f0;color:#334155;font-size:11px">+${count - 1}</span>`
+      : ''
+    const content = `<span style="color:#111827">${name}</span><span style="margin-left:6px;color:${riskStyle.color}">${pipeline.riskScore}分</span>${more}`
+    const label = new TdtMap.Label(content, {
+      position: new TdtMap.Point(midpoint[0], midpoint[1]),
+      offset: new TdtMap.Size(0, -18)
+    })
+    label.setStyle({
+      fontFamily: LABEL_FONT,
+      fontSize: '12px',
+      fontWeight: 600,
+      lineHeight: '18px',
+      color: '#111827',
+      padding: '3px 9px',
+      backgroundColor: 'rgba(255,255,255,0.97)',
+      border: `1px solid #cbd5e1`,
+      borderLeft: `3px solid ${riskStyle.color}`,
+      borderRadius: '4px',
+      boxShadow: '0 2px 6px rgba(15,23,42,.28)',
+      whiteSpace: 'nowrap',
+      pointerEvents: 'none'
+    })
+    mapInstance.addOverlay(label)
+    pipelineLabels.push(label)
+  })
+}
+
+function scheduleLabels() {
+  if (isRenderingPipelines) return
+  clearTimeout(labelTimer)
+  labelTimer = setTimeout(() => {
+    labelTimer = null
+    renderPipelineLabels()
+  }, 120)
 }
 
 // ==================== 工具栏操作 ====================
@@ -423,12 +465,24 @@ function zoomOut() {
 function fitBounds() {
   if (mapInstance) {
     const TdtMap = window.TdtMap
-    const coordinates = filteredPipelines.value.flatMap(p => Array.isArray(p.path) ? p.path : [])
-    if (coordinates.length >= 2) {
-      const points = coordinates.map(c => {
-        const [lng, lat] = convertCoord(Number(c[0]), Number(c[1]))
-        return new TdtMap.Point(lng, lat)
+    let minLng = Infinity
+    let minLat = Infinity
+    let maxLng = -Infinity
+    let maxLat = -Infinity
+    filteredPipelines.value.forEach(pipeline => {
+      if (!Array.isArray(pipeline.path)) return
+      pipeline.path.forEach(([lng, lat]) => {
+        minLng = Math.min(minLng, lng)
+        minLat = Math.min(minLat, lat)
+        maxLng = Math.max(maxLng, lng)
+        maxLat = Math.max(maxLat, lat)
       })
+    })
+    if (Number.isFinite(minLng) && Number.isFinite(minLat)) {
+      const points = [
+        new TdtMap.Point(minLng, minLat),
+        new TdtMap.Point(maxLng, maxLat)
+      ]
       try { mapInstance.setViewport(points, { margins: [40, 40, 40, 40], zoomFactor: -1 }) }
       catch { mapInstance.setViewport(points) }
       return
@@ -450,8 +504,11 @@ function locateSearch() {
   if (found && mapInstance) {
     const TdtMap = window.TdtMap
     const mid = found.path[Math.floor(found.path.length / 2)]
-    const [midlng, midlat] = convertCoord(mid[0], mid[1])
-    mapInstance.centerAndZoom(new TdtMap.Point(midlng, midlat), 16)
+    if (!mid) {
+      ElMessage.warning('匹配的管段缺少可定位坐标')
+      return
+    }
+    mapInstance.centerAndZoom(new TdtMap.Point(mid[0], mid[1]), 16)
     currentPipeline.value = found
     detailDrawerVisible.value = true
     ElMessage.success(`已定位到: ${found.name}`)
@@ -464,8 +521,11 @@ function locatePipeline() {
   if (!currentPipeline.value || !mapInstance) return
   const TdtMap = window.TdtMap
   const mid = currentPipeline.value.path[Math.floor(currentPipeline.value.path.length / 2)]
-  const [midlng, midlat] = convertCoord(mid[0], mid[1])
-  mapInstance.centerAndZoom(new TdtMap.Point(midlng, midlat), 16)
+  if (!mid) {
+    ElMessage.warning('当前管段缺少可定位坐标')
+    return
+  }
+  mapInstance.centerAndZoom(new TdtMap.Point(mid[0], mid[1]), 16)
   detailDrawerVisible.value = false
 }
 
@@ -475,10 +535,15 @@ function viewDetail() {
 
 // ==================== 悬浮卡定位 ====================
 function onWindowMouseMove(e) {
-  if (hoverPipeline.value) {
-    hoverX.value = e.clientX + 12
-    hoverY.value = e.clientY - 40
-  }
+  if (!hoverPipeline.value) return
+  latestMousePosition = { x: e.clientX, y: e.clientY }
+  if (hoverPositionFrame !== null) return
+  hoverPositionFrame = requestAnimationFrame(() => {
+    hoverPositionFrame = null
+    if (!hoverPipeline.value || !latestMousePosition) return
+    hoverX.value = latestMousePosition.x + 12
+    hoverY.value = latestMousePosition.y - 40
+  })
 }
 
 // ==================== 生命周期 ====================
@@ -487,15 +552,26 @@ onMounted(async () => {
   loadRiskData()
   try {
     await ensureTdtMap()
-    nextTick(() => initMap())
+    if (isUnmounted) return
+    nextTick(() => {
+      if (!isUnmounted) initMap()
+    })
   } catch {
-    mapError.value = '天地图加载失败,请刷新页面重试'
+    if (!isUnmounted) mapError.value = '天地图加载失败,请刷新页面重试'
   }
 })
 
 onBeforeUnmount(() => {
+  isUnmounted = true
   window.removeEventListener('mousemove', onWindowMouseMove)
+  if (hoverPositionFrame !== null) {
+    cancelAnimationFrame(hoverPositionFrame)
+    hoverPositionFrame = null
+  }
   if (mapInstance) {
+    clearOverlays()
+    try { mapInstance.removeEventListener('zoomend', scheduleLabels) } catch {}
+    try { mapInstance.removeEventListener('moveend', scheduleLabels) } catch {}
     try { mapInstance.destroy() } catch {}
     mapInstance = null
   }

+ 92 - 0
tests/riskFourColorMap.test.mjs

@@ -0,0 +1,92 @@
+import test from 'node:test'
+import assert from 'node:assert/strict'
+
+import {
+  calculateRiskStatistics,
+  getRiskLevel,
+  groupRiskLabelCandidates,
+  normalizeRiskPipeline,
+  sortRiskLabelCandidates
+} from '../src/utils/riskFourColorMapModel.js'
+
+test('four-color risk thresholds preserve their exact boundary levels', () => {
+  assert.deepEqual(
+    [34.9, 35, 54.9, 55, 74.9, 75].map(getRiskLevel),
+    ['low', 'general', 'general', 'larger', 'larger', 'major']
+  )
+})
+
+test('risk normalization maps GeoJSON geometry and color without changing risk semantics', () => {
+  const pipeline = normalizeRiskPipeline(
+    { networkId: 'gas-1', riskScore: 75, riskFactors: ['腐蚀'] },
+    {
+      properties: { networkCode: 'G-1', networkName: '测试管段' },
+      geometry: { type: 'MultiLineString', coordinates: [[[110, 28], [111, 29]], [[112, 30], [113, 31]]] }
+    }
+  )
+
+  assert.equal(pipeline.riskLevel, 'major')
+  assert.equal(pipeline.riskLevelName, '重大风险')
+  assert.equal(pipeline.color, '#f56c6c')
+  assert.equal(pipeline.lineWidth, 6)
+  assert.equal(pipeline.code, 'G-1')
+  assert.equal(pipeline.name, '测试管段')
+  assert.deepEqual(pipeline.path, [[110, 28], [111, 29], [112, 30], [113, 31]])
+})
+
+test('risk statistics calculate counts, percentages, and average in one pass', () => {
+  const statistics = calculateRiskStatistics([
+    { riskLevel: 'major', riskScore: 80 },
+    { riskLevel: 'larger', riskScore: 60 },
+    { riskLevel: 'low', riskScore: 20 }
+  ])
+
+  assert.deepEqual(statistics.counts, { major: 1, larger: 1, general: 0, low: 1 })
+  assert.deepEqual(statistics.percentages, { major: '33.3', larger: '33.3', general: '0.0', low: '33.3' })
+  assert.equal(statistics.average, '53.3')
+})
+
+test('empty risk data produces zero counts and percentages', () => {
+  const statistics = calculateRiskStatistics([])
+
+  assert.deepEqual(statistics.counts, { major: 0, larger: 0, general: 0, low: 0 })
+  assert.deepEqual(statistics.percentages, { major: '0.0', larger: '0.0', general: '0.0', low: '0.0' })
+  assert.equal(statistics.average, '0.0')
+})
+
+test('map labels are limited to one per screen cell and prioritize higher risks', () => {
+  const pipelines = [
+    { riskLevel: 'low', name: '低风险', path: [[0, 0], [1, 1]] },
+    { riskLevel: 'major', name: '重大风险', path: [[2, 2], [3, 3]] },
+    { riskLevel: 'general', name: '一般风险', path: [[300, 300], [301, 301]] }
+  ]
+  const candidates = sortRiskLabelCandidates(pipelines)
+  const groups = groupRiskLabelCandidates(
+    candidates,
+    ['major', 'general', 'low'],
+    (_pipeline, midpoint) => ({ x: midpoint[0], y: midpoint[1] }),
+    { x: 120, y: 44 }
+  )
+
+  assert.equal(groups.length, 2)
+  assert.equal(groups[0].pipeline.name, '重大风险')
+  assert.equal(groups[0].count, 2)
+  assert.equal(groups[1].pipeline.name, '一般风险')
+})
+
+test('large sets of overlapping risk points produce only one label per screen cell', () => {
+  const pipelines = Array.from({ length: 10000 }, (_, index) => ({
+    riskLevel: 'low',
+    name: `管段-${index}`,
+    path: [[110, 28], [110, 28]]
+  }))
+  const groups = groupRiskLabelCandidates(
+    sortRiskLabelCandidates(pipelines),
+    ['low'],
+    () => ({ x: 80, y: 30 }),
+    { x: 120, y: 44 }
+  )
+
+  assert.equal(groups.length, 1)
+  assert.equal(groups[0].count, 10000)
+})