<!--窨井盖安全实时监测一张图-->
<template>
  <div class="gis-monitor-container">
    <!-- 头部面板 -->
    <div class="header-panel">
      <div class="title-logo">
        <el-icon :size="26"><Monitor /></el-icon>
        <span class="title">窨井盖安全实时监测一张图</span>
        <span class="version">GIS动态态势平台</span>
      </div>
      <div class="stats-badge">
        <div class="stat-badge-item"><span class="dot online"></span> 在线 {{ stats.online }}</div>
        <div class="stat-badge-item"><span class="dot alert"></span> 告警 {{ stats.alarm }}</div>
        <div class="stat-badge-item"><span class="dot offline"></span> 离线 {{ stats.offline }}</div>
        <div class="stat-badge-item">总计 {{ stats.total }}</div>
        <el-button size="small" :icon="Refresh" @click="loadData" :loading="loading">刷新</el-button>
      </div>
    </div>

    <!-- 主内容区：左侧图层控制 + 右侧GIS地图 -->
    <div class="main-layout">
      <!-- 左侧图层控制面板 -->
      <div class="layer-panel">
        <div class="layer-header"><el-icon><Location /></el-icon> 动态监测图层</div>
        <!-- 类型筛选 -->
        <div class="layer-section">
          <div class="layer-section-title">设备类型</div>
          <el-checkbox-group v-model="typeFilter" @change="refreshMarkers">
            <el-checkbox label="5">供水窨井</el-checkbox>
            <el-checkbox label="9">排水窨井</el-checkbox>
            <el-checkbox label="10">燃气窨井</el-checkbox>
          </el-checkbox-group>
        </div>
        <!-- 状态筛选 -->
        <div class="layer-section">
          <div class="layer-section-title">设备状态</div>
          <el-checkbox-group v-model="statusFilter" @change="refreshMarkers">
            <el-checkbox label="normal">正常</el-checkbox>
            <el-checkbox label="alert">告警</el-checkbox>
            <el-checkbox label="offline">离线</el-checkbox>
          </el-checkbox-group>
        </div>
        <!-- 图例 -->
        <div class="legend-box">
          <div class="legend-title">图例</div>
          <div class="legend-item"><span class="legend-icon normal-icon"></span> 正常设备</div>
          <div class="legend-item"><span class="legend-icon alert-icon"></span> 告警设备</div>
          <div class="legend-item"><span class="legend-icon offline-icon"></span> 离线设备</div>
        </div>
      </div>

      <!-- 右侧 GIS 地图 -->
      <div class="gis-stage">
        <div class="map-toolbar">
          <span class="map-title">窨井设备分布图</span>
          <div class="legend">
            <span><i class="legend-dot online"></i> 在线</span>
            <span><i class="legend-dot alert"></i> 告警</span>
            <span><i class="legend-dot offline"></i> 离线</span>
          </div>
        </div>
        <div class="map-area">
          <div id="manholeStateMap" class="bmap-container"></div>
        </div>
      </div>
    </div>

    <!-- 设备详情抽屉 -->
    <el-drawer v-model="drawerVisible" :title="selectedDevice?.name + ' - 监测数据详情'" direction="rtl" size="520px">
      <div v-if="selectedDevice" v-loading="detailLoading">
        <!-- 基本信息 -->
        <el-descriptions :column="1" border size="small">
          <el-descriptions-item label="设备编号">{{ selectedDevice.code }}</el-descriptions-item>
          <el-descriptions-item label="设备名称">{{ selectedDevice.name }}</el-descriptions-item>
          <el-descriptions-item label="设备类型">{{ selectedDevice.typeName }}</el-descriptions-item>
          <el-descriptions-item label="详细地址">{{ selectedDevice.location }}</el-descriptions-item>
          <el-descriptions-item label="经纬度" v-if="selectedDevice.lng">{{ selectedDevice.lng }}, {{ selectedDevice.lat }}</el-descriptions-item>
          <el-descriptions-item label="运行状态">
            <el-tag :type="getStatusTagType(selectedDevice.status)" size="small">{{ getStatusText(selectedDevice.status) }}</el-tag>
          </el-descriptions-item>
        </el-descriptions>

        <!-- 井盖监测数据 (jg_device_data) -->
        <template v-if="selectedDevice.manholeData">
          <el-divider content-position="left">井盖监测数据</el-divider>
          <el-row :gutter="12">
            <el-col :span="8">
              <div class="metric-card">
                <div class="metric-label">倾斜角度</div>
                <div class="metric-value" :class="{ 'metric-alert': isTiltAlert(selectedDevice.manholeData) }">
                  {{ selectedDevice.manholeData.tiltAngle || '0' }}°
                </div>
                <div class="metric-sub">阈值: {{ selectedDevice.manholeData.angleAlarmThreshold || '-' }}°</div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="metric-card">
                <div class="metric-label">电池电量</div>
                <div class="metric-value" :class="{ 'metric-warn': Number(selectedDevice.manholeData.batteryLevel) <= 20 }">
                  {{ selectedDevice.manholeData.batteryLevel || '0' }}%
                </div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="metric-card">
                <div class="metric-label">信号强度</div>
                <div class="metric-value" :class="{ 'metric-warn': Number(selectedDevice.manholeData.signalStrength) <= 20 }">
                  {{ selectedDevice.manholeData.signalStrength || '0' }}%
                </div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="metric-card">
                <div class="metric-label">温度值</div>
                <div class="metric-value">{{ selectedDevice.manholeData.temperatureValue || '-' }}°C</div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="metric-card">
                <div class="metric-label">水浸状态</div>
                <div class="metric-value" :class="{ 'metric-alert': Number(selectedDevice.manholeData.waterInfiltrationAlarmStatus) === 1 }">
                  {{ Number(selectedDevice.manholeData.waterInfiltrationAlarmStatus) === 1 ? '报警' : '正常' }}
                </div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="metric-card">
                <div class="metric-label">水位状态</div>
                <div class="metric-value" :class="{ 'metric-alert': Number(selectedDevice.manholeData.waterLevelAlarmStatus) === 1 }">
                  {{ Number(selectedDevice.manholeData.waterLevelAlarmStatus) === 1 ? '报警' : '正常' }}
                </div>
              </div>
            </el-col>
          </el-row>
          <div class="upload-time">数据上传时间: {{ selectedDevice.manholeData.uploadTime || '-' }}</div>
        </template>
        <el-empty v-else description="暂无井盖监测数据" :image-size="60" />

        <!-- 关联井下设备监测数据 -->
        <el-divider content-position="left">关联井下设备监测</el-divider>
        <div v-if="relDevices.length === 0" class="empty-rel">暂无关联井下设备</div>
        <div v-else class="rel-device-list">
          <div v-for="rel in relDevices" :key="rel.relId" class="rel-device-card">
            <div class="rel-device-header">
              <span class="rel-device-name">{{ rel.equipmentName || '未知设备' }}</span>
              <el-tag size="small" effect="plain">{{ rel.equipmentTypeName || '未知类型' }}</el-tag>
            </div>
            <div class="rel-device-location" v-if="rel.equipmentLocation">
              <el-icon><Location /></el-icon> {{ rel.equipmentLocation }}
            </div>
            <!-- 雷达流量计数据 -->
            <template v-if="rel.monitorData?.dataType === '雷达流量计'">
              <el-row :gutter="8" class="rel-metrics">
                <el-col :span="6"><div class="rel-metric"><span class="rm-label">瞬时流量</span><span class="rm-value">{{ rel.monitorData.instantFlow || '-' }}</span></div></el-col>
                <el-col :span="6"><div class="rel-metric"><span class="rm-label">流速</span><span class="rm-value">{{ rel.monitorData.flowSpeed || '-' }}</span></div></el-col>
                <el-col :span="6"><div class="rel-metric"><span class="rm-label">水位</span><span class="rm-value">{{ rel.monitorData.waterLevel || '-' }}</span></div></el-col>
                <el-col :span="6"><div class="rel-metric"><span class="rm-label">累计流量</span><span class="rm-value">{{ rel.monitorData.totalFlow || '-' }}</span></div></el-col>
              </el-row>
            </template>
            <!-- 环境监测数据 -->
            <template v-else-if="rel.monitorData?.dataType === '环境监测'">
              <el-row :gutter="8" class="rel-metrics">
                <el-col :span="8"><div class="rel-metric"><span class="rm-label">温度</span><span class="rm-value">{{ rel.monitorData.temperature ?? '-' }}°C</span></div></el-col>
                <el-col :span="8"><div class="rel-metric"><span class="rm-label">{{ rel.monitorData.metricName || '湿度' }}</span><span class="rm-value">{{ rel.monitorData.metricValue ?? rel.monitorData.humidity ?? '-' }}</span></div></el-col>
                <el-col :span="8"><div class="rel-metric"><span class="rm-label">节点</span><span class="rm-value">{{ rel.monitorData.createTime || '-' }}</span></div></el-col>
              </el-row>
            </template>
            <div v-else class="rel-no-data">暂无监测数据</div>
          </div>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount, nextTick } from 'vue'
