<template>
  <div class="app-container">
    <el-row :gutter="12" style="height:100%">
      <!-- Left panel: Layer Control -->
      <el-col :span="5">
        <el-card shadow="never" style="height:100%">
          <template #header>
            <div class="card-header">
              <span>图层控制</span>
              <el-button size="small" icon="Refresh" @click="refreshData">刷新</el-button>
            </div>
          </template>
          <div class="layer-list">
            <div v-for="zone in zones" :key="zone.key" class="layer-item">
              <el-checkbox v-model="zone.visible" @change="onZoneToggle">
                <span class="zone-dot" :style="{ background: zone.color }"></span>
                {{ zone.label }}
              </el-checkbox>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- Center panel: Map -->
      <el-col :span="14">
        <el-card shadow="never" style="height:100%">
          <template #header>
            <div class="card-header">
              <span>GIS水质水文监测</span>
            </div>
          </template>
          <div id="viewDiv" class="map-container"></div>
          <div class="coord-bar" v-if="coord">
            经度: {{ coord.lng.toFixed(6) }} &nbsp;|&nbsp; 纬度: {{ coord.lat.toFixed(6) }}
          </div>
        </el-card>
      </el-col>

      <!-- Right panel: 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="onSearch"
          />
        </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="tableData"
            stripe
            size="small"
            max-height="calc(100vh - 400px)"
            v-loading="loading"
            style="width:100%"
          >
            <el-table-column prop="name" label="站名" min-width="90" show-overflow-tooltip />
            <el-table-column prop="level" label="水位(m)" width="75" />
            <el-table-column prop="flow" label="流量(m³/s)" width="85" />
            <el-table-column prop="ph" label="pH" width="55" />
            <el-table-column prop="nh3n" label="NH₃-N(mg/L)" width="95" />
            <el-table-column prop="cod" label="COD(mg/L)" width="80" />
            <el-table-column label="状态" width="65">
              <template #default="scope">
                <el-tag
                  :type="scope.row.status === '正常' ? 'success' : 'danger'"
                  size="small"
                >
                  {{ scope.row.status }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup name="GisWater">
import { getStationList, getWaterQualityData } from '@/api/slgc/hydrology/index'
import { getSyqStation } from '@/api/slgc/syq/index'
import { getAllSWS } from '@/api/slgc/waterSource/index'
import { ZONE_CONFIG, ZONE_COLORS, ZONE_LABELS } from '@/utils/gis-config'
import { useArcGisMap } from '@/composables/useArcGisMap'

const {
  map, view, coord,
  initMap: initArcGisMap, ensureModules,
  createGraphicsLayer, createPointMarker, createCircleSymbol,
  openPopup, destroy, addBasinBoundary,
} = useArcGisMap()

const loading = ref(false)
const keyword = ref('')
const stations = ref([])
const tableData = ref([])

const zones = reactive(
  ZONE_CONFIG.map(z => ({ ...z, visible: true, layer: null }))
)



function getFlowRadius(flow) {
  if (flow === 0) return 6
  if (flow < 50) return 8
  if (flow < 100) return 10
  return 14
}

function buildPopupContent(s, zoneCfg) {
  return `<div style="min-width:210px">
    <div style="font-size:15px;font-weight:700;margin-bottom:4px">${s.name}</div>
    <div style="font-size:12px;color:#666;margin-bottom:6px">
      <span style="display:inline-block;width:8px;height:8px;border-radius:50%;background:${zoneCfg?.color || '#409EFF'};margin-right:4px;vertical-align:middle"></span>
      ${ZONE_LABELS[s.zone] || s.zone}
    </div>
    <table style="font-size:12px;width:100%;border-collapse:collapse">
      <tr><td style="padding:2px 4px;color:#888">水位</td><td style="padding:2px 4px;font-weight:600">${s.level} m</td></tr>
      <tr><td style="padding:2px 4px;color:#888">流量</td><td style="padding:2px 4px;font-weight:600">${s.flow} m³/s</td></tr>
      <tr><td style="padding:2px 4px;color:#888">pH</td><td style="padding:2px 4px;font-weight:600">${s.ph}</td></tr>
      <tr><td style="padding:2px 4px;color:#888">NH₃-N</td><td style="padding:2px 4px;font-weight:600">${s.nh3n} mg/L</td></tr>
      <tr><td style="padding:2px 4px;color:#888">COD</td><td style="padding:2px 4px;font-weight:600">${s.cod} mg/L</td></tr>
      <tr><td style="padding:2px 4px;color:#888">状态</td><td style="padding:2px 4px;font-weight:600">${s.status}</td></tr>
    </table>
    <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(s.name)}', '_blank')">
        查看历史图表 &gt;
      </a>
    </div>
  </div>`
}

function renderMarkers() {
  zones.forEach(z => {
    if (z.layer) {
      map.value.remove(z.layer)
      z.layer = null
    }
  })

  const grouped = {}
  stations.value.forEach(s => {
    if (!grouped[s.zone]) grouped[s.zone] = []
    grouped[s.zone].push(s)
  })

  zones.forEach(z => {
    const items = grouped[z.key] || []
    if (!items.length) return

    const layer = createGraphicsLayer(z.key)
    items.forEach(s => {
      const flow = s.flow === '-' ? 0 : Number(s.flow)
      const radius = getFlowRadius(flow)
      const symbol = createCircleSymbol(z.color, radius)
      const graphic = createPointMarker(s.lat, s.lng, symbol, {
        name: s.name,
        zone: z.key,
        level: s.level,
        flow: s.flow,
        ph: s.ph,
        nh3n: s.nh3n,
        cod: s.cod,
        status: s.status,
      })
      layer.add(graphic)
    })

    map.value.add(layer)
    if (!z.visible) {
      layer.visible = false
    }
    z.layer = layer
  })
}

function onZoneToggle() {
  zones.forEach(z => {
    if (!z.layer) return
    z.layer.visible = z.visible
  })
  updateTable()
}

function updateTable() {
  const kw = keyword.value.trim().toLowerCase()
  const visibleKeys = zones.filter(z => z.visible).map(z => z.key)
  tableData.value = stations.value.filter(s => {
    if (!visibleKeys.includes(s.zone)) return false
    if (kw && !s.name.toLowerCase().includes(kw)) return false
    return true
  })
}

function onSearch() {
  updateTable()
}

async function initMap() {
  await ensureModules()
  const result = await initArcGisMap('viewDiv', [31.2, 120.8], 9)
  await addBasinBoundary()

  result.view.popup.autoOpenEnabled = false

  result.view.on('click', (event) => {
    result.view.hitTest(event).then(response => {
      if (response.results.length > 0) {
        const graphic = response.results[0].graphic
        if (graphic && graphic.attributes && graphic.attributes.name) {
          const attrs = graphic.attributes
          const zoneCfg = zones.find(z => z.key === attrs.zone)
          const content = buildPopupContent(attrs, zoneCfg)
          openPopup(result.view, attrs.name, content, graphic.geometry)
        }
      }
    })
  })

  if (stations.value.length) {
    renderMarkers()
  }
}

function loadData() {
  loading.value = true

  Promise.all([
    getStationList().then(res => res.rows || res.data || []).catch(() => []),
    getWaterQualityData().then(res => res.rows || res.data?.list || res.data || []).catch(() => []),
    getSyqStation().then(res => res.rows || res.data || []).catch(() => []),
    getAllSWS({ type: '' }).then(res => res.rows || res.data || []).catch(() => []),
  ]).then(([stationRows, , syqRows, swsRows]) => {
    const allRows = [...stationRows, ...syqRows, ...swsRows]
    if (allRows.length > 0) {
      stations.value = allRows.map(item => ({
        name: item.station || item.STNM || item.name || '-',
        zone: item.zone || item.category || 'tph',
        lng: Number(item.lng || item.LGTD || item.long || 0),
        lat: Number(item.lat || item.LTTD || item.latitude || 0),
        level: item.level ?? item.waterLevel ?? item.W0 ?? '-',
        flow: item.flow ?? item.Q0 ?? '-',
        ph: item.ph ?? item.PH ?? '-',
        nh3n: item.nh3n ?? item.NH3N ?? '-',
        cod: item.cod ?? item.COD ?? '-',
        status: item.status || '正常',
      })).filter(s => s.lng && s.lat)
    }
    if (map.value) renderMarkers()
    updateTable()
  }).finally(() => {
    loading.value = false
  })
}

function refreshData() {
  loadData()
}

onMounted(() => {
  initMap()
  loadData()
})
</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-bar {
  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;
}

.zone-dot {
  display: inline-block;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  margin-right: 6px;
  vertical-align: middle;
}

.side-card {
  min-height: auto;
}
</style>
