<!--场站可燃气体浓度报警-->
<template>
  <div class="methane-alert-center">
    <!-- 页面头部 -->
    <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 critical"><i class="dot"></i>报警设备 {{ alarmStats.realtimeCount }}</span>
          <span class="stat-item warning"><i class="dot"></i>设备总数 {{ equipments.length }}</span>
          <span class="stat-item"><i class="dot"></i>最高浓度 {{ alarmStats.maxConcentration }}ppm</span>
        </div>
      </div>
      <div class="header-right">
        <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 260px"
            size="default"
        />
        <el-select v-model="companyFilter" placeholder="燃气公司" clearable style="width: 140px" size="default">
          <el-option label="沅陵燃气" value="yuanling" />
        </el-select>
        <el-button type="primary" :icon="Refresh" @click="refreshData">刷新</el-button>
        <el-button :icon="Download" @click="exportReport">导出报表</el-button>
      </div>
    </div>

    <!-- KPI指标卡片 -->
    <div class="kpi-cards">
      <div class="kpi-card critical">
        <div class="kpi-value">{{ alarmStats.realtimeCount }}</div>
        <div class="kpi-label">实时报警</div>
        <div class="kpi-trend">较昨日 ↑{{ realtimeTrend }}</div>
      </div>
      <div class="kpi-card warning">
        <div class="kpi-value">{{ todayHistoryCount }}</div>
        <div class="kpi-label">今日历史报警</div>
        <div class="kpi-trend">待处理 {{ pendingCount }}</div>
      </div>
      <div class="kpi-card">
        <div class="kpi-value">{{ maxConcentration }}<span class="unit">ppm</span></div>
        <div class="kpi-label">最高浓度</div>
        <div class="kpi-trend">点位: {{ maxConcentrationPoint }}</div>
      </div>
      <div class="kpi-card">
        <div class="kpi-value">{{ avgResponseTime }}</div>
        <div class="kpi-label">平均响应时间(分钟)</div>
      </div>
    </div>

    <!-- 主内容区：左侧实时报警 + 右侧历史报警 -->
    <div class="main-layout">
      <!-- 左侧设备列表 -->
      <div class="alert-panel">
        <div class="panel-header">
          <span><el-icon><BellFilled /></el-icon> 探测器设备</span>
          <el-tag type="danger" effect="dark">{{ alarmStats.realtimeCount }} 个报警</el-tag>
        </div>
        <div class="alert-list realtime">
          <div
              v-for="eq in equipments"
              :key="eq.equipmentId"
              class="alert-item"
              :class="{ critical: eq.level === 'critical', warning: eq.level === 'warning', selected: selectedEquipment?.equipmentId === eq.equipmentId }"
              @click="selectEquipment(eq)"
          >
            <div class="alert-level">
              <el-tag :type="eq.level === 'critical' ? 'danger' : eq.level === 'warning' ? 'warning' : 'info'" size="small">
                {{ eq.level === 'critical' ? '严重' : eq.level === 'warning' ? '预警' : '正常' }}
              </el-tag>
            </div>
            <div class="alert-content">
              <div class="alert-title">{{ eq.equipmentName }}</div>
              <div class="alert-company">
                <el-icon><OfficeBuilding /></el-icon> 沅陵燃气
              </div>
              <div class="alert-location">
                <el-icon><Location /></el-icon> {{ eq.location }}
              </div>
              <div class="alert-data">
                <span class="data-item" v-if="eq.latestConcentration != null">甲烷浓度: <strong :class="{ 'critical-value': eq.latestConcentration > 30 }">{{ eq.latestConcentration }} ppm</strong></span>
                <span class="data-item" v-if="eq.latestThreshold != null">阈值: {{ eq.latestThreshold }} ppm</span>
                <span class="data-item" v-if="eq.latestConcentration == null" style="color:#67c23a">无报警记录</span>
              </div>
              <div class="alert-time" v-if="eq.alertTime">{{ eq.alertTime }}</div>
            </div>
          </div>
          <div v-if="equipments.length === 0" class="empty-state">
            <el-empty description="暂无探测器设备" :image-size="80" />
          </div>
        </div>
      </div>

      <!-- 右侧历史报警列表 -->
      <div class="history-panel">
        <div class="panel-header">
          <span><el-icon><Document /></el-icon> 历史报警</span>
          <el-input
              v-model="historySearch"
              placeholder="搜索场站/地址"
              clearable
              :prefix-icon="Search"
              style="width: 180px"
              size="small"
          />
        </div>
        <div class="alert-list history">
          <el-table :data="paginatedHistory" stripe border style="width: 100%" @row-click="viewAlertDetail">
            <el-table-column prop="stationName" label="场站名称" min-width="140" show-overflow-tooltip />
            <el-table-column prop="companyName" label="燃气公司" width="100" />
            <el-table-column prop="address" label="位置" min-width="150" show-overflow-tooltip />
            <el-table-column prop="concentration" label="甲烷浓度(ppm)" width="120" sortable>
              <template #default="{ row }">
                <span :class="{ 'critical-value': row.concentration > 30 }">{{ row.concentration }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="threshold" label="阈值(ppm)" width="90" />
            <el-table-column prop="level" label="级别" width="80" align="center">
              <template #default="{ row }">
                <el-tag :type="row.level === 'critical' ? 'danger' : 'warning'" size="small">
                  {{ row.level === 'critical' ? '严重' : '预警' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="alertTime" label="报警时间" width="150" sortable />
            <el-table-column prop="status" label="状态" width="80" align="center">
              <template #default="{ row }">
                <el-tag :type="row.status === 'resolved' ? 'success' : 'warning'" size="small">
                  {{ row.status === 'resolved' ? '已处理' : '待处理' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80" fixed="right" align="center">
              <template #default="{ row }">
                <el-button link type="primary" size="small" @click.stop="viewAlertDetail(row)">详情</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="pagination-area">
          <el-pagination
              small
              layout="total, prev, pager, next"
              :total="historyTotal"
              :page-size="historyPageSize"
              v-model:current-page="historyPage"
              @current-change="loadHistory"
          />
        </div>
      </div>
    </div>

    <!-- 报警详情抽屉 -->
    <el-drawer v-model="detailDrawerVisible" :title="`报警详情 - ${currentAlert?.stationName}`" size="480px" direction="rtl" @opened="onDrawerOpened">
      <div v-if="currentAlert" class="alert-detail">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="场站名称">{{ currentAlert.stationName }}</el-descriptions-item>
          <el-descriptions-item label="场站编号">{{ currentAlert.stationCode }}</el-descriptions-item>
          <el-descriptions-item label="燃气公司">{{ currentAlert.companyName }}</el-descriptions-item>
          <el-descriptions-item label="详细地址">{{ currentAlert.address }}</el-descriptions-item>
          <el-descriptions-item label="报警级别">
            <el-tag :type="currentAlert.level === 'critical' ? 'danger' : 'warning'">
              {{ currentAlert.level === 'critical' ? '严重报警' : '预警' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="甲烷浓度">
            <span :class="{ 'critical-value': currentAlert.concentration > 30 }">{{ currentAlert.concentration }} ppm</span>
          </el-descriptions-item>
          <el-descriptions-item label="报警阈值">{{ currentAlert.threshold }} ppm</el-descriptions-item>
          <el-descriptions-item label="报警时间">{{ currentAlert.alertTime }}</el-descriptions-item>
          <el-descriptions-item label="处理状态">
            <el-tag :type="currentAlert.status === 'resolved' ? 'success' : 'danger'">
              {{ currentAlert.status === 'resolved' ? '已处理' : '待处理' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item v-if="currentAlert.resolveTime" label="处理时间">{{ currentAlert.resolveTime }}</el-descriptions-item>
          <el-descriptions-item label="处理人">{{ currentAlert.handler || '—' }}</el-descriptions-item>
          <el-descriptions-item label="处理说明">{{ currentAlert.remark || '—' }}</el-descriptions-item>
        </el-descriptions>

        <!-- 浓度趋势图 -->
        <div class="trend-section">
          <div class="section-title">甲烷浓度趋势（最近1小时）</div>
          <div ref="chartRef" class="trend-chart"></div>
        </div>

        <!-- 处理操作 -->
        <div class="action-section" v-if="currentAlert.status !== 'resolved'">
          <el-button type="primary" @click="resolveAlert">标记已处理</el-button>
          <el-button type="warning" @click="dispatchWorkOrder">派发现场工单</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, computed, watch, nextTick, onBeforeUnmount, onMounted } from 'vue'
import { Warning, Refresh, Download, BellFilled, Document, Location, Search, OfficeBuilding } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'
import { getGasAlarmEquipment, getGasAlarmHistory, getGasAlarmStats, resolveGasAlarm, dispatchGasAlarm } from '@/api/pipeNetwork/basic'

// 左侧: 所有探测器设备(去重)
const equipments = ref([])
const selectedEquipment = ref(null)
// 右侧: 历史报警
const historyAlerts = ref([])
const historyPage = ref(1)
const historyPageSize = 8
const historyTotal = ref(0)
const alarmStats = ref({ realtimeCount: 0, pendingCount: 0, maxConcentration: 0, totalStations: 0 })

async function loadEquipment() {
  try {
    const res = await getGasAlarmEquipment()
    equipments.value = (res.data || []).map(e => ({
      ...e,
      stationName: e.equipmentName,
      concentration: e.latestConcentration,
      threshold: e.latestThreshold || 20,
      alertTime: e.latestAlarmTime,
      level: e.hasAlarm ? (e.latestAlarmLevel === 1 ? 'critical' : 'warning') : 'normal',
      status: e.hasAlarm ? 'pending' : 'normal'
    }))
  } catch (e) { console.error(e) }
}
const currentDeviceCode = ref('')
async function loadHistory() {
  try {
    const d = dateRange.value
    const res = await getGasAlarmHistory(historyPage.value, historyPageSize, d?.[0] || '', d?.[1] || '', currentDeviceCode.value || '')
    historyAlerts.value = (res.data?.records || []).map(mapAlarm)
    historyTotal.value = res.data?.total || 0
  } catch (e) { console.error(e) }
}
function selectEquipment(eq) {
  selectedEquipment.value = eq
  currentDeviceCode.value = eq.equipmentCode
  historyPage.value = 1
  loadHistory()
}
function mapAlarm(a) {
  const lv = (a.alarmLevel === 1 || a.alarmLevelText === '严重') ? 'critical' : 'warning'
  const status = (a.alarmStatus === 0 || a.statusText === '待处理') ? 'pending' : 'resolved'
  return {
    id: a.id, deviceCode: a.deviceCode,
    stationName: a.stationName || a.deviceCode,
    companyName: '沅陵燃气', companyId: 'yuanling',
    address: a.address || '',
    concentration: a.concentration || a.actualValue || 0,
    threshold: a.threshold || a.maxValue || 20,
    level: lv, alertTime: a.alarmTime || '', status,
    resolveTime: a.resolveTime || a.handleTime || null,
    handler: a.handler || a.handleUser || null,
    remark: a.remark || a.handleRemark || null
  }
}

const realtimeTrend = 1
const todayHistoryCount = computed(() => equipments.value.filter(e => e.alertTime && e.alertTime.startsWith(new Date().toISOString().substring(0,10))).length)
const pendingCount = computed(() => alarmStats.value.pendingCount)
const maxConcentration = computed(() => alarmStats.value.maxConcentration)
const maxConcentrationPoint = computed(() => alarmStats.value.maxConcentrationPoint || '—')
const avgResponseTime = computed(() => '--')

// 筛选
const dateRange = ref([])
const companyFilter = ref('')
const historySearch = ref('')
const paginatedHistory = computed(() => historyAlerts.value)

// 当前选中报警
const currentAlert = ref(null)
const detailDrawerVisible = ref(false)
const chartRef = ref(null)
let chartInstance = null

function renderChart() {
  if (!chartRef.value || !currentAlert.value?.trendData) return
  if (!chartInstance) {
    chartInstance = echarts.init(chartRef.value)
  }
  const times = Array.from({ length: 24 }, (_, i) => `${i}:00`)
  const threshold = currentAlert.value.threshold
  chartInstance.setOption({
    tooltip: { trigger: 'axis' },
    xAxis: { type: 'category', data: times, axisLabel: { rotate: 45, interval: 4 } },
    yAxis: { type: 'value', name: '甲烷浓度 (ppm)' },
    series: [
      { name: '甲烷浓度', type: 'line', data: currentAlert.value.trendData, smooth: true, lineStyle: { color: '#f56c6c', width: 2 }, areaStyle: { opacity: 0.1 } },
      { name: '报警阈值', type: 'line', data: Array(24).fill(threshold), lineStyle: { color: '#e6a23c', width: 2, type: 'dashed' }, symbol: 'none' }
    ]
  })
}

function onDrawerOpened() {
  nextTick(() => renderChart())
}

// 方法
const viewAlertDetail = (alert) => {
  currentAlert.value = alert
  detailDrawerVisible.value = true
}

const handleAlert = (alert) => {
  currentAlert.value = alert
  detailDrawerVisible.value = true
}

const resolveAlert = async () => {
  if (currentAlert.value?.status === 'pending') {
    try {
      await resolveGasAlarm(currentAlert.value.id)
      currentAlert.value.status = 'resolved'
      ElMessage.success('已标记为已处理')
      detailDrawerVisible.value = false
      loadEquipment(); loadHistory(); loadStats()
    } catch (e) { ElMessage.error('处理失败') }
  }
}

const dispatchWorkOrder = async () => {
  if (currentAlert.value?.id) {
    try {
      await dispatchGasAlarm(currentAlert.value.id)
      ElMessage.success('已派发现场处置工单(伪)')
    } catch (e) { ElMessage.error('派发失败') }
  }
}

async function loadStats() {
  try {
    const res = await getGasAlarmStats()
    if (res.data) {
      alarmStats.value = res.data
      totalStations.value = res.data.totalStations || 0
    }
  } catch (e) { console.error(e) }
}

onMounted(async () => {
  await loadEquipment()
  await loadHistory()
  await loadStats()
})

const refreshData = () => {
  ElMessage.success('数据已刷新')
}

const exportReport = () => {
  ElMessage.success('导出报表（演示）')
}

// 日期范围变化重载历史
watch(dateRange, () => { historyPage.value = 1; loadHistory() })

onBeforeUnmount(() => {
  try { chartInstance?.dispose() } catch {}
  chartInstance = null
})
</script>

<style scoped>
.methane-alert-center {
  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; }
.stats-badge { display: flex; gap: 20px; }
.stat-item { font-size: 13px; display: flex; align-items: center; gap: 6px; }
.stat-item.critical { color: #f56c6c; }
.stat-item.warning { color: #e6a23c; }
.stat-item .dot { width: 8px; height: 8px; border-radius: 50%; background: #67c23a; }
.stat-item.critical .dot { background: #f56c6c; }
.stat-item.warning .dot { background: #e6a23c; }
.header-right { display: flex; gap: 12px; flex-wrap: wrap; }

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

.main-layout {
  display: flex;
  gap: 20px;
}
.alert-panel {
  width: 420px;
  background: white;
  border-radius: 16px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}
.history-panel {
  flex: 1;
  background: white;
  border-radius: 16px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}
.panel-header {
  padding: 16px;
  border-bottom: 1px solid #e9ecef;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
}
.alert-list {
  flex: 1;
  overflow-y: auto;
  padding: 12px;
}
.alert-item {
  display: flex;
  gap: 12px;
  padding: 14px;
  margin-bottom: 12px;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.2s;
}
.alert-item.critical { background: #fff8f8; border: 1px solid #ffd4d4; }
.alert-item.warning { background: #fffef5; border: 1px solid #ffe4b5; }
.alert-item.selected { background: #ecf5ff; border: 2px solid #409eff; }
.alert-item:hover { transform: translateX(2px); box-shadow: 0 2px 8px rgba(0,0,0,0.1); }
.alert-level { flex-shrink: 0; }
.alert-content { flex: 1; }
.alert-title { font-weight: 600; margin-bottom: 6px; }
.alert-company { font-size: 12px; color: #409eff; display: flex; align-items: center; gap: 4px; margin-bottom: 4px; }
.alert-location { font-size: 12px; color: #6c757d; display: flex; align-items: center; gap: 4px; margin-bottom: 6px; }
.alert-data { display: flex; gap: 16px; font-size: 12px; margin-bottom: 6px; }
.alert-data .data-item { background: #f5f5f5; padding: 2px 8px; border-radius: 12px; }
.critical-value { color: #f56c6c; font-weight: bold; }
.alert-time { font-size: 11px; color: #aaa; }
.alert-action { display: flex; align-items: center; }
.empty-state { padding: 40px 0; text-align: center; }
.pagination-area { padding: 12px; text-align: center; border-top: 1px solid #eee; }

.alert-detail { padding: 8px; }
.section-title { font-weight: 600; margin: 16px 0 12px 0; }
.trend-chart { height: 200px; }
.action-section { margin-top: 20px; display: flex; gap: 12px; justify-content: flex-end; }
</style>