<!--监测阈值管理-->
<template>
  <div class="threshold-management">
    <!-- 主内容区域 -->
    <div class="main-content">
      <!-- 左侧：监测点列表 -->
      <div class="point-list-panel">
        <div class="panel-title">
          <span>监测点列表</span>
          <el-input v-model="searchKeyword" placeholder="搜索设备编号/名称" clearable :prefix-icon="Search" size="small" style="width: 180px" />
        </div>
        <div class="point-list">
          <div
              v-for="point in filteredPoints"
              :key="point.id"
              class="point-item"
              :class="{ active: selectedPoint?.id === point.id }"
              @click="selectPoint(point)"
          >
            <div class="point-header">
              <span class="point-name">{{ point.name }}</span>
              <el-tag :type="getPointStatusType(point)" size="small">{{ point.status }}</el-tag>
            </div>
            <div class="point-location">
              <el-icon><Location /></el-icon> {{ point.location }}
            </div>
            <div class="point-device">{{ point.deviceModel }}</div>
          </div>
        </div>
      </div>

      <!-- 右侧：阈值配置详情区 -->
      <div class="config-panel" v-if="selectedPoint">
        <!-- 设备基本信息卡片 -->
        <div class="info-card">
          <div class="card-title">
            <span><el-icon><Monitor /></el-icon> 监测设备基本信息</span>
          </div>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="设备编号">{{ selectedPoint.deviceId }}</el-descriptions-item>
            <el-descriptions-item label="设备类型">{{ selectedPoint.deviceType }}</el-descriptions-item>
            <el-descriptions-item label="设备型号">{{ selectedPoint.deviceModel }}</el-descriptions-item>
            <el-descriptions-item label="生产厂商">{{ selectedPoint.manufacturer }}</el-descriptions-item>
            <el-descriptions-item label="安装日期">{{ selectedPoint.installDate }}</el-descriptions-item>
            <el-descriptions-item label="通讯协议">{{ selectedPoint.protocol }}</el-descriptions-item>
            <el-descriptions-item label="监测点ID">{{ selectedPoint.id }}</el-descriptions-item>
            <el-descriptions-item label="最近校准">{{ selectedPoint.lastCalibration }}</el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 阈值配置区域 - 多参数标签页 -->
        <div class="threshold-card">
          <div class="card-title">
            <span><el-icon><Setting /></el-icon> 报警阈值设置</span>
            <div class="card-actions">
              <el-button size="small" @click="resetThresholds">重置</el-button>
              <el-button size="small" type="primary" @click="saveThresholds">保存设置</el-button>
            </div>
          </div>

          <el-tabs v-model="activeTab" class="threshold-tabs">
            <!-- 倾斜阈值 -->
            <el-tab-pane label="倾斜监测" name="tilt">
              <div class="threshold-config">
                <div class="threshold-item">
                  <div class="item-label">
                    <span>倾斜角度阈值</span>
                    <el-tooltip content="当井盖倾斜角度超过此值时触发报警" placement="top">
                      <el-icon><QuestionFilled /></el-icon>
                    </el-tooltip>
                  </div>
                  <div class="item-control">
                    <el-input-number v-model="thresholds.tilt.warning" :min="0" :max="45" :step="0.5" size="default" style="width: 120px" />
                    <span class="unit">度</span>
                    <span class="level-tag warning">预警值</span>
                    <el-input-number v-model="thresholds.tilt.critical" :min="0" :max="90" :step="0.5" size="default" style="width: 120px; margin-left: 20px" />
                    <span class="unit">度</span>
                    <span class="level-tag critical">告警值</span>
                  </div>
                  <div class="history-suggestion">
                    <el-icon><DataLine /></el-icon>
                    历史数据分析建议: 基于近30天数据，95%倾斜角在 <strong>{{ suggested.tilt.suggestedWarning }}°</strong> 以内，建议预警值 ≤ {{ suggested.tilt.suggestedWarning }}
                  </div>
                </div>
              </div>
            </el-tab-pane>

            <!-- 水位/溢水阈值 -->
            <el-tab-pane label="水位监测" name="water">
              <div class="threshold-config">
                <div class="threshold-item">
                  <div class="item-label">水位深度阈值</div>
                  <div class="item-control">
                    <el-input-number v-model="thresholds.water.warning" :min="0" :max="100" :step="1" style="width: 120px" />
                    <span class="unit">cm</span>
                    <span class="level-tag warning">预警值</span>
                    <el-input-number v-model="thresholds.water.critical" :min="0" :max="150" :step="1" style="width: 120px; margin-left: 20px" />
                    <span class="unit">cm</span>
                    <span class="level-tag critical">告警值</span>
                  </div>
                  <div class="history-suggestion">
                    <el-icon><DataLine /></el-icon>
                    历史最高水位: {{ selectedPoint.historyData?.maxWaterLevel || 32 }}cm，建议告警值设置在 {{ suggested.water.suggestedCritical }}cm
                  </div>
                </div>
              </div>
            </el-tab-pane>

            <!-- 震动阈值 -->
            <el-tab-pane label="震动监测" name="vibration">
              <div class="threshold-config">
                <div class="threshold-item">
                  <div class="item-label">震动强度阈值</div>
                  <div class="item-control">
                    <el-input-number v-model="thresholds.vibration.warning" :min="0" :max="200" :step="5" style="width: 120px" />
                    <span class="unit">mg</span>
                    <span class="level-tag warning">预警值</span>
                    <el-input-number v-model="thresholds.vibration.critical" :min="0" :max="300" :step="5" style="width: 120px; margin-left: 20px" />
                    <span class="unit">mg</span>
                    <span class="level-tag critical">告警值</span>
                  </div>
                  <div class="history-suggestion">
                    <el-icon><DataLine /></el-icon>
                    历史震动峰值: {{ selectedPoint.historyData?.maxVibration || 78 }}mg，建议阈值动态调整
                  </div>
                </div>
              </div>
            </el-tab-pane>

            <!-- 气体阈值 -->
            <el-tab-pane label="有害气体" name="gas">
              <div class="threshold-config">
                <div class="threshold-item">
                  <div class="item-label">H₂S浓度阈值</div>
                  <div class="item-control">
                    <el-input-number v-model="thresholds.gas.warning" :min="0" :max="50" :step="1" style="width: 120px" />
                    <span class="unit">ppm</span>
                    <span class="level-tag warning">预警值</span>
                    <el-input-number v-model="thresholds.gas.critical" :min="0" :max="100" :step="1" style="width: 120px; margin-left: 20px" />
                    <span class="unit">ppm</span>
                    <span class="level-tag critical">告警值</span>
                  </div>
                </div>
              </div>
            </el-tab-pane>

            <!-- 电池/信号阈值 -->
            <el-tab-pane label="设备状态" name="device">
              <div class="threshold-config">
                <div class="threshold-item">
                  <div class="item-label">电池电压阈值</div>
                  <div class="item-control">
                    <el-input-number v-model="thresholds.battery.warning" :min="0" :max="100" :step="5" style="width: 120px" />
                    <span class="unit">%</span>
                    <span class="level-tag warning">低电量预警</span>
                  </div>
                </div>
                <div class="threshold-item">
                  <div class="item-label">信号强度阈值</div>
                  <div class="item-control">
                    <el-input-number v-model="thresholds.signal.warning" :min="0" :max="100" :step="5" style="width: 120px" />
                    <span class="unit">%</span>
                    <span class="level-tag warning">弱信号预警</span>
                  </div>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>

        <!-- 历史监测数据趋势图 (帮助科学设置阈值) -->
        <div class="history-chart-card">
          <div class="card-title">
            <span><el-icon><TrendCharts /></el-icon> 历史监测数据趋势（近30天）</span>
            <el-select v-model="historyMetric" size="small" style="width: 120px">
              <el-option label="倾斜角度" value="tilt" />
              <el-option label="水位深度" value="water" />
              <el-option label="震动强度" value="vibration" />
              <el-option label="气体浓度" value="gas" />
            </el-select>
          </div>
          <div class="chart-container">
            <v-chart :option="historyChartOption" autoresize />
          </div>

        </div>
      </div>

      <!-- 未选中状态 -->
      <div v-else class="empty-panel">
        <el-empty description="请从左侧选择一个监测点查看阈值配置" :image-size="140" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { Location, Monitor, Setting, QuestionFilled, DataLine, TrendCharts, Document, Check, Search } from '@element-plus/icons-vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart } from 'echarts/charts'
