<!--管线风险评估四色图-->
<template>
  <div class="risk-four-color-map">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <el-icon><MapLocation /></el-icon>
        <span class="title">燃气管网风险四色图</span>
        <div class="stats-badge">
          <span class="stat-item major"><i class="dot"></i>重大风险 {{ majorCount }}</span>
          <span class="stat-item larger"><i class="dot"></i>较大风险 {{ largerCount }}</span>
          <span class="stat-item general"><i class="dot"></i>一般风险 {{ generalCount }}</span>
          <span class="stat-item low"><i class="dot"></i>低风险 {{ lowCount }}</span>
        </div>
      </div>
      <div class="header-right">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索管段/位置"
          clearable
          :prefix-icon="Search"
          style="width: 200px"
        />
        <el-button type="primary" :icon="Location" @click="locateSearch">定位</el-button>
        <el-button :icon="Refresh" @click="refreshMap">刷新</el-button>
        <el-button :icon="FullScreen" @click="fitBounds">全图</el-button>
      </div>
    </div>

    <!-- 主内容区：左侧图例面板 + 右侧GIS地图 -->
    <div class="main-layout">
      <!-- 左侧图例和控制面板 -->
      <div class="legend-panel">
        <div class="panel-title">风险等级图例</div>
        <div class="legend-item major">
          <span class="legend-color"></span>
          <div class="legend-info">
            <span class="level-name">重大风险</span>
            <span class="level-desc">红色标识 - 需要立即采取控制措施</span>
          </div>
        </div>
        <div class="legend-item larger">
          <span class="legend-color"></span>
          <div class="legend-info">
            <span class="level-name">较大风险</span>
            <span class="level-desc">橙色标识 - 需要重点关注并制定整改计划</span>
          </div>
        </div>
        <div class="legend-item general">
          <span class="legend-color"></span>
          <div class="legend-info">
            <span class="level-name">一般风险</span>
            <span class="level-desc">黄色标识 - 需要保持关注并定期检查</span>
          </div>
        </div>
        <div class="legend-item low">
          <span class="legend-color"></span>
          <div class="legend-info">
            <span class="level-name">低风险</span>
            <span class="level-desc">蓝色标识 - 维持现有管理措施</span>
          </div>
        </div>

        <div class="divider"></div>

        <div class="stats-section">
          <div class="stats-title">风险统计</div>
          <div class="stats-grid">
            <div class="stat-card major">
              <div class="stat-value">{{ majorCount }}</div>
              <div class="stat-label">重大风险管段</div>
              <div class="stat-percent">{{ majorPercent }}%</div>
            </div>
            <div class="stat-card larger">
              <div class="stat-value">{{ largerCount }}</div>
              <div class="stat-label">较大风险管段</div>
              <div class="stat-percent">{{ largerPercent }}%</div>
            </div>
            <div class="stat-card general">
              <div class="stat-value">{{ generalCount }}</div>
              <div class="stat-label">一般风险管段</div>
              <div class="stat-percent">{{ generalPercent }}%</div>
            </div>
            <div class="stat-card low">
              <div class="stat-value">{{ lowCount }}</div>
              <div class="stat-label">低风险管段</div>
              <div class="stat-percent">{{ lowPercent }}%</div>
            </div>
          </div>
        </div>

        <div class="divider"></div>

        <div class="filter-section">
          <div class="filter-title">风险筛选</div>
          <el-checkbox-group v-model="visibleRisks" class="risk-checkbox" @change="onLayerChange">
            <el-checkbox value="major">重大风险（红）</el-checkbox>
            <el-checkbox value="larger">较大风险（橙）</el-checkbox>
            <el-checkbox value="general">一般风险（黄）</el-checkbox>
            <el-checkbox value="low">低风险（蓝）</el-checkbox>
          </el-checkbox-group>
        </div>

        <div class="info-note">
          <el-icon><InfoFilled /></el-icon>
          <span>风险等级依据《燃气管网安全风险评估规范》评定，按紧急程度、发展态势和危害程度划分</span>
        </div>
      </div>

      <!-- 右侧GIS地图 -->
      <div class="gis-container">
        <div class="map-toolbar">
          <el-button-group>
            <el-button size="small" :icon="ZoomIn" @click="zoomIn">放大</el-button>
            <el-button size="small" :icon="ZoomOut" @click="zoomOut">缩小</el-button>
            <el-button size="small" :icon="Location" @click="fitBounds">重置</el-button>
          </el-button-group>
          <div class="risk-summary">
            综合风险指数: <span :class="riskIndexClass">{{ riskIndex }}</span>
          </div>
        </div>
        <div class="map-wrapper">
          <div id="riskFourColorBaiduMap" class="map-div"></div>
          <div v-if="mapError" class="map-error">{{ mapError }}</div>
          <!-- 悬浮信息卡 -->
          <div v-if="hoverPipeline" class="hover-card" :style="{ top: hoverY + 'px', left: hoverX + 'px' }">
            <div class="hover-title">{{ hoverPipeline.name }}</div>
            <div>风险等级: {{ hoverPipeline.riskLevelName }}</div>
            <div>风险评分: {{ hoverPipeline.riskScore }}分</div>
            <div>管材: {{ hoverPipeline.material }}</div>
            <div>压力级别: {{ hoverPipeline.pressureLevel }}</div>
            <div>长度: {{ hoverPipeline.length }}km</div>
          </div>
        </div>

        <!-- 详情抽屉 -->
        <el-drawer v-model="detailDrawerVisible" :title="`管段详情 - ${currentPipeline?.name}`" size="450px" direction="rtl">
          <div v-if="currentPipeline" class="pipeline-detail">
            <div class="risk-tag" :class="currentPipeline.riskLevel">
              <span class="tag-name">{{ currentPipeline.riskLevelName }}</span>
              <span class="tag-score">风险评分: {{ currentPipeline.riskScore }}分</span>
            </div>
            <el-descriptions :column="1" border size="small">
              <el-descriptions-item label="管段编号">{{ currentPipeline.code }}</el-descriptions-item>
              <el-descriptions-item label="管材材质">{{ currentPipeline.material }}</el-descriptions-item>
              <el-descriptions-item label="压力级别">{{ currentPipeline.pressureLevel }}</el-descriptions-item>
              <el-descriptions-item label="管径">{{ currentPipeline.diameter }}mm</el-descriptions-item>
              <el-descriptions-item label="长度">{{ currentPipeline.length }}km</el-descriptions-item>
              <el-descriptions-item label="埋设年代">{{ currentPipeline.buryYear }}</el-descriptions-item>
              <el-descriptions-item label="权属单位">{{ currentPipeline.owner }}</el-descriptions-item>
              <el-descriptions-item label="最近检测">{{ currentPipeline.lastInspection }}</el-descriptions-item>
            </el-descriptions>
            <div class="risk-factors">
              <div class="sub-title">主要风险因素</div>
              <ul>
                <li v-for="(factor, idx) in currentPipeline.riskFactors" :key="idx">{{ factor }}</li>
              </ul>
            </div>
            <div class="action-buttons">
              <el-button type="primary" size="small" @click="viewDetail">查看详细报告</el-button>
              <el-button size="small" @click="locatePipeline">地图定位</el-button>
            </div>
          </div>
        </el-drawer>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, 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'