import { Monitor, Location, Refresh } from '@element-plus/icons-vue'
import { getManholeLayerData, getManholeRelDeviceData } from '@/api/pipeNetwork/basic'
import { ElMessage } from 'element-plus'
import locationIcon from '@/assets/images/location.png'

// ==================== 数据状态 ====================
const loading = ref(false)
const allDevices = ref([])
const stats = reactive({ total: 0, online: 0, offline: 0, alarm: 0 })

// 筛选条件
const typeFilter = ref(['5', '9', '10'])
const statusFilter = ref(['normal', 'alert', 'offline'])

// 选中设备 & 详情
const drawerVisible = ref(false)
const detailLoading = ref(false)
const selectedDevice = ref(null)
const relDevices = ref([])

// ==================== 加载数据 ====================
async function loadData() {
  loading.value = true
  try {
    const res = await getManholeLayerData({ isQueryManholeData: true })
    const devices = res.data?.devices || []
    allDevices.value = devices.map(d => {
      const onlineStatus = Number(d.equipmentStatus?.onlineStatus)
      const alarmStatus = Number(d.equipmentStatus?.alarmStatus)
      const manholeAlarm = Number(d.manholeData?.alarmStatus)
      const isAlert = alarmStatus === 1 || manholeAlarm === 1 ||
        Number(d.manholeData?.waterInfiltrationAlarmStatus) === 1 ||
        Number(d.manholeData?.waterLevelAlarmStatus) === 1
      const isOnline = onlineStatus === 1
      let status = 'offline'
      if (isAlert) status = 'alert'
      else if (isOnline) status = 'normal'
      return {
        id: d.equipmentId,
        code: d.equipmentCode,
        name: d.equipmentName,
        typeId: d.equipmentTypeId,
        typeName: d.equipmentTypeName,
        location: d.equipmentLocation,
        lng: d.longitude != null ? Number(d.longitude) : null,
        lat: d.latitude != null ? Number(d.latitude) : null,
        status,
        manholeData: d.manholeData || null
      }
    })
    const statistics = res.data?.statistics || {}
    stats.total = statistics.total || allDevices.value.length
    stats.online = statistics.online || 0
    stats.offline = statistics.offline || 0
    stats.alarm = statistics.alarm || 0
    refreshMarkers()
  } catch (e) {
    ElMessage.error('设备数据加载失败')
  } finally {
    loading.value = false
  }
}

