<template>
  <div class="app-container">
    <el-row :gutter="12" style="height:100%">
      <!-- Left sidebar -->
      <el-col :span="5">
        <el-card shadow="never" style="height:100%">
          <template #header>
            <div class="card-header"><span>图层控制</span></div>
          </template>
          <div class="layer-list">
            <div v-for="layer in layers" :key="layer.key" class="layer-item">
              <el-checkbox v-model="layer.visible">{{ layer.label }}</el-checkbox>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- Map area -->
      <el-col :span="14">
        <el-card shadow="never" style="height:100%">
          <template #header>
            <div class="card-header">
              <span>GIS实时监测</span>
              <el-button size="small" icon="Refresh" @click="loadData">刷新</el-button>
            </div>
          </template>
          <div id="viewDiv" class="map-container"></div>
          <div class="coord-display" v-if="coord">
            经度: {{ coord.lng.toFixed(6) }} 纬度: {{ coord.lat.toFixed(6) }}
          </div>
        </el-card>
      </el-col>

      <!-- Right sidebar: search + table -->
      <el-col :span="5">
        <el-card shadow="never" class="side-card">
          <template #header>
            <div class="card-header"><span>站点查询</span></div>
          </template>
          <el-input v-model="keyword" placeholder="搜索站点名称" clearable size="small" prefix-icon="Search" @input="filterStations" />
        </el-card>
        <el-card shadow="never" class="side-card" style="margin-top:12px">
          <template #header>
            <div class="card-header"><span>站点数据</span></div>
          </template>
          <el-table :data="filteredStations" stripe size="small" max-height="420" v-loading="loading">
            <el-table-column prop="station" label="站名" min-width="100" show-overflow-tooltip />
            <el-table-column prop="waterLevel" label="水位(m)" width="80" />
            <el-table-column prop="flow" label="流量(m³/s)" width="90" />
            <el-table-column label="状态" width="60">
              <template #default="s">
                <el-tag :type="s.row.status==='正常'?'success':s.row.status==='超警'?'danger':'warning'" size="small">
                  {{ s.row.status }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup name="GisMonitor">
import { getMonitorList, getRealtimeTbadd } from '@/api/slgc/monitor/index'
import { getRealtimeData } from '@/api/slgc/hydrology/index'
import { useArcGisMap } from '@/composables/useArcGisMap'

const { proxy } = getCurrentInstance()

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

const loading = ref(true)
const keyword = ref('')
const stationList = ref([])
const filteredStations = ref([])
const warningList = ref([])

const CATEGORY_COLORS = {
  largeReservoir: '#409EFF',
  mediumReservoir: '#67C23A',
  smallReservoir: '#E6A23C',
  lakeGate: '#F56C6C',
  taipuGate: '#9B59B6',
  wangyuGate: '#1ABC9C',
  other: '#909399',
}

const layers = reactive([
  { key: 'largeReservoir', label: '大型水库', visible: true },
  { key: 'mediumReservoir', label: '中型水库', visible: true },
  { key: 'smallReservoir', label: '小型水库', visible: false },
  { key: 'lakeGate', label: '环湖口门', visible: false },
  { key: 'taipuGate', label: '太浦河口门', visible: false },
  { key: 'wangyuGate', label: '望虞河口门', visible: false },
  { key: 'other', label: '其他', visible: false },
  { key: 'externalWarning', label: '外部预警(水情)', visible: false },
  { key: 'arcgisLargeRes', label: 'ArcGIS-大型水库', visible: false },
  { key: 'arcgisMidRes', label: 'ArcGIS-中型水库', visible: false },
  { key: 'arcgisSmallRes', label: 'ArcGIS-小型水库', visible: false },
  { key: 'arcgisHuanhu', label: 'ArcGIS-环湖口门', visible: false },
  { key: 'arcgisTaipu', label: 'ArcGIS-太浦河口门', visible: false },
  { key: 'arcgisWangyu', label: 'ArcGIS-望虞河口门', visible: false },
])

const layerInstances = {}

const ARCGIS_SERVER_IDS = {
  arcgisLargeRes: 0,
  arcgisMidRes: 1,
  arcgisSmallRes: 2,
  arcgisHuanhu: 3,
  arcgisTaipu: 4,
  arcgisWangyu: 5,
}

const ARCGIS_COLORS = {
  arcgisLargeRes: '#F56C6C',
  arcgisMidRes: '#E6A23C',
  arcgisSmallRes: '#67C23A',
  arcgisHuanhu: '#409EFF',
  arcgisTaipu: '#9B59B6',
  arcgisWangyu: '#1ABC9C',
}

async function loadData() {
  loading.value = true
  try {
    const [monitorRes, tbaddRes] = await Promise.allSettled([
      getMonitorList(),
      getRealtimeTbadd(),
    ])

    const allStations = []

    if (monitorRes.status === 'fulfilled') {
      const rows = monitorRes.value.rows || monitorRes.value.data || []
      allStations.push(...rows.map(item => ({
        station: item.station || item.STNM || item.name || '-',
        waterLevel: item.waterLevel ?? item.W0 ?? item.w ?? '-',
        flow: item.flow ?? item.Q0 ?? item.q ?? '-',
        status: item.status || '正常',
        lng: Number(item.lng || item.LGTD || item.long || 0),
        lat: Number(item.lat || item.LTTD || item.lat || 0),
        category: item.category || item.type || '',
      })))
    }

    if (tbaddRes.status === 'fulfilled') {
      const tbaddData = tbaddRes.value.data || tbaddRes.value.rows || []
      if (Array.isArray(tbaddData)) {
        allStations.push(...tbaddData.map(item => ({
          station: item.STNM || item.station || '-',
          waterLevel: item.SW || item.waterLevel || '-',
          flow: item.YSL || item.flow || '-',
          status: '正常',
          lng: 0,
          lat: 0,
          category: 'other',
        })))
      }
    }

    stationList.value = allStations
    filterStations()
    renderMarkers()
  } catch {
    proxy.$modal.msgError('监测数据加载失败')
  } finally {
    loading.value = false
  }
}

function renderMarkers() {
  for (const layer of layers) {
    const key = layer.key
    if (layerInstances[key]) {
      layerInstances[key].removeAll()
    } else {
      const gl = createGraphicsLayer(key)
      layerInstances[key] = gl
      view.value.map.add(gl)
      gl.visible = layer.visible
    }
  }

  for (const station of stationList.value) {
    if (!station.lat || !station.lng) continue
    const cat = station.category
    const layerKey = layers.find(l => l.key === cat) ? cat : 'other'
    const color = CATEGORY_COLORS[layerKey] || '#909399'
    const symbol = createCircleSymbol(color, 14)
    const graphic = createPointMarker(station.lat, station.lng, symbol, {
      station: station.station,
      waterLevel: station.waterLevel,
      flow: station.flow,
      status: station.status,
      category: station.category,
    })
    const gl = layerInstances[layerKey]
    if (gl) {
      gl.add(graphic)
    }
  }
}

async function loadWarningData() {
  try {
    const res = await getRealtimeData()
    const rows = res.rows || res.data || []
    warningList.value = rows.map(item => ({
      station: item.STNM || item.stnm || item.name || '-',
      waterLevel: item.Z ?? item.z ?? '-',
      flow: item.Q ?? item.q ?? '-',
      status: item.status || '超警',
      lng: Number(item.LGTD || item.lng || item.long || 0),
      lat: Number(item.LTTD || item.lat || item.latitude || 0),
      category: 'externalWarning',
    })).filter(s => s.lat && s.lng)

    renderWarningMarkers()
  } catch {
    // external data — silent fail
  }
}

function renderWarningMarkers() {
  const key = 'externalWarning'
  if (layerInstances[key]) {
    layerInstances[key].removeAll()
  } else {
    const gl = createGraphicsLayer(key)
    layerInstances[key] = gl
    view.value.map.add(gl)
    gl.visible = false
  }

  const symbol = createCircleSymbol('#F56C6C', 18)
  for (const station of warningList.value) {
    const graphic = createPointMarker(station.lat, station.lng, symbol, {
      station: station.station,
      waterLevel: station.waterLevel,
      flow: station.flow,
      status: station.status,
      category: 'externalWarning',
    })
    layerInstances[key].add(graphic)
  }
}

async function loadArcGisLayer(layerKey, mapServerId) {
  const url = `http://10.8.4.128/server/rest/services/OneMap/TH_SLGC/MapServer/${mapServerId}/query?f=json&where=1%3D1&returnGeometry=true&outFields=*&outSR=4490&resultOffset=0&resultRecordCount=500`
  try {
    const res = await fetch(url)
    const data = await res.json()
    if (!data.features || !data.features.length) return

    const color = ARCGIS_COLORS[layerKey] || '#909399'
    if (layerInstances[layerKey]) {
      layerInstances[layerKey].removeAll()
    } else {
      const gl = createGraphicsLayer(layerKey)
      layerInstances[layerKey] = gl
      view.value.map.add(gl)
    }

    const gl = layerInstances[layerKey]
    const symbol = createCircleSymbol(color, 14)
    for (const feat of data.features) {
      const attrs = feat.attributes || {}
      const geom = feat.geometry
      if (!geom) continue
      const graphic = createPointMarker(geom.y, geom.x, symbol, {
        ...attrs,
        _arcgis: true,
        _layerKey: layerKey,
      })
      gl.add(graphic)
    }
  } catch {
    proxy.$modal.msgError('ArcGIS图层加载失败')
  }
}

function constructArcGisPopupContent(attrs) {
  const fields = ['水库名称', '水库所在位置', '水库类型', '工程等别', '工程规模', '集雨面积', '总库容', '正常蓄水位']
  let html = ''
  for (const f of fields) {
    if (attrs[f] !== undefined && attrs[f] !== null && attrs[f] !== '') {
      html += `${f}: ${attrs[f]}<br/>`
    }
  }
  return html
}

function filterStations() {
  const kw = keyword.value.trim().toLowerCase()
  let list = [...stationList.value]
  const warningVisible = layers.find(l => l.key === 'externalWarning')?.visible
  if (warningVisible) {
    list = list.concat(warningList.value)
  }
  filteredStations.value = list.filter(s => {
    const matchKw = !kw || (s.station && s.station.toLowerCase().includes(kw))
    return matchKw
  })
}

watch(
  () => layers.map(l => l.visible),
  () => {
    for (const l of layers) {
      const instance = layerInstances[l.key]
      if (l.key.startsWith('arcgis')) {
        if (l.visible && !instance) {
          loadArcGisLayer(l.key, ARCGIS_SERVER_IDS[l.key])
        } else if (!l.visible && instance) {
          view.value.map.remove(instance)
          delete layerInstances[l.key]
        } else if (instance) {
          instance.visible = l.visible
        }
      } else {
        if (instance) {
          instance.visible = l.visible
        }
      }
    }
    filterStations()
  }
)

function setupClickHandler() {
  if (!view.value) return
  view.value.on('click', (event) => {
    view.value.hitTest(event).then(response => {
      const result = response.results.find(r => r.graphic)
      if (!result) return
      const graphic = result.graphic
      const attrs = graphic.attributes
      if (!attrs) return
      if (attrs._arcgis) {
        const title = `ArcGIS: ${attrs['水库名称'] || '-'}`
        const content = constructArcGisPopupContent(attrs)
        openPopup(view.value, title, content, graphic.geometry)
      } else {
        openPopup(
          view.value,
          `站点: ${attrs.station || '-'}`,
          `水位: ${attrs.waterLevel || '-'}m<br/>流量: ${attrs.flow || '-'}m³/s<br/>状态: ${attrs.status || '-'}`,
          graphic.geometry
        )
      }
    })
  })
}

onMounted(async () => {
  await initMap('viewDiv', [32.0, 119.5], 8)
  setupClickHandler()
  loadData()
  loadWarningData()
})
</script>

<style scoped>
.card-header { font-weight:600;font-size:16px;display:flex;justify-content:space-between;align-items:center; }
.map-container { width:100%;height:calc(100vh - 300px);min-height:400px;border-radius:6px;overflow:hidden; }
.coord-display { margin-top:8px;font-size:12px;color:#999; }
.layer-list { display:flex;flex-direction:column;gap:8px; }
.layer-item { padding:4px 0;border-bottom:1px solid #f0f0f0; }
.layer-item:last-child { border-bottom:none; }
.side-card { min-height:auto; }
</style>