import { TitleComponent, TooltipComponent, LegendComponent, GridComponent, ToolboxComponent } from 'echarts/components'

use([CanvasRenderer, LineChart, TitleComponent, TooltipComponent, LegendComponent, GridComponent, ToolboxComponent])

// 模拟监测点数据
const monitoringPoints = ref([
  {
    id: 'MP-1001',
    name: '人民路监测点',
    location: '人民路与解放路口东50m',
    status: '正常',
    deviceId: 'MN-1001',
    deviceType: '智能井盖监测仪',
    deviceModel: 'WATCHMAN-S2',
    manufacturer: '华盾科技',
    installDate: '2024-03-15',
    protocol: 'LoRaWAN',
    lastCalibration: '2025-02-10',
    historyData: {
      tiltHistory: [1.2, 1.5, 2.1, 1.8, 2.3, 3.2, 2.8, 2.5, 3.0, 2.2, 1.9, 2.4, 3.5, 4.1, 3.8, 3.2, 2.9, 3.3, 4.5, 5.2, 4.8, 4.2, 3.6, 3.9, 4.3, 5.0, 4.6, 4.1, 3.7, 4.2],
      waterHistory: [5, 6, 7, 8, 10, 12, 15, 18, 20, 22, 25, 28, 30, 32, 35, 38, 36, 34, 33, 35, 37, 40, 42, 39, 36, 34, 32, 30, 28, 26],
      vibrationHistory: [12, 15, 18, 22, 25, 30, 35, 42, 48, 52, 58, 62, 65, 70, 68, 72, 75, 78, 80, 76, 72, 68, 64, 60, 55, 50, 45, 40, 38, 35],
      gasHistory: [0.5, 0.8, 1.2, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5, 6.0, 6.5, 7.0, 7.5, 8.0, 8.5, 9.0, 9.5, 10.0, 9.8, 9.5, 9.0, 8.5, 8.0, 7.5, 7.0, 6.5, 6.0],
      maxWaterLevel: 42,
      maxVibration: 80
    }
  },
  {
    id: 'MP-1002',
    name: '滨江路监测点',
    location: '滨江路化工园区南门',
    status: '告警',
    deviceId: 'MN-1002',
    deviceType: '防爆井盖监测仪',
    deviceModel: 'WATCHMAN-EX',
    manufacturer: '华盾科技',
    installDate: '2024-06-20',
    protocol: 'NB-IoT',
    lastCalibration: '2025-01-15',
    historyData: {
      tiltHistory: [0.5, 0.8, 1.0, 1.2, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 5.2, 6.5, 7.8, 8.2, 9.0, 8.5, 7.5, 6.8, 5.5, 4.8, 4.0, 3.5, 3.0, 2.5, 2.0, 1.8, 1.5, 1.2, 1.0, 0.8],
      waterHistory: [15, 18, 22, 28, 35, 42, 50, 58, 62, 55, 48, 45, 42, 40, 38, 35, 32, 30, 28, 25, 22, 20, 18, 16, 15, 14, 13, 12, 11, 10],
      vibrationHistory: [20, 25, 32, 40, 48, 55, 62, 70, 78, 85, 92, 98, 105, 110, 115, 108, 100, 92, 85, 78, 70, 62, 55, 48, 42, 38, 35, 32, 28, 25],
      gasHistory: [2, 3, 5, 7, 10, 15, 20, 25, 30, 28, 25, 22, 20, 18, 16, 15, 14, 12, 10, 9, 8, 7, 6, 5, 4, 3.5, 3, 2.5, 2, 1.5],
      maxWaterLevel: 62,
      maxVibration: 115
    }
  },
  {
    id: 'MP-1003',
    name: '高新区监测点',
    location: '高新大道云计算中心旁',
    status: '正常',
    deviceId: 'MN-1004',
    deviceType: '智能井盖监测仪',
    deviceModel: 'WATCHMAN-S2',
    manufacturer: '华盾科技',
    installDate: '2024-09-10',
    protocol: 'LoRaWAN',
    lastCalibration: '2025-03-01',
    historyData: {
      tiltHistory: [0.3, 0.5, 0.4, 0.6, 0.8, 0.7, 0.9, 1.0, 0.8, 0.6, 0.5, 0.7, 0.9, 1.1, 1.0, 0.8, 0.6, 0.5, 0.4, 0.6, 0.8, 0.7, 0.5, 0.3, 0.4, 0.6, 0.9, 1.2, 0.9, 0.7],
      waterHistory: [3, 4, 5, 6, 5, 7, 8, 6, 5, 4, 5, 6, 7, 8, 9, 10, 8, 7, 6, 5, 4, 3, 4, 5, 6, 7, 8, 9, 7, 6],
      vibrationHistory: [8, 10, 12, 15, 14, 16, 18, 20, 18, 15, 12, 10, 11, 13, 15, 17, 16, 14, 12, 10, 9, 8, 7, 9, 11, 13, 15, 14, 12, 10],
      gasHistory: [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.5, 0.4, 0.3, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.5, 0.4, 0.3, 0.2],
      maxWaterLevel: 10,
      maxVibration: 20
    }
  }
])

