<template>
  <div class="app-container portal-page">
    <!-- Top bar -->
    <div class="portal-header">
      <div class="portal-title">
        <el-icon :size="24"><Monitor /></el-icon>
        <span>工程实时监控指挥中心</span>
      </div>
      <div class="portal-actions">
        <el-button type="primary" :icon="VideoCamera" @click="goVideoAll">视频监控</el-button>
        <el-button :icon="Folder" @click="goFileAll">工程附件</el-button>
        <el-button :icon="Refresh" @click="handleRefresh" :loading="refreshing">刷新</el-button>
      </div>
    </div>

    <!-- Station cards -->
    <div class="station-cards" v-loading="loading">
      <el-row :gutter="16">
        <el-col :span="8" v-for="st in stations" :key="st.stcd">
          <el-card shadow="never" class="station-card">
            <template #header>
              <div class="station-card-header" :style="{ background: st.status === '超警' ? '#F56C6C' : '#086560' }">
                <span class="station-name">{{ st.name }}</span>
                <el-tag :type="st.status === '超警' ? 'danger' : 'success'" size="small" effect="dark" class="status-tag">
                  {{ st.status }}
                </el-tag>
              </div>
            </template>
            <div class="station-metrics">
              <div class="metric-row">
                <div class="metric-item">
                  <div class="metric-label">孔数</div>
                  <div class="metric-value">{{ st.holeCount }}</div>
                </div>
                <div class="metric-item">
                  <div class="metric-label">孔高(m)</div>
                  <div class="metric-value">{{ st.holeHeight }}</div>
                </div>
              </div>
              <div class="metric-row">
                <div class="metric-item" :class="st.waterLevelWarn ? 'warn' : ''">
                  <div class="metric-label">
                    水位(m)
                    <el-tooltip v-if="st.waterLevelWarn" content="超警戒水位" placement="top">
                      <el-icon style="margin-left:2px;color:#F56C6C"><WarningFilled /></el-icon>
                    </el-tooltip>
                  </div>
                  <div class="metric-value">
                    {{ st.waterLevel }}
                    <span v-if="st.waterLevelWarn" class="warn-dot" />
                  </div>
                </div>
                <div class="metric-item">
                  <div class="metric-label">流量(m³/s)</div>
                  <div class="metric-value">{{ st.flow }}</div>
                </div>
              </div>
              <el-divider style="margin:8px 0" />
              <div class="year-water">
                <div class="year-item">
                  <span class="year-label">今年引水量</span>
                  <span class="year-value">{{ st.yearEnterWater }}</span>
                  <span class="year-unit">亿m³</span>
                </div>
                <div class="year-item">
                  <span class="year-label">今年排水量</span>
                  <span class="year-value">{{ st.yearCommWater }}</span>
                  <span class="year-unit">亿m³</span>
                </div>
              </div>
              <el-divider style="margin:8px 0" />
              <div class="dispatch-order">
                <el-icon><Notification /></el-icon>
                <span class="dispatch-label">当前调度令：</span>
                <span class="dispatch-value">{{ st.dispatchOrder }}</span>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- ArcGIS map -->
    <div class="map-section">
      <el-card shadow="never" class="map-card">
        <template #header>
          <div class="card-header">
            <span>站址分布地图</span>
            <el-space>
              <el-tag size="small" type="success">● 正常</el-tag>
              <el-tag size="small" type="danger">● 超警</el-tag>
            </el-space>
          </div>
        </template>
        <div id="viewDiv" class="map-container" />
      </el-card>
    </div>
  </div>
</template>

<script setup name="ZggcPortal">
import { Monitor, VideoCamera, Folder, Refresh, WarningFilled, Notification } from '@element-plus/icons-vue'
import { getPortalData } from '@/api/slgc/zggc/index'
import { useArcGisMap } from '@/composables/useArcGisMap'

const router = useRouter()

const loading = ref(true)
const refreshing = ref(false)
const stations = ref([])

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

let graphicsLayer = null
let currentHitGraphic = null

const warningLevels = {
  '69642': 3.8,
  '69643': 3.6,
  '69644': 3.5,
}

const stationCoords = {
  '太浦闸': [31.0, 120.7],
  '望亭枢纽': [31.45, 120.45],
  '常熟水利枢纽': [31.65, 120.7],
}

