<!--场站可燃气体浓度监测-->
<template>
  <div class="gas-station-monitor">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <el-icon><Warning /></el-icon>
        <span class="title">燃气场站安全监测中心</span>
        <div class="stats-badge">
          <span class="stat-item" :class="{ alert: alertCount > 0 }">
            <i class="dot"></i>告警场站 {{ alertCount }}
          </span>
          <span class="stat-item">正常场站 {{ normalCount }}</span>
          <span class="stat-item">接入场站 {{ totalStations }}</span>
        </div>
      </div>
      <div class="header-right">
        <el-button type="primary" :icon="Refresh" @click="refreshData">刷新</el-button>
      </div>
    </div>

    <!-- KPI指标卡片 -->
    <div class="kpi-cards">
      <div class="kpi-card critical">
        <div class="kpi-value">{{ maxMethane }}<span class="unit">ppm</span></div>
        <div class="kpi-label">最高甲烷浓度</div>
        <div class="kpi-trend">场站: {{ maxMethaneStation }}</div>
      </div>
      <div class="kpi-card">
        <div class="kpi-value">{{ riskScore }}<span class="unit">分</span></div>
        <div class="kpi-label">综合风险评分</div>
        <div class="kpi-trend trend-down">越低越安全</div>
      </div>
    </div>

    <!-- 主内容区：左侧场站列表 + 右侧详情曲线 -->
    <div class="main-layout">
      <!-- 左侧场站列表 -->
      <div class="station-list-panel">
        <div class="list-header">
          <span>燃气场站列表</span>
          <el-input
              v-model="searchKeyword"
              placeholder="搜索场站名称"
              clearable
              :prefix-icon="Search"
              style="width: 160px"
              size="small"
          />
        </div>
        <div class="station-list">
          <div
              v-for="station in paginatedStations"
              :key="station.pointId"
              class="station-item"
              :class="{
              selected: selectedStation?.pointId === station.pointId,
              alert: station.alertStatus
            }"
              @click="selectStation(station)"
          >
            <div class="station-header">
              <span class="station-name">{{ station.pointName }}</span>
              <el-tag :type="station.alertStatus ? 'danger' : 'success'" size="small">
                {{ station.alertStatus ? '告警' : '正常' }}
              </el-tag>
            </div>
            <div class="station-address">
              <el-icon><Location /></el-icon> {{ station.location }}
            </div>
            <div class="station-metrics">
              <div class="metric">
                <span class="label">甲烷浓度</span>
                <span class="value" :class="{ 'alert-value': station.alertStatus }">
                  {{ station.methaneValue }} ppm
                </span>
              </div>
            </div>
          </div>
        </div>
        <div class="pagination-area">
          <el-pagination
              small
              layout="prev, pager, next"
              :total="filteredStations.length"
              :page-size="pageSize"
              v-model:current-page="currentPage"
          />
        </div>
      </div>

      <!-- 右侧场站详情 -->
      <div class="detail-panel" v-if="selectedStation">
        <div class="detail-header">
          <div class="title-section">
            <h3>{{ selectedStation.pointName }}</h3>
            <el-tag :type="selectedStation.alertStatus ? 'danger' : 'success'" size="large">
              {{ selectedStation.alertStatus ? '实时告警中' : '运行正常' }}
            </el-tag>
          </div>
          <div class="address-info">
            <el-icon><Location /></el-icon> {{ selectedStation.location }}
          </div>
        </div>

        <!-- 实时监测数据卡片 -->
        <div class="realtime-cards">
          <div class="realtime-card" :class="{ warning: selectedStation.alertStatus }">
            <div class="card-icon"><el-icon><WindPower /></el-icon></div>
            <div class="card-content">
              <div class="card-label">甲烷浓度 (CH₄)</div>
              <div class="card-value">{{ selectedStation.methaneValue }} <span class="unit">ppm</span></div>
              <div class="card-threshold">阈值: {{ selectedStation.methaneThreshold }} ppm</div>
            </div>
          </div>
          <div class="realtime-card">
            <div class="card-icon"><el-icon><Odometer /></el-icon></div>
            <div class="card-content">
              <div class="card-label">环境温度</div>
              <div class="card-value">{{ selectedStation.temperature }} <span class="unit">°C</span></div>
              <div class="card-threshold">正常范围</div>
            </div>
          </div>
        </div>

        <!-- 监测数据趋势图 -->
        <div class="chart-section">
          <div class="section-header">
            <span><el-icon><TrendCharts /></el-icon> 甲烷浓度趋势（最近24小时）</span>
          </div>
          <div ref="trendChartRef" class="chart-container"></div>
        </div>

        <!-- SCADA系统接入信息 -->
        <div class="scada-section">
          <div class="section-header">
            <span><el-icon><Monitor /></el-icon> SCADA系统接入信息</span>
          </div>
          <el-descriptions :column="2" border size="small">
            <el-descriptions-item label="数据来源">燃气公司SCADA系统</el-descriptions-item>
            <el-descriptions-item label="最后通讯时间">{{ selectedStation.lastUpdateTime || '--' }}</el-descriptions-item>
            <el-descriptions-item label="数据采集频率">10秒/次</el-descriptions-item>
            <el-descriptions-item label="通讯状态">
              <el-tag type="success">在线</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="场站编号">{{ selectedStation.stationCode }}</el-descriptions-item>
            <el-descriptions-item label="关联设备">{{ selectedStation.deviceCount }}台</el-descriptions-item>
          </el-descriptions>
        </div>
      </div>

      <!-- 未选中状态 -->
      <div v-else class="empty-panel">
        <el-empty description="请从左侧选择燃气场站查看详情" :image-size="140" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount, nextTick } from 'vue'