// ==================== 百度地图初始化 ====================
const MAP_CENTER = { lng: 110.386, lat: 28.445 }
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: []
}

function waitForBMapGL() {
  return new Promise((resolve, reject) => {
    let attempts = 0
    const timer = setInterval(() => {
      attempts++
      if (window.BMapGL) { clearInterval(timer); resolve(window.BMapGL) }
      if (attempts > 150) { clearInterval(timer); reject(new Error('百度地图API加载超时')) }
    }, 200)
  })
}

function initMap() {
  const BMapGL = window.BMapGL
  const el = document.getElementById('riskFourColorBaiduMap')
  if (!el) return
  mapInstance = new BMapGL.Map(el, { enableMapClick: true })
  const [clng, clat] = convertCoord(MAP_CENTER.lng, MAP_CENTER.lat)
  mapInstance.centerAndZoom(new BMapGL.Point(clng, clat), MAP_DEFAULT_ZOOM)
  mapInstance.enableScrollWheelZoom(true)
  mapInstance.setMapStyleV2({ styleId: 'a0f4e6e6f9e7a6c5d8e7f7e7f7e7f7e5' })
  mapInstance.addEventListener('mousemove', (e) => {
    currentLng.value = e.latlng.lng
    currentLat.value = e.latlng.lat
  })
  renderAllOverlays()
}

