<template>
  <div class="zggc-page">
    <!-- 左侧内部面板：站点切换（不跳转路由） -->
    <div class="zggc-sidebar">
      <div
        v-for="(st, i) in stations"
        :key="st.stcd || i"
        :class="['sidebar-item', { active: activeIdx === i }]"
        @click="switchStation(i)"
      >
        <span class="station-dot" :class="{ online: st.status !== '离线' }"></span>
        <span>{{ st.name || st.stationName }}</span>
      </div>
    </div>

    <!-- 右侧地图 -->
    <div class="zggc-main">
      <div class="map-container" v-loading="mapLoading">
        <div id="zggcMap" class="map-inner"></div>
      </div>

      <!-- 站点详情弹窗 -->
      <el-dialog
        v-model="dialogVisible"
        :title="currentStation?.name || currentStation?.stationName || '站点详情'"
        width="860px"
        append-to-body
        :close-on-click-modal="true"
      >
        <el-tabs v-model="activeTab">
          <!-- 基本信息 -->
          <el-tab-pane label="基本信息" name="basic">
            <div v-if="stationDetail" class="detail-content">
              <div class="detail-section">
                <el-descriptions :column="2" border size="small">
                  <el-descriptions-item label="站名">{{ stationDetail.name || stationDetail.stationName }}</el-descriptions-item>
                  <el-descriptions-item label="行政区划">{{ stationDetail.area }}</el-descriptions-item>
                  <el-descriptions-item label="类型">{{ stationDetail.type }}</el-descriptions-item>
                  <el-descriptions-item label="所属水系">{{ stationDetail.riverSystem }}</el-descriptions-item>
                  <el-descriptions-item label="经度">{{ stationDetail.lng }}</el-descriptions-item>
                  <el-descriptions-item label="纬度">{{ stationDetail.lat }}</el-descriptions-item>
                </el-descriptions>
                <div v-if="stationDetail.description" class="station-desc">
                  <p>{{ stationDetail.description }}</p>
                </div>
              </div>
            </div>
          </el-tab-pane>

          <!-- 实时工情 -->
          <el-tab-pane label="实时工情" name="realtime">
            <div class="realtime-grid">
              <div class="metric-card">
                <div class="metric-label">水位(m)</div>
                <div class="metric-value">{{ currentStation?.waterLevel || '-' }}</div>
              </div>
              <div class="metric-card">
                <div class="metric-label">流量(m³/s)</div>
                <div class="metric-value">{{ currentStation?.flow || '-' }}</div>
              </div>
              <div class="metric-card">
                <div class="metric-label">孔数</div>
                <div class="metric-value">{{ currentStation?.holeCount || '-' }}</div>
              </div>
              <div class="metric-card">
                <div class="metric-label">孔高(m)</div>
                <div class="metric-value">{{ currentStation?.holeHeight || '-' }}</div>
              </div>
            </div>
          </el-tab-pane>

          <!-- 实时监控 -->
          <el-tab-pane label="实时监控" name="video">
            <div class="video-section">
              <el-empty v-if="!videoUrl" description="暂无视频监控" />
              <video v-else :src="videoUrl" controls style="width:100%;max-height:400px" />
            </div>
          </el-tab-pane>

          <!-- 文档资料 -->
          <el-tab-pane label="文档资料" name="docs">
            <div class="doc-section">
              <el-table :data="docList" stripe size="small" v-loading="docLoading">
                <el-table-column prop="fileName" label="文件名" min-width="200" />
                <el-table-column prop="createBy" label="上传人" width="100" />
                <el-table-column prop="createTime" label="上传时间" width="160" />
                <el-table-column label="操作" width="80" align="center">
                  <template #default="{ row }">
                    <el-button type="primary" link icon="Download" @click="downloadDoc(row)">下载</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-dialog>
    </div>
  </div>
</template>

<script setup name="ZggcMonitor">
import { ref, onMounted, onBeforeUnmount, onActivated, nextTick } from 'vue'
import { getPortalData, getStationDetail } from '@/api/slgc/zggc/index'
import { getDocFileList } from '@/api/slgc/doc/index'
import { fromLonLat } from 'ol/proj.js'
import { useMap } from '@/composables/useMap'

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

const mapLoading = ref(true)
const stations = ref([])
const activeIdx = ref(null)
const dialogVisible = ref(false)
const currentStation = ref(null)
const activeTab = ref('basic')
const stationDetail = ref(null)
const videoUrl = ref('')
const docList = ref([])
const docLoading = ref(false)

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

const DEFAULT_STATIONS = [
  { stcd: '69642', name: '太浦闸', stationName: '太浦闸', waterLevel: '3.43', flow: '723', holeCount: '30', holeHeight: '4.0', status: '正常' },
  { stcd: '69485', name: '望亭枢纽', stationName: '望亭枢纽', waterLevel: '3.46', flow: '474', holeCount: '24', holeHeight: '3.5', status: '正常' },
  { stcd: '69462', name: '常熟水利枢纽', stationName: '常熟水利枢纽', waterLevel: '3.45', flow: '0', holeCount: '16', holeHeight: '3.8', status: '正常' },
]

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

let stationLayer = null

