<!--管线压力异常提醒-->
<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>实时异常 {{ alarmStats.realtimeCount }}</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">{{ 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">{{ 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">{{ alarmStats.realtimeCount }} 个异常</el-tag>
        </div>
        <div class="alert-list realtime">
          <div
              v-for="alert in paginatedRealtime"
              :key="alert.id || alert.equipmentId"
              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.pressure }} kPa</span>
                <span class="data-item">流量: {{ alert.flow }} m³/h</span>
                <span class="data-item">阈值: {{ alert.threshold }} kPa</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="alarmStats.realtimeCount === 0" class="empty-state">
            <el-empty description="暂无实时异常" :image-size="80" />
          </div>
        </div>
        <div class="pagination-area" v-if="alarmStats.realtimeCount > realtimePageSize">
          <el-pagination
            small
            layout="prev, pager, next"
            :total="alarmStats.realtimeCount"
            :page-size="realtimePageSize"
            v-model:current-page="realtimePage"
            @update:current-page="handleRealtimePageChange"
          />
        </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="pressure" label="异常压力(kPa)" width="110" sortable>
              <template #default="{ row }">
                <span class="alert-value">{{ row.pressure }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="flow" label="实时流量(m³/h)" width="110" />
            <el-table-column prop="threshold" label="阈值(kPa)" width="90" />
            <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"
              @update:current-page="handleHistoryPageChange"
          />
        </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.pressure }} kPa</el-descriptions-item>
          <el-descriptions-item label="实时流量">{{ currentAlert.flow }} m³/h</el-descriptions-item>
          <el-descriptions-item label="报警阈值">{{ currentAlert.threshold }} kPa</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 } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'
import { getPressureAlarmEquipment, getPressureAlarmHistory, getPressureAlarmStats, resolvePressureAlarm, dispatchPressureAlarm } from '@/api/pipeNetwork/basic'

// 从 API 加载
const equipments = ref([])
const selectedEquipment = ref(null)
const historyAlerts = ref([])
const realtimePage = ref(1)
const realtimePageSize = 10
const historyPage = ref(1)
const historyPageSize = 8
const historyTotal = ref(0)
const alarmStats = ref({ realtimeCount: 0, pendingCount: 0, maxPressure: 0, totalPoints: 0 })

async function loadEquipment() {
  try {
    const res = await getPressureAlarmEquipment()
    equipments.value = (res.data || []).map(e => ({ ...e,
      pointName: e.equipmentName, address: e.location,
      pressure: e.latestPressure, threshold: e.latestThreshold || 250,
      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 getPressureAlarmHistory(historyPage.value, historyPageSize, d?.[0] || '', d?.[1] || '', currentDeviceCode.value || '')
    historyAlerts.value = (res.data?.records || []).map(a => ({
      id: a.id, pointCode: a.deviceCode, pointName: a.pointName, address: a.address,
      pressure: a.pressure, threshold: a.threshold || 250, alertTime: a.alarmTime, status: a.alarmStatus === 0 ? 'pending' : 'resolved',
      resolveTime: a.resolveTime, handler: a.handler, remark: a.remark, flow: 0
    }))
    historyTotal.value = res.data?.total || 0
  } catch (e) { console.error(e) }
}

function handleRealtimePageChange(newPage) {
  realtimePage.value = newPage
}

function handleHistoryPageChange(newPage) {
  historyPage.value = newPage
  loadHistory()
}
function selectEquipment(eq) {
  selectedEquipment.value = eq
  currentDeviceCode.value = eq.equipmentCode
  historyPage.value = 1; loadHistory()
}

const realtimeTrend = 1
const todayHistoryCount = ref(0)
const pendingCount = computed(() => alarmStats.value.pendingCount)
const totalPoints = computed(() => alarmStats.value.totalPoints)
const abnormalRate = computed(() => totalPoints.value > 0 ? ((alarmStats.value.realtimeCount / totalPoints.value) * 100).toFixed(1) : 0)
const avgResponseTime = computed(() => '--')
const dateRange = ref([])
const historySearch = ref('')

// 实时异常分页
const paginatedRealtime = computed(() => {
  const start = (realtimePage.value - 1) * realtimePageSize
  return equipments.value.slice(start, start + realtimePageSize)
})

// 历史异常筛选和分页
const filteredHistory = computed(() => {
  if (!historySearch.value) return historyAlerts.value
  const keyword = historySearch.value.toLowerCase()
  return historyAlerts.value.filter(item => 
    item.pointName?.toLowerCase().includes(keyword) || 
    item.address?.toLowerCase().includes(keyword)
  )
})

const paginatedHistory = computed(() => {
  const start = (historyPage.value - 1) * historyPageSize
  const filtered = filteredHistory.value
  return filtered.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) return
  if (!chartInstance) chartInstance = echarts.init(chartRef.value)
  const threshold = currentAlert.value.threshold
  chartInstance.setOption({
    tooltip: { trigger: 'axis' },
    xAxis: { type: 'category', data: Array.from({length:24},(_,i)=>`${i}:00`), axisLabel:{rotate:45,interval:4} },
    yAxis: { type: 'value', name: '压力(kPa)' },
    series: [
      { name:'实时压力', type:'line', data: Array(24).fill(currentAlert.value.pressure||0), 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 = (a) => { currentAlert.value = a; detailDrawerVisible.value = true }
const handleAlert = (a) => { currentAlert.value = a; detailDrawerVisible.value = true }
const resolveAlert = async () => {
  if (currentAlert.value?.status === 'pending') {
    try {
      await resolvePressureAlarm(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 dispatchPressureAlarm(currentAlert.value.id); ElMessage.success('已派发工单(伪)') } catch (e) { ElMessage.error('派发失败') } }
}
async function loadStats() {
  try { const res = await getPressureAlarmStats(); if (res.data) alarmStats.value = res.data } catch (e) { console.error(e) }
}
const refreshData = () => { loadEquipment(); loadStats() }
const exportReport = () => { ElMessage.success('导出报表（演示）') }

watch(dateRange, () => { historyPage.value = 1; loadHistory() })

onMounted(async () => { await loadEquipment(); await loadHistory(); await loadStats() })
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>