// ==================== 筛选后的设备 ====================
function getFilteredDevices() {
  return allDevices.value.filter(d => {
    if (!typeFilter.value.includes(d.typeId)) return false
    if (!statusFilter.value.includes(d.status)) return false
    return true
  })
}

// ==================== 百度地图 ====================
let mapInstance = null
const markerMap = new Map()
const YUANLING_CENTER = { lng: 110.393, lat: 28.452 }

function initMap() {
  const container = document.getElementById('manholeStateMap')
  if (!container || typeof BMapGL === 'undefined') {
    console.warn('BMapGL 未加载或容器不存在')
    return
  }
  try {
    mapInstance = new BMapGL.Map('manholeStateMap')
    mapInstance.centerAndZoom(new BMapGL.Point(YUANLING_CENTER.lng, YUANLING_CENTER.lat), 13)
    mapInstance.enableScrollWheelZoom(true)
  } catch (e) {
    console.error('百度地图初始化失败：', e)
  }
}

function getStatusColor(status) {
  if (status === 'alert') return '#F56C6C'
  if (status === 'offline') return '#909399'
  return '#67C23A'
}

function addMapMarker(device) {
  if (!mapInstance || device.lng == null || device.lat == null) return
  const color = getStatusColor(device.status)
  const bPoint = new BMapGL.Point(device.lng, device.lat)
  const html = `<div style="text-align:center;cursor:pointer;">
    <div style="color:#fff;background:${color};border-radius:4px;padding:2px 8px;font-size:11px;white-space:nowrap;display:inline-block;margin-bottom:2px;box-shadow:0 1px 4px rgba(0,0,0,0.3);">
      ${device.name}
    </div>
    <div><img src="${locationIcon}" style="width:28px;height:28px;display:block;margin:0 auto;"/></div>
  </div>`
  const label = new BMapGL.Label(html, {
    position: bPoint,
    offset: new BMapGL.Size(-30, -50)
  })
  label.setStyle({ border: 'none', background: 'transparent', padding: '0', zIndex: '10' })
  label.addEventListener('click', () => selectDevice(device))
  mapInstance.addOverlay(label)
  markerMap.set(device.id, label)
}

