<!--管线压力监测-->
<template>
  <div class="pressure-monitor">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <el-icon><Odometer /></el-icon>
        <span class="title">管线压力监测</span>
        <div class="stats-badge">
          <span class="stat-item normal"><i class="dot"></i>正常 {{ normalCount }}</span>
          <span class="stat-item warning"><i class="dot"></i>预警 {{ warningCount }}</span>
          <span class="stat-item danger"><i class="dot"></i>告警 {{ dangerCount }}</span>
          <span class="stat-item offline"><i class="dot"></i>离线 {{ offlineCount }}</span>
        </div>
      </div>
      <div class="header-right">
        <el-input v-model="searchKeyword" placeholder="搜索测点名称/管线" clearable :prefix-icon="Search" style="width:200px" />
        <el-button type="primary" :icon="Refresh" @click="refreshData">刷新</el-button>
      </div>
    </div>

    <!-- 主内容区：左侧测点列表 + 右侧压力趋势 -->
    <div class="main-layout">
      <!-- 左侧：测点列表 -->
      <div class="point-list-panel">
        <div class="list-header">
          <span>压力监测点</span>
          <span class="total-num">共 {{ filteredPoints.length }} 个测点</span>
        </div>
        <div class="filter-row">
          <el-select v-model="pressureLevel" placeholder="压力等级" clearable size="small" style="width:100%">
            <el-option label="高压" value="high" />
            <el-option label="中压" value="medium" />
            <el-option label="低压" value="low" />
          </el-select>
        </div>
        <div class="filter-row">
          <el-select v-model="statusFilter" placeholder="运行状态" clearable size="small" style="width:100%">
            <el-option label="正常" value="normal" />
            <el-option label="预警" value="warning" />
            <el-option label="告警" value="danger" />
            <el-option label="离线" value="offline" />
          </el-select>
        </div>
        <div class="point-list">
          <div
            v-for="point in filteredPoints"
            :key="point.pointId"
            class="point-item"
            :class="{ active: selectedPoint?.pointId === point.pointId, [point.status]: true }"
            @click="selectPoint(point)"
          >
            <div class="point-header">
              <span class="point-name">{{ point.name }}</span>
              <el-tag :type="statusTagType(point.status)" size="small">{{ statusLabel(point.status) }}</el-tag>
            </div>
            <div class="point-pipeline">{{ point.pipelineName }}</div>
            <div class="point-value">
              <span class="val">{{ point.latestPressure }}</span>
              <span class="unit">kPa</span>
              <span class="threshold">阈值: {{ point.minPressure }}~{{ point.maxPressure }} kPa</span>
            </div>
            <div class="point-addr">{{ point.address }}</div>
            <div class="point-time">{{ point.latestTime }}</div>
          </div>
          <el-empty v-if="filteredPoints.length === 0" description="暂无匹配测点" :image-size="50" />
        </div>
      </div>

      <!-- 右侧：压力详情 -->
      <div class="detail-panel">
        <template v-if="selectedPoint">
          <!-- 测点信息卡片 -->
          <div class="detail-header">
            <div class="detail-title">
              <span class="point-name">{{ selectedPoint.name }}</span>
              <el-tag :type="statusTagType(selectedPoint.status)" size="small">{{ statusLabel(selectedPoint.status) }}</el-tag>
            </div>
            <div class="detail-meta">
              <span>所属管线：{{ selectedPoint.pipelineName }}</span>
              <span>压力等级：{{ pressureLevelLabel(selectedPoint.pressureLevel) }}</span>
              <span>安装位置：{{ selectedPoint.address }}</span>
              <span>监测单位：沅陵县燃气安全监测中心</span>
            </div>
          </div>

          <!-- 实时读数卡片 -->
          <div class="gauge-cards">
            <div class="gauge-card" :class="selectedPoint.status">
              <div class="gauge-label">当前压力</div>
              <div class="gauge-value">{{ selectedPoint.latestPressure }} <span class="unit">kPa</span></div>
              <div class="gauge-sub">采集时间 {{ selectedPoint.latestTime }}</div>
            </div>
            <div class="gauge-card">
              <div class="gauge-label">今日最高</div>
              <div class="gauge-value high">{{ todayMax }} <span class="unit">kPa</span></div>
              <div class="gauge-sub">近24小时</div>
            </div>
            <div class="gauge-card">
              <div class="gauge-label">今日最低</div>
              <div class="gauge-value low">{{ todayMin }} <span class="unit">kPa</span></div>
              <div class="gauge-sub">近24小时</div>
            </div>
            <div class="gauge-card">
              <div class="gauge-label">压力状态</div>
              <div class="gauge-status" :class="selectedPoint.status">{{ statusLabel(selectedPoint.status) }}</div>
              <div class="gauge-sub">阈值 {{ selectedPoint.minPressure }}~{{ selectedPoint.maxPressure }} kPa</div>
            </div>
          </div>

          <!-- 压力趋势图 -->
          <div class="chart-card">
            <div class="chart-header">
              <span>压力趋势（近10天）</span>
              <div class="chart-legend">
                <span class="leg-item"><i class="leg-dot pressure"></i> 实测压力</span>
                <span class="leg-item"><i class="leg-line max"></i> 上限</span>
                <span class="leg-item"><i class="leg-line min"></i> 下限</span>
              </div>
            </div>
            <div ref="chartRef" class="chart-container"></div>
          </div>

          <!-- 历史数据表格 -->
          <div class="table-card">
            <div class="table-header">
              <span>历史监测记录</span>
            </div>
            <el-table :data="pagedHistory" border stripe size="small">
              <el-table-column prop="time" label="采集时间" width="160" />
              <el-table-column prop="pressure" label="压力值(kPa)" width="120">
                <template #default="{ row }">
                  <span :style="{ color: row.pressure > selectedPoint.maxPressure || row.pressure < selectedPoint.minPressure ? '#f56c6c' : '#303133', fontWeight: row.pressure > selectedPoint.maxPressure || row.pressure < selectedPoint.minPressure ? '600' : '400' }">
                    {{ row.pressure }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column prop="status" label="状态" width="100">
                <template #default="{ row }">
                  <el-tag :type="row.pressure > selectedPoint.maxPressure || row.pressure < selectedPoint.minPressure ? 'danger' : 'success'" size="small">
                    {{ row.pressure > selectedPoint.maxPressure || row.pressure < selectedPoint.minPressure ? '异常' : '正常' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="collector" label="采集设备" min-width="140" />
              <el-table-column prop="remark" label="备注" min-width="120" show-overflow-tooltip />
            </el-table>
            <el-pagination
                v-model:current-page="historyPage"
                v-model:page-size="historyPageSize"
                :total="pagedTotal"
                layout="total, prev, pager, next"
                small
            />
          </div>

        </template>

        <!-- 未选中状态 -->
        <div v-else class="empty-detail">
          <el-empty description="请从左侧选择压力监测点查看详情" :image-size="100" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount, nextTick, watch } from 'vue'
import { Odometer, Search, Refresh } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import { getPressureMonitorPoints, getPressureMonitorTrend, getPressureMonitorHistory } from '@/api/pipeNetwork/gasMonitor'

// 筛选
const searchKeyword = ref('')
const pressureLevel = ref('')
const statusFilter = ref('')

// 选中测点
const selectedPoint = ref(null)

// 历史数据分页
const historyPage = ref(1)
const historyPageSize = ref(10)

// ECharts实例
const chartRef = ref(null)
let chartInstance = null

// ==================== 从后端加载测点数据 ====================
const points = ref([])
const loading = ref(false)
const trendData = ref({ times: [], pressures: [], minPressure: 0, maxPressure: 0 })
const historyTotal = ref(0)

async function loadPoints() {
  loading.value = true
  try {
    const res = await getPressureMonitorPoints()
    points.value = res.data || []
    if (points.value.length > 0) {
      selectPoint(points.value[0])
    }
  } finally {
    loading.value = false
  }
}

// 统计数据
const normalCount = computed(() => points.value.filter(p => p.status === 'normal').length)
const warningCount = computed(() => points.value.filter(p => p.status === 'warning').length)
const dangerCount = computed(() => points.value.filter(p => p.status === 'danger').length)
const offlineCount = computed(() => points.value.filter(p => p.status === 'offline').length)

// 筛选
const filteredPoints = computed(() => {
  let list = points.value
  if (searchKeyword.value) {
    const kw = searchKeyword.value.toLowerCase()
    list = list.filter(p => p.name.toLowerCase().includes(kw) || p.pipelineName.toLowerCase().includes(kw))
  }
  if (pressureLevel.value) list = list.filter(p => p.pressureLevel === pressureLevel.value)
  if (statusFilter.value) list = list.filter(p => p.status === statusFilter.value)
  return list
})

function statusTagType(status) {
  const map = { normal: 'success', warning: 'warning', danger: 'danger', offline: 'info' }
  return map[status] || 'info'
}
function statusLabel(status) {
  const map = { normal: '正常', warning: '预警', danger: '告警', offline: '离线' }
  return map[status] || '未知'
}
function pressureLevelLabel(level) {
  const map = { high: '高压 (0.4MPa)', medium: '中压 (0.2MPa)', low: '低压 (0.1MPa)' }
  return map[level] || level
}

// ==================== 历史数据（从API分页获取） ====================
const historyData = ref([])
const pagedHistory = ref([])
const pagedTotal = ref(0)

async function loadHistory() {
  if (!selectedPoint.value) return
  try {
    const res = await getPressureMonitorHistory(selectedPoint.value.pointId, historyPage.value, historyPageSize.value)
    const data = res.data || {}
    pagedHistory.value = data.rows || []
    pagedTotal.value = data.total || 0
  } catch {
    pagedHistory.value = []
    pagedTotal.value = 0
  }
}

// 今日极值
const todayMax = computed(() => {
  const today = new Date().toISOString().substring(0, 10)
  const todayData = pagedHistory.value.filter(d => d.time && d.time.startsWith(today))
  if (!todayData.length) return '--'
  return Math.max(...todayData.map(d => d.pressure))
})
const todayMin = computed(() => {
  const today = new Date().toISOString().substring(0, 10)
  const todayData = pagedHistory.value.filter(d => d.time && d.time.startsWith(today))
  if (!todayData.length) return '--'
  return Math.min(...todayData.map(d => d.pressure))
})

// ==================== 选择测点 ====================
async function selectPoint(point) {
  selectedPoint.value = point
  historyPage.value = 1
  // 并行加载趋势和分页历史
  await Promise.all([loadTrend(point.pointId), loadHistory()])
  nextTick(() => renderChart())
}

async function loadTrend(pointId) {
  try {
    const res = await getPressureMonitorTrend(pointId, 10)
    if (res.data) {
      trendData.value = res.data
    }
  } catch {
    trendData.value = { times: [], pressures: [], minPressure: 0, maxPressure: 0 }
  }
}

// ==================== ECharts趋势图 ====================
function renderChart() {
  if (!chartRef.value || !selectedPoint.value) return
  if (!chartInstance) {
    chartInstance = echarts.init(chartRef.value)
  }
  const point = selectedPoint.value
  const times = trendData.value.times || []
  const pressures = trendData.value.pressures || []

  chartInstance.setOption({
    tooltip: {
      trigger: 'axis',
      formatter: params => {
        const p = params[0]
        const val = p.value
        const status = val > point.maxPressure ? '⚠ 超上限' : val < point.minPressure ? '⚠ 低于下限' : '✓ 正常'
        return `${p.axisValue.replace('\n', ' ')}<br/>压力: <b>${val} kPa</b> ${status}`
      }
    },
    grid: { left: '3%', right: '5%', top: 20, bottom: 30, containLabel: true },
    xAxis: {
      type: 'category', data: times, boundaryGap: false,
      axisLine: { lineStyle: { color: '#ccc' } },
      axisTick: { show: false },
      axisLabel: { fontSize: 10, interval: 5 }
    },
    yAxis: {
      type: 'value', name: 'kPa',
      axisLine: { show: false }, axisTick: { show: false },
      splitLine: { lineStyle: { color: '#f0f0f0' } },
      min: Math.min(point.minPressure - 30, ...pressures.filter(v => v > 0)) - 10,
      max: Math.max(point.maxPressure + 30, ...pressures) + 10
    },
    series: [
      {
        name: '实测压力', type: 'line', data: pressures,
        smooth: true, symbol: 'circle', symbolSize: 4,
        lineStyle: { width: 2, color: '#409eff' },
        itemStyle: { color: '#409eff' },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(64,158,255,0.25)' },
            { offset: 1, color: 'rgba(64,158,255,0.02)' }
          ])
        },
        markLine: {
          silent: true,
          symbol: 'none',
          label: { fontSize: 11, formatter: '{b} {c} kPa' },
          data: [
            { name: '上限', yAxis: point.maxPressure, lineStyle: { color: '#f56c6c', type: 'dashed', width: 1.5 } },
            { name: '下限', yAxis: point.minPressure, lineStyle: { color: '#e6a23c', type: 'dashed', width: 1.5 } }
          ]
        }
      }
    ]
  })
}

