<!--报警管理-->
<template>
  <div class="auto-alert-system">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <el-icon><AlarmClock /></el-icon>
        <span class="title">监测设备自动报警系统</span>
        <div class="stats-badge">
          <span class="stat-item"><i class="dot"></i>报警规则 {{ ruleCount }}</span>
          <span class="stat-item critical"><i class="dot"></i>实时报警 {{ activeAlertCount }}</span>
          <span class="stat-item"><i class="dot"></i>今日触发 {{ todayTriggerCount }}</span>
        </div>
      </div>
      <div class="header-right">
        <el-button type="primary" :icon="Plus" @click="showRuleDialog">新增规则</el-button>
        <el-button :icon="Refresh" @click="refreshData">刷新</el-button>
        <el-button :icon="Setting" @click="showGlobalConfig">全局配置</el-button>
      </div>
    </div>

    <!-- 实时报警看板 -->
    <div class="alert-board">
      <div class="board-header">
        <span><el-icon><BellFilled /></el-icon> 实时报警看板</span>
        <el-tag v-if="activeAlertCount > 0" type="danger" effect="dark">{{ activeAlertCount }} 个活跃报警</el-tag>
        <el-tag v-else type="success" effect="dark">系统正常</el-tag>
      </div>
      <div class="alert-list">
        <div
            v-for="alert in activeAlerts"
            :key="alert.id"
            class="alert-item"
            :class="{ critical: alert.level === 'critical', warning: alert.level === 'warning' }"
        >
          <div class="alert-icon">
            <el-icon><WarningFilled /></el-icon>
          </div>
          <div class="alert-content">
            <div class="alert-title">{{ alert.deviceName }}</div>
            <div class="alert-desc">{{ alert.ruleName }}: {{ alert.currentValue }} {{ alert.unit }} (阈值: {{ alert.threshold }} {{ alert.unit }})</div>
            <div class="alert-time">{{ alert.triggerTime }}</div>
          </div>
          <div class="alert-action">
            <el-button size="small" type="primary" @click="viewAlertDetail(alert)">处理</el-button>
          </div>
        </div>
        <div v-if="activeAlerts.length === 0" class="empty-alert">
          <el-empty description="暂无活跃报警" :image-size="80" />
        </div>
      </div>
    </div>

    <!-- 报警规则列表 -->
    <div class="rule-panel">
      <div class="panel-header">
        <span><el-icon><List /></el-icon> 报警规则配置</span>
        <el-input
            v-model="ruleSearch"
            placeholder="搜索规则名称/设备类型"
            clearable
            :prefix-icon="Search"
            style="width: 200px"
            size="small"
        />
      </div>
      <el-table :data="filteredRules" stripe border style="width: 100%">
        <el-table-column prop="name" label="规则名称" width="160" />
        <el-table-column prop="deviceType" label="适用设备类型" width="140" />
        <el-table-column prop="monitorParam" label="监测参数" width="120" />
        <el-table-column prop="condition" label="触发条件" width="100">
          <template #default="{ row }">
            <el-tag size="small">{{ getConditionText(row.condition) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="threshold" label="阈值" width="100">
          <template #default="{ row }">
            {{ row.threshold }} {{ row.unit }}
          </template>
        </el-table-column>
        <el-table-column prop="alertLevel" label="报警级别" width="100">
          <template #default="{ row }">
            <el-tag :type="row.alertLevel === 'critical' ? 'danger' : 'warning'" size="small">
              {{ row.alertLevel === 'critical' ? '严重' : '预警' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80" align="center">
          <template #default="{ row }">
            <el-switch v-model="row.status" active-text="启用" inactive-text="停用" @change="toggleRule(row)" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right" align="center">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="editRule(row)">编辑</el-button>
            <el-button link type="danger" size="small" @click="deleteRule(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 规则编辑对话框 -->
    <el-dialog v-model="ruleDialogVisible" :title="ruleDialogTitle" width="500px">
      <el-form :model="ruleForm" label-width="100px">
        <el-form-item label="规则名称" required>
          <el-input v-model="ruleForm.name" placeholder="请输入规则名称" />
        </el-form-item>
        <el-form-item label="适用设备类型" required>
          <el-select v-model="ruleForm.deviceType" placeholder="请选择" style="width: 100%">
            <el-option label="智能井盖" value="smart" />
            <el-option label="水位计" value="water" />
            <el-option label="气体监测仪" value="gas" />
            <el-option label="压力监测仪" value="pressure" />
            <el-option label="流量计" value="flow" />
          </el-select>
        </el-form-item>
        <el-form-item label="监测参数" required>
          <el-select v-model="ruleForm.monitorParam" placeholder="请选择" style="width: 100%">
            <el-option label="甲烷浓度" value="methane" />
            <el-option label="水位深度" value="waterLevel" />
            <el-option label="倾斜角度" value="tilt" />
            <el-option label="管道压力" value="pressure" />
            <el-option label="瞬时流量" value="flow" />
          </el-select>
        </el-form-item>
        <el-form-item label="触发条件" required>
          <el-radio-group v-model="ruleForm.condition">
            <el-radio value="gt">大于 (>)</el-radio>
            <el-radio value="lt">小于 (<)</el-radio>
            <el-radio value="gte">大于等于 (≥)</el-radio>
            <el-radio value="lte">小于等于 (≤)</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="阈值" required>
          <el-input-number v-model="ruleForm.threshold" :min="0" :step="1" style="width: 150px" />
          <span style="margin-left: 8px">{{ ruleForm.unit }}</span>
        </el-form-item>
        <el-form-item label="报警级别" required>
          <el-radio-group v-model="ruleForm.alertLevel">
            <el-radio value="warning">预警</el-radio>
            <el-radio value="critical">严重报警</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="报警说明">
          <el-input type="textarea" v-model="ruleForm.description" placeholder="报警触发时的说明信息" rows="2" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="ruleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveRule">保存</el-button>
      </template>
    </el-dialog>

    <!-- 全局配置对话框 -->
    <el-dialog v-model="globalConfigVisible" title="全局报警配置" width="450px">
      <el-form label-width="120px">
        <el-form-item label="报警轮询间隔">
          <el-input-number v-model="globalConfig.pollInterval" :min="5" :max="300" /> 秒
        </el-form-item>
        <el-form-item label="重复报警间隔">
          <el-input-number v-model="globalConfig.repeatInterval" :min="1" :max="60" /> 分钟
        </el-form-item>
        <el-form-item label="报警静默时段">
          <el-time-picker
              v-model="globalConfig.silencePeriod"
              is-range
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="HH:mm"
          />
        </el-form-item>
        <el-form-item label="通知方式">
          <el-checkbox-group v-model="globalConfig.notifyMethods">
            <el-checkbox value="sms">短信通知</el-checkbox>
            <el-checkbox value="email">邮件通知</el-checkbox>
            <el-checkbox value="app">APP推送</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="globalConfigVisible = false">取消</el-button>
        <el-button type="primary" @click="saveGlobalConfig">保存配置</el-button>
      </template>
    </el-dialog>

    <!-- 报警详情抽屉 -->
    <el-drawer v-model="alertDetailVisible" :title="`报警详情 - ${currentAlert?.deviceName}`" size="400px" direction="rtl">
      <div v-if="currentAlert" class="alert-detail">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="设备名称">{{ currentAlert.deviceName }}</el-descriptions-item>
          <el-descriptions-item label="设备编号">{{ currentAlert.deviceCode }}</el-descriptions-item>
          <el-descriptions-item label="报警规则">{{ currentAlert.ruleName }}</el-descriptions-item>
          <el-descriptions-item label="当前值">{{ currentAlert.currentValue }} {{ currentAlert.unit }}</el-descriptions-item>
          <el-descriptions-item label="报警阈值">{{ currentAlert.threshold }} {{ currentAlert.unit }}</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="触发时间">{{ currentAlert.triggerTime }}</el-descriptions-item>
        </el-descriptions>
        <div class="action-buttons">
          <el-button type="primary" @click="resolveAlert">确认处理</el-button>
          <el-button @click="snoozeAlert">稍后处理</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { AlarmClock, Plus, Refresh, Setting, BellFilled, List, Search, WarningFilled } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 报警规则列表
const rules = ref([
  { id: 1, name: '甲烷浓度超标', deviceType: '气体监测仪', monitorParam: '甲烷浓度', condition: 'gt', threshold: 20, unit: 'ppm', alertLevel: 'critical', status: true, description: '甲烷浓度超过20ppm触发严重报警' },
  { id: 2, name: '水位超限', deviceType: '水位计', monitorParam: '水位深度', condition: 'gt', threshold: 40, unit: 'cm', alertLevel: 'critical', status: true, description: '水位超过40cm触发严重报警' },
  { id: 3, name: '倾斜超标', deviceType: '智能井盖', monitorParam: '倾斜角度', condition: 'gt', threshold: 8, unit: '°', alertLevel: 'critical', status: true, description: '倾斜角度超过8°触发严重报警' },
  { id: 4, name: '管道压力异常', deviceType: '压力监测仪', monitorParam: '管道压力', condition: 'lt', threshold: 300, unit: 'kPa', alertLevel: 'warning', status: true, description: '压力低于300kPa触发预警' },
  { id: 5, name: '流量异常', deviceType: '流量计', monitorParam: '瞬时流量', condition: 'gt', threshold: 1200, unit: 'm³/h', alertLevel: 'warning', status: true, description: '流量超过1200m³/h触发预警' }
])

// 模拟实时报警数据
const activeAlerts = ref([
  { id: 1, deviceName: '世纪大道流量计', deviceCode: 'FM-001', ruleName: '流量异常', currentValue: 1350, threshold: 1200, unit: 'm³/h', level: 'warning', triggerTime: '2025-04-02 15:23:45' },
  { id: 2, deviceName: '人民广场气体监测仪', deviceCode: 'CH4-001', ruleName: '甲烷浓度超标', currentValue: 28, threshold: 20, unit: 'ppm', level: 'critical', triggerTime: '2025-04-02 15:18:22' }
])

const ruleSearch = ref('')
const ruleDialogVisible = ref(false)
const ruleDialogTitle = ref('新增规则')
const ruleForm = ref({
  id: null, name: '', deviceType: '', monitorParam: '', condition: 'gt', threshold: 0, unit: '', alertLevel: 'warning', description: ''
})
const globalConfigVisible = ref(false)
const globalConfig = ref({
  pollInterval: 30, repeatInterval: 5, silencePeriod: null, notifyMethods: ['sms', 'app']
})
const alertDetailVisible = ref(false)
const currentAlert = ref(null)

const ruleCount = computed(() => rules.value.length)
const activeAlertCount = computed(() => activeAlerts.value.length)
const todayTriggerCount = computed(() => 8)

const filteredRules = computed(() => {
  if (!ruleSearch.value) return rules.value
  const kw = ruleSearch.value.toLowerCase()
  return rules.value.filter(r => r.name.toLowerCase().includes(kw) || r.deviceType.toLowerCase().includes(kw))
})

const getConditionText = (cond) => {
  const map = { gt: '>', lt: '<', gte: '≥', lte: '≤' }
  return map[cond] || cond
}

// 模拟数据监测触发
const simulateMonitor = () => {
  // 模拟新报警触发（演示用）
  const newAlert = {
    id: Date.now(),
    deviceName: '张杨路水位计',
    deviceCode: 'WL-003',
    ruleName: '水位超限',
    currentValue: 45,
    threshold: 40,
    unit: 'cm',
    level: 'critical',
    triggerTime: new Date().toLocaleString()
  }
  // 避免重复添加
  if (!activeAlerts.value.some(a => a.deviceCode === 'WL-003')) {
    activeAlerts.value.unshift(newAlert)
    ElNotification({
      title: '新报警触发',
      message: `${newAlert.deviceName} 触发 ${newAlert.ruleName}`,
      type: 'warning'
    })
  }
}

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

const showRuleDialog = () => {
  ruleDialogTitle.value = '新增规则'
  ruleForm.value = { id: null, name: '', deviceType: '', monitorParam: '', condition: 'gt', threshold: 0, unit: '', alertLevel: 'warning', description: '' }
  ruleDialogVisible.value = true
}

const editRule = (row) => {
  ruleDialogTitle.value = '编辑规则'
  ruleForm.value = { ...row }
  ruleDialogVisible.value = true
}

const saveRule = () => {
  if (!ruleForm.value.name || !ruleForm.value.deviceType || !ruleForm.value.threshold) {
    ElMessage.warning('请填写完整信息')
    return
  }
  if (ruleForm.value.id) {
    const index = rules.value.findIndex(r => r.id === ruleForm.value.id)
    if (index !== -1) rules.value[index] = { ...ruleForm.value }
    ElMessage.success('规则已更新')
  } else {
    ruleForm.value.id = Date.now()
    ruleForm.value.status = true
    rules.value.push({ ...ruleForm.value })
    ElMessage.success('规则已添加')
  }
  ruleDialogVisible.value = false
}

const deleteRule = (row) => {
  ElMessageBox.confirm(`确定删除规则"${row.name}"吗？`, '提示', { type: 'warning' }).then(() => {
    const index = rules.value.findIndex(r => r.id === row.id)
    if (index !== -1) rules.value.splice(index, 1)
    ElMessage.success('规则已删除')
  })
}

const toggleRule = (row) => {
  ElMessage.success(`规则${row.status ? '已启用' : '已停用'}`)
}

const showGlobalConfig = () => { globalConfigVisible.value = true }
const saveGlobalConfig = () => { globalConfigVisible.value = false; ElMessage.success('全局配置已保存') }

const viewAlertDetail = (alert) => {
  currentAlert.value = alert
  alertDetailVisible.value = true
}

const resolveAlert = () => {
  const index = activeAlerts.value.findIndex(a => a.id === currentAlert.value.id)
  if (index !== -1) activeAlerts.value.splice(index, 1)
  alertDetailVisible.value = false
  ElMessage.success('报警已处理')
}

const snoozeAlert = () => {
  alertDetailVisible.value = false
  ElMessage.info('已设置稍后提醒')
}

// 定时模拟触发新报警
let interval
onMounted(() => {
  interval = setInterval(() => {
    // 随机触发新报警（演示用）
    if (Math.random() < 0.3) {
      simulateMonitor()
    }
  }, 30000)
})

// 清理定时器
import { onUnmounted } from 'vue'
import { ElNotification } from 'element-plus'
onUnmounted(() => {
  if (interval) clearInterval(interval)
})
</script>

<style scoped>
.auto-alert-system {
  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;
}
.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 .dot { width: 8px; height: 8px; border-radius: 50%; background: #909399; }
.header-right { display: flex; gap: 12px; }

.alert-board {
  background: white;
  border-radius: 16px;
  margin-bottom: 20px;
  overflow: hidden;
}
.board-header {
  padding: 16px;
  border-bottom: 1px solid #e9ecef;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
}
.alert-list { max-height: 300px; overflow-y: auto; padding: 12px; }
.alert-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 12px;
  margin-bottom: 8px;
  border-radius: 12px;
  background: #fafbfc;
  border: 1px solid #e9ecef;
}
.alert-item.critical { background: #fff8f8; border-left: 3px solid #f56c6c; }
.alert-item.warning { background: #fffef5; border-left: 3px solid #e6a23c; }
.alert-icon .el-icon { font-size: 24px; color: #f56c6c; }
.alert-content { flex: 1; }
.alert-title { font-weight: 600; margin-bottom: 4px; }
.alert-desc { font-size: 12px; color: #606266; }
.alert-time { font-size: 11px; color: #aaa; margin-top: 4px; }
.empty-alert { padding: 20px; text-align: center; }

.rule-panel {
  background: white;
  border-radius: 16px;
  padding: 16px;
}
.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  font-weight: 600;
}

.alert-detail { padding: 8px; }
.action-buttons { margin-top: 20px; display: flex; gap: 12px; justify-content: flex-end; }
</style>