const searchKeyword = ref('')
const selectedPoint = ref(monitoringPoints.value[0])
const activeTab = ref('tilt')
const historyMetric = ref('tilt')

// 当前阈值配置
const thresholds = ref({
  tilt: { warning: 5, critical: 10 },
  water: { warning: 25, critical: 40 },
  vibration: { warning: 60, critical: 100 },
  gas: { warning: 10, critical: 20 },
  battery: { warning: 20 },
  signal: { warning: 30 }
})

// 智能建议值（基于历史数据）
const suggested = computed(() => {
  const hist = selectedPoint.value?.historyData
  if (!hist) return { tilt: { suggestedWarning: 5 }, water: { suggestedCritical: 40 }, vibration: {} }
  const tilt95 = hist.tiltHistory ? Math.ceil(hist.tiltHistory.sort((a,b)=>a-b)[Math.floor(hist.tiltHistory.length*0.95)] * 10) / 10 : 5
  const waterMax = hist.maxWaterLevel || 40
  return {
    tilt: { suggestedWarning: Math.min(tilt95 + 1, 12) },
    water: { suggestedCritical: Math.min(waterMax + 5, 80) },
    vibration: { suggestedPeak: hist.maxVibration || 80 }
  }
})

const filteredPoints = computed(() => {
  if (!searchKeyword.value) return monitoringPoints.value
  const kw = searchKeyword.value.toLowerCase()
  return monitoringPoints.value.filter(p =>
      p.name.toLowerCase().includes(kw) ||
      p.deviceId.toLowerCase().includes(kw) ||
      p.location.toLowerCase().includes(kw)
  )
})

