<!--窨井盖状态监测-->
<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" @keyup.enter="loadDevices" @clear="loadDevices" />
        </div>
        <div class="card-container" v-loading="loading">
          <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.waterInfiltration }" title="水浸告警">
                <el-icon><Position /></el-icon> 水浸
              </div>
              <div class="status-item" :class="{ active: device.status.waterLevel }" title="水位告警">
                <el-icon><Opportunity /></el-icon> 水位
              </div>
              <div class="status-item" :class="{ active: device.status.lowBattery }" title="低电量">
                <el-icon><Warning /></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 && !device.workOrderSubmitted" type="danger" size="small" plain @click.stop="handleAlert(device)">处理告警</el-button>
              <el-tag v-else-if="device.workOrderSubmitted" type="warning" size="small" effect="plain">工单处理中</el-tag>
            </div>
          </div>
          <el-empty v-if="!loading && filteredDevices.length === 0" description="暂无设备数据" :image-size="80" />
        </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.tilt ? 'danger' : 'success'">{{ selectedDevice.status.tilt ? '倾斜告警' : '水平' }}</el-tag>
              <span v-if="selectedDevice.tiltAngle > 0" class="sub-value">(倾斜角: {{ selectedDevice.tiltAngle }}°, 阈值: {{ selectedDevice.threshold }}°)</span>
            </el-descriptions-item>
            <el-descriptions-item label="水浸状态">
              <el-tag :type="selectedDevice.status.waterInfiltration ? 'danger' : 'success'">{{ selectedDevice.status.waterInfiltration ? '水浸告警' : '正常' }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="水位状态">
              <el-tag :type="selectedDevice.status.waterLevel ? 'danger' : 'success'">{{ selectedDevice.status.waterLevel ? '水位告警' : '正常' }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="综合报警">
              <el-tag :type="selectedDevice.raw?.manholeData?.alarmStatus === '1' ? 'danger' : 'success'">{{ selectedDevice.raw?.manholeData?.alarmStatus === '1' ? '报警中' : '无报警' }}</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.tilt">⚠️ 井盖发生位移倾斜（{{ selectedDevice.tiltAngle }}°），超过阈值 {{ selectedDevice.threshold }}°，可能损坏或移位。</li>
                <li v-if="selectedDevice.status.waterInfiltration">⚠️ 检测到水浸报警，井内可能进水，需前往现场检查。</li>
                <li v-if="selectedDevice.status.waterLevel">⚠️ 水位超限，溢水风险，需排水处理。</li>
                <li v-if="selectedDevice.status.lowBattery">🔋 电池电压过低（{{ selectedDevice.battery }}%），请及时更换电池。</li>
                <li v-if="selectedDevice.status.lowSignal">📶 设备信号弱（{{ selectedDevice.signal }}%），可能影响数据传输。</li>
              </ul>
            </div>
            <div class="action-buttons" v-if="!selectedDevice.workOrderSubmitted">
              <el-button type="primary" :loading="submitting" @click="handleDispatch(selectedDevice)">启动处理机制</el-button>
              <el-button @click="simulateFix(selectedDevice)">模拟修复/复位</el-button>
            </div>
            <el-alert v-else title="工单已派发，正在处理中" description="相关部门将即刻前往现场处理，请耐心等待。" type="success" :closable="false" show-icon class="submitted-alert" />

            <!-- 处理记录与工单 -->
            <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, onMounted } from 'vue'
import { WarningFilled, Location, TurnOff, Position, Opportunity, Warning, Search } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { getManholeAlarmMonitorList, addManholeWorkOrder } from '@/api/pipeNetwork/basic'

/* ============ 状态 ============ */
const devices = ref([])
const loading = ref(false)
const searchText = ref('')
const selectedDevice = ref(null)
const dialogVisible = ref(false)
const submitting = ref(false)
const taskForm = ref({ taskType: 'repair', owner: '', remark: '' })

/* ============ 数据加载 ============ */
async function loadDevices() {
  loading.value = true
  try {
    const keyword = searchText.value?.trim()
    const res = await getManholeAlarmMonitorList({ keyword: keyword || undefined })
    const result = res.data || {}
    devices.value = (result.devices || []).map(item => normalizeDevice(item))
  } catch (error) {
    devices.value = []
    const msg = error?.message || error?.msg || '未知错误'
    console.error('[mRealApicture] 设备数据加载失败:', error)
    ElMessage.error('设备数据加载失败: ' + msg)
  } finally {
    loading.value = false
  }
}

/**
 * 将后端返回的设备数据（含 jg_device_data 最新记录）规范化为前端展示对象
 *
 * 报警等级判定逻辑：
 *   严重告警(critical) — 倾斜角度超阈值 / 水浸报警 / 水位报警
 *   一般告警(warning)  — 低电量(battery<=20) / 弱信号(signal<=20)
 */
function normalizeDevice(raw) {
  const md = raw?.manholeData || {}
  const st = raw?.equipmentStatus || {}

  // 数值解析
  const tiltAngle = parseFloat(md.tiltAngle) || 0
  const angleThreshold = parseFloat(md.angleAlarmThreshold) || 15
  const battery = parseFloat(md.batteryLevel) || 0
  const signal = parseFloat(md.signalStrength) || 0
  const isOnline = Number(st.onlineStatus) === 1

  // 状态标志
  const tilt = isOnline && tiltAngle > angleThreshold
  const waterInfiltration = isOnline && `${md.waterInfiltrationAlarmStatus}` === '1'
  const waterLevel = isOnline && `${md.waterLevelAlarmStatus}` === '1'
  const lowBattery = battery > 0 && battery <= 20
  const lowSignal = signal > 0 && signal <= 20

  // 告警等级：严重 > 一般
  const isCritical = tilt || waterInfiltration || waterLevel
  const isWarning = !isCritical && (lowBattery || lowSignal)
  const hasAlert = isCritical || isWarning
  const alertLevel = isCritical ? 'critical' : (isWarning ? 'warning' : null)

  // 电压近似值（2.4V ~ 4.2V 映射到 0~100%）
  const voltage = battery > 0 ? (2.4 + battery * 0.018).toFixed(1) : '—'

  return {
    id: raw?.equipmentCode || raw?.equipmentId || '',
    equipmentId: raw?.equipmentId || '',
    name: raw?.equipmentName || raw?.equipmentCode || '未命名设备',
    location: raw?.equipmentLocation || '暂无位置信息',
    battery,
    voltage,
    signal,
    signalStrength: signal > 60 ? '强' : signal > 30 ? '中' : signal > 0 ? '弱' : '—',
    status: { tilt, waterInfiltration, waterLevel, lowBattery, lowSignal },
    hasAlert,
    alertLevel,
    tiltAngle,
    threshold: angleThreshold,
    lastTime: md.uploadTime || md.createTime || '',
    alertHistory: [],
    workOrderSubmitted: !!raw?.workOrderSubmitted,
    raw
  }
}

/* ============ 计算属性 ============ */
const filteredDevices = computed(() => {
  if (!searchText.value) return devices.value
  const kw = searchText.value.toLowerCase()
  return devices.value.filter(d =>
    d.id.toLowerCase().includes(kw) || d.name.toLowerCase().includes(kw)
  )
})

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(() => {
  if (!devices.value.length) return 0
  const online = devices.value.filter(d => d.signal > 0).length
  return Math.round((online / devices.value.length) * 100)
})

const avgBattery = computed(() => {
  if (!devices.value.length) return 0
  const sum = devices.value.reduce((acc, d) => acc + d.battery, 0)
  return Math.round(sum / devices.value.length)
})

/* ============ 辅助函数 ============ */
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 = () => {
  taskForm.value = { taskType: 'repair', owner: '', remark: '' }
  dialogVisible.value = true
}

// 工单类型映射: taskType → orderType(1-故障维修 2-日常巡检 3-设备保养)
const ORDER_TYPE_MAP = { repair: 1, inspect: 2, drain: 1, replace: 3 }
const TYPE_LABEL_MAP = { repair: '故障维修', inspect: '日常巡检', drain: '排水作业', replace: '设备保养' }

const submitTask = async () => {
  if (!selectedDevice.value?.equipmentId) {
    ElMessage.warning('设备信息缺失，无法提交工单')
    return
  }
  if (!taskForm.value.remark?.trim()) {
    ElMessage.warning('请填写工单问题描述')
    return
  }
  submitting.value = true
  try {
    const device = selectedDevice.value
    await addManholeWorkOrder({
      deviceId: device.equipmentId,
      orderType: ORDER_TYPE_MAP[taskForm.value.taskType] || 1,
      orderLevel: device.alertLevel === 'critical' ? 1 : 2,
      orderDesc: `[${TYPE_LABEL_MAP[taskForm.value.taskType] || '故障维修'}] ${taskForm.value.remark}${taskForm.value.owner ? '（负责人：' + taskForm.value.owner + '）' : ''}`
    })
    // 提交成功：标记工单已派发，隐藏按钮
    device.workOrderSubmitted = true
    const typeLabel = TYPE_LABEL_MAP[taskForm.value.taskType] || '处理'
    device.alertHistory.unshift({
      time: new Date().toLocaleString(),
      content: `已派发${typeLabel}工单${taskForm.value.owner ? '，负责人：' + taskForm.value.owner : ''}，${taskForm.value.remark}`,
      type: 'primary'
    })
    ElMessage.success('工单已派发，相关部门将即刻处理')
    dialogVisible.value = false
  } catch (error) {
    const msg = error?.message || error?.msg || '未知错误'
    ElMessage.error('工单派发失败: ' + msg)
  } finally {
    submitting.value = false
  }
}

const simulateFix = (device) => {
  device.status = { tilt: false, waterInfiltration: false, waterLevel: false, lowBattery: false, lowSignal: 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' }
  device.alertHistory.unshift(fixLog)
  ElMessage.success('已模拟修复，设备状态恢复正常')
}

const simulateAlert = (device) => {
  device.status.tilt = true
  device.tiltAngle = 9.3
  device.status.waterLevel = true
  device.hasAlert = true
  device.alertLevel = 'critical'
  const alertLog = { time: new Date().toLocaleString(), content: '【模拟触发】倾斜+水位告警', type: 'danger' }
  device.alertHistory.unshift(alertLog)
  ElMessage.warning('已触发模拟告警，请及时处置')
}

const refreshDevice = () => {
  loadDevices()
}

/* ============ 生命周期 ============ */
onMounted(() => {
  loadDevices()
})
</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);
}
.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;
}
.sub-value {
  margin-left: 8px;
  font-size: 12px;
  color: #909399;
}
.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;
}
.submitted-alert {
  margin: 16px 0;
}
.empty-panel {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
