<template>
  <div class="app-container monitor-page">
    <div class="monitor-layout">
      <div class="monitor-sidebar">
        <div class="sidebar-title">站点列表</div>
        <div
          v-for="(st, i) in stationList"
          :key="st.stcd"
          class="sidebar-item"
          :class="{ active: activeStation === i }"
          @click="selectStation(i)"
        >
          <span class="station-dot" :class="{ online: st.status !== '离线' }"></span>
          <span class="station-name">{{ st.name || st.stationName }}</span>
        </div>
      </div>
      <div class="monitor-main">
        <div class="map-wrapper" v-loading="mapLoading">
          <div id="viewDiv" class="map-container"></div>
          <div class="station-popup" v-if="activeStation !== null && stationList[activeStation]">
            <div class="popup-header">{{ stationList[activeStation].name || stationList[activeStation].stationName }}</div>
            <div class="popup-body">
              <div class="popup-row"><span class="popup-label">水位</span><span class="popup-value">{{ stationList[activeStation].waterLevel || '-' }}</span></div>
              <div class="popup-row"><span class="popup-label">流量</span><span class="popup-value">{{ stationList[activeStation].flow || '-' }} m³/s</span></div>
              <div class="popup-row"><span class="popup-label">孔数</span><span class="popup-value">{{ stationList[activeStation].holeCount || '-' }}</span></div>
              <div class="popup-row"><span class="popup-label">孔高</span><span class="popup-value">{{ stationList[activeStation].holeHeight || '-' }} m</span></div>
            </div>
            <div style="padding:6px 14px 10px;text-align:right;border-top:1px solid #eee">
              <a style="color:#409EFF;font-size:12px;text-decoration:none;cursor:pointer"
                 @click.stop="openHistoryChart(stationList[activeStation])">查看历史图表 &gt;</a>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup name="MonitorIndex">
import { getPortalData } from '@/api/slgc/zggc/index'
import { ref, onMounted, nextTick } from 'vue'
import { useArcGisMap } from '@/composables/useArcGisMap'

const {
  view,
  initMap,
  createGraphicsLayer,
  createPointMarker,
  createCircleSymbol,
  addBasinBoundary,
} = useArcGisMap()

const mapLoading = ref(true)
const stationList = ref([])
const activeStation = ref(null)

const STATION_IDX = '_stIdx'

const stationCoords = {
  太浦闸: [30.98, 120.56],
  望亭枢纽: [31.46, 120.42],
  常熟水利枢纽: [31.65, 120.75],
}

const DEFAULT_CENTER = [31.2, 120.6]
const DEFAULT_ZOOM = 9

function popupContent(st) {
  const name = st.name || st.stationName
  return `<div style="font-weight:600;font-size:14px;margin-bottom:6px">${name}</div>
<div>水位：${st.waterLevel || '-'}</div>
<div>流量：${st.flow || '-'} m³/s</div>
<div>孔数：${st.holeCount || '-'}</div>
<div>孔高：${st.holeHeight || '-'} m</div>
<div style="margin-top:8px;border-top:1px solid #eee;padding-top:6px;text-align:right">
  <a href="javascript:void(0)" style="color:#409EFF;font-size:12px;text-decoration:none"
     onclick="window.open('/slgc/hydrology?stnm=${encodeURIComponent(name)}', '_blank')">
    查看历史图表 &gt;
  </a>
</div>`
}

function openHistoryChart(st) {
  const name = st.name || st.stationName
  window.open(`/slgc/hydrology?stnm=${encodeURIComponent(name)}`, '_blank')
}

async function selectStation(i) {
  activeStation.value = i
  const st = stationList.value[i]
  if (!st) return
  const name = st.name || st.stationName
  const coords = stationCoords[name]
  if (!coords || !view.value) return
  await view.value.goTo({ center: coords, zoom: 11 })
  view.value.popup.open({
    title: name,
    content: popupContent(st),
    location: coords,
  })
}