// 面板切换：不跳转路由，只切换内容
function switchStation(i) {
  activeIdx.value = i
  const st = stations.value[i]
  if (!st) return
  currentStation.value = st
  dialogVisible.value = true
  activeTab.value = 'basic'

  const name = st.name || st.stationName
  const coords = STATION_COORDS[name]  // [纬度, 经度]
  if (coords && view.value) {
    view.value.animate({ center: fromLonLat([coords[1], coords[0]], 'EPSG:3857'), zoom: 11 })
  }
  loadStationDetail(st)
  loadDocs(st)
}

async function loadStationDetail(st) {
  stationDetail.value = null
  try {
    const res = await getStationDetail({ stcd: st.stcd, name: st.name || st.stationName })
    stationDetail.value = res.data || st
  } catch {
    stationDetail.value = st
  }
}

function loadDocs(st) {
  docLoading.value = true
  // 与旧版约定一致：附件通过 fileCate = 站点stcd 关联
  const stcd = st.stcd || ''
  getDocFileList({ fileCate: stcd }).then(res => {
    docList.value = res.rows || []
    docLoading.value = false
  }).catch(() => {
    docList.value = []
    docLoading.value = false
  })
}

function downloadDoc(row) {
  if (row.filePath) {
    window.open(row.filePath, '_blank')
  }
}

// 更新站点标记（数据刷新时调用）
function updateStationMarkers() {
  if (!stationLayer) return
  stationLayer.removeAll()
  stations.value.forEach((st, i) => {
    const name = st.name || st.stationName
    const coords = STATION_COORDS[name]
    if (!coords) return
    const [lat, lng] = coords
    const sym = createCircleSymbol('#086560', 16)
    const g = createPointMarker(lat, lng, sym, { _idx: i })
    stationLayer.add(g)
  })
}

async function renderMap() {
  try {
    await initMap('zggcMap', DEFAULT_CENTER, DEFAULT_ZOOM)
    await addBasinBoundary()
    stationLayer = createGraphicsLayer('zggc-stations')
    updateStationMarkers()

    // 图层诊断日志
    console.log('[ZggcMonitor] 站点标记数:', stationLayer._source.getFeatures().length)

    map.value.on('click', (evt) => {
      map.value.forEachFeatureAtPixel(evt.pixel, (feature) => {
        const idx = feature.get('_idx')
        if (idx === undefined || idx === null) return
        switchStation(idx)
        return true
      })
    })
  } catch (e) {
    console.error('[ZggcMonitor] 地图初始化失败:', e)
  } finally {
    // 无论成败都结束 loading，保证页面可用
    mapLoading.value = false
  }
}

// 带超时的接口请求（防止外部API挂起导致页面一直loading）
function fetchPortalData(timeout = 8000) {
  return Promise.race([
    getPortalData(),
    new Promise((_, reject) => setTimeout(() => reject(new Error('timeout')), timeout)),
  ])
}

onMounted(() => {
  // 1. 先使用默认站点立即渲染地图（不依赖外部接口）
  stations.value = [...DEFAULT_STATIONS]
  nextTick(() => { renderMap() })

  // 2. 异步获取真实站点数据，成功则刷新列表和标记
  fetchPortalData().then(res => {
    const data = res.data || []
    if (data.length > 0) {
      stations.value = data
      updateStationMarkers()
      // 若当前无选中站点，默认选中第一个
      if (activeIdx.value === null && stations.value.length > 0) {
        activeIdx.value = 0
      }
    }
  }).catch(() => {
    // 外部接口不可用时保持默认站点
  })
})

onBeforeUnmount(() => {
  stationLayer = null
})

// keep-alive 缓存重新激活时刷新地图尺寸（否则画布尺寸可能为0）
onActivated(() => {
  nextTick(() => {
    if (map.value) map.value.updateSize()
  })
})
</script>

<style scoped>
.zggc-page {
  display: flex;
  height: calc(100vh - 60px);
  overflow: hidden;
}
.zggc-sidebar {
  width: 150px;
  flex-shrink: 0;
  background: #fff;
  border-right: 1px solid #e4e7ed;
  padding: 8px 0;
  overflow-y: auto;
}
.sidebar-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 14px 16px;
  cursor: pointer;
  font-size: 14px;
  color: #606266;
  transition: all 0.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;
  background: #67c23a;
}
.zggc-main {
  flex: 1;
  position: relative;
  overflow: hidden;
}
.map-container {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}
.map-inner {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

/* 详情弹窗 */
.detail-content {
  padding: 8px 0;
}
.station-desc {
  margin-top: 16px;
  padding: 12px 16px;
  background: #f5f7fa;
  border-radius: 4px;
  color: #606266;
  font-size: 14px;
  line-height: 1.8;
}

/* 实时工情 */
.realtime-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
  padding: 16px 0;
}
.metric-card {
  background: #f5f7fa;
  border-radius: 6px;
  padding: 20px;
  text-align: center;
}
.metric-label {
  font-size: 13px;
  color: #909399;
  margin-bottom: 8px;
}
.metric-value {
  font-size: 28px;
  font-weight: 700;
  color: #303133;
}

/* 视频 */
.video-section {
  min-height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 文档 */
.doc-section {
  padding: 8px 0;
}
</style>