const demoData = [
  { stcd: '69642', name: '太浦闸', data: [{ upz: '3.5', tgtq: '120', gtopNum: '30', goptHgt: '4.0', nowOrder: '开闸放水', yearEnterWater: '1.2', yearCommWater: '0.8' }] },
  { stcd: '69643', name: '望亭枢纽', data: [{ upz: '3.2', tgtq: '85', gtopNum: '22', goptHgt: '3.5', nowOrder: '正常调度', yearEnterWater: '0.9', yearCommWater: '0.5' }] },
  { stcd: '69644', name: '常熟水利枢纽', data: [{ upz: '3.8', tgtq: '150', gtopNum: '18', goptHgt: '3.8', nowOrder: '排水调度', yearEnterWater: '0.6', yearCommWater: '1.1' }] },
]

function mapStation(s) {
  const d = (s.data && s.data[0]) || {}
  const wl = parseFloat(d.upz || d.waterLevel)
  const warnLevel = warningLevels[s.stcd]
  return {
    name: s.name,
    stcd: s.stcd,
    holeCount: d.gtopNum || d.holeCount || '-',
    holeHeight: d.goptHgt || d.holeHeight || '-',
    waterLevel: wl || d.upz || d.waterLevel || '-',
    flow: d.tgtq || d.flow || '-',
    dispatchOrder: d.nowOrder || d.dispatchOrder || '-',
    yearEnterWater: d.yearEnterWater || d.yrEnter || '-',
    yearCommWater: d.yearCommWater || d.yrComm || '-',
    waterLevelWarn: !isNaN(wl) && !isNaN(warnLevel) ? wl > warnLevel : false,
    status: (!isNaN(wl) && !isNaN(warnLevel) && wl > warnLevel) ? '超警' : '正常',
  }
}

function loadPortalData() {
  loading.value = true
  return getPortalData().then(res => {
    const data = res.data || res.rows || res
    stations.value = (Array.isArray(data) ? data : []).map(mapStation)
  }).catch(() => {
    stations.value = demoData.map(mapStation)
  }).finally(() => {
    loading.value = false
  })
}

function buildPopupContent(st) {
  const isWarn = st.waterLevelWarn
  return `
    <div style="min-width:180px">
      <div style="font-size:15px;font-weight:600;margin-bottom:6px">${st.name}</div>
      <table style="font-size:13px;line-height:1.8">
        <tr><td style="padding-right:12px;color:#909399">水位</td><td><b>${st.waterLevel}</b> m</td></tr>
        <tr><td style="padding-right:12px;color:#909399">流量</td><td><b>${st.flow}</b> m³/s</td></tr>
        <tr><td style="padding-right:12px;color:#909399">孔数</td><td><b>${st.holeCount}</b></td></tr>
        <tr><td style="padding-right:12px;color:#909399">孔高</td><td><b>${st.holeHeight}</b> m</td></tr>
        <tr><td style="padding-right:12px;color:#909399">调度令</td><td>${st.dispatchOrder}</td></tr>
        <tr><td style="padding-right:12px;color:#909399">状态</td><td style="color:${isWarn ? '#F56C6C' : '#67C23A'};font-weight:600">${st.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(st.name)}', '_blank')">
          查看历史图表 &gt;
        </a>
      </div>
    </div>
  `
}

function updateMapMarkers() {
  if (!graphicsLayer || !view.value) return
  graphicsLayer.removeAll()
  stations.value.forEach(st => {
    const coords = stationCoords[st.name]
    if (!coords) return
    const isWarn = st.waterLevelWarn
    const color = isWarn ? '#F56C6C' : '#67C23A'
    const symbol = createCircleSymbol(color, 12)
    const graphic = createPointMarker(coords[0], coords[1], symbol, {
      _popupTitle: st.name,
      _popupContent: buildPopupContent(st),
      _stcd: st.stcd,
    })
    graphicsLayer.add(graphic)
  })
}

