<!--管线流量异常提醒-->
<template>
  <div class="pressure-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>实时异常 {{ realtimeAlerts.length }}</span>
          <span class="stat-item warning"><i class="dot"></i>历史异常 {{ historyAlerts.length }}</span>
          <span class="stat-item"><i class="dot"></i>监测点 {{ totalPoints }}</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-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">{{ realtimeAlerts.length }}</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">{{ abnormalRate }}%</div>
        <div class="kpi-label">异常率</div>
        <div class="kpi-trend trend-down">较昨日 ↓2.1%</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">{{ realtimeAlerts.length }} 个异常</el-tag>
        </div>
        <div class="alert-list realtime">
          <div
              v-for="alert in paginatedRealtime"
              :key="alert.id"
              class="alert-item critical"
              @click="viewAlertDetail(alert)"
          >
            <div class="alert-level">
              <el-tag type="danger" size="small">严重</el-tag>
            </div>
            <div class="alert-content">
              <div class="alert-title">{{ alert.pointName }}</div>
              <div class="alert-location">
                <el-icon><Location /></el-icon> {{ alert.address }}
              </div>
              <div class="alert-data">
                <span class="data-item">瞬时流量: {{ alert.flow }} Nm³/h</span>
                <span class="data-item">上限: {{ alert.threshold }} Nm³/h</span>
              </div>
              <div class="alert-time">{{ alert.alertTime }}</div>
            </div>
            <div class="alert-action">
              <el-button size="small" type="primary" @click.stop="handleAlert(alert)">处理</el-button>
            </div>
          </div>
          <div v-if="realtimeAlerts.length === 0" class="empty-state">
            <el-empty description="暂无实时异常" :image-size="80" />
          </div>
        </div>
        <div class="pagination-area" v-if="realtimeAlerts.length > pageSize">
          <el-pagination small layout="prev, pager, next" :total="realtimeAlerts.length" :page-size="pageSize" v-model:current-page="realtimePage" />
        </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="pointName" label="监测点位" min-width="140" show-overflow-tooltip />
            <el-table-column prop="address" label="位置" min-width="160" show-overflow-tooltip />
            <el-table-column prop="flow" label="瞬时流量(Nm³/h)" width="130" sortable>
              <template #default="{ row }">
                <span class="alert-value">{{ row.flow }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="threshold" label="上限(Nm³/h)" width="110" />
            <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="filteredHistory.length"
              :page-size="historyPageSize"
              v-model:current-page="historyPage"
          />
        </div>
      </div>
    </div>

    <!-- 异常详情抽屉 -->
    <el-drawer v-model="detailDrawerVisible" :title="`异常详情 - ${currentAlert?.pointName}`" size="480px" direction="rtl" @opened="onDrawerOpened">
      <div v-if="currentAlert" class="alert-detail">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="监测点位">{{ currentAlert.pointName }}</el-descriptions-item>
          <el-descriptions-item label="点位编号">{{ currentAlert.pointCode }}</el-descriptions-item>
          <el-descriptions-item label="详细地址">{{ currentAlert.address }}</el-descriptions-item>
          <el-descriptions-item label="所属管线">{{ currentAlert.pipelineName }}</el-descriptions-item>
          <el-descriptions-item label="异常流量">{{ currentAlert.flow }} Nm³/h</el-descriptions-item>
          <el-descriptions-item label="报警阈值">{{ currentAlert.threshold }} Nm³/h</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 } from 'vue'
import { Warning, Refresh, Download, BellFilled, Document, Location, Search } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'

// ==================== 沅陵县管线流量异常报警数据 ====================
// 实时异常（当前未处理）
const realtimeAlerts = ref([
  { id: 1, pointCode: 'FL-YL-002', pointName: '辰州中路流量计2#', address: '沅陵县太常片区辰州中路调压站进口侧', pipelineName: '辰州中路高压段',
    flow: 2620, threshold: 2500, alertTime: '2026-06-13 15:31:45', status: 'pending',
    trendData: [2100, 2150, 2200, 2250, 2300, 2350, 2380, 2420, 2480, 2520, 2550, 2580, 2600, 2620, 2620, 2610, 2600, 2580, 2560, 2540, 2520, 2500, 2480, 2450] },
  { id: 2, pointCode: 'FL-YL-003', pointName: '古城中路流量计2#', address: '沅陵县太常片区古城中路太常安置区段', pipelineName: '古城中路中压段',
    flow: 820, threshold: 800, alertTime: '2026-06-13 15:29:58', status: 'pending',
    trendData: [680, 700, 720, 740, 750, 760, 770, 780, 790, 800, 810, 820, 820, 815, 810, 805, 800, 795, 790, 785, 780, 775, 770, 765] },
  { id: 3, pointCode: 'FL-YL-006', pointName: '滨江东路流量计2#', address: '沅陵县太常片区滨江东路商业街', pipelineName: '滨江东路低压段',
    flow: 210, threshold: 200, alertTime: '2026-06-13 15:30:40', status: 'pending',
    trendData: [155, 160, 165, 170, 175, 180, 185, 190, 195, 200, 205, 210, 210, 208, 206, 204, 200, 198, 195, 192, 190, 185, 180, 175] },
  { id: 4, pointCode: 'FL-YL-015', pointName: '建设东路流量计3#', address: '沅陵县太常片区建设东路工业园入口处', pipelineName: '建设东路高压段',
    flow: 2480, threshold: 2500, alertTime: '2026-06-13 14:55:20', status: 'pending',
    trendData: [2200, 2250, 2280, 2300, 2320, 2350, 2380, 2400, 2420, 2440, 2460, 2480, 2480, 2470, 2460, 2440, 2420, 2400, 2380, 2360, 2340, 2320, 2300, 2280] }
])

