<!--监测设备台账-->
<template>
  <div class="manhole-cover-management">
    <!-- 页面头部 -->
    <div class="page-header">

      <div class="stats-section">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <el-icon><Monitor /></el-icon>
            <div>
              <div class="stat-label">在用设备</div>
              <div class="stat-number">{{ activeDevicesCount }}</div>
            </div>
          </div>
        </el-card>
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <el-icon><CircleClose /></el-icon>
            <div>
              <div class="stat-label">已用/停用</div>
              <div class="stat-number">{{ inactiveDevicesCount }}</div>
            </div>
          </div>
        </el-card>
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <el-icon><Location /></el-icon>
            <div>
              <div class="stat-label">监测点<br/>覆盖区域</div>
              <div class="stat-number">{{ locationsCount }}</div>
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 筛选工具栏 -->
    <div class="filter-bar">
      <el-input
          v-model="searchKeyword"
          placeholder="搜索设备编号/名称/位置"
          clearable
          style="width: 240px"
          :prefix-icon="Search"
      />
      <el-select v-model="statusFilter" placeholder="运维状态" clearable style="width: 140px">
        <el-option label="全部" value="" />
        <el-option label="正常运行" value="normal" />
        <el-option label="需维护" value="maintenance" />
        <el-option label="故障" value="fault" />
        <el-option label="停用" value="inactive" />
      </el-select>
      <el-select v-model="typeFilter" placeholder="设备类型" clearable style="width: 140px">
        <el-option label="全部" value="" />
        <el-option label="普通井盖" value="standard" />
        <el-option label="智能井盖" value="smart" />
        <el-option label="防爆井盖" value="explosion" />
      </el-select>
      <el-button type="primary" :icon="Refresh" @click="resetFilters">重置筛选</el-button>
    </div>

    <!-- 设备列表展示区 - 卡片 + 表格融合风格 -->
    <div class="device-list-container">
      <el-table
          :data="filteredDevices"
          stripe
          border
          style="width: 100%"
          :row-class-name="tableRowClassName"
          @row-click="handleRowClick"
      >
        <el-table-column type="expand">
          <template #default="{ row }">
            <div class="expand-detail">
              <el-descriptions title="设备历史安装信息" :column="2" border size="small">
                <el-descriptions-item label="首次安装时间">{{ row.installHistory?.firstInstall || '—' }}</el-descriptions-item>
                <el-descriptions-item label="最近安装时间">{{ row.installHistory?.lastInstall || '—' }}</el-descriptions-item>
                <el-descriptions-item label="历史安装次数">{{ row.installHistory?.installCount || 0 }}次</el-descriptions-item>
                <el-descriptions-item label="历史测点记录">{{ row.installHistory?.previousLocations?.join(', ') || '无' }}</el-descriptions-item>
                <el-descriptions-item label="备注">{{ row.installHistory?.remark || '暂无' }}</el-descriptions-item>
              </el-descriptions>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="deviceId" label="设备编号" width="140" sortable />
        <el-table-column prop="deviceName" label="设备名称" width="160" show-overflow-tooltip />
        <el-table-column prop="deviceType" label="设备类型" width="110">
          <template #default="{ row }">
            <el-tag :type="getDeviceTypeTag(row.deviceType)">{{ getDeviceTypeText(row.deviceType) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="location" label="所在测点及位置" min-width="180" show-overflow-tooltip>
          <template #default="{ row }">
            <div><el-icon><Location /></el-icon> {{ row.location }}</div>
            <div style="font-size:12px; color:#909399;">测点ID: {{ row.measurePointId }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="运维状态" width="120" align="center">
          <template #default="{ row }">
            <el-badge :value="row.status === 'fault' ? '告警' : ''" :type="row.status === 'fault' ? 'danger' : 'primary'">
              <el-tag :type="getStatusType(row.status)" effect="plain">{{ getStatusText(row.status) }}</el-tag>
            </el-badge>
          </template>
        </el-table-column>
        <el-table-column prop="lastMaintenance" label="最近运维时间" width="160" sortable />
        <el-table-column prop="operationStatus" label="在用/已用" width="110" align="center">
          <template #default="{ row }">
            <el-switch
                v-model="row.isActive"
                disabled
                active-text="在用"
                inactive-text="已用"
                active-color="#13ce66"
                inactive-color="#909399"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click.stop="showDetail(row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 简易分页 -->
      <div class="pagination-wrapper">
        <el-pagination
            background
            layout="prev, pager, next"
            :total="filteredDevices.length"
            :page-size="pageSize"
            v-model:current-page="currentPage"
        />
      </div>
    </div>

    <!-- 右侧侧边详情卡片 (动态监测信息面板) -->
    <el-drawer v-model="drawerVisible" title="设备电子档案 - 详细信息" size="40%" direction="rtl">
      <template v-if="selectedDevice">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="设备编号">{{ selectedDevice.deviceId }}</el-descriptions-item>
          <el-descriptions-item label="设备名称">{{ selectedDevice.deviceName }}</el-descriptions-item>
          <el-descriptions-item label="设备类型">{{ getDeviceTypeText(selectedDevice.deviceType) }}</el-descriptions-item>
          <el-descriptions-item label="运维状态">
            <el-tag :type="getStatusType(selectedDevice.status)">{{ getStatusText(selectedDevice.status) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="在用状态">
            <el-tag :type="selectedDevice.isActive ? 'success' : 'info'">{{ selectedDevice.isActive ? '在用' : '已用' }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="所在测点ID">{{ selectedDevice.measurePointId }}</el-descriptions-item>
          <el-descriptions-item label="详细地理位置">{{ selectedDevice.location }}</el-descriptions-item>
          <el-descriptions-item label="最近运维时间">{{ selectedDevice.lastMaintenance }}</el-descriptions-item>
          <el-descriptions-item label="电池电量/健康度" v-if="selectedDevice.battery">{{ selectedDevice.battery }}%</el-descriptions-item>
          <el-descriptions-item label="最后通讯时间">{{ selectedDevice.lastCommunication || '—' }}</el-descriptions-item>
        </el-descriptions>

        <el-divider content-position="left">历史安装记录</el-divider>
        <el-timeline>
          <el-timeline-item
              v-for="(record, idx) in selectedDevice.historyRecords"
              :key="idx"
              :timestamp="record.time"
              placement="top"
              :type="record.type"
          >
            {{ record.content }}
          </el-timeline-item>
          <el-timeline-item v-if="!selectedDevice.historyRecords?.length" timestamp="暂无" placement="top">
            尚无历史安装迁移记录
          </el-timeline-item>
        </el-timeline>
        <el-divider content-position="left">动态监测指标</el-divider>
        <div class="monitor-metrics">
          <el-row :gutter="12">
            <el-col :span="12"><el-statistic title="井盖倾斜角" :value="selectedDevice.metrics?.tilt || 0" suffix="°" /></el-col>
            <el-col :span="12"><el-statistic title="水浸状态" :value="selectedDevice.metrics?.waterIntrusion ? '已浸水' : '正常'" /></el-col>
            <el-col :span="12"><el-statistic title="气体浓度(ppm)" :value="selectedDevice.metrics?.gas || 0" /></el-col>
            <el-col :span="12"><el-statistic title="振动强度" :value="selectedDevice.metrics?.vibration || 0" suffix="Hz" /></el-col>
          </el-row>
        </div>
        <div style="margin-top: 20px; text-align: right;">
          <el-button type="primary" @click="closeDrawer">关闭</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { Monitor, CircleClose, Location, Search, Refresh } from '@element-plus/icons-vue'

// --- 模拟设备数据 ---
const mockDevices = [
  {
    deviceId: 'MN-1001',
    deviceName: '人民路智能井盖',
    deviceType: 'smart',
    location: '人民路与解放路口东50m',
    measurePointId: 'MP-A021',
    status: 'normal',
    lastMaintenance: '2025-03-15',
    isActive: true,
    battery: 87,
    lastCommunication: '2025-04-02 14:23:11',
    installHistory: {
      firstInstall: '2021-06-10',
      lastInstall: '2024-10-20',
      installCount: 2,
      previousLocations: ['人民路与中山路口'],
      remark: '因道路改造迁移'
    },
    historyRecords: [
      { time: '2024-10-20', content: '设备迁移至当前测点人民路与解放路口', type: 'primary' },
      { time: '2021-06-10', content: '初次安装于人民路与中山路口', type: 'info' }
    ],
    metrics: { tilt: 2.3, waterIntrusion: false, gas: 12, vibration: 0.4 }
  },
  {
    deviceId: 'MN-1002',
    deviceName: '滨江路防爆井盖',
    deviceType: 'explosion',
    location: '滨江路化工园区南门',
    measurePointId: 'MP-B045',
    status: 'maintenance',
    lastMaintenance: '2025-02-28',
    isActive: true,
    battery: 34,
    lastCommunication: '2025-04-01 08:52:03',
    installHistory: {
      firstInstall: '2022-03-22',
      lastInstall: '2023-11-05',
      installCount: 1,
      previousLocations: [],
      remark: '高危区域需定期维护'
    },
    historyRecords: [
      { time: '2023-11-05', content: '替换原有普通井盖升级防爆型号', type: 'success' }
    ],
    metrics: { tilt: 5.1, waterIntrusion: false, gas: 89, vibration: 1.2 }
  },
  {
    deviceId: 'MN-1003',
    deviceName: '老城区铸铁井盖',
    deviceType: 'standard',
    location: '古城街北段树下',
    measurePointId: 'MP-C102',
    status: 'fault',
    lastMaintenance: '2024-12-10',
    isActive: true,
    battery: null,
    lastCommunication: '2025-03-28 06:15:44',
    installHistory: {
      firstInstall: '2018-07-15',
      lastInstall: '2020-03-01',
      installCount: 1,
      previousLocations: ['古城街南段'],
      remark: '井盖出现沉降'
    },
    historyRecords: [
      { time: '2020-03-01', content: '迁移至古城街北段树下', type: 'warning' }
    ],
    metrics: { tilt: 15.2, waterIntrusion: true, gas: 5, vibration: 0.9 }
  },
  {
    deviceId: 'MN-1004',
    deviceName: '高新区智能井盖',
    deviceType: 'smart',
    location: '高新大道云计算中心旁',
    measurePointId: 'MP-D209',
    status: 'normal',
    lastMaintenance: '2025-03-28',
    isActive: true,
    battery: 96,
    lastCommunication: '2025-04-02 16:00:21',
    installHistory: {
      firstInstall: '2023-09-18',
      lastInstall: '2023-09-18',
      installCount: 1,
      previousLocations: [],
      remark: '新建道路配套'
    },
    historyRecords: [],
    metrics: { tilt: 0.8, waterIntrusion: false, gas: 3, vibration: 0.1 }
  },
  {
    deviceId: 'MN-1005',
    deviceName: '南港路井盖（已停用）',
    deviceType: 'standard',
    location: '南港路旧车站段',
    measurePointId: 'MP-E176',
    status: 'inactive',
    lastMaintenance: '2024-06-20',
    isActive: false,
    battery: null,
    lastCommunication: '2024-07-01 02:00:00',
    installHistory: {
      firstInstall: '2017-05-02',
      lastInstall: '2019-12-15',
      installCount: 2,
      previousLocations: ['南港路中段', '南港路西段'],
      remark: '区域改造，设备已封存'
    },
    historyRecords: [
      { time: '2024-08-01', content: '设备停用，进入已用状态', type: 'info' },
      { time: '2019-12-15', content: '迁移至当前测点安装', type: 'primary' }
    ],
    metrics: { tilt: 0, waterIntrusion: false, gas: 0, vibration: 0 }
  }
]

// 状态筛选 & 分页
const searchKeyword = ref('')
const statusFilter = ref('')
const typeFilter = ref('')
const currentPage = ref(1)
const pageSize = 5

const filteredDevices = computed(() => {
  let result = [...mockDevices]
  // 搜索关键字过滤
  if (searchKeyword.value) {
    const kw = searchKeyword.value.toLowerCase()
    result = result.filter(d =>
        d.deviceId.toLowerCase().includes(kw) ||
        d.deviceName.toLowerCase().includes(kw) ||
        d.location.toLowerCase().includes(kw)
    )
  }
  // 状态过滤
  if (statusFilter.value) {
    result = result.filter(d => d.status === statusFilter.value)
  }
  // 类型过滤
  if (typeFilter.value) {
    result = result.filter(d => d.deviceType === typeFilter.value)
  }
  return result
})

const pagedDevices = computed(() => {
  const start = (currentPage.value - 1) * pageSize
  return filteredDevices.value.slice(start, start + pageSize)
})

// 统计卡片数据（基于原始数据）
const activeDevicesCount = computed(() => mockDevices.filter(d => d.isActive).length)
const inactiveDevicesCount = computed(() => mockDevices.filter(d => !d.isActive).length)
const locationsCount = computed(() => new Set(mockDevices.map(d => d.measurePointId)).size)

const resetFilters = () => {
  searchKeyword.value = ''
  statusFilter.value = ''
  typeFilter.value = ''
  currentPage.value = 1
}

const getStatusType = (status) => {
  switch(status) {
    case 'normal': return 'success'
    case 'maintenance': return 'warning'
    case 'fault': return 'danger'
    case 'inactive': return 'info'
    default: return 'info'
  }
}
const getStatusText = (status) => {
  switch(status) {
    case 'normal': return '正常运行'
    case 'maintenance': return '需维护'
    case 'fault': return '故障'
    case 'inactive': return '停用'
    default: return '未知'
  }
}
const getDeviceTypeTag = (type) => {
  if (type === 'smart') return 'success'
  if (type === 'explosion') return 'danger'
  return ''
}
const getDeviceTypeText = (type) => {
  if (type === 'smart') return '智能井盖'
  if (type === 'explosion') return '防爆井盖'
  return '普通井盖'
}
const tableRowClassName = ({ row }) => {
  if (row.status === 'fault') return 'warning-row'
  if (!row.isActive) return 'inactive-row'
  return ''
}

const drawerVisible = ref(false)
const selectedDevice = ref(null)

const showDetail = (device) => {
  selectedDevice.value = device
  drawerVisible.value = true
}
const handleRowClick = (row) => {
  showDetail(row)
}
const closeDrawer = () => {
  drawerVisible.value = false
}
</script>

<style scoped>
.manhole-cover-management {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
}
.title-section {
  display: flex;
  align-items: baseline;
  gap: 12px;
}
.title-section h1 {
  margin: 0;
  font-size: 24px;
  font-weight: 500;
  color: #1f2d3d;
}
.stats-section {
  display: flex;
  gap: 16px;
}
.stat-card {
  width: 160px;
  border-radius: 10px;
}
.stat-content {
  display: flex;
  align-items: center;
  gap: 12px;
}
.stat-content .el-icon {
  font-size: 32px;
  color: #409eff;
}
.stat-label {
  font-size: 14px;
  color: #6c757d;
}
.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #2c3e50;
}
.filter-bar {
  margin-bottom: 20px;
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
  background: white;
  padding: 12px 16px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}
.device-list-container {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.08);
  overflow: hidden;
}
.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  padding: 15px 20px;
  background: white;
  border-top: 1px solid #e4e7ed;
}
.expand-detail {
  padding: 16px 24px;
  background-color: #fafbfc;
}
.monitor-metrics {
  background: #f8f9fc;
  border-radius: 8px;
  padding: 10px;
}
:deep(.warning-row) {
  --el-table-tr-bg-color: #fdf6ec;
}
:deep(.inactive-row) {
  --el-table-tr-bg-color: #f5f5f5;
  color: #a8a8a8;
}
</style>