<!--窨井盖状态监测-->
<template>
  <div class="monitor-dashboard">
    <!-- 头部统计区 -->
    <div class="dashboard-header">
      <div class="stats-row">
        <div class="stat-card" :class="{ warning: alertStats.critical > 0 }">
          <div class="stat-value">{{ alertStats.critical }}</div>
          <div class="stat-label">严重告警</div>
        </div>
        <div class="stat-card" :class="{ warning: alertStats.warning > 0 }">
          <div class="stat-value">{{ alertStats.warning }}</div>
          <div class="stat-label">一般告警</div>
        </div>
        <div class="stat-card">
          <div class="stat-value">{{ onlineRate }}%</div>
          <div class="stat-label">设备在线率</div>
        </div>
        <div class="stat-card">
          <div class="stat-value">{{ avgBattery }}%</div>
          <div class="stat-label">平均电量</div>
        </div>
      </div>
    </div>

    <!-- 主内容区：左侧设备网格 + 右侧详情/处置面板 -->
    <div class="main-layout">
      <!-- 左侧设备卡片列表 -->
      <div class="device-grid">
        <div class="grid-header">
          <span>监测设备列表</span>
          <el-input v-model="searchText" placeholder="搜索设备编号/位置" prefix-icon="Search" clearable size="small" style="width: 200px" />
        </div>
        <div class="card-container">
          <div
              v-for="device in filteredDevices"
              :key="device.id"
              class="device-card"
              :class="{ 'has-alert': device.hasAlert, 'selected': selectedDevice?.id === device.id }"
              @click="selectDevice(device)"
          >
            <div class="card-header">
              <span class="device-name">{{ device.name }}</span>
              <el-badge :value="device.alertLevel ? device.alertLevel === 'critical' ? '严重' : '警告' : ''" :type="device.alertLevel === 'critical' ? 'danger' : 'warning'" v-if="device.hasAlert">
                <el-icon><WarningFilled /></el-icon>
              </el-badge>
              <el-tag v-else size="small" type="success">正常</el-tag>
            </div>
            <div class="device-location">
              <el-icon><Location /></el-icon> {{ device.location }}
            </div>
            <div class="status-icons">
              <div class="status-item" :class="{ active: device.status.tilt }" title="位移倾斜">
                <el-icon><TurnOff /></el-icon> 倾斜
              </div>
              <div class="status-item" :class="{ active: device.status.open }" title="井盖开启">
                <el-icon><Position /></el-icon> 开启
              </div>
              <div class="status-item" :class="{ active: device.status.vibration }" title="异常震动">
                <el-icon><Opportunity /></el-icon> 震动
              </div>
              <div class="status-item" :class="{ active: device.status.water }" title="溢水/积水">
                <el-icon></el-icon> 溢水
              </div>
            </div>
            <div class="device-metrics">
              <div class="metric">
                <span>电量</span>
                <el-progress :percentage="device.battery" :stroke-width="6" :color="batteryColor(device.battery)" :show-text="false" />
                <span class="metric-value">{{ device.battery }}%</span>
              </div>
              <div class="metric">
                <span>信号</span>
                <el-progress :percentage="device.signal" :stroke-width="6" :color="signalColor(device.signal)" :show-text="false" />
                <span class="metric-value">{{ device.signal }}%</span>
              </div>
            </div>
            <div class="card-footer">
              <span class="update-time">最后通讯: {{ device.lastTime }}</span>
              <el-button v-if="device.hasAlert" type="danger" size="small" plain @click.stop="handleAlert(device)">处理告警</el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧详情及处置面板 -->
      <div class="detail-panel">
        <div v-if="selectedDevice" class="detail-container">
          <div class="panel-title">
            <span>设备详情 & 处置机制</span>
            <el-button type="primary" size="small" link @click="refreshDevice">刷新状态</el-button>
          </div>
          <div class="device-basic">
            <h3>{{ selectedDevice.name }}</h3>
            <p><el-icon><Location /></el-icon> {{ selectedDevice.location }} | 编号: {{ selectedDevice.id }}</p>
          </div>

          <!-- 实时状态监测模块 -->
          <el-descriptions :column="2" border class="status-description">
            <el-descriptions-item label="井盖开启状态">
              <el-tag :type="selectedDevice.status.open ? 'danger' : 'success'">{{ selectedDevice.status.open ? '已开启' : '关闭' }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="位移倾斜状态">
              <el-tag :type="selectedDevice.status.tilt ? 'danger' : 'success'">{{ selectedDevice.status.tilt ? '倾斜告警' : '水平' }}</el-tag>
              <span v-if="selectedDevice.status.tilt" class="sub-value">(倾斜角: {{ selectedDevice.tiltAngle }}°)</span>
            </el-descriptions-item>
            <el-descriptions-item label="异常震动">
              <el-tag :type="selectedDevice.status.vibration ? 'warning' : 'success'">{{ selectedDevice.status.vibration ? '检测到震动' : '正常' }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="溢水/积水">
              <el-tag :type="selectedDevice.status.water ? 'warning' : 'success'">{{ selectedDevice.status.water ? '溢水告警' : '干燥' }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="电池电压">
              <el-progress :percentage="selectedDevice.battery" :format="() => `${selectedDevice.battery}%`" :color="batteryColor(selectedDevice.battery)" />
              <span>{{ selectedDevice.voltage }}V</span>
            </el-descriptions-item>
            <el-descriptions-item label="设备信号">
              <el-progress :percentage="selectedDevice.signal" :format="() => `${selectedDevice.signal}%`" :color="signalColor(selectedDevice.signal)" />
              <span>{{ selectedDevice.signalStrength }}</span>
            </el-descriptions-item>
          </el-descriptions>

          <!-- 报警与处理机制区域 -->
          <div class="alert-section" v-if="selectedDevice.hasAlert">
            <div class="alert-header">
              <el-icon color="red"><Warning /></el-icon>
              <span class="alert-title">设备告警详情</span>
              <el-tag :type="selectedDevice.alertLevel === 'critical' ? 'danger' : 'warning'" effect="dark">
                {{ selectedDevice.alertLevel === 'critical' ? '严重告警' : '一般告警' }}
              </el-tag>
            </div>
            <div class="alert-message">
              <ul>
                <li v-if="selectedDevice.status.open">⚠️ 井盖被异常开启，请立即前往现场检查。</li>
                <li v-if="selectedDevice.status.tilt">⚠️ 井盖发生位移倾斜（{{ selectedDevice.tiltAngle }}°），可能损坏或移位。</li>
                <li v-if="selectedDevice.status.vibration">⚠️ 持续异常震动，可能存在外力冲击或车辆碾压异常。</li>
                <li v-if="selectedDevice.status.water">⚠️ 井内水位超限，溢水风险，需排水处理。</li>
                <li v-if="selectedDevice.battery < 20">🔋 电池电压过低，请及时更换电池。</li>
                <li v-if="selectedDevice.signal < 30">📶 设备信号弱，可能影响数据传输。</li>
              </ul>
            </div>
            <div class="action-buttons">
              <el-button type="primary" @click="handleDispatch(selectedDevice)">启动处理机制</el-button>
              <el-button @click="simulateFix(selectedDevice)">模拟修复/复位</el-button>
            </div>

            <!-- 处理记录与工单 -->
            <div class="history-log" v-if="selectedDevice.alertHistory.length">
              <div class="history-title">处置记录</div>
              <el-timeline>
                <el-timeline-item v-for="(log, idx) in selectedDevice.alertHistory" :key="idx" :timestamp="log.time" :type="log.type">
                  {{ log.content }}
                </el-timeline-item>
              </el-timeline>
            </div>
          </div>

          <!-- 正常时显示机制说明 -->
          <div v-else class="normal-message">
            <el-result icon="success" title="设备运行正常" sub-title="所有监测指标均在正常范围内，无报警事件。">
              <template #extra>
                <el-button type="primary" @click="simulateAlert(selectedDevice)">模拟触发告警（测试）</el-button>
              </template>
            </el-result>
          </div>
        </div>

        <div v-else class="empty-panel">
          <el-empty description="请从左侧选择一个设备查看状态" :image-size="120" />
        </div>
      </div>
    </div>

    <!-- 处理机制弹窗 -->
    <el-dialog v-model="dialogVisible" title="启动处理机制 - 工单派发" width="450px">
      <el-form :model="taskForm">
        <el-form-item label="处理类型">
          <el-select v-model="taskForm.taskType" placeholder="请选择">
            <el-option label="维修派遣" value="repair" />
            <el-option label="现场巡检" value="inspect" />
            <el-option label="排水作业" value="drain" />
            <el-option label="更换电池/模块" value="replace" />
          </el-select>
        </el-form-item>
        <el-form-item label="负责人">
          <el-input v-model="taskForm.owner" placeholder="指派负责人" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="taskForm.remark" placeholder="处理说明" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitTask">确认派发</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { WarningFilled, Location, TurnOff, Position, Opportunity, Warning, Search } from '@element-plus/icons-vue'

// 模拟设备数据
const createMockDevices = () => [
  {
    id: 'MN-001', name: '人民路智能井盖', location: '人民路与解放路口', battery: 87, voltage: 3.6, signal: 92, signalStrength: '强',
    status: { open: false, tilt: false, vibration: false, water: false }, hasAlert: false, alertLevel: null, tiltAngle: 0,
    lastTime: '2025-04-02 10:23', alertHistory: []
  },
  {
    id: 'MN-002', name: '滨江路防爆井盖', location: '滨江路化工园南门', battery: 34, voltage: 2.9, signal: 45, signalStrength: '中',
    status: { open: true, tilt: true, vibration: false, water: false }, hasAlert: true, alertLevel: 'critical', tiltAngle: 12.5,
    lastTime: '2025-04-02 09:15', alertHistory: [{ time: '2025-04-01 16:20', content: '触发倾斜告警，系统已记录', type: 'danger' }]
  },
  {
    id: 'MN-003', name: '古城街铸铁井盖', location: '古城街北段', battery: 12, voltage: 2.2, signal: 22, signalStrength: '弱',
    status: { open: false, tilt: false, vibration: true, water: true }, hasAlert: true, alertLevel: 'critical', tiltAngle: 0,
    lastTime: '2025-04-02 08:47', alertHistory: [{ time: '2025-04-02 07:30', content: '溢水告警触发', type: 'warning' }]
  },
  {
    id: 'MN-004', name: '高新区智能井盖', location: '高新大道云计算中心', battery: 96, voltage: 3.8, signal: 88, signalStrength: '强',
    status: { open: false, tilt: false, vibration: false, water: false }, hasAlert: false, alertLevel: null, tiltAngle: 0,
    lastTime: '2025-04-02 11:02', alertHistory: []
  },
  {
    id: 'MN-005', name: '南港路井盖', location: '南港路旧车站', battery: 55, voltage: 3.2, signal: 67, signalStrength: '中',
    status: { open: false, tilt: true, vibration: false, water: false }, hasAlert: true, alertLevel: 'warning', tiltAngle: 8.2,
    lastTime: '2025-04-02 10:05', alertHistory: []
  }
]

const devices = ref(createMockDevices())
const searchText = ref('')
const selectedDevice = ref(null)
const dialogVisible = ref(false)
const taskForm = ref({ taskType: 'repair', owner: '值班人员', remark: '' })

const filteredDevices = computed(() => {
  if (!searchText.value) return devices.value
  return devices.value.filter(d => d.id.toLowerCase().includes(searchText.value.toLowerCase()) || d.name.includes(searchText.value))
})

// 统计告警数据
const alertStats = computed(() => {
  let critical = 0, warning = 0
  devices.value.forEach(d => {
    if (d.hasAlert) {
      if (d.alertLevel === 'critical') critical++
      else warning++
    }
  })
  return { critical, warning }
})

const onlineRate = computed(() => {
  // 模拟在线判断: 最后通讯时间在一小时内的视为在线，简单起见所有设备在线率基于信号>0
  const online = devices.value.filter(d => d.signal > 0).length
  return Math.round((online / devices.value.length) * 100)
})
const avgBattery = computed(() => {
  const sum = devices.value.reduce((acc, d) => acc + d.battery, 0)
  return Math.round(sum / devices.value.length)
})
const hasActiveAlert = computed(() => alertStats.value.critical > 0 || alertStats.value.warning > 0)

const batteryColor = (percent) => percent < 20 ? '#f56c6c' : percent < 50 ? '#e6a23c' : '#67c23a'
const signalColor = (percent) => percent < 30 ? '#f56c6c' : percent < 60 ? '#e6a23c' : '#67c23a'

const selectDevice = (device) => {
  selectedDevice.value = device
}

const handleAlert = (device) => {
  selectedDevice.value = device
  // 滚动到右侧面板
}

const handleDispatch = (device) => {
  dialogVisible.value = true
}

const submitTask = () => {
  if (selectedDevice.value) {
    const newLog = {
      time: new Date().toLocaleString(),
      content: `已派发${taskForm.value.taskType === 'repair' ? '维修' : taskForm.value.taskType === 'inspect' ? '巡检' : taskForm.value.taskType === 'drain' ? '排水作业' : '电池更换'}工单，负责人：${taskForm.value.owner}，备注：${taskForm.value.remark || '无'}`,
      type: 'primary'
    }
    if (!selectedDevice.value.alertHistory) selectedDevice.value.alertHistory = []
    selectedDevice.value.alertHistory.unshift(newLog)

    // 模拟处理后自动清除告警（如果在处置中置为修复，为了方便展示，不清除演示，点模拟修复会清除）
    ElMessage.success('处置工单已派发，相关部门将即刻处理')
    dialogVisible.value = false
    taskForm.value = { taskType: 'repair', owner: '值班人员', remark: '' }
  }
}

const simulateFix = (device) => {
  // 模拟修复：关闭所有异常标志，清除告警，重置电池略回升
  device.status = { open: false, tilt: false, vibration: false, water: false }
  device.hasAlert = false
  device.alertLevel = null
  device.tiltAngle = 0
  if (device.battery < 30) device.battery += 20
  const fixLog = { time: new Date().toLocaleString(), content: '运维人员已现场检修，设备恢复正常', type: 'success' }
  if (!device.alertHistory) device.alertHistory = []
  device.alertHistory.unshift(fixLog)
  ElMessage.success('已模拟修复，设备状态恢复正常')
}

const simulateAlert = (device) => {
  // 模拟告警（测试用）
  device.status.tilt = true
  device.tiltAngle = 9.3
  device.status.open = true
  device.hasAlert = true
  device.alertLevel = 'critical'
  const alertLog = { time: new Date().toLocaleString(), content: '【模拟触发】井盖开启+倾斜告警', type: 'danger' }
  device.alertHistory.unshift(alertLog)
  ElMessage.warning('已触发模拟告警，请及时处置')
}

const refreshDevice = () => {
  // 模拟刷新数据
  ElMessage.info('已刷新设备状态')
}

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

<style scoped>
.monitor-dashboard {
  padding: 20px;
  background: #f0f2f6;
  min-height: 100vh;
}
.dashboard-header {
  background: white;
  border-radius: 16px;
  padding: 16px 24px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.04);
}
.title-area {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 16px;
}
.title-area h2 {
  margin: 0;
  font-weight: 600;
}
.stats-row {
  display: flex;
  gap: 24px;
  flex-wrap: wrap;
}
.stat-card {
  background: #f8fafc;
  border-radius: 12px;
  padding: 12px 20px;
  min-width: 100px;
  text-align: center;
  transition: all 0.2s;
}
.stat-card.warning {
  background: #fff3f0;
  border-left: 4px solid #f56c6c;
}
.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #2c3e50;
}
.stat-label {
  font-size: 13px;
  color: #6c757d;
}
.main-layout {
  display: grid;
  grid-template-columns: 380px 1fr;
  gap: 20px;
}
.device-grid {
  background: white;
  border-radius: 20px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0,0,0,0.05);
  display: flex;
  flex-direction: column;
}
.grid-header {
  display: flex;
  justify-content: space-between;
  padding: 16px;
  border-bottom: 1px solid #e9ecef;
  font-weight: 600;
}
.card-container {
  padding: 12px;
  max-height: 75vh;
  overflow-y: auto;
}
.device-card {
  border: 1px solid #e4e7ed;
  border-radius: 16px;
  padding: 14px;
  margin-bottom: 12px;
  cursor: pointer;
  transition: all 0.2s;
  background: white;
}
.device-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 14px rgba(0,0,0,0.08);
}
.device-card.has-alert {
  border-left: 4px solid #f56c6c;
  background: #fffaf9;
}
.device-card.selected {
  border: 2px solid #409eff;
  background: #ecf5ff;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}
.device-name {
  font-weight: 700;
  font-size: 15px;
}
.device-location {
  font-size: 12px;
  color: #6c757d;
  margin-bottom: 10px;
}
.status-icons {
  display: flex;
  gap: 16px;
  margin: 10px 0;
}
.status-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  background: #f5f5f5;
  padding: 2px 8px;
  border-radius: 20px;
  color: #909399;
}
.status-item.active {
  background: #ffeded;
  color: #f56c6c;
}
.device-metrics {
  margin: 12px 0;
}
.metric {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 12px;
  margin-bottom: 6px;
}
.metric-value {
  width: 36px;
  text-align: right;
}
.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 11px;
  color: #aaa;
}
.detail-panel {
  background: white;
  border-radius: 20px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.05);
  padding: 20px;
  overflow-y: auto;
}
.panel-title {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16px;
  font-weight: bold;
  font-size: 18px;
  border-bottom: 2px solid #eef2f6;
  padding-bottom: 10px;
}
.status-description {
  margin-top: 10px;
}
.alert-section {
  margin-top: 24px;
  border: 1px solid #ffd6d6;
  background: #fff8f6;
  border-radius: 16px;
  padding: 16px;
}
.alert-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 12px;
}
.alert-title {
  font-weight: bold;
  font-size: 16px;
}
.alert-message ul {
  margin: 8px 0 16px;
  padding-left: 20px;
}
.action-buttons {
  display: flex;
  gap: 12px;
  margin: 16px 0;
}
.history-log {
  margin-top: 16px;
  background: #f8f9fc;
  border-radius: 12px;
  padding: 12px;
}
.normal-message {
  margin-top: 40px;
}
.empty-panel {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>