<!--数据统计-->
<template>
  <div class="terminal-operation-dashboard">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <el-icon><Monitor /></el-icon>
        <span class="title">井盖设备智能终端运维看板</span>
        <el-tag type="danger" effect="dark">异常终端 {{ abnormalCount }}</el-tag>
      </div>
      <div class="header-right">
        <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 260px"
            size="default"
        />
        <el-button type="primary" :icon="Refresh" @click="refreshData">刷新</el-button>
        <el-button :icon="Download" @click="exportReport">导出报表</el-button>
      </div>
    </div>

    <!-- KPI 指标卡片 -->
    <div class="kpi-cards">
      <div class="kpi-card">
        <div class="kpi-value">{{ totalDevices }}</div>
        <div class="kpi-label">终端总数</div>
      </div>
      <div class="kpi-card warning">
        <div class="kpi-value">{{ abnormalCount }}</div>
        <div class="kpi-label">异常终端</div>
        <div class="kpi-trend">占比 {{ abnormalRate }}%</div>
      </div>
      <div class="kpi-card success">
        <div class="kpi-value">{{ problemSolvedRate }}%</div>
        <div class="kpi-label">问题解决率</div>
        <div class="kpi-trend">环比 +2.5%</div>
      </div>
      <div class="kpi-card">
        <div class="kpi-value">{{ caseDisposalRate }}%</div>
        <div class="kpi-label">案件处置率</div>
        <div class="kpi-trend">同比 +5.2%</div>
      </div>
      <div class="kpi-card">
        <div class="kpi-value">{{ delayRate }}%</div>
        <div class="kpi-label">延期率</div>
        <div class="kpi-trend trend-down">环比 -1.2%</div>
      </div>
      <div class="kpi-card">
        <div class="kpi-value">{{ avgResponseTime }}</div>
        <div class="kpi-label">平均响应时长(小时)</div>
      </div>
    </div>

    <!-- 图表区域 -->
    <div class="charts-row">
      <div class="chart-card">
        <div class="chart-header">
          <span>问题数量趋势（近6个月）</span>
          <el-radio-group v-model="trendPeriod" size="small">
            <el-radio-button label="month">月度</el-radio-button>
            <el-radio-button label="week">周度</el-radio-button>
          </el-radio-group>
        </div>
        <div class="chart-container">
          <v-chart :option="trendChartOption" autoresize />
        </div>
      </div>
      <div class="chart-card">
        <div class="chart-header">
          <span>问题类型分布</span>
        </div>
        <div class="chart-container">
          <v-chart :option="problemTypeOption" autoresize />
        </div>
      </div>
    </div>

    <div class="charts-row">
      <div class="chart-card">
        <div class="chart-header">
          <span>处置率 vs 延期率趋势</span>
        </div>
        <div class="chart-container">
          <v-chart :option="disposalTrendOption" autoresize />
        </div>
      </div>
      <div class="chart-card">
        <div class="chart-header">
          <span>区域运维情况排行</span>
        </div>
        <div class="chart-container">
          <v-chart :option="regionRankOption" autoresize />
        </div>
      </div>
    </div>

    <!-- 异常终端列表 -->
    <div class="device-list-container">
      <div class="list-header">
        <span><el-icon><List /></el-icon> 异常终端列表（默认展示异常终端）</span>
        <div class="list-filters">
          <el-input
              v-model="searchKeyword"
              placeholder="搜索设备编号/名称/位置"
              clearable
              :prefix-icon="Search"
              style="width: 200px"
              size="small"
          />
          <el-select v-model="faultTypeFilter" placeholder="故障类型" clearable size="small" style="width: 120px">
            <el-option label="倾斜超标" value="tilt" />
            <el-option label="水位超限" value="water" />
            <el-option label="异常震动" value="vibration" />
            <el-option label="通讯故障" value="communication" />
            <el-option label="电池低电量" value="battery" />
          </el-select>
          <el-button type="primary" size="small" @click="refreshList">查询</el-button>
        </div>
      </div>
      <el-table :data="paginatedAbnormalDevices" stripe border style="width: 100%" v-loading="loading">
        <el-table-column type="index" label="序号" width="55" align="center" />
        <el-table-column prop="code" label="设备编号" width="140" sortable />
        <el-table-column prop="name" label="设备名称" width="140" show-overflow-tooltip />
        <el-table-column prop="deviceTypeName" label="设备类型" width="100" />
        <el-table-column prop="faultTypeName" label="故障类型" width="110">
          <template #default="{ row }">
            <el-tag :type="getFaultTagType(row.faultType)" size="small">{{ row.faultTypeName }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="faultDesc" label="故障描述" min-width="180" show-overflow-tooltip />
        <el-table-column prop="locationShort" label="所在位置" min-width="140" show-overflow-tooltip />
        <el-table-column prop="faultTime" label="故障时间" width="150" sortable />
        <el-table-column prop="status" label="处理状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusTag(row.status)" size="small">{{ getStatusText(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="elapsedHours" label="已耗时(h)" width="100" sortable align="center">
          <template #default="{ row }">
            <span :class="{ 'over-time': row.elapsedHours > 48 }">{{ row.elapsedHours }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" fixed="right" align="center">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="viewDetail(row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-wrapper">
        <el-pagination
            background
            layout="total, sizes, prev, pager, next"
            :total="filteredAbnormalDevices.length"
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50]"
        />
      </div>
    </div>

    <!-- 终端详情抽屉 -->
    <el-drawer v-model="detailDrawerVisible" :title="`终端详情 - ${currentDevice?.code}`" size="450px" direction="rtl">
      <div v-if="currentDevice" class="device-detail">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="设备编号">{{ currentDevice.code }}</el-descriptions-item>
          <el-descriptions-item label="设备名称">{{ currentDevice.name }}</el-descriptions-item>
          <el-descriptions-item label="设备类型">{{ currentDevice.deviceTypeName }}</el-descriptions-item>
          <el-descriptions-item label="设备型号">{{ currentDevice.model }}</el-descriptions-item>
          <el-descriptions-item label="权属单位">{{ currentDevice.ownerUnit }}</el-descriptions-item>
          <el-descriptions-item label="运维部门">{{ currentDevice.maintenanceDept }}</el-descriptions-item>
          <el-descriptions-item label="故障类型">{{ currentDevice.faultTypeName }}</el-descriptions-item>
          <el-descriptions-item label="故障描述">{{ currentDevice.faultDesc }}</el-descriptions-item>
          <el-descriptions-item label="故障时间">{{ currentDevice.faultTime }}</el-descriptions-item>
          <el-descriptions-item label="处理状态">
            <el-tag :type="getStatusTag(currentDevice.status)">{{ getStatusText(currentDevice.status) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="已耗时">{{ currentDevice.elapsedHours }} 小时</el-descriptions-item>
          <el-descriptions-item label="详细地址">{{ currentDevice.address }}</el-descriptions-item>
        </el-descriptions>
        <div class="history-section" v-if="currentDevice.historyRecords?.length">
          <div class="sub-title">处置记录</div>
          <el-timeline>
            <el-timeline-item v-for="record in currentDevice.historyRecords" :key="record.id" :timestamp="record.time" :type="record.type">
              {{ record.content }}
            </el-timeline-item>
          </el-timeline>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { Monitor, Refresh, Download, List, Search } from '@element-plus/icons-vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { BarChart, LineChart, PieChart } from 'echarts/charts'
import { TitleComponent, TooltipComponent, LegendComponent, GridComponent, ToolboxComponent } from 'echarts/components'

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

// 模拟设备数据（含异常终端）
const mockDevices = ref([
  { id: 1, code: 'DEV-1001', name: '人民路智能井盖', deviceType: 'smart', deviceTypeName: '智能井盖', model: 'WATCHMAN-S2', ownerUnit: '市政工程管理处', maintenanceDept: '市政维修一队', faultType: 'tilt', faultTypeName: '倾斜超标', faultDesc: '倾斜角度14.2°，超过阈值8°', faultTime: '2025-04-02 14:23:15', status: 'pending', statusText: '待处理', elapsedHours: 2.5, lng: 121.487, lat: 31.249, address: '人民路与解放路口东50m', locationShort: '人民路口', historyRecords: [] },
  { id: 2, code: 'DEV-1002', name: '滨江路防爆井盖', deviceType: 'explosion', deviceTypeName: '防爆井盖', model: 'WATCHMAN-EX', ownerUnit: '水务集团', maintenanceDept: '水务抢修队', faultType: 'water', faultTypeName: '水位超限', faultDesc: '水位62cm，超过阈值40cm', faultTime: '2025-04-02 13:55:02', status: 'pending', statusText: '待处理', elapsedHours: 3.2, lng: 121.502, lat: 31.235, address: '滨江路化工园区南门', locationShort: '滨江园区', historyRecords: [] },
  { id: 3, code: 'DEV-1003', name: '古城街井盖', deviceType: 'smart', deviceTypeName: '智能井盖', model: 'WATCHMAN-S1', ownerUnit: '市政设施管理处', maintenanceDept: '市政维修二队', faultType: 'vibration', faultTypeName: '异常震动', faultDesc: '震动112mg，超过阈值80mg', faultTime: '2025-04-02 12:10:33', status: 'processing', statusText: '处理中', elapsedHours: 5.8, lng: 121.478, lat: 31.258, address: '古城街北段树下', locationShort: '古城街', historyRecords: [{ id: 1, time: '2025-04-02 13:00:00', type: 'primary', content: '维修人员已出发前往现场' }] },
  { id: 4, code: 'DEV-1004', name: '南港路井盖', deviceType: 'smart', deviceTypeName: '智能井盖', model: 'WATCHMAN-S2', ownerUnit: '市政工程管理处', maintenanceDept: '市政维修一队', faultType: 'communication', faultTypeName: '通讯故障', faultDesc: '设备离线超2小时', faultTime: '2025-04-02 11:45:20', status: 'pending', statusText: '待处理', elapsedHours: 6.3, lng: 121.495, lat: 31.228, address: '南港路旧车站段', locationShort: '南港路', historyRecords: [] },
  { id: 5, code: 'DEV-1005', name: '石化区防爆井盖', deviceType: 'explosion', deviceTypeName: '防爆井盖', model: 'WATCHMAN-EX', ownerUnit: '生态环境局', maintenanceDept: '应急抢修队', faultType: 'battery', faultTypeName: '电池低电量', faultDesc: '电池电量仅剩12%', faultTime: '2025-04-02 10:30:45', status: 'completed', statusText: '已完成', elapsedHours: 4.5, lng: 121.524, lat: 31.239, address: '石化大道南侧', locationShort: '石化大道', historyRecords: [{ id: 1, time: '2025-04-02 11:30:00', type: 'success', content: '电池更换完成' }] },
  { id: 6, code: 'DEV-1006', name: '高新区智能井盖', deviceType: 'smart', deviceTypeName: '智能井盖', model: 'WATCHMAN-S2', ownerUnit: '市政设施管理处', maintenanceDept: '市政维修二队', faultType: 'tilt', faultTypeName: '倾斜超标', faultDesc: '倾斜角度5.6°', faultTime: '2025-04-02 09:20:00', status: 'pending', statusText: '待处理', elapsedHours: 8.7, lng: 121.512, lat: 31.242, address: '高新大道云计算中心旁', locationShort: '高新区', historyRecords: [] },
  { id: 7, code: 'DEV-1007', name: '中山路智能井盖', deviceType: 'smart', deviceTypeName: '智能井盖', model: 'WATCHMAN-S2', ownerUnit: '市政工程管理处', maintenanceDept: '市政维修一队', faultType: 'water', faultTypeName: '水位超限', faultDesc: '水位45cm', faultTime: '2025-04-01 16:30:00', status: 'completed', statusText: '已完成', elapsedHours: 12, lng: 121.488, lat: 31.252, address: '中山路与人民路口', locationShort: '中山路口', historyRecords: [] },
  { id: 8, code: 'DEV-1008', name: '迎宾大道井盖', deviceType: 'smart', deviceTypeName: '智能井盖', model: 'WATCHMAN-S1', ownerUnit: '市政设施管理处', maintenanceDept: '市政维修二队', faultType: 'vibration', faultTypeName: '异常震动', faultDesc: '震动95mg', faultTime: '2025-04-01 14:00:00', status: 'completed', statusText: '已完成', elapsedHours: 8, lng: 121.505, lat: 31.245, address: '迎宾大道88号', locationShort: '迎宾大道', historyRecords: [] }
])

// 正常设备数量（模拟）
const normalDeviceCount = 42
const totalDevices = computed(() => mockDevices.value.length + normalDeviceCount)
const abnormalDevices = computed(() => mockDevices.value.filter(d => d.status !== 'completed'))
const abnormalCount = computed(() => abnormalDevices.value.length)
const abnormalRate = computed(() => ((abnormalCount.value / totalDevices.value) * 100).toFixed(1))

// 运维指标模拟
const problemSolvedRate = computed(() => {
  const completed = mockDevices.value.filter(d => d.status === 'completed').length
  const total = mockDevices.value.length
  return Math.round((completed / total) * 100)
})
const caseDisposalRate = computed(() => 94)
const delayRate = computed(() => 8.5)
const avgResponseTime = computed(() => 3.2)

// 筛选条件
const searchKeyword = ref('')
const faultTypeFilter = ref('')
const dateRange = ref([])
const trendPeriod = ref('month')
const currentPage = ref(1)
const pageSize = ref(10)
const loading = ref(false)
const detailDrawerVisible = ref(false)
const currentDevice = ref(null)

// 过滤异常终端
const filteredAbnormalDevices = computed(() => {
  let list = abnormalDevices.value
  if (searchKeyword.value) {
    const kw = searchKeyword.value.toLowerCase()
    list = list.filter(d => d.code.toLowerCase().includes(kw) || d.name.toLowerCase().includes(kw) || d.locationShort.toLowerCase().includes(kw))
  }
  if (faultTypeFilter.value) {
    list = list.filter(d => d.faultType === faultTypeFilter.value)
  }
  return list
})
const paginatedAbnormalDevices = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  return filteredAbnormalDevices.value.slice(start, start + pageSize.value)
})

// 趋势图数据（模拟）
const trendChartOption = computed(() => {
  const months = ['1月', '2月', '3月', '4月', '5月', '6月']
  const problems = [12, 15, 18, 22, 25, 20]
  const solved = [8, 11, 14, 18, 21, 18]
  return {
    tooltip: { trigger: 'axis' },
    legend: { data: ['新增问题数', '解决问题数'] },
    xAxis: { type: 'category', data: months },
    yAxis: { type: 'value', name: '数量' },
    series: [
      { name: '新增问题数', type: 'line', data: problems, smooth: true, lineStyle: { color: '#f56c6c' }, areaStyle: { opacity: 0.1 } },
      { name: '解决问题数', type: 'line', data: solved, smooth: true, lineStyle: { color: '#67c23a' }, areaStyle: { opacity: 0.1 } }
    ]
  }
})

// 问题类型分布饼图
const problemTypeOption = computed(() => ({
  tooltip: { trigger: 'item' },
  legend: { orient: 'vertical', left: 'left' },
  series: [{
    type: 'pie', radius: '55%', center: ['50%', '50%'],
    data: [
      { name: '倾斜超标', value: 32, itemStyle: { color: '#f56c6c' } },
      { name: '水位超限', value: 25, itemStyle: { color: '#e6a23c' } },
      { name: '异常震动', value: 18, itemStyle: { color: '#409eff' } },
      { name: '通讯故障', value: 15, itemStyle: { color: '#909399' } },
      { name: '电池低电量', value: 10, itemStyle: { color: '#67c23a' } }
    ],
    label: { show: true, formatter: '{b}: {d}%' }
  }]
}))

// 处置率 vs 延期率趋势
const disposalTrendOption = computed(() => ({
  tooltip: { trigger: 'axis' },
  legend: { data: ['处置率(%)', '延期率(%)'] },
  xAxis: { type: 'category', data: ['1月', '2月', '3月', '4月', '5月', '6月'] },
  yAxis: { type: 'value', name: '百分比(%)' },
  series: [
    { name: '处置率(%)', type: 'line', data: [85, 88, 90, 91, 93, 94], lineStyle: { color: '#67c23a' }, smooth: true },
    { name: '延期率(%)', type: 'line', data: [12, 11, 10, 9.5, 9, 8.5], lineStyle: { color: '#e6a23c' }, smooth: true }
  ]
}))

// 区域运维排行
const regionRankOption = computed(() => ({
  tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
  xAxis: { type: 'value', name: '问题数量' },
  yAxis: { type: 'category', data: ['浦东新区', '徐汇区', '黄浦区', '静安区', '杨浦区'], axisLabel: { rotate: 0 } },
  series: [{ name: '问题数量', type: 'bar', data: [28, 22, 18, 15, 12], itemStyle: { color: '#409eff', borderRadius: [0, 4, 4, 0] } }]
}))

const getFaultTagType = (type) => {
  const map = { tilt: 'danger', water: 'danger', vibration: 'warning', communication: 'info', battery: 'warning' }
  return map[type] || 'info'
}
const getStatusTag = (status) => {
  const map = { pending: 'danger', processing: 'warning', completed: 'success' }
  return map[status] || 'info'
}
const getStatusText = (status) => {
  const map = { pending: '待处理', processing: '处理中', completed: '已完成' }
  return map[status] || status
}

const refreshData = () => { ElMessage.success('数据已刷新') }
const refreshList = () => { currentPage.value = 1; ElMessage.success('列表已刷新') }
const exportReport = () => { ElMessage.success('导出运维报表（演示）') }
const viewDetail = (device) => { currentDevice.value = device; detailDrawerVisible.value = true }

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

<style scoped>
.terminal-operation-dashboard {
  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;
  flex-wrap: wrap;
  gap: 12px;
}
.header-left { display: flex; align-items: center; gap: 12px; }
.header-left .title { font-size: 20px; font-weight: 600; }
.header-right { display: flex; gap: 12px; flex-wrap: wrap; }

.kpi-cards {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  gap: 16px;
  margin-bottom: 20px;
}
.kpi-card {
  background: white;
  border-radius: 16px;
  padding: 16px;
  text-align: center;
  box-shadow: 0 1px 4px rgba(0,0,0,0.05);
}
.kpi-value { font-size: 32px; font-weight: bold; color: #1f2d3d; }
.kpi-label { font-size: 13px; color: #909399; margin-top: 6px; }
.kpi-trend { font-size: 11px; color: #67c23a; margin-top: 4px; }
.kpi-trend.trend-down { color: #f56c6c; }
.kpi-card.warning .kpi-value { color: #e6a23c; }
.kpi-card.success .kpi-value { color: #67c23a; }

.charts-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-bottom: 20px;
}
.chart-card {
  background: white;
  border-radius: 16px;
  padding: 16px;
}
.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  font-weight: 600;
}
.chart-container { height: 280px; }

.device-list-container {
  background: white;
  border-radius: 16px;
  padding: 16px;
}
.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  font-weight: 600;
}
.list-filters { display: flex; gap: 12px; align-items: center; }
.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
  padding-top: 12px;
  border-top: 1px solid #e9ecef;
}
.device-detail { padding: 8px; }
.sub-title { font-weight: 600; margin: 16px 0 12px 0; }
.over-time { color: #f56c6c; font-weight: 600; }
</style>