async function renderMap() {
  await initMap('viewDiv', DEFAULT_CENTER, DEFAULT_ZOOM)
  await addBasinBoundary()

  const layer = createGraphicsLayer('stations')
  view.value.map.add(layer)

  stationList.value.forEach((st, i) => {
    const name = st.name || st.stationName
    const coords = stationCoords[name]
    if (!coords) return
    const [lat, lng] = coords
    const sym = createCircleSymbol('#409EFF', 16)
    const g = createPointMarker(lat, lng, sym, { [STATION_IDX]: i })
    layer.add(g)
  })

  view.value.on('click', (evt) => {
    view.value.hitTest(evt).then((res) => {
      const hit = res.results.find(
        (r) => r.graphic && r.graphic.attributes && r.graphic.attributes[STATION_IDX] !== undefined
      )
      if (!hit) return
      const idx = hit.graphic.attributes[STATION_IDX]
      activeStation.value = idx
      const st = stationList.value[idx]
      const name = st.name || st.stationName
      view.value.popup.open({
        title: name,
        content: popupContent(st),
        location: hit.graphic.geometry,
      })
    })
  })

  mapLoading.value = false
}

onMounted(() => {
  getPortalData().then(res => {
    stationList.value = res.data || []
    nextTick(() => { renderMap() })
  }).catch(() => {
    stationList.value = [
      { stcd: '69642', name: '太浦闸', stationName: '太浦闸', waterLevel: '3.43', flow: '723', holeCount: '30', holeHeight: '4.0' },
      { stcd: '69485', name: '望亭枢纽', stationName: '望亭枢纽', waterLevel: '3.46', flow: '474', holeCount: '24', holeHeight: '3.5' },
      { stcd: '69462', name: '常熟水利枢纽', stationName: '常熟水利枢纽', waterLevel: '3.45', flow: '0', holeCount: '16', holeHeight: '3.8' },
    ]
    nextTick(() => { renderMap() })
  })
})
</script>

<style scoped>
.monitor-page { height: calc(100vh - 100px); padding: 0; }
.monitor-layout { display: flex; height: 100%; gap: 0; }
.monitor-sidebar { width: 180px; flex-shrink: 0; background: #fff; border-right: 1px solid #e4e7ed; overflow-y: auto; padding: 12px 0; }
.sidebar-title { font-size: 15px; font-weight: 600; padding: 8px 16px; color: #303133; border-bottom: 1px solid #eee; margin-bottom: 8px; }
.sidebar-item { display: flex; align-items: center; gap: 8px; padding: 10px 16px; cursor: pointer; font-size: 14px; color: #606266; transition: all .2s; border-left: 3px solid transparent; }
.sidebar-item:hover { background: #f5f7fa; color: #409EFF; }
.sidebar-item.active { background: #ecf5ff; color: #409EFF; font-weight: 600; border-left-color: #409EFF; }
.station-dot { width: 8px; height: 8px; border-radius: 50%; flex-shrink: 0; }
.station-dot.online { background: #67C23A; }
.station-dot:not(.online) { background: #C0C4CC; }
.monitor-main { flex: 1; position: relative; }
.map-wrapper { height: 100%; width: 100%; position: relative; }
.map-container { height: 100%; width: 100%; }
.station-popup { position: absolute; bottom: 24px; left: 24px; width: 220px; background: #fff; border-radius: 8px; box-shadow: 0 4px 16px rgba(0,0,0,0.12); z-index: 1000; overflow: hidden; }
.popup-header { background: #409EFF; color: #fff; padding: 10px 14px; font-weight: 600; font-size: 14px; }
.popup-body { padding: 10px 14px; }
.popup-row { display: flex; justify-content: space-between; padding: 4px 0; font-size: 13px; }
.popup-label { color: #909399; }
.popup-value { color: #303133; font-weight: 500; }
</style>