// 历史异常（已处理/待处理）
const historyAlerts = ref([
  { id: 101, pointCode: 'FL-YL-001', pointName: '辰州北路流量计1#', address: '沅陵县太常片区辰州北路门站出口计量间', pipelineName: '辰州北路高压段',
    flow: 2550, threshold: 2500, alertTime: '2026-06-12 14:30:00', status: 'resolved', resolveTime: '2026-06-12 15:45:00', handler: '张建国', remark: '下游用气高峰，调压后恢复正常',
    trendData: [2100, 2150, 2200, 2280, 2350, 2420, 2500, 2550, 2550, 2520, 2460, 2360, 2250, 2150, 2100, 2050, 2000, 1980, 1950, 1920, 1900, 1880, 1850, 1830] },
  { id: 102, pointCode: 'FL-YL-004', pointName: '古城北路流量计1#', address: '沅陵县太常片区古城北路与天宁路交叉口', pipelineName: '古城北路中压段',
    flow: 850, threshold: 800, alertTime: '2026-06-12 09:15:00', status: 'resolved', resolveTime: '2026-06-12 10:30:00', handler: '李志强', remark: '管网流量波动，阀门微调后稳定',
    trendData: [680, 700, 720, 740, 760, 780, 810, 840, 850, 850, 840, 810, 780, 750, 730, 710, 690, 680, 670, 660, 650, 640, 630, 620] },
  { id: 103, pointCode: 'FL-YL-007', pointName: '迎宾西路流量计1#', address: '沅陵县太常片区迎宾西路县政府对面', pipelineName: '迎宾西路中压段',
    flow: 520, threshold: 500, alertTime: '2026-06-11 16:20:00', status: 'pending', resolveTime: null, handler: null, remark: '持续超限，待现场巡检确认',
    trendData: [430, 440, 450, 460, 470, 480, 490, 500, 510, 520, 520, 520, 525, 530, 530, 525, 520, 520, 515, 510, 510, 505, 500, 495] },
  { id: 104, pointCode: 'FL-YL-012', pointName: '滨江东路流量计2#', address: '沅陵县太常片区滨江东路商业街', pipelineName: '滨江东路低压段',
    flow: 215, threshold: 200, alertTime: '2026-06-11 10:45:00', status: 'resolved', resolveTime: '2026-06-11 12:00:00', handler: '王大明', remark: '商业街午间用气高峰，属正常波动',
    trendData: [160, 165, 170, 178, 188, 195, 205, 212, 215, 215, 210, 200, 190, 180, 172, 165, 160, 156, 152, 150, 148, 145, 143, 140] },
  { id: 105, pointCode: 'FL-YL-009', pointName: '建设路流量计1#', address: '沅陵县太常片区建设路县政府南侧计量站', pipelineName: '建设路中压段',
    flow: 0, threshold: 800, alertTime: '2026-06-13 08:15:00', status: 'pending', resolveTime: null, handler: null, remark: '设备离线，数据中断，需现场检查',
    trendData: [820, 810, 800, 780, 750, 700, 620, 500, 350, 180, 50, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] },
  { id: 106, pointCode: 'FL-YL-015', pointName: '建设东路流量计3#', address: '沅陵县太常片区建设东路工业园入口处', pipelineName: '建设东路高压段',
    flow: 2580, threshold: 2500, alertTime: '2026-06-10 22:30:00', status: 'resolved', resolveTime: '2026-06-10 23:15:00', handler: '赵志远', remark: '工业园区夜间加班用气高峰导致',
    trendData: [2200, 2250, 2300, 2350, 2400, 2450, 2500, 2550, 2580, 2580, 2550, 2480, 2380, 2280, 2200, 2150, 2100, 2080, 2050, 2020, 2000, 1980, 1950, 1930] },
  { id: 107, pointCode: 'FL-YL-002', pointName: '辰州中路流量计2#', address: '沅陵县太常片区辰州中路调压站进口侧', pipelineName: '辰州中路高压段',
    flow: 2510, threshold: 2500, alertTime: '2026-06-10 18:20:00', status: 'resolved', resolveTime: '2026-06-10 19:30:00', handler: '陈志明', remark: '晚高峰居民用气激增，调压后恢复',
    trendData: [2180, 2220, 2280, 2350, 2420, 2480, 2510, 2510, 2480, 2400, 2300, 2220, 2150, 2100, 2060, 2020, 1980, 1950, 1920, 1900, 1880, 1850, 1830, 1800] }
])