import { Warning, Refresh, Location, WindPower, Odometer, TrendCharts, Monitor, Search } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'
import { getGasMonitorPoints, getGasMonitorTrend } from '@/api/pipeNetwork/gasMonitor'

// ECharts实例
const trendChartRef = ref(null)
let trendChartInstance = null

// 加载数据
const stations = ref([])
const loading = ref(false)

async function loadStations() {
  loading.value = true
  try {
    const res = await getGasMonitorPoints()
    stations.value = res.data || []
    if (stations.value.length > 0) {
      selectStation(stations.value[0])
    }
  } finally {
    loading.value = false
  }
}

// 统计数据
const totalStations = computed(() => stations.value.length)
const alertCount = computed(() => stations.value.filter(s => s.alertStatus).length)
const normalCount = computed(() => totalStations.value - alertCount.value)
const maxMethane = computed(() => {
  if (!stations.value.length) return 0
  return Math.max(...stations.value.map(s => s.methaneValue))
})
const maxMethaneStation = computed(() => {
  const max = maxMethane.value
  return stations.value.find(s => s.methaneValue === max)?.pointName || '—'
})
const riskScore = computed(() => {
  if (!stations.value.length) return 0
  const alertRatio = alertCount.value / totalStations.value
  const avgMethane = stations.value.reduce((sum, s) => sum + s.methaneValue, 0) / totalStations.value
  let score = 100 - (alertRatio * 50 + (avgMethane / 40) * 30)
  return Math.max(0, Math.min(100, Math.round(score)))
})

// 筛选
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = 5
const selectedStation = ref(null)

const filteredStations = computed(() => {
  let list = stations.value
  if (searchKeyword.value) {
    const kw = searchKeyword.value.toLowerCase()
    list = list.filter(s => s.pointName.toLowerCase().includes(kw))
  }
  return list
})
const paginatedStations = computed(() => {
  const start = (currentPage.value - 1) * pageSize
  return filteredStations.value.slice(start, start + pageSize)
})

// 趋势图
function renderTrendChart(trendRes) {
  if (!trendChartRef.value || !selectedStation.value) return
  if (!trendChartInstance) {
    trendChartInstance = echarts.init(trendChartRef.value)
  }
  const data = trendRes || {}
  const times = data.times || []
  const values = data.methaneValues || []
  const threshold = data.threshold || 20

  trendChartInstance.setOption({
    tooltip: { trigger: 'axis' },
    legend: { data: ['甲烷浓度', '报警阈值'], bottom: 0 },
    grid: { left: 50, right: 30, top: 20, bottom: 30 },
    xAxis: {
      type: 'category', data: times,
      axisLabel: { rotate: 45, interval: 3, fontSize: 10 }
    },
    yAxis: { type: 'value', name: 'ppm', axisLabel: { fontSize: 10 } },
    series: [
      {
        name: '甲烷浓度', type: 'line', data: values,
        smooth: true,
        lineStyle: { color: '#f56c6c', width: 2 },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(245,108,108,0.3)' },
            { offset: 1, color: 'rgba(255,255,255,0.05)' }
          ])
        },
        symbol: 'none'
      },
      {
        name: '报警阈值', type: 'line',
        data: Array(times.length || 24).fill(threshold),
        lineStyle: { color: '#f56c6c', width: 1.5, type: 'dashed' },
        symbol: 'none'
      }
    ]
  })
}

async function selectStation(station) {
  selectedStation.value = station
  currentPage.value = 1
  try {
    const res = await getGasMonitorTrend(station.pointId, 24)
    await nextTick()
    renderTrendChart(res.data || {})
  } catch {
    await nextTick()
    renderTrendChart({})
  }
}

