<template>
  <div class="gwyxqk-screen">
    <!-- ==================== 顶部标题栏 ==================== -->
    <div class="screen-header">
      <div class="header-left">
        <span class="header-time">{{ currentDateTime }}</span>
      </div>
      <div class="header-center">
        <h1 class="header-title">管网运行情况GIS一张图</h1>
      </div>
      <div class="header-right">
      </div>
    </div>

    <!-- ==================== 主体三栏布局 ==================== -->
    <div class="screen-body">
      <!-- ========== 左侧面板 ========== -->
      <div class="panel-left">
        <!-- 管网概况 -->
        <div class="panel-box">
          <div class="panel-title">
            <span class="title-icon">▶</span> 管网概况
          </div>
          <div class="stats-cards">
            <div class="stat-card">
              <div class="stat-val">{{ overviewStats.total }}</div>
              <div class="stat-label">监测点总数</div>
            </div>
            <div class="stat-card">
              <div class="stat-val green">{{ overviewStats.normal }}</div>
              <div class="stat-label">正常运行</div>
            </div>
            <div class="stat-card">
              <div class="stat-val orange">{{ overviewStats.alarm }}</div>
              <div class="stat-label">异常报警</div>
            </div>
            <div class="stat-card">
              <div class="stat-val gray">{{ overviewStats.offline }}</div>
              <div class="stat-label">离线设备</div>
            </div>
          </div>
          <div class="pie-chart-wrapper">
            <div id="gwyxqkPieChart" class="chart-area"></div>
            <div class="pie-legend">
              <div class="legend-item" v-for="(item, i) in pieData" :key="i">
                <span class="legend-dot" :style="{ background: item.color }"></span>
                <span class="legend-label">{{ item.name }}</span>
                <span class="legend-value">{{ item.value }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 实时数据表 -->
        <div class="panel-box" style="flex: 1;">
          <div class="panel-title">
            <span class="title-icon">▶</span> 实时数据
            <span class="refresh-time">刷新: {{ refreshTime }}</span>
          </div>
          <div class="realtime-table-wrap">
            <table class="dark-table">
              <thead>
                <tr>
                  <th>监测点名称</th>
                  <th>流量(m³/h)</th>
                  <th>液位(m)</th>
                  <th>状态</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(row, i) in realtimeData" :key="i">
                  <td :title="row.name">{{ row.name }}</td>
                  <td>{{ row.flow }}</td>
                  <td>{{ row.level }}</td>
                  <td>
                    <span :class="'status-tag status-' + row.statusClass">{{ row.status }}</span>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>

      <!-- ========== 中间地图区域 ========== -->
      <div class="panel-center">
        <div class="map-search">
          <input type="text" placeholder="输入监测点名称" class="search-input" />
          <span class="search-icon">🔍</span>
        </div>
        <div id="gwyxqkMap" class="map-container"></div>
      </div>

      <!-- ========== 右侧面板 ========== -->
      <div class="panel-right">
        <!-- 监测曲线 -->
        <div class="panel-box">
          <div class="panel-title">
            <span class="title-icon">▶</span> 监测曲线
          </div>
          <div class="curve-tabs">
            <span
              v-for="tab in curveTabs"
              :key="tab.value"
              :class="['curve-tab', { active: activeCurveTab === tab.value }]"
              @click="activeCurveTab = tab.value"
            >{{ tab.label }}</span>
          </div>
          <div id="gwyxqkLineChart" class="chart-area-sm"></div>
        </div>

        <!-- 流量统计 -->
        <div class="panel-box">
          <div class="panel-title">
            <span class="title-icon">▶</span> 流量统计
          </div>
          <div id="gwyxqkBarChart" class="chart-area-sm"></div>
        </div>

        <!-- 报警信息 -->
        <div class="panel-box">
          <div class="panel-title">
            <span class="title-icon">▶</span> 报警信息
          </div>
          <div class="alert-stats">
            <div class="alert-stat-card">
              <div class="alert-stat-val">{{ alarmStats.total }}</div>
              <div class="alert-stat-label">报警总数</div>
            </div>
            <div class="alert-stat-card">
              <div class="alert-stat-val green">{{ alarmStats.handled }}</div>
              <div class="alert-stat-label">已处理</div>
            </div>
            <div class="alert-stat-card">
              <div class="alert-stat-val red">{{ alarmStats.unhandled }}</div>
              <div class="alert-stat-label">未处理</div>
            </div>
          </div>
          <div class="alert-table-wrap">
            <table class="dark-table">
              <thead>
                <tr>
                  <th>序号</th>
                  <th>监测点</th>
                  <th>时间</th>
                  <th>类型</th>
                  <th>状态</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(row, i) in alarmList" :key="i">
                  <td>{{ i + 1 }}</td>
                  <td :title="row.point">{{ row.point }}</td>
                  <td>{{ row.time }}</td>
                  <td>{{ row.type }}</td>
                  <td>
                    <span :class="'status-tag status-' + row.handleClass">{{ row.handleStatus }}</span>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup name="Gwyxqk">
import { ref, reactive, onMounted, onUnmounted, watch } from 'vue'
import * as echarts from 'echarts'
import locationIcon from '@/assets/images/location.png'
import { getPipeNetworkPage, getEquipmentPage } from '@/api/drainage'

// ==================== 实时时间 ====================
const currentDateTime = ref('')
let timer = null

function updateTime() {
  const now = new Date()
  const pad = n => String(n).padStart(2, '0')
  const weekDays = ['日', '一', '二', '三', '四', '五', '六']
  currentDateTime.value = `${now.getFullYear()}/${pad(now.getMonth() + 1)}/${pad(now.getDate())} ${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())} 星期${weekDays[now.getDay()]}`
}

// ==================== 刷新时间 ====================
const refreshTime = ref('')
function updateRefreshTime() {
  const now = new Date()
  const pad = n => String(n).padStart(2, '0')
  refreshTime.value = `${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}`
}

// ==================== 管网概况（从API数据计算）====================
const overviewStats = reactive({ total: 0, normal: 0, alarm: 0, offline: 0 })

const pieData = ref([
  { name: '正常运行', value: 0, color: '#67c23a' },
  { name: '预警', value: 0, color: '#e6a23c' },
  { name: '报警', value: 0, color: '#f56c6c' },
  { name: '离线', value: 0, color: '#909399' }
])

// ==================== 实时数据 ====================
// TODO: 后端暂无实时流量/液位监测数据API，以下为mock数据，待API就绪后替换
const realtimeData = ref([
  { name: '沅陵大道1号闸口', flow: 125.6, level: 0.85, status: '正常', statusClass: 'normal' },
  { name: '城北路段排水井A3', flow: 89.3, level: 1.42, status: '正常', statusClass: 'normal' },
  { name: '河西大道排水管道B7', flow: 210.5, level: 3.15, status: '报警', statusClass: 'alarm' },
  { name: '人民路地下管网C2', flow: 178.9, level: 2.68, status: '预警', statusClass: 'warning' },
  { name: '南环路排水管道D3', flow: 56.2, level: 0.52, status: '正常', statusClass: 'normal' },
  { name: '北环路排水泵站出口', flow: 195.4, level: 2.35, status: '预警', statusClass: 'warning' },
  { name: '西环路河道排放口', flow: 302.1, level: 4.82, status: '报警', statusClass: 'alarm' },
  { name: '东环路市政大楼段', flow: 78.5, level: 0.68, status: '正常', statusClass: 'normal' },
  { name: '开发区管委会路段', flow: 245.7, level: 3.56, status: '报警', statusClass: 'alarm' },
  { name: '城北二号排水井A7', flow: 112.3, level: 1.05, status: '正常', statusClass: 'normal' },
  { name: '白羊坪村监测点', flow: 45.8, level: 0.35, status: '离线', statusClass: 'offline' },
  { name: '杜家山监测站', flow: 92.1, level: 1.18, status: '正常', statusClass: 'normal' }
])

// ==================== 监测曲线 ====================
const curveTabs = [
  { label: '24小时', value: '24h' },
  { label: '7天', value: '7d' },
  { label: '15天', value: '15d' },
  { label: '30天', value: '30d' }
]
const activeCurveTab = ref('24h')

// ==================== 报警信息 ====================
// TODO: 后端暂无报警信息API，以下为mock数据，待API就绪后替换
const alarmStats = reactive({ total: 8, handled: 5, unhandled: 3 })

const alarmList = ref([
  { point: '西环路河道排放口', time: '06-12 08:32', type: '液位超限', handleStatus: '未处理', handleClass: 'alarm' },
  { point: '开发区管委会路段', time: '06-12 08:28', type: '液位超限', handleStatus: '未处理', handleClass: 'alarm' },
  { point: '河西大道排水管道B7', time: '06-12 08:15', type: '流量异常', handleStatus: '未处理', handleClass: 'alarm' },
  { point: '人民路地下管网C2', time: '06-12 07:55', type: '液位超限', handleStatus: '已处理', handleClass: 'normal' },
  { point: '北环路排水泵站出口', time: '06-12 07:42', type: '流量异常', handleStatus: '已处理', handleClass: 'normal' },
  { point: '白羊坪村监测点', time: '06-12 07:30', type: '设备离线', handleStatus: '已处理', handleClass: 'normal' },
  { point: '南环路排水管道D3', time: '06-11 22:18', type: '流量异常', handleStatus: '已处理', handleClass: 'normal' },
  { point: '东环路市政大楼段', time: '06-11 20:05', type: '液位超限', handleStatus: '已处理', handleClass: 'normal' }
])

// ==================== 地图数据（从API加载）====================
const mapPoints = ref([])
const pipeNetworkData = ref([])

// ==================== 设备状态映射 ====================
function getEquipStatusInfo(equipment) {
  if (equipment.onlineStatus === 0) return { status: '离线', color: '#909399' }
  if (equipment.alarmStatus === 1) return { status: '报警', color: '#f56c6c' }
  if (equipment.currentStatus === 3) return { status: '预警', color: '#e6a23c' }
  return { status: '正常', color: '#67c23a' }
}

function getCurrentStatusText(val) {
  const map = { 1: '在用', 2: '闲置', 3: '维修', 4: '报废', 5: '待入库' }
  return map[val] || '未知'
}

// ==================== 数据加载 ====================
async function loadMapData() {
  try {
    // 获取设备分页数据（排水类型）
    const eqRes = await getEquipmentPage(1, 999, { equipmentType: 'drainage' })
    const eqPage = eqRes.code !== undefined ? eqRes.data : eqRes
    const equipmentList = eqPage.records || []

    // 获取管网分页数据
    const pnRes = await getPipeNetworkPage(1, 999, {})
    const pnPage = pnRes.code !== undefined ? pnRes.data : pnRes
    pipeNetworkData.value = pnPage.records || []

    // 转换设备数据为地图点位
    mapPoints.value = equipmentList
      .filter(e => e.longitude && e.latitude)
      .map(e => {
        const statusInfo = getEquipStatusInfo(e)
        return {
          name: e.equipmentName || '未命名设备',
          lng: parseFloat(e.longitude),
          lat: parseFloat(e.latitude),
          status: statusInfo.status,
          color: statusInfo.color,
          equipment: e
        }
      })

    // 计算统计面板数据
    overviewStats.total = equipmentList.length
    overviewStats.offline = equipmentList.filter(e => e.onlineStatus === 0).length
    overviewStats.alarm = equipmentList.filter(e => e.onlineStatus === 1 && e.alarmStatus === 1).length
    const warningCount = equipmentList.filter(e => e.onlineStatus === 1 && e.alarmStatus !== 1 && e.currentStatus === 3).length
    overviewStats.normal = equipmentList.filter(e => e.onlineStatus === 1 && e.alarmStatus !== 1 && e.currentStatus !== 3).length

    // 更新饼图数据
    pieData.value = [
      { name: '正常运行', value: overviewStats.normal, color: '#67c23a' },
      { name: '预警', value: warningCount, color: '#e6a23c' },
      { name: '报警', value: overviewStats.alarm, color: '#f56c6c' },
      { name: '离线', value: overviewStats.offline, color: '#909399' }
    ]
  } catch (error) {
    console.error('加载地图数据失败：', error)
  }
}

// ==================== 地图初始化 ====================
let mapInstance = null

function initMap() {
  const container = document.getElementById('gwyxqkMap')
  if (!container || typeof BMapGL === 'undefined') {
    console.warn('BMapGL 未加载或容器不存在')
    return
  }

  try {
    mapInstance = new BMapGL.Map('gwyxqkMap')
    // 默认中心点，有数据时以第一个设备点为中心
    let centerLng = 110.393
    let centerLat = 28.452
    if (mapPoints.value.length > 0) {
      centerLng = mapPoints.value[0].lng
      centerLat = mapPoints.value[0].lat
    }
    const centerPoint = new BMapGL.Point(centerLng, centerLat)
    mapInstance.centerAndZoom(centerPoint, 14)
    mapInstance.enableScrollWheelZoom(true)

    // 添加管网标记点
    pipeNetworkData.value.forEach(network => {
      addPipeNetworkMarker(network)
    })

    // 添加设备监测点标记
    mapPoints.value.forEach(point => {
      addMapMarker(point)
    })
  } catch (e) {
    console.error('百度地图初始化失败：', e)
  }
}

function addMapMarker(point) {
  const color = point.color || '#409eff'
  const bPoint = new BMapGL.Point(point.lng, point.lat)

  const html = `<div style="text-align:center;cursor:pointer;">
    <div style="color:#fff;background:${color};border-radius:4px;padding:2px 6px;font-size:11px;white-space:nowrap;display:inline-block;margin-bottom:2px;">${point.name}</div>
    <div style="color:#fff;font-size:10px;background:rgba(0,0,0,0.6);border-radius:3px;padding:1px 4px;margin-bottom:2px;">状态：${point.status}</div>
    <div><img src="${locationIcon}" style="width:24px;height:24px;display:block;margin:0 auto;"/></div>
  </div>`

  const label = new BMapGL.Label(html, {
    position: bPoint,
    offset: new BMapGL.Size(-30, -55)
  })
  label.setStyle({
    border: 'none',
    background: 'transparent',
    padding: '0'
  })
  mapInstance.addOverlay(label)

  // 点击标记弹出设备信息窗口
  label.addEventListener('click', function () {
    const eq = point.equipment || {}
    const infoContent = `<div style="color:#333;font-size:13px;padding:4px;">
      <div style="font-weight:bold;margin-bottom:6px;">${point.name}</div>
      <div>设备编号：${eq.equipmentCode || '-'}</div>
      <div>安装位置：${eq.equipmentLocation || '-'}</div>
      <div>设备状态：<b style="color:${color}">${getCurrentStatusText(eq.currentStatus)}</b></div>
      <div>报警状态：<b style="color:${eq.alarmStatus === 1 ? '#f56c6c' : '#67c23a'}">${eq.alarmStatus === 1 ? '报警' : '正常'}</b></div>
      <div>在线状态：<b style="color:${eq.onlineStatus === 1 ? '#67c23a' : '#909399'}">${eq.onlineStatus === 1 ? '在线' : '离线'}</b></div>
      <div>最近维护：${eq.lastMaintainDate || '-'}</div>
      <div>下次维护：${eq.nextMaintainDate || '-'}</div>
      <div>经度：${point.lng}</div>
      <div>纬度：${point.lat}</div>
    </div>`
    const infoWindow = new BMapGL.InfoWindow(infoContent, {
      width: 240,
      title: ''
    })
    mapInstance.openInfoWindow(infoWindow, bPoint)
  })
}

function addPipeNetworkMarker(network) {
  if (!network.longitude || !network.latitude) return
  const bPoint = new BMapGL.Point(parseFloat(network.longitude), parseFloat(network.latitude))

  const html = `<div style="text-align:center;cursor:pointer;">
    <div style="color:#fff;background:#409eff;border-radius:4px;padding:2px 6px;font-size:11px;white-space:nowrap;display:inline-block;margin-bottom:2px;">${network.networkName || '管网'}</div>
    <div style="color:#fff;font-size:10px;background:rgba(0,0,0,0.6);border-radius:3px;padding:1px 4px;margin-bottom:2px;">${network.networkType || '-'}</div>
    <div><img src="${locationIcon}" style="width:20px;height:20px;display:block;margin:0 auto;"/></div>
  </div>`

  const label = new BMapGL.Label(html, {
    position: bPoint,
    offset: new BMapGL.Size(-30, -50)
  })
  label.setStyle({
    border: 'none',
    background: 'transparent',
    padding: '0'
  })
  mapInstance.addOverlay(label)

  // 点击标记弹出管网信息窗口
  label.addEventListener('click', function () {
    const infoContent = `<div style="color:#333;font-size:13px;padding:4px;">
      <div style="font-weight:bold;margin-bottom:6px;">${network.networkName || '管网'}</div>
      <div>管网类型：${network.networkType || '-'}</div>
      <div>所在区域：${network.area || '-'} / ${network.district || '-'}</div>
      <div>管径：${network.pipeDiameter || '-'} mm</div>
      <div>管材：${network.pipeMaterial || '-'}</div>
      <div>管长：${network.pipeLength || '-'} m</div>
      <div>起点：${network.startPoint || '-'}</div>
      <div>终点：${network.endPoint || '-'}</div>
      <div>经度：${network.longitude}</div>
      <div>纬度：${network.latitude}</div>
    </div>`
    const infoWindow = new BMapGL.InfoWindow(infoContent, {
      width: 240,
      title: ''
    })
    mapInstance.openInfoWindow(infoWindow, bPoint)
  })
}

// ==================== ECharts 图表 ====================
let pieChart = null
let lineChart = null
let barChart = null

function initPieChart() {
  const dom = document.getElementById('gwyxqkPieChart')
  if (!dom) return
  pieChart = echarts.init(dom)
  const total = pieData.value.reduce((s, d) => s + d.value, 0)
  pieChart.setOption({
    tooltip: { trigger: 'item', formatter: '{b}: {c} ({d}%)' },
    legend: { show: false },
    graphic: [{
      type: 'text',
      left: 'center',
      top: '38%',
      style: { text: '管网状态', fill: '#a0cfff', fontSize: 12, textAlign: 'center' }
    }, {
      type: 'text',
      left: 'center',
      top: '52%',
      style: { text: String(total), fill: '#fff', fontSize: 22, fontWeight: 'bold', textAlign: 'center' }
    }],
    series: [{
      type: 'pie',
      radius: ['45%', '70%'],
      center: ['50%', '50%'],
      label: { show: false },
      labelLine: { show: false },
      data: pieData.value.map(d => ({ name: d.name, value: d.value, itemStyle: { color: d.color } })),
      emphasis: { scale: true, scaleSize: 5 }
    }]
  })
}

// TODO: 后端暂无历史监测曲线数据API，以下为mock随机数据，待API就绪后替换
function generateLineData(tab) {
  const labels = []
  const flowData = []
  const levelData = []
  if (tab === '24h') {
    for (let i = 0; i < 24; i++) {
      labels.push(String(i).padStart(2, '0') + ':00')
      flowData.push(Math.round((80 + Math.random() * 200) * 10) / 10)
      levelData.push(Math.round((0.3 + Math.random() * 4) * 100) / 100)
    }
  } else if (tab === '7d') {
    for (let i = 6; i >= 0; i--) {
      const d = new Date()
      d.setDate(d.getDate() - i)
      labels.push(`${d.getMonth() + 1}/${d.getDate()}`)
      flowData.push(Math.round((100 + Math.random() * 180) * 10) / 10)
      levelData.push(Math.round((0.5 + Math.random() * 3.5) * 100) / 100)
    }
  } else if (tab === '15d') {
    for (let i = 14; i >= 0; i--) {
      const d = new Date()
      d.setDate(d.getDate() - i)
      labels.push(`${d.getMonth() + 1}/${d.getDate()}`)
      flowData.push(Math.round((90 + Math.random() * 200) * 10) / 10)
      levelData.push(Math.round((0.4 + Math.random() * 3.8) * 100) / 100)
    }
  } else {
    for (let i = 29; i >= 0; i--) {
      const d = new Date()
      d.setDate(d.getDate() - i)
      labels.push(`${d.getMonth() + 1}/${d.getDate()}`)
      flowData.push(Math.round((85 + Math.random() * 210) * 10) / 10)
      levelData.push(Math.round((0.3 + Math.random() * 4.2) * 100) / 100)
    }
  }
  return { labels, flowData, levelData }
}

function initLineChart(tab) {
  const dom = document.getElementById('gwyxqkLineChart')
  if (!dom) return
  if (!lineChart) {
    lineChart = echarts.init(dom)
  }
  const { labels, flowData, levelData } = generateLineData(tab || '24h')
  lineChart.setOption({
    tooltip: { trigger: 'axis' },
    legend: {
      data: ['流量(m³/h)', '液位(m)'],
      textStyle: { color: '#7ec8e3', fontSize: 10 },
      top: 0,
      right: 10,
      itemWidth: 12,
      itemHeight: 8
    },
    grid: { left: 40, right: 40, top: 30, bottom: 25 },
    xAxis: {
      type: 'category',
      data: labels,
      axisLabel: { color: '#7ec8e3', fontSize: 9, interval: tab === '30d' ? 4 : tab === '15d' ? 2 : 'auto' },
      axisLine: { lineStyle: { color: '#1a3a5c' } }
    },
    yAxis: [
      {
        type: 'value',
        name: 'm³/h',
        nameTextStyle: { color: '#7ec8e3', fontSize: 10 },
        axisLabel: { color: '#7ec8e3', fontSize: 10 },
        splitLine: { lineStyle: { color: '#1a3a5c' } },
        axisLine: { show: false }
      },
      {
        type: 'value',
        name: 'm',
        nameTextStyle: { color: '#e6a23c', fontSize: 10 },
        axisLabel: { color: '#e6a23c', fontSize: 10 },
        splitLine: { show: false },
        axisLine: { show: false }
      }
    ],
    series: [
      {
        name: '流量(m³/h)',
        type: 'line',
        data: flowData,
        smooth: true,
        symbol: 'none',
        lineStyle: { color: '#409eff', width: 2 },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(64,158,255,0.3)' },
            { offset: 1, color: 'rgba(64,158,255,0.02)' }
          ])
        }
      },
      {
        name: '液位(m)',
        type: 'line',
        yAxisIndex: 1,
        data: levelData,
        smooth: true,
        symbol: 'none',
        lineStyle: { color: '#e6a23c', width: 2 },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(230,162,60,0.3)' },
            { offset: 1, color: 'rgba(230,162,60,0.02)' }
          ])
        }
      }
    ]
  })
}