// 统计数据
const totalPoints = computed(() => 15)
const realtimeTrend = computed(() => 1)
const todayHistoryCount = computed(() => historyAlerts.value.filter(a => a.alertTime.startsWith('2026-06-13')).length)
const pendingCount = computed(() => historyAlerts.value.filter(a => a.status === 'pending').length)
const abnormalRate = computed(() => (realtimeAlerts.value.length / totalPoints.value * 100).toFixed(1))
const avgResponseTime = computed(() => 62)

// 筛选
const dateRange = ref([])
const historySearch = ref('')
const realtimePage = ref(1)
const historyPage = ref(1)
const pageSize = 5
const historyPageSize = 8

const filteredHistory = computed(() => {
  let list = historyAlerts.value
  if (dateRange.value && dateRange.value.length === 2) {
    const start = new Date(dateRange.value[0])
    const end = new Date(dateRange.value[1])
    list = list.filter(a => {
      const alertDate = new Date(a.alertTime)
      return alertDate >= start && alertDate <= end
    })
  }
  if (historySearch.value) {
    const kw = historySearch.value.toLowerCase()
    list = list.filter(a => a.pointName.toLowerCase().includes(kw) || a.address.toLowerCase().includes(kw))
  }
  return list
})

const paginatedRealtime = computed(() => {
  const start = (realtimePage.value - 1) * pageSize
  return realtimeAlerts.value.slice(start, start + pageSize)
})

const paginatedHistory = computed(() => {
  const start = (historyPage.value - 1) * historyPageSize
  return filteredHistory.value.slice(start, start + historyPageSize)
})

// 当前选中告警
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: 'Nm³/h', min: 0 },
    series: [
      { name: '瞬时流量', type: 'line', data: currentAlert.value.trendData, smooth: true, symbol: 'circle', symbolSize: 3, lineStyle: { color: '#f56c6c', width: 2 }, itemStyle: { color: '#f56c6c' }, areaStyle: { color: 'rgba(245,108,108,0.1)' } },
      { name: '报警阈值', type: 'line', data: Array(24).fill(threshold), lineStyle: { color: '#e6a23c', width: 2, type: 'dashed' }, symbol: 'none', itemStyle: { color: '#e6a23c' } }
    ]
  })
}

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

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

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

const resolveAlert = () => {
  if (currentAlert.value.status === 'pending') {
    // 从实时异常移到历史异常
    const index = realtimeAlerts.value.findIndex(a => a.id === currentAlert.value.id)
    if (index !== -1) {
      const resolved = { ...currentAlert.value, status: 'resolved', resolveTime: new Date().toLocaleString(), handler: '当前用户' }
      realtimeAlerts.value.splice(index, 1)
      historyAlerts.value.unshift(resolved)
    } else {
      // 如果是历史异常中的待处理
      const histIndex = historyAlerts.value.findIndex(a => a.id === currentAlert.value.id)
      if (histIndex !== -1) {
        historyAlerts.value[histIndex].status = 'resolved'
        historyAlerts.value[histIndex].resolveTime = new Date().toLocaleString()
        historyAlerts.value[histIndex].handler = '当前用户'
      }
    }
    currentAlert.value.status = 'resolved'
    ElMessage.success('已标记为已处理')
    detailDrawerVisible.value = false
  }
}

const dispatchWorkOrder = () => {
  ElMessage.success('已派发维修工单')
}

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

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

// 监听日期范围变化重置页码
watch([dateRange, historySearch], () => { historyPage.value = 1 })

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

<style scoped>
.pressure-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; }

.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-label { font-size: 13px; color: #909399; margin-top: 4px; }
.kpi-trend { font-size: 11px; color: #67c23a; margin-top: 4px; }
.kpi-trend.trend-down { color: #f56c6c; }

.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;
  background: #fff8f8;
  border: 1px solid #ffd4d4;
  cursor: pointer;
  transition: all 0.2s;
}
.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-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; }
.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-value { color: #f56c6c; font-weight: bold; }

.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>