function refreshData() {
  ElMessage.success('数据已刷新')
  loadStations()
}

onMounted(() => {
  loadStations()
})

onBeforeUnmount(() => {
  if (trendChartInstance) {
    trendChartInstance.dispose()
    trendChartInstance = null
  }
})
</script>

<style scoped>
.gas-station-monitor {
  background: #f0f2f6;
  min-height: 100vh;
  padding: 20px;
}
.page-header {
  background: white;
  border-radius: 16px;
  padding: 16px 24px;
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px;
}
.header-left { display: flex; align-items: center; gap: 20px; }
.header-left .title { font-size: 1.3rem; font-weight: 600; color: #1f2d3d; }
.stats-badge { display: flex; gap: 20px; }
.stat-item { font-size: 13px; display: flex; align-items: center; gap: 6px; }
.stat-item.alert { color: #f56c6c; }
.dot { width: 10px; height: 10px; border-radius: 50%; background: #67c23a; display: inline-block; }
.stat-item.alert .dot { background: #f56c6c; }
.header-right { display: flex; gap: 12px; }

.kpi-cards {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
  margin-bottom: 20px;
}
.kpi-card {
  background: white;
  border-radius: 16px;
  padding: 16px;
  text-align: center;
}
.kpi-card.critical .kpi-value { color: #f56c6c; }
.kpi-value { font-size: 32px; font-weight: bold; color: #1f2d3d; }
.kpi-value .unit { font-size: 14px; font-weight: normal; margin-left: 4px; }
.kpi-label { font-size: 13px; color: #909399; margin-top: 6px; }
.kpi-trend { font-size: 11px; color: #67c23a; margin-top: 4px; }
.kpi-trend.trend-down { color: #f56c6c; }

.main-layout {
  display: flex;
  gap: 20px;
}
.station-list-panel {
  width: 360px;
  background: white;
  border-radius: 16px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}
.list-header {
  padding: 16px;
  border-bottom: 1px solid #e9ecef;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
}
.station-list {
  flex: 1;
  overflow-y: auto;
  padding: 12px;
  max-height: calc(100vh - 320px);
}
.station-item {
  padding: 14px;
  margin-bottom: 10px;
  border-radius: 12px;
  background: #fafbfc;
  border: 1px solid #e9ecef;
  cursor: pointer;
  transition: all 0.2s;
}
.station-item.selected { background: #ecf5ff; border-color: #409eff; }
.station-item.alert { border-left: 3px solid #f56c6c; background: #fff8f8; }
.station-header { display: flex; justify-content: space-between; margin-bottom: 8px; }
.station-name { font-weight: 600; }
.station-address { font-size: 12px; color: #6c757d; display: flex; align-items: center; gap: 4px; margin-bottom: 8px; }
.station-metrics { display: flex; gap: 16px; font-size: 12px; }
.metric .label { color: #909399; }
.metric .value { font-weight: 500; }
.metric .value.alert-value { color: #f56c6c; font-weight: bold; }

.detail-panel {
  flex: 1;
  background: white;
  border-radius: 16px;
  padding: 20px;
  overflow-y: auto;
  max-height: calc(100vh - 180px);
}
.detail-header { margin-bottom: 20px; }
.title-section { display: flex; align-items: center; gap: 12px; margin-bottom: 8px; }
.title-section h3 { margin: 0; font-size: 20px; }
.address-info { color: #6c757d; font-size: 13px; display: flex; align-items: center; gap: 6px; }

.realtime-cards {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
  margin-bottom: 24px;
}
.realtime-card {
  background: #f8f9fc;
  border-radius: 12px;
  padding: 14px;
  display: flex;
  align-items: center;
  gap: 12px;
}
.realtime-card.warning { background: #fff8f0; border: 1px solid #f56c6c; }
.card-icon .el-icon { font-size: 32px; color: #409eff; }
.realtime-card.warning .card-icon .el-icon { color: #f56c6c; }
.card-label { font-size: 12px; color: #909399; }
.card-value { font-size: 22px; font-weight: bold; color: #1f2d3d; }
.card-value .unit { font-size: 12px; font-weight: normal; }
.card-threshold { font-size: 11px; color: #aaa; margin-top: 4px; }

.chart-section, .scada-section {
  margin-bottom: 24px;
}
.section-header {
  font-weight: 600;
  margin-bottom: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.chart-container { height: 260px; }
.empty-panel { flex: 1; display: flex; align-items: center; justify-content: center; background: white; border-radius: 16px; }
.pagination-area { padding: 12px; text-align: center; border-top: 1px solid #eee; }
</style>