function refreshMarkers() {
  if (!mapInstance) return
  markerMap.forEach(label => mapInstance.removeOverlay(label))
  markerMap.clear()
  getFilteredDevices().forEach(device => addMapMarker(device))
}

// ==================== 选中设备 & 详情 ====================
async function selectDevice(device) {
  selectedDevice.value = device
  drawerVisible.value = true
  relDevices.value = []
  detailLoading.value = true
  if (mapInstance && device.lng && device.lat) {
    mapInstance.centerAndZoom(new BMapGL.Point(device.lng, device.lat), 16)
  }
  highlightMarker(device.id)
  try {
    const res = await getManholeRelDeviceData(device.id)
    relDevices.value = res.data || []
  } catch (e) {
    ElMessage.error('关联设备数据加载失败')
  } finally {
    detailLoading.value = false
  }
}

function highlightMarker(id) {
  markerMap.forEach((label, key) => {
    const dom = label.getContentContainer ? label.getContentContainer() : null
    if (dom) {
      const isSelected = key === id
      dom.style.zIndex = isSelected ? '999' : '10'
      const title = dom.querySelector('div')
      if (title) {
        title.style.transform = isSelected ? 'scale(1.15)' : 'scale(1)'
        title.style.transition = 'transform 0.2s'
        title.style.boxShadow = isSelected ? '0 0 0 2px #409eff' : '0 1px 4px rgba(0,0,0,0.3)'
      }
    }
  })
}

// ==================== 辅助方法 ====================
function isTiltAlert(manholeData) {
  const tilt = Number(manholeData?.tiltAngle)
  const threshold = Number(manholeData?.angleAlarmThreshold)
  return threshold > 0 && tilt > threshold
}
function getStatusText(status) {
  return { normal: '正常', alert: '告警', offline: '离线' }[status] || status
}
function getStatusTagType(status) {
  return { normal: 'success', alert: 'danger', offline: 'info' }[status] || ''
}

const handleResize = () => { mapInstance && mapInstance.resize && mapInstance.resize() }

// ==================== 生命周期 ====================
onMounted(async () => {
  await nextTick()
  initMap()
  window.addEventListener('resize', handleResize)
  loadData()
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
  if (mapInstance) {
    mapInstance.clearOverlays && mapInstance.clearOverlays()
    mapInstance = null
  }
  markerMap.clear()
})
</script>