// TODO: 后端暂无流量统计数据API，以下为mock数据，待API就绪后替换
function initBarChart() {
  const dom = document.getElementById('gwyxqkBarChart')
  if (!dom) return
  barChart = echarts.init(dom)
  const names = ['沅陵大道', '城北路段', '河西大道', '人民路', '南环路', '北环泵站', '西环路', '东环路']
  const values = [125.6, 89.3, 210.5, 178.9, 56.2, 195.4, 302.1, 78.5]
  barChart.setOption({
    tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
    grid: { left: 50, right: 10, top: 10, bottom: 30 },
    xAxis: {
      type: 'category',
      data: names,
      axisLabel: { color: '#7ec8e3', fontSize: 9, rotate: 20 },
      axisLine: { lineStyle: { color: '#1a3a5c' } }
    },
    yAxis: {
      type: 'value',
      name: 'm³/h',
      nameTextStyle: { color: '#7ec8e3', fontSize: 10 },
      axisLabel: { color: '#7ec8e3', fontSize: 10 },
      splitLine: { lineStyle: { color: '#1a3a5c' } },
      axisLine: { show: false }
    },
    series: [{
      type: 'bar',
      data: values,
      barWidth: 14,
      itemStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: '#409eff' },
          { offset: 1, color: '#1a3a5c' }
        ]),
        borderRadius: [2, 2, 0, 0]
      }
    }]
  })
}