const getPointStatusType = (point) => point.status === '正常' ? 'success' : 'danger'

const selectPoint = (point) => {
  selectedPoint.value = point
  // 加载该点已有阈值（演示用，模拟从后端加载）
  if (point.id === 'MP-1002') {
    thresholds.value = { tilt: { warning: 8, critical: 15 }, water: { warning: 35, critical: 55 }, vibration: { warning: 80, critical: 120 }, gas: { warning: 15, critical: 25 }, battery: { warning: 20 }, signal: { warning: 30 } }
  } else {
    thresholds.value = { tilt: { warning: 5, critical: 10 }, water: { warning: 25, critical: 40 }, vibration: { warning: 60, critical: 100 }, gas: { warning: 10, critical: 20 }, battery: { warning: 20 }, signal: { warning: 30 } }
  }
}

const historyChartOption = computed(() => {
  const point = selectedPoint.value
  if (!point) return {}
  let data = []
  let yName = ''
  let color = '#409eff'
  switch (historyMetric.value) {
    case 'tilt': data = point.historyData.tiltHistory; yName = '倾斜角度 (°)'; color = '#e6a23c'; break
    case 'water': data = point.historyData.waterHistory; yName = '水位深度 (cm)'; color = '#3b82f6'; break
    case 'vibration': data = point.historyData.vibrationHistory; yName = '震动强度 (mg)'; color = '#f56c6c'; break
    case 'gas': data = point.historyData.gasHistory; yName = '气体浓度 (ppm)'; color = '#9b59b6'; break
  }
  const days = data.map((_, idx) => `Day ${idx + 1}`)
  return {
    tooltip: { trigger: 'axis' },
    xAxis: { type: 'category', data: days, axisLabel: { rotate: 45, interval: 5 } },
    yAxis: { type: 'value', name: yName },
    series: [{ data, type: 'line', smooth: true, lineStyle: { color, width: 2 }, areaStyle: { opacity: 0.1, color }, symbol: 'circle', symbolSize: 6 }],
    grid: { containLabel: true, left: '10%' }
  }
})