<style scoped>
.gis-monitor-container {
  background: #eef2f0;
  height: 100vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  font-family: 'Segoe UI', 'PingFang SC', Roboto, sans-serif;
}
.header-panel {
  background: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 24px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
  z-index: 10;
}
.title-logo { display: flex; align-items: center; gap: 12px; }
.title {
  font-size: 1.3rem; font-weight: 600;
  background: linear-gradient(135deg, #2e7d32, #1b5e20);
  -webkit-background-clip: text; background-clip: text; color: transparent;
}
.version { background: #e9f5e9; padding: 2px 8px; border-radius: 20px; font-size: 12px; }
.stats-badge { display: flex; gap: 16px; align-items: center; font-size: 13px; }
.stat-badge-item { display: flex; align-items: center; gap: 4px; }
.dot { width: 10px; height: 10px; border-radius: 50%; display: inline-block; }
.dot.online { background: #67c23a; }
.dot.alert { background: #f56c6c; }
.dot.offline { background: #909399; }
.main-layout { display: flex; flex: 1; overflow: hidden; gap: 12px; padding: 12px; }
.layer-panel {
  width: 240px; background: white; border-radius: 16px; padding: 16px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.05); display: flex; flex-direction: column;
}
.layer-header {
  font-weight: bold; font-size: 15px; margin-bottom: 16px;
  display: flex; align-items: center; gap: 8px;
}
.layer-section { margin-bottom: 16px; }
.layer-section-title { font-size: 13px; font-weight: 600; color: #606266; margin-bottom: 8px; }
.legend-box { margin-top: auto; border-top: 1px solid #e9ecef; padding-top: 12px; }
.legend-title { font-weight: 600; font-size: 13px; margin-bottom: 8px; }
.legend-item { font-size: 12px; color: #606266; margin-bottom: 6px; display: flex; align-items: center; gap: 6px; }
.legend-icon { width: 14px; height: 14px; border-radius: 3px; display: inline-block; }
.normal-icon { background: #67c23a; }
.alert-icon { background: #f56c6c; }
.offline-icon { background: #909399; }
.gis-stage {
  flex: 1; background: white; border-radius: 16px;
  display: flex; flex-direction: column; overflow: hidden;
  box-shadow: 0 6px 14px rgba(0,0,0,0.08);
}
.map-toolbar {
  padding: 10px 16px; display: flex; justify-content: space-between;
  border-bottom: 1px solid #f0f0f0; background: white; z-index: 2;
}
.map-title { font-weight: 600; color: #303133; font-size: 14px; }
.legend { display: flex; gap: 16px; font-size: 12px; align-items: center; }
.legend-dot { display: inline-block; width: 10px; height: 10px; border-radius: 50%; margin-right: 4px; }
.legend-dot.online { background: #67C23A; }
.legend-dot.alert { background: #F56C6C; }
.legend-dot.offline { background: #909399; }
.map-area { flex: 1; position: relative; min-height: 0; }
.bmap-container { width: 100%; height: 100%; }

/* 详情抽屉样式 */
.metric-card {
  background: #f8f9fc; border-radius: 8px; padding: 10px;
  text-align: center; margin-bottom: 8px;
}
.metric-label { font-size: 12px; color: #909399; margin-bottom: 4px; }
.metric-value { font-size: 18px; font-weight: bold; color: #303133; }
.metric-alert { color: #f56c6c; }
.metric-warn { color: #e6a23c; }
.metric-sub { font-size: 11px; color: #c0c4cc; margin-top: 2px; }
.upload-time { font-size: 12px; color: #909399; margin-top: 8px; text-align: right; }
.empty-rel { text-align: center; color: #909399; padding: 20px; font-size: 13px; }
.rel-device-list { display: flex; flex-direction: column; gap: 12px; }
.rel-device-card {
  background: #f8f9fc; border-radius: 8px; padding: 12px;
  border: 1px solid #ebeef5;
}
.rel-device-header {
  display: flex; justify-content: space-between; align-items: center; margin-bottom: 6px;
}
.rel-device-name { font-weight: 600; font-size: 13px; }
.rel-device-location { font-size: 12px; color: #606266; display: flex; align-items: center; gap: 4px; margin-bottom: 8px; }
.rel-metrics { margin-top: 4px; }
.rel-metric {
  text-align: center; background: white; border-radius: 6px; padding: 6px;
}
.rm-label { display: block; font-size: 11px; color: #909399; }
.rm-value { display: block; font-size: 14px; font-weight: 600; color: #303133; margin-top: 2px; }
.rel-no-data { font-size: 12px; color: #c0c4cc; text-align: center; padding: 8px; }
</style>