// ==================== 沅陵县燃气管网四色风险数据 ====================
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]
}

const pipelines = ref([
  {
    id: 1, code: 'PL-YL-001', name: '燃气1',
    riskScore: 86.5, riskLevel: 'major', riskLevelName: '重大风险', color: '#f56c6c', lineWidth: 6,
    material: '钢管', pressureLevel: '高压 (1.6MPa)', diameter: 500, length: 3.8,
    buryYear: '2015年', owner: '燃气公司', lastInspection: '2026-03-15',
    path: [[110.404947, 28.433419], [110.404836, 28.433429], [110.403275, 28.433571], [110.401084, 28.433876], [110.399601, 28.433876], [110.398112, 28.433979], [110.396717, 28.434314], [110.394299, 28.434538], [110.394352, 28.434887], [110.391969, 28.434985], [110.384374, 28.435695], [110.381418, 28.43559], [110.377993, 28.436193], [110.376062, 28.436385], [110.374231, 28.43655], [110.372584, 28.437107], [110.371292, 28.4377], [110.370581, 28.438198], [110.369831, 28.438821]],
    riskFactors: ['管道服役超过10年', '交通密集', '防腐层多处破损', '沿线施工活动']
  },
  {
    id: 2, code: 'PL-YL-002', name: '燃气2',
    riskScore: 64.3, riskLevel: 'larger', riskLevelName: '较大风险', color: '#e6a23c', lineWidth: 5,
    material: 'PE管', pressureLevel: '中压 (0.4MPa)', diameter: 300, length: 3.2,
    buryYear: '2018年', owner: '燃气公司', lastInspection: '2026-02-10',
    path: [[110.361433, 28.454979], [110.362363, 28.453169], [110.362851, 28.452213], [110.364377, 28.452443], [110.365138, 28.45246], [110.366462, 28.452157], [110.369549, 28.451441], [110.37219, 28.450897], [110.372753, 28.450901], [110.373875, 28.451194], [110.373913, 28.451107], [110.374597, 28.451476]],
    riskFactors: ['沿线有在建工程', '防腐层老化', '人流量大']
  },
])

// ==================== 统计数据 ====================
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(() => ((majorCount.value / totalCount.value) * 100).toFixed(1))
const largerPercent = computed(() => ((largerCount.value / totalCount.value) * 100).toFixed(1))
const generalPercent = computed(() => ((generalCount.value / totalCount.value) * 100).toFixed(1))
const lowPercent = computed(() => ((lowCount.value / totalCount.value) * 100).toFixed(1))
const riskIndex = computed(() => {
  const totalScore = pipelines.value.reduce((sum, p) => sum + p.riskScore, 0)
  return (totalScore / totalCount.value).toFixed(1)
})
const riskIndexClass = computed(() => {
  const score = parseFloat(riskIndex.value)
  if (score >= 70) return 'high'
  if (score >= 50) return 'medium'
  return 'low'
})

// ==================== 筛选 ====================
const visibleRisks = ref(['major', 'larger', 'general', 'low'])
const searchKeyword = ref('')

const filteredPipelines = computed(() => {
  let list = pipelines.value
  if (searchKeyword.value) {
    const kw = searchKeyword.value.toLowerCase()
    list = list.filter(p => p.name.toLowerCase().includes(kw) || p.code.toLowerCase().includes(kw))
  }
  return list.filter(p => visibleRisks.value.includes(p.riskLevel))
})

// ==================== 交互状态 ====================
const hoverPipeline = ref(null)
const hoverX = ref(0)
const hoverY = ref(0)
const currentPipeline = ref(null)
const detailDrawerVisible = ref(false)

// ==================== 地图覆盖物渲染 ====================
function clearOverlays() {
  Object.values(overlayStore).forEach(arr => {
    arr.forEach(o => { try { mapInstance.removeOverlay(o) } catch {} })
    arr.length = 0
  })
}

function addToStore(layer, overlay) {
  if (overlayStore[layer]) overlayStore[layer].push(overlay)
}

function renderPipelines() {
  const BMapGL = window.BMapGL
  pipelines.value.forEach(p => {
    if (!visibleRisks.value.includes(p.riskLevel)) return
    const points = p.path.map(c => { const [lng, lat] = convertCoord(c[0], c[1]); return new BMapGL.Point(lng, lat) })
    const polyline = new BMapGL.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 BMapGL.Label(p.riskScore + '分', {
      position: points[mid],
      offset: new BMapGL.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 BMapGL.Label(p.name, {
      position: points[mid],
      offset: new BMapGL.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)
  })
}

function renderAllOverlays() {
  clearOverlays()
  renderPipelines()
  onLayerChange()
}

// ==================== 图层显隐 ====================
function onLayerChange() {
  const set = new Set(visibleRisks.value)
  Object.entries(overlayStore).forEach(([layer, overlays]) => {
    overlays.forEach(o => {
      try { set.has(layer) ? o.show() : o.hide() } catch {}
    })
  })
}

// ==================== 工具栏操作 ====================
function zoomIn() {
  if (mapInstance) mapInstance.zoomIn()
}

function zoomOut() {
  if (mapInstance) mapInstance.zoomOut()
}

function fitBounds() {
  if (mapInstance) {
    const BMapGL = window.BMapGL
    const [clng, clat] = convertCoord(MAP_CENTER.lng, MAP_CENTER.lat)
    mapInstance.centerAndZoom(new BMapGL.Point(clng, clat), MAP_DEFAULT_ZOOM)
  }
}

function refreshMap() {
  renderAllOverlays()
  ElMessage.success('地图已刷新')
}

function locateSearch() {
  if (!searchKeyword.value) return
  const found = pipelines.value.find(p =>
    p.name.includes(searchKeyword.value) || p.code.includes(searchKeyword.value)
  )
  if (found && mapInstance) {
    const BMapGL = window.BMapGL
    const mid = found.path[Math.floor(found.path.length / 2)]
    const [midlng, midlat] = convertCoord(mid[0], mid[1])
    mapInstance.centerAndZoom(new BMapGL.Point(midlng, midlat), 16)
    currentPipeline.value = found
    detailDrawerVisible.value = true
    ElMessage.success(`已定位到: ${found.name}`)
  } else {
    ElMessage.warning('未找到匹配的管段')
  }
}

function locatePipeline() {
  if (!currentPipeline.value || !mapInstance) return
  const BMapGL = window.BMapGL
  const mid = currentPipeline.value.path[Math.floor(currentPipeline.value.path.length / 2)]
  const [midlng, midlat] = convertCoord(mid[0], mid[1])
  mapInstance.centerAndZoom(new BMapGL.Point(midlng, midlat), 16)
  detailDrawerVisible.value = false
}

function viewDetail() {
  ElMessage.info('查看详细风险评估报告（演示）')
}

// ==================== 悬浮卡定位 ====================
function onWindowMouseMove(e) {
  if (hoverPipeline.value) {
    hoverX.value = e.clientX + 12
    hoverY.value = e.clientY - 40
  }
}

// ==================== 生命周期 ====================
onMounted(async () => {
  window.addEventListener('mousemove', onWindowMouseMove)
  try {
    await waitForBMapGL()
    nextTick(() => initMap())
  } catch {
    mapError.value = '百度地图加载失败，请刷新页面重试'
  }
})

onBeforeUnmount(() => {
  window.removeEventListener('mousemove', onWindowMouseMove)
  if (mapInstance) {
    try { mapInstance.destroy() } catch {}
    mapInstance = null
  }
})
</script>

<style scoped>
.risk-four-color-map {
  background: #f0f2f6;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.page-header {
  background: #fff;
  padding: 12px 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #e9ecef;
  flex-shrink: 0;
}

.header-left { display: flex; align-items: center; gap: 20px; }
.header-left .title { font-size: 1.3rem; font-weight: 600; }

.stats-badge { display: flex; gap: 16px; }
.stat-item { font-size: 12px; display: flex; align-items: center; gap: 6px; }
.stat-item.major { color: #f56c6c; }
.stat-item.larger { color: #e6a23c; }
.stat-item.general { color: #d4a017; }
.stat-item.low { color: #409eff; }
.stat-item .dot { width: 8px; height: 8px; border-radius: 50%; }
.stat-item.major .dot { background: #f56c6c; }
.stat-item.larger .dot { background: #e6a23c; }
.stat-item.general .dot { background: #f4d03f; }
.stat-item.low .dot { background: #409eff; }

.header-right { display: flex; gap: 12px; align-items: center; }

.main-layout {
  display: flex;
  flex: 1;
  overflow: hidden;
  padding: 12px;
  gap: 12px;
}

.legend-panel {
  width: 260px;
  background: #fff;
  border-radius: 12px;
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 16px;
  overflow-y: auto;
  flex-shrink: 0;
}

.panel-title { font-size: 16px; font-weight: 600; margin-bottom: 4px; }

.legend-item { display: flex; align-items: center; gap: 12px; margin-bottom: 12px; }
.legend-color { width: 30px; height: 20px; border-radius: 4px; flex-shrink: 0; }
.legend-item.major .legend-color { background: #f56c6c; }
.legend-item.larger .legend-color { background: #e6a23c; }
.legend-item.general .legend-color { background: #f4d03f; }
.legend-item.low .legend-color { background: #409eff; }
.legend-info { flex: 1; }
.level-name { font-weight: 600; display: block; font-size: 13px; }
.level-desc { font-size: 11px; color: #909399; }

.divider { height: 1px; background: #e9ecef; margin: 4px 0; }

.stats-section .stats-title { font-weight: 600; margin-bottom: 12px; font-size: 14px; }
.stats-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 12px; }
.stat-card { text-align: center; padding: 10px; border-radius: 8px; }
.stat-card.major { background: #fff8f8; border-left: 3px solid #f56c6c; }
.stat-card.larger { background: #fffef5; border-left: 3px solid #e6a23c; }
.stat-card.general { background: #fffef0; border-left: 3px solid #f4d03f; }
.stat-card.low { background: #f5f9ff; border-left: 3px solid #409eff; }
.stat-value { font-size: 24px; font-weight: bold; }
.stat-card.major .stat-value { color: #f56c6c; }
.stat-card.larger .stat-value { color: #e6a23c; }
.stat-card.general .stat-value { color: #d4a017; }
.stat-card.low .stat-value { color: #409eff; }
.stat-label { font-size: 11px; color: #606266; }
.stat-percent { font-size: 11px; color: #909399; }

.filter-section .filter-title { font-weight: 600; margin-bottom: 12px; font-size: 14px; }
.risk-checkbox { display: flex; flex-direction: column; gap: 8px; }

.info-note { background: #f5f7fa; border-radius: 8px; padding: 10px; font-size: 11px; color: #606266; display: flex; align-items: flex-start; gap: 8px; }

/* GIS地图 */
.gis-container {
  flex: 1;
  background: #fff;
  border-radius: 12px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.map-toolbar {
  padding: 10px 16px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-shrink: 0;
}

.risk-summary { font-size: 13px; }
.risk-summary .high { color: #f56c6c; font-weight: bold; }
.risk-summary .medium { color: #e6a23c; font-weight: bold; }
.risk-summary .low { color: #67c23a; font-weight: bold; }

.map-wrapper { flex: 1; position: relative; overflow: hidden; }
.map-div { width: 100%; height: 100%; }
.map-error { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); color: #f56c6c; font-size: 14px; }

/* 悬浮信息卡 */
.hover-card {
  position: fixed;
  background: rgba(0, 0, 0, 0.82);
  color: #fff;
  padding: 10px 14px;
  border-radius: 10px;
  font-size: 12px;
  pointer-events: none;
  z-index: 2000;
  line-height: 1.6;
}
.hover-title { font-weight: 600; margin-bottom: 4px; font-size: 13px; }

/* 详情抽屉 */
.pipeline-detail { padding: 8px; }
.risk-tag { text-align: center; padding: 12px; border-radius: 8px; margin-bottom: 16px; }
.risk-tag.major { background: #f56c6c20; border: 1px solid #f56c6c; color: #f56c6c; }
.risk-tag.larger { background: #e6a23c20; border: 1px solid #e6a23c; color: #e6a23c; }
.risk-tag.general { background: #f4d03f20; border: 1px solid #f4d03f; color: #d4a017; }
.risk-tag.low { background: #409eff20; border: 1px solid #409eff; color: #409eff; }
.tag-name { font-size: 18px; font-weight: bold; display: block; }
.tag-score { font-size: 12px; }

.risk-factors { margin-top: 16px; }
.risk-factors .sub-title { font-weight: 600; margin-bottom: 8px; }
.risk-factors ul { margin: 0; padding-left: 20px; }
.risk-factors li { margin: 6px 0; font-size: 13px; }

.action-buttons { margin-top: 20px; display: flex; gap: 12px; justify-content: flex-end; }
</style>