function setupHover() {
  if (!view.value) return
  view.value.on('pointer-move', (event) => {
    view.value.hitTest(event).then(response => {
      const results = response.results.filter(r =>
        r.graphic && r.graphic.layer && r.graphic.layer.id === 'portal-markers'
      )
      if (results.length > 0) {
        const graphic = results[0].graphic
        if (graphic !== currentHitGraphic) {
          currentHitGraphic = graphic
          const attrs = graphic.attributes
          view.value.popup.open({
            title: attrs._popupTitle,
            content: attrs._popupContent,
            location: graphic.geometry,
          })
        }
      } else if (currentHitGraphic) {
        currentHitGraphic = null
        view.value.popup.close()
      }
    })
  })
}

async function initPortalMap() {
  await initMap('viewDiv', [31.4, 120.55], 10)
  await addBasinBoundary()
  graphicsLayer = createGraphicsLayer('portal-markers')
  map.value.add(graphicsLayer)
  updateMapMarkers()
  setTimeout(() => view.value.resize(), 300)
  setupHover()
}

function goVideoAll() {
  router.push({ path: '/slgc/zggc/video', query: { name: '指挥中心' } })
}

function goFileAll() {
  router.push({ path: '/slgc/zggc/file', query: { stcd: '0' } })
}

function handleRefresh() {
  refreshing.value = true
  loadPortalData().then(() => {
    updateMapMarkers()
    ElMessage.success('数据已刷新')
  }).finally(() => {
    refreshing.value = false
  })
}

onMounted(() => {
  loadPortalData()
  initPortalMap()
})
</script>

<style scoped>
.portal-page {
  height: calc(100vh - 120px);
  display: flex;
  flex-direction: column;
  gap: 12px;
  overflow: hidden;
}

.card-header {
  font-weight: 600;
  font-size: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/* Portal header */
.portal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #fff;
  border-radius: 6px;
  padding: 12px 20px;
  box-shadow: 0 1px 4px rgba(0,0,0,0.06);
  flex-shrink: 0;
}

.portal-title {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 18px;
  font-weight: 700;
  color: #303133;
}

.portal-actions {
  display: flex;
  gap: 8px;
}

/* Station cards area */
.station-cards {
  flex-shrink: 0;
  min-height: 0;
}

.station-card {
  border-radius: 6px;
  overflow: hidden;
}

.station-card :deep(.el-card__header) {
  padding: 0;
  border-bottom: none;
}

.station-card :deep(.el-card__body) {
  padding: 12px 16px 16px;
}

.station-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 16px;
  color: #fff;
}

.station-name {
  font-size: 15px;
  font-weight: 700;
  letter-spacing: 1px;
}

.status-tag {
  flex-shrink: 0;
}

.station-metrics {
  font-size: 13px;
}

.metric-row {
  display: flex;
  gap: 12px;
  margin-bottom: 6px;
}

.metric-item {
  flex: 1;
  background: #f8f9fb;
  border-radius: 4px;
  padding: 8px 10px;
  text-align: center;
  transition: background 0.2s;
}

.metric-item.warn {
  background: #fef0f0;
}

.metric-label {
  font-size: 12px;
  color: #909399;
  margin-bottom: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.metric-value {
  font-size: 22px;
  font-weight: 700;
  color: #303133;
  line-height: 1.2;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
}

.metric-item.warn .metric-value {
  color: #F56C6C;
}

.warn-dot {
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #F56C6C;
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.3; }
}

.year-water {
  display: flex;
  gap: 12px;
}

.year-item {
  flex: 1;
  display: flex;
  align-items: baseline;
  gap: 4px;
  padding: 4px 0;
}

.year-label {
  font-size: 12px;
  color: #909399;
}

.year-value {
  font-size: 16px;
  font-weight: 700;
  color: #086560;
}

.year-unit {
  font-size: 11px;
  color: #909399;
}

.dispatch-order {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 2px 0;
  color: #086560;
  font-size: 13px;
}

.dispatch-label {
  color: #909399;
  font-weight: 400;
}

.dispatch-value {
  font-weight: 600;
}

/* Map section */
.map-section {
  flex: 1;
  min-height: 300px;
}

.map-card {
  height: 100%;
}

.map-card :deep(.el-card__body) {
  height: calc(100% - 50px);
  padding: 0;
}

.map-container {
  width: 100%;
  height: 100%;
  border-radius: 0 0 6px 6px;
  overflow: hidden;
}

#viewDiv {
  width: 100%;
  height: 100%;
}
</style>