const getMetricName = (metric) => {
  const map = { tilt: '倾斜角度', water: '水位深度', vibration: '震动强度', gas: '气体浓度' }
  return map[metric]
}

const getSuggestedThreshold = () => {
  const metric = historyMetric.value
  if (metric === 'tilt') return `${suggested.value.tilt.suggestedWarning}°`
  if (metric === 'water') return `${suggested.value.water.suggestedCritical}cm`
  if (metric === 'vibration') return `${selectedPoint.value?.historyData?.maxVibration || 80}mg`
  return '科学建议值'
}

const applySuggestedThreshold = () => {
  const metric = historyMetric.value
  if (metric === 'tilt') thresholds.value.tilt.warning = suggested.value.tilt.suggestedWarning
  if (metric === 'water') thresholds.value.water.critical = suggested.value.water.suggestedCritical
  if (metric === 'vibration') thresholds.value.vibration.critical = (selectedPoint.value?.historyData?.maxVibration || 80) + 10
  if (metric === 'gas') thresholds.value.gas.warning = 12
  ElMessage.success('已应用AI建议阈值')
}

const resetThresholds = () => {
  selectPoint(selectedPoint.value)
  ElMessage.info('已重置为当前监测点默认阈值')
}

const saveThresholds = () => {
  ElMessage.success('阈值配置已保存，将即时生效')
}

const exportConfig = () => {
  ElMessage.info('导出阈值配置文件（模拟）')
}

const applyAllThresholds = () => {
  ElMessage.success('已对所有监测点应用推荐阈值（演示）')
}

import { ElMessage } from 'element-plus'
</script>

<style scoped>
.threshold-management {
  padding: 20px;
  background: #f0f2f6;
  min-height: 100vh;
}
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
  padding: 16px 24px;
  border-radius: 16px;
  margin-bottom: 20px;
}
.header-left h2 { margin: 0 0 6px 0; font-weight: 600; }
.main-content {
  display: flex;
  gap: 20px;
}
.point-list-panel {
  width: 320px;
  background: white;
  border-radius: 16px;
  padding: 16px;
  display: flex;
  flex-direction: column;
}
.panel-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  font-weight: 600;
}
.point-list {
  max-height: calc(100vh - 200px);
  overflow-y: auto;
}
.point-item {
  padding: 14px;
  margin-bottom: 12px;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.2s;
  border: 1px solid #e4e7ed;
}
.point-item:hover { background: #f5f7fa; transform: translateX(2px); }
.point-item.active { background: #ecf5ff; border-color: #409eff; }
.point-header { display: flex; justify-content: space-between; margin-bottom: 6px; }
.point-name { font-weight: 600; }
.point-location { font-size: 12px; color: #6c757d; display: flex; align-items: center; gap: 4px; margin-bottom: 6px; }
.point-device { font-size: 12px; color: #409eff; }
.config-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 20px;
}
.info-card, .threshold-card, .history-chart-card {
  background: white;
  border-radius: 16px;
  padding: 16px 20px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.04);
}
.card-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  font-weight: 600;
  font-size: 16px;
  border-left: 4px solid #409eff;
  padding-left: 12px;
}
.threshold-item {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}
.item-label {
  font-weight: 500;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  gap: 6px;
}
.item-control {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-bottom: 12px;
}
.unit { margin-right: 12px; color: #6c757d; }
.level-tag { font-size: 12px; padding: 2px 8px; border-radius: 12px; margin-left: 8px; }
.level-tag.warning { background: #fdf6ec; color: #e6a23c; }
.level-tag.critical { background: #fef0f0; color: #f56c6c; }
.history-suggestion { background: #f8f9fc; padding: 8px 12px; border-radius: 8px; font-size: 13px; display: flex; align-items: center; gap: 8px; color: #606266; }
.chart-container { height: 260px; margin: 12px 0; }
.ai-suggestion { display: flex; justify-content: space-between; align-items: center; margin-top: 12px; }
.empty-panel { flex: 1; display: flex; align-items: center; justify-content: center; background: white; border-radius: 16px; }
</style>