// ==================== 监测曲线Tab切换 ====================
watch(activeCurveTab, (val) => {
  initLineChart(val)
})

// ==================== 生命周期 ====================
onMounted(async () => {
  updateTime()
  timer = setInterval(() => {
    updateTime()
    updateRefreshTime()
  }, 1000)
  updateRefreshTime()

  // 先从API加载数据
  await loadMapData()

  // 延迟初始化确保 DOM 渲染完成
  setTimeout(() => {
    initMap()
    initPieChart()
    initLineChart('24h')
    initBarChart()
  }, 300)
})

onUnmounted(() => {
  if (timer) clearInterval(timer)
  if (pieChart) pieChart.dispose()
  if (lineChart) lineChart.dispose()
  if (barChart) barChart.dispose()
  if (mapInstance) mapInstance = null
})

// 监听窗口大小变化，重绘图表
window.addEventListener('resize', () => {
  if (pieChart) pieChart.resize()
  if (lineChart) lineChart.resize()
  if (barChart) barChart.resize()
})
</script>

<style scoped>
/* ==================== 全局暗色大屏 ==================== */
.gwyxqk-screen {
  width: 100%;
  height: 100vh;
  background: #0a1929;
  color: #fff;
  font-family: 'Microsoft YaHei', sans-serif;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

/* ==================== 顶部标题栏 ==================== */
.screen-header {
  height: 64px;
  background: linear-gradient(180deg, #0d2137 0%, #0a1929 100%);
  border-bottom: 1px solid rgba(64, 158, 255, 0.3);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24px;
  flex-shrink: 0;
  position: relative;
}

.screen-header::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 10%;
  right: 10%;
  height: 1px;
  background: linear-gradient(90deg, transparent, #409eff, transparent);
}

.header-left {
  flex: 1;
  text-align: left;
}

.header-time {
  font-size: 15px;
  color: #a0cfff;
  letter-spacing: 1px;
}

.header-center {
  flex: 2;
  text-align: center;
}

.header-title {
  font-size: 26px;
  font-weight: 700;
  margin: 0;
  letter-spacing: 4px;
  background: linear-gradient(180deg, #fff 0%, #7ec8e3 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  text-shadow: none;
}

.header-right {
  flex: 1;
  text-align: right;
}

/* ==================== 主体三栏 ==================== */
.screen-body {
  flex: 1;
  display: flex;
  padding: 12px;
  gap: 12px;
  min-height: 0;
}

.panel-left,
.panel-right {
  width: 22%;
  min-width: 260px;
  display: flex;
  flex-direction: column;
  gap: 12px;
  min-height: 0;
}

.panel-center {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
  position: relative;
}

/* ==================== 面板盒子 ==================== */
.panel-box {
  background: rgba(6, 30, 65, 0.8);
  border: 1px solid rgba(64, 158, 255, 0.2);
  border-radius: 6px;
  padding: 12px;
  display: flex;
  flex-direction: column;
  min-height: 0;
  overflow: hidden;
}

.panel-title {
  font-size: 14px;
  font-weight: 600;
  color: #7ec8e3;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  gap: 4px;
  flex-shrink: 0;
}

.title-icon {
  color: #409eff;
  font-size: 10px;
}

.refresh-time {
  margin-left: auto;
  font-size: 11px;
  color: #607080;
  font-weight: 400;
}

/* ==================== 管网概况统计卡片 ==================== */
.stats-cards {
  display: flex;
  gap: 8px;
  margin-bottom: 10px;
  flex-shrink: 0;
}

.stat-card {
  flex: 1;
  background: rgba(10, 25, 50, 0.6);
  border: 1px solid rgba(64, 158, 255, 0.15);
  border-radius: 6px;
  padding: 8px 4px;
  text-align: center;
}

.stat-val {
  font-size: 20px;
  font-weight: 700;
  color: #409eff;
}

.stat-val.green {
  color: #67c23a;
}

.stat-val.orange {
  color: #e6a23c;
}

.stat-val.gray {
  color: #909399;
}

.stat-label {
  font-size: 10px;
  color: #7ec8e3;
  margin-top: 2px;
}

/* ==================== 环形图 ==================== */
.pie-chart-wrapper {
  display: flex;
  align-items: center;
  height: 140px;
}

.chart-area {
  width: 55%;
  height: 140px;
}

.pie-legend {
  width: 45%;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
}

.legend-dot {
  width: 10px;
  height: 10px;
  border-radius: 2px;
  flex-shrink: 0;
}

.legend-label {
  color: #a0cfff;
  flex: 1;
}

.legend-value {
  color: #fff;
  font-weight: 600;
}

/* ==================== 实时数据表格 ==================== */
.realtime-table-wrap {
  flex: 1;
  overflow-y: auto;
  min-height: 0;
}

.dark-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 12px;
}

.dark-table th {
  background: rgba(20, 60, 110, 0.6);
  color: #7ec8e3;
  padding: 7px 6px;
  text-align: center;
  border-bottom: 1px solid rgba(64, 158, 255, 0.2);
  font-weight: 500;
  white-space: nowrap;
}

.dark-table td {
  padding: 6px;
  text-align: center;
  color: #d0e8ff;
  border-bottom: 1px solid rgba(64, 158, 255, 0.08);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 80px;
}

.dark-table tbody tr:nth-child(odd) {
  background: rgba(10, 25, 50, 0.4);
}

.dark-table tbody tr:nth-child(even) {
  background: rgba(20, 40, 70, 0.3);
}

.dark-table tbody tr:hover {
  background: rgba(64, 158, 255, 0.1);
}

.status-tag {
  padding: 1px 6px;
  border-radius: 3px;
  font-size: 11px;
}

.status-normal {
  color: #67c23a;
  background: rgba(103, 194, 58, 0.15);
}

.status-warning {
  color: #e6a23c;
  background: rgba(230, 162, 60, 0.15);
}

.status-alarm {
  color: #f56c6c;
  background: rgba(245, 108, 108, 0.15);
}

.status-offline {
  color: #909399;
  background: rgba(144, 147, 153, 0.15);
}

/* ==================== 中间地图 ==================== */
.map-container {
  flex: 1;
  border-radius: 6px;
  overflow: hidden;
  border: 1px solid rgba(64, 158, 255, 0.2);
  min-height: 0;
}

.map-search {
  position: absolute;
  top: 12px;
  left: 12px;
  z-index: 10;
  display: flex;
  align-items: center;
}

.search-input {
  background: rgba(6, 30, 65, 0.85);
  border: 1px solid rgba(64, 158, 255, 0.3);
  color: #a0cfff;
  padding: 6px 30px 6px 12px;
  border-radius: 4px;
  font-size: 12px;
  outline: none;
  width: 160px;
}

.search-input::placeholder {
  color: #4a6a8a;
}

.search-icon {
  position: absolute;
  right: 8px;
  font-size: 14px;
  cursor: pointer;
}

/* ==================== 监测曲线Tab ==================== */
.curve-tabs {
  display: flex;
  gap: 0;
  background: rgba(10, 25, 50, 0.6);
  border: 1px solid rgba(64, 158, 255, 0.2);
  border-radius: 4px;
  margin-bottom: 8px;
  flex-shrink: 0;
  overflow: hidden;
}

.curve-tab {
  flex: 1;
  text-align: center;
  padding: 5px 4px;
  font-size: 11px;
  color: #a0cfff;
  cursor: pointer;
  transition: all 0.3s;
  border-right: 1px solid rgba(64, 158, 255, 0.1);
}

.curve-tab:last-child {
  border-right: none;
}

.curve-tab.active {
  background: rgba(64, 158, 255, 0.25);
  color: #fff;
  font-weight: 600;
}

.curve-tab:hover {
  background: rgba(64, 158, 255, 0.15);
}

.chart-area-sm {
  width: 100%;
  height: 150px;
  flex-shrink: 0;
}

/* ==================== 报警信息 ==================== */
.alert-stats {
  display: flex;
  gap: 8px;
  margin-bottom: 8px;
  flex-shrink: 0;
}

.alert-stat-card {
  flex: 1;
  background: rgba(10, 25, 50, 0.6);
  border: 1px solid rgba(64, 158, 255, 0.15);
  border-radius: 6px;
  padding: 8px;
  text-align: center;
}

.alert-stat-val {
  font-size: 20px;
  font-weight: 700;
  color: #e6a23c;
}

.alert-stat-val.green {
  color: #67c23a;
}

.alert-stat-val.red {
  color: #f56c6c;
}

.alert-stat-label {
  font-size: 10px;
  color: #7ec8e3;
  margin-top: 2px;
}

.alert-table-wrap {
  flex: 1;
  overflow-y: auto;
  min-height: 0;
}

/* ==================== 滚动条样式 ==================== */
::-webkit-scrollbar {
  width: 4px;
}

::-webkit-scrollbar-track {
  background: rgba(10, 25, 50, 0.3);
}

::-webkit-scrollbar-thumb {
  background: rgba(64, 158, 255, 0.3);
  border-radius: 2px;
}

::-webkit-scrollbar-thumb:hover {
  background: rgba(64, 158, 255, 0.5);
}
</style>