async function refreshData() {
  await loadPoints()
}

// 分页变化时重载历史
watch(historyPage, () => { loadHistory() })

onMounted(() => {
  window.addEventListener('resize', () => { try { chartInstance?.resize() } catch {} })
  loadPoints()
})

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

<style scoped>
.pressure-monitor {
  background: #f0f2f6;
  height: 100vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.page-header {
  background: #fff;
  padding: 12px 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #e9ecef;
  flex-shrink: 0;
}
.header-left { display: flex; align-items: center; gap: 20px; }
.header-left .title { font-size: 1.25rem; 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 .dot { width: 8px; height: 8px; border-radius: 50%; }
.stat-item.normal { color: #67c23a; } .stat-item.normal .dot { background: #67c23a; }
.stat-item.warning { color: #e6a23c; } .stat-item.warning .dot { background: #e6a23c; }
.stat-item.danger { color: #f56c6c; } .stat-item.danger .dot { background: #f56c6c; }
.stat-item.offline { color: #909399; } .stat-item.offline .dot { background: #909399; }
.header-right { display: flex; gap: 12px; }

.main-layout {
  display: flex;
  flex: 1;
  overflow: hidden;
  padding: 12px;
  gap: 12px;
}

/* 左侧测点列表 */
.point-list-panel {
  width: 360px;
  background: #fff;
  border-radius: 12px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  flex-shrink: 0;
}
.list-header {
  padding: 14px 16px;
  border-bottom: 1px solid #e9ecef;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
}
.total-num { font-size: 12px; color: #909399; font-weight: 400; }
.filter-row { padding: 6px 16px; }
.point-list { flex: 1; overflow-y: auto; padding: 4px 8px 8px; }
.point-item {
  padding: 12px;
  margin-bottom: 6px;
  border-radius: 12px;
  background: #fafbfc;
  cursor: pointer;
  transition: all 0.2s;
  border: 1px solid #e9ecef;
}
.point-item:hover { background: #f0f5ff; }
.point-item.active { background: #ecf5ff; border-color: #409eff; }
.point-item.danger { border-left: 3px solid #f56c6c; }
.point-item.warning { border-left: 3px solid #e6a23c; }
.point-item.offline { opacity: 0.65; }
.point-header { display: flex; align-items: center; gap: 8px; margin-bottom: 4px; }
.point-name { font-weight: 600; font-size: 14px; flex: 1; }
.point-pipeline { font-size: 12px; color: #909399; margin-bottom: 6px; }
.point-value { display: flex; align-items: baseline; gap: 6px; margin-bottom: 4px; }
.point-value .val { font-size: 24px; font-weight: 700; color: #1f2d3d; }
.point-value .unit { font-size: 12px; color: #909399; }
.point-value .threshold { font-size: 11px; color: #c0c4cc; margin-left: auto; }
.point-addr { font-size: 11px; color: #909399; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.point-time { font-size: 11px; color: #c0c4cc; margin-top: 2px; }

/* 右侧详情面板 */
.detail-panel {
  flex: 1;
  background: #fff;
  border-radius: 12px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}
.empty-detail {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.detail-header {
  padding: 16px 20px;
  border-bottom: 1px solid #e9ecef;
}
.detail-title { display: flex; align-items: center; gap: 12px; margin-bottom: 8px; }
.detail-title .point-name { font-size: 18px; font-weight: 600; }
.detail-meta { display: flex; flex-wrap: wrap; gap: 0 24px; font-size: 13px; color: #909399; }

/* 读数卡片 */
.gauge-cards {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
  padding: 16px 20px;
}
.gauge-card {
  background: #f8f9fc;
  border-radius: 12px;
  padding: 16px;
  text-align: center;
}
.gauge-card.danger { background: #fef0f0; }
.gauge-card.warning { background: #fdf6ec; }
.gauge-label { font-size: 12px; color: #909399; margin-bottom: 8px; }
.gauge-value { font-size: 28px; font-weight: 700; color: #1f2d3d; }
.gauge-value .unit { font-size: 13px; font-weight: 400; color: #909399; }
.gauge-value.high { color: #f56c6c; }
.gauge-value.low { color: #67c23a; }
.gauge-status { font-size: 20px; font-weight: 700; }
.gauge-status.normal { color: #67c23a; }
.gauge-status.warning { color: #e6a23c; }
.gauge-status.danger { color: #f56c6c; }
.gauge-status.offline { color: #909399; }
.gauge-sub { font-size: 11px; color: #c0c4cc; margin-top: 6px; }

/* 趋势图 */
.chart-card {
  margin: 0 20px 16px;
  padding: 16px;
  background: #fafbfc;
  border-radius: 12px;
}
.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  font-weight: 600;
}
.chart-legend { display: flex; gap: 16px; font-size: 12px; font-weight: 400; }
.leg-item { display: flex; align-items: center; gap: 4px; }
.leg-dot { width: 10px; height: 10px; border-radius: 50%; display: inline-block; }
.leg-dot.pressure { background: #409eff; }
.leg-line { width: 20px; height: 2px; display: inline-block; }
.leg-line.max { background: #f56c6c; background: repeating-linear-gradient(90deg, #f56c6c 0, #f56c6c 4px, transparent 4px, transparent 7px); }
.leg-line.min { background: #e6a23c; background: repeating-linear-gradient(90deg, #e6a23c 0, #e6a23c 4px, transparent 4px, transparent 7px); }
.chart-container { width: 100%; height: 300px; }

/* 历史表格 */
.table-card {
  margin: 0 20px 16px;
  padding: 16px;
  background: #fafbfc;
  border-radius: 12px;
  flex: 1;
  overflow: auto;
}
.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  font-weight: 600;
}
</style>
