<template>
  <div class="risk-map-container">
    <el-card class="legend-card">
      <template #header><span>风险四色图例</span></template>
      <div class="legend-items">
        <div class="legend-item" v-for="item in colorLegend" :key="item.value">
          <span class="line" :style="{ background: item.color }"></span> {{ item.riskLabel }} - {{ item.colorLabel }}
        </div>
      </div>
    </el-card>
    <div id="riskMap" class="map"></div>
    <el-drawer v-model="detailVisible" title="管线风险评估" size="400px">
      <template v-if="currentItem">
        <el-descriptions :column="1" border size="small">
          <el-descriptions-item label="管网名称">{{ currentItem.networkName }}</el-descriptions-item>
          <el-descriptions-item label="管网编码">{{ currentItem.networkCode }}</el-descriptions-item>
          <el-descriptions-item label="风险等级">{{ getDictLabel(riskLevelDict, currentItem.riskLevel) }}</el-descriptions-item>
          <el-descriptions-item label="风险评分">{{ currentItem.riskScore }}</el-descriptions-item>
          <el-descriptions-item label="风险颜色">{{ getDictLabel(riskColorDict, currentItem.riskColor) }}</el-descriptions-item>
        </el-descriptions>
      </template>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import { getFourColorMap } from '@/api/pipeNetwork/hazard'
import { getDicts } from '@/api/system/dict/data'

const detailVisible = ref(false)
const currentItem = ref(null)
let mapInstance = null

const riskLevelDict = ref([])
const riskColorDict = ref([])

function getDictLabel(dict, value) {
  const item = dict.find(d => d.dictValue === value)
  return item ? item.dictLabel : value
}

const colorMap = { '0': '#f5222d', '1': '#fa8c16', '2': '#fadb14', '3': '#1890ff' }

const colorLegend = computed(() =>
  riskColorDict.value.map(d => ({
    value: d.dictValue,
    colorLabel: d.dictLabel,
    color: colorMap[d.dictValue] || '#999',
    riskLabel: getDictLabel(riskLevelDict, d.dictValue)
  }))
)

async function loadDicts() {
  const [levelRes, colorRes] = await Promise.all([
    getDicts('risk_level'),
    getDicts('risk_color')
  ])
  riskLevelDict.value = levelRes.data
  riskColorDict.value = colorRes.data
}

async function initMap() {
  await nextTick()
  const el = document.getElementById('riskMap')
  if (!el) return
  try {
    const L = await import('leaflet')
    mapInstance = L.map('riskMap').setView([34.77, 113.65], 12)
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
      attribution: '&copy; OpenStreetMap contributors'
    }).addTo(mapInstance)

    const res = await getFourColorMap()
    const items = res.data || []
    for (const item of items) {
      if (!item.longitude || !item.latitude) continue
      const color = colorMap[item.riskColor] || '#999'
      const marker = L.circleMarker([item.latitude, item.longitude], {
        radius: 8, fillColor: color, color: '#fff', weight: 2, fillOpacity: 0.9
      }).addTo(mapInstance)
      const levelLabel = getDictLabel(riskLevelDict, item.riskLevel)
      marker.bindPopup(`<b>${item.networkName || item.networkId}</b><br/>${levelLabel}<br/>评分: ${item.riskScore}`)
      marker.on('click', () => { currentItem.value = item; detailVisible.value = true })
    }
  } catch (e) {
    el.innerHTML = '<div style="display:flex;align-items:center;justify-content:center;height:100%;color:#999;">请安装Leaflet: npm install leaflet</div>'
  }
}

onMounted(async () => { await loadDicts(); initMap() })
</script>

<style scoped>
.risk-map-container { position: relative; height: calc(100vh - 100px); padding: 16px; }
.legend-card { position: absolute; top: 32px; right: 32px; z-index: 1000; width: 180px; }
.legend-items { display: flex; flex-direction: column; gap: 6px; }
.legend-item { display: flex; align-items: center; gap: 6px; font-size: 13px; }
.line { width: 30px; height: 4px; border-radius: 2px; display: inline-block; }
.map { width: 100%; height: 100%; border-radius: 4px; }
</style>
