<!--监测设备统计分析-->
<template>
  <div class="device-statistics-dashboard">


    <!-- 筛选区域 -->
    <div class="filter-bar">
      <div class="filter-group">
        <span class="filter-label">所属区域：</span>
        <el-select v-model="selectedRegion" placeholder="全部区域" clearable style="width: 160px">
          <el-option label="全部区域" value="" />
          <el-option v-for="region in regionList" :key="region" :label="region" :value="region" />
        </el-select>
      </div>
      <div class="filter-group">
        <span class="filter-label">设备类型：</span>
        <el-select v-model="selectedType" placeholder="全部类型" clearable style="width: 160px">
          <el-option label="全部类型" value="" />
          <el-option v-for="type in typeList" :key="type" :label="type" :value="type" />
        </el-select>
      </div>
      <el-button type="primary" @click="resetFilters">重置筛选</el-button>
      <el-button @click="exportData" :icon="Download">导出数据</el-button>
    </div>

    <!-- 图表展示区域：左右两列 -->
    <div class="charts-container">
      <!-- 左侧：区域分布柱状图 -->
      <div class="chart-card">
        <div class="card-header">
          <span class="card-title">
            <el-icon><Location /></el-icon>
            设备区域分布（柱状图）
          </span>
          <el-radio-group v-model="barChartType" size="small">
            <el-radio-button label="count">设备数量</el-radio-button>
            <el-radio-button label="percent">占比 (%)</el-radio-button>
          </el-radio-group>
        </div>
        <div class="chart-wrapper">
          <v-chart :option="regionBarOption" autoresize />
        </div>
      </div>

      <!-- 右侧：设备类型分布饼图 -->
      <div class="chart-card">
        <div class="card-header">
          <span class="card-title">
            <el-icon><PieChart /></el-icon>
            设备类型分布（饼图）
          </span>
          <el-radio-group v-model="pieChartType" size="small">
            <el-radio-button label="normal">标准饼图</el-radio-button>
            <el-radio-button label="doughnut">环形图</el-radio-button>
          </el-radio-group>
        </div>
        <div class="chart-wrapper">
          <v-chart :option="deviceTypePieOption" autoresize />
        </div>
      </div>
    </div>

    <!-- 下方：详细数据表格 -->
    <div class="data-table-container">
      <div class="table-header">
        <span class="card-title">
          <el-icon><List /></el-icon>
          设备明细数据
        </span>
        <el-input
            v-model="searchKeyword"
            placeholder="搜索设备名称/编号/区域"
            clearable
            style="width: 240px"
            :prefix-icon="Search"
            size="small"
        />
      </div>
      <el-table :data="paginatedTableData" stripe border style="width: 100%">
        <el-table-column prop="deviceCode" label="设备编号" width="130" />
        <el-table-column prop="deviceName" label="设备名称" width="150" show-overflow-tooltip />
        <el-table-column prop="deviceType" label="设备类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getTypeTagColor(row.deviceType)" size="small">{{ row.deviceType }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="region" label="所属行政区域" width="140" />
        <el-table-column prop="address" label="详细位置" min-width="180" show-overflow-tooltip />
        <el-table-column prop="status" label="运行状态" width="100" align="center">
          <template #default="{ row }">
            <el-badge :value="row.status === '故障' ? '!' : ''" :type="row.status === '故障' ? 'danger' : 'primary'">
              <el-tag :type="getStatusType(row.status)" effect="plain" size="small">{{ row.status }}</el-tag>
            </el-badge>
          </template>
        </el-table-column>
        <el-table-column prop="installDate" label="安装日期" width="120" />
      </el-table>
      <div class="pagination-wrapper">
        <el-pagination
            background
            layout="total, prev, pager, next"
            :total="filteredTableData.length"
            :page-size="pageSize"
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[5, 10, 20]"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { Location, PieChart, List, Search, Download } from '@element-plus/icons-vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { BarChart, PieChart as EChartsPie } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  DatasetComponent,
  TransformComponent
} from 'echarts/components'

// 注册 ECharts 组件
use([
  CanvasRenderer,
  BarChart,
  EChartsPie,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  DatasetComponent,
  TransformComponent
])

// ---------- 模拟设备数据 ----------
const mockDevices = [
  { deviceCode: 'DEV-1001', deviceName: '智能水位监测仪', deviceType: '水位计', region: '浦东新区', address: '世纪大道100号', status: '正常', installDate: '2024-03-15' },
  { deviceCode: 'DEV-1002', deviceName: '井盖状态传感器', deviceType: '智能井盖', region: '浦东新区', address: '张江高科技园区', status: '正常', installDate: '2024-05-20' },
  { deviceCode: 'DEV-1003', deviceName: '流量监测终端', deviceType: '流量计', region: '徐汇区', address: '漕溪北路88号', status: '维护', installDate: '2023-11-02' },
  { deviceCode: 'DEV-1004', deviceName: '水质分析仪', deviceType: '水质仪', region: '徐汇区', address: '龙吴路1500号', status: '正常', installDate: '2024-01-10' },
  { deviceCode: 'DEV-1005', deviceName: '智能井盖终端', deviceType: '智能井盖', region: '黄浦区', address: '人民大道200号', status: '故障', installDate: '2023-09-18' },
  { deviceCode: 'DEV-1006', deviceName: '压力传感器', deviceType: '压力计', region: '黄浦区', address: '外马路99号', status: '正常', installDate: '2024-02-28' },
  { deviceCode: 'DEV-1007', deviceName: '多参数水质仪', deviceType: '水质仪', region: '静安区', address: '南京西路1266号', status: '正常', installDate: '2024-04-12' },
  { deviceCode: 'DEV-1008', deviceName: '智慧井盖监测器', deviceType: '智能井盖', region: '静安区', address: '万荣路700号', status: '正常', installDate: '2024-06-01' },
  { deviceCode: 'DEV-1009', deviceName: '超声波流量计', deviceType: '流量计', region: '浦东新区', address: '金桥路1851号', status: '维护', installDate: '2023-12-10' },
  { deviceCode: 'DEV-1010', deviceName: '遥测水位计', deviceType: '水位计', region: '杨浦区', address: '淞沪路388号', status: '正常', installDate: '2024-03-20' },
  { deviceCode: 'DEV-1011', deviceName: '智能井盖传感模块', deviceType: '智能井盖', region: '杨浦区', address: '军工路516号', status: '故障', installDate: '2023-10-05' },
  { deviceCode: 'DEV-1012', deviceName: '气体监测仪', deviceType: '气体仪', region: '闵行区', address: '剑川路930号', status: '正常', installDate: '2024-05-16' },
  { deviceCode: 'DEV-1013', deviceName: '液位传感器', deviceType: '水位计', region: '闵行区', address: '东川路800号', status: '正常', installDate: '2024-01-25' },
  { deviceCode: 'DEV-1014', deviceName: '防爆智能井盖', deviceType: '智能井盖', region: '浦东新区', address: '临港新城主城区', status: '正常', installDate: '2024-07-08' },
  { deviceCode: 'DEV-1015', deviceName: '管网压力监测', deviceType: '压力计', region: '徐汇区', address: '虹漕路421号', status: '维护', installDate: '2023-08-30' },
]

// 提取区域列表和设备类型列表（用于筛选）
const regionList = computed(() => [...new Set(mockDevices.map(d => d.region))])
const typeList = computed(() => [...new Set(mockDevices.map(d => d.deviceType))])

// 筛选条件
const selectedRegion = ref('')
const selectedType = ref('')
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(10)

// 图表显示模式
const barChartType = ref('count')   // count / percent
const pieChartType = ref('normal')  // normal / doughnut

// 计算设备总数
const totalDevices = computed(() => mockDevices.length)
const regionCount = computed(() => regionList.value.length)
const deviceTypeCount = computed(() => typeList.value.length)

// 获取区域分布数据（基于筛选后的设备，但柱状图展示全局分布，为了直观，默认展示全部数据，但可考虑筛选联动）
// 这里设计：区域分布图展示全局设备按区域分布，不做筛选联动即可体现整体分布。
const regionDistribution = computed(() => {
  const regionMap = new Map()
  mockDevices.forEach(device => {
    const region = device.region
    regionMap.set(region, (regionMap.get(region) || 0) + 1)
  })
  return Array.from(regionMap.entries())
      .map(([region, count]) => ({ region, count }))
      .sort((a, b) => b.count - a.count)
})

// 设备类型分布
const typeDistribution = computed(() => {
  const typeMap = new Map()
  mockDevices.forEach(device => {
    const type = device.deviceType
    typeMap.set(type, (typeMap.get(type) || 0) + 1)
  })
  return Array.from(typeMap.entries())
      .map(([type, count]) => ({ type, count }))
      .sort((a, b) => b.count - a.count)
})

// 柱状图配置
const regionBarOption = computed(() => {
  const regions = regionDistribution.value.map(item => item.region)
  const counts = regionDistribution.value.map(item => item.count)
  const total = counts.reduce((a, b) => a + b, 0)
  const percentages = counts.map(c => ((c / total) * 100).toFixed(1))

  const seriesData = barChartType.value === 'count' ? counts : percentages
  const yAxisName = barChartType.value === 'count' ? '设备数量 (台)' : '占比 (%)'
  const seriesName = barChartType.value === 'count' ? '设备数量' : '设备占比'

  return {
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      formatter: function(params) {
        if (barChartType.value === 'count') {
          return `${params[0].axisValue}<br/>${params[0].seriesName}: ${params[0].value} 台`
        } else {
          return `${params[0].axisValue}<br/>${params[0].seriesName}: ${params[0].value}%`
        }
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: regions,
      axisLabel: { rotate: 30, interval: 0, fontSize: 11 }
    },
    yAxis: {
      type: 'value',
      name: yAxisName,
      nameLocation: 'middle',
      nameGap: 45
    },
    series: [
      {
        name: seriesName,
        type: 'bar',
        data: seriesData,
        itemStyle: {
          borderRadius: [4, 4, 0, 0],
          color: '#409eff',
          shadowColor: 'rgba(0,0,0,0.1)',
          shadowBlur: 6
        },
        label: {
          show: true,
          position: 'top',
          formatter: ({ value }) => barChartType.value === 'count' ? value : value + '%'
        }
      }
    ]
  }
})

// 饼图配置
const deviceTypePieOption = computed(() => {
  const pieData = typeDistribution.value.map(item => ({
    name: item.type,
    value: item.count
  }))
  const total = pieData.reduce((sum, d) => sum + d.value, 0)

  return {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c}台 ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: pieData.map(d => d.name)
    },
    series: [
      {
        name: '设备类型占比',
        type: 'pie',
        radius: pieChartType.value === 'doughnut' ? ['40%', '70%'] : '55%',
        center: ['50%', '50%'],
        data: pieData,
        emphasis: {
          scale: true,
          label: { show: true, formatter: '{b}: {d}%' }
        },
        label: {
          show: true,
          formatter: '{b}: {d}%',
          position: 'outside'
        },
        itemStyle: {
          borderRadius: 6,
          borderColor: '#fff',
          borderWidth: 2
        },
        color: ['#409eff', '#67c23a', '#e6a23c', '#f56c6c', '#909399', '#9b59b6', '#1abc9c']
      }
    ]
  }
})

// 表格数据筛选 (支持区域、类型、关键词)
const filteredTableData = computed(() => {
  let data = [...mockDevices]
  if (selectedRegion.value) {
    data = data.filter(d => d.region === selectedRegion.value)
  }
  if (selectedType.value) {
    data = data.filter(d => d.deviceType === selectedType.value)
  }
  if (searchKeyword.value) {
    const kw = searchKeyword.value.toLowerCase()
    data = data.filter(d =>
        d.deviceCode.toLowerCase().includes(kw) ||
        d.deviceName.toLowerCase().includes(kw) ||
        d.region.toLowerCase().includes(kw)
    )
  }
  return data
})

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

// 监听筛选变化重置页码
watch([selectedRegion, selectedType, searchKeyword], () => {
  currentPage.value = 1
})

const resetFilters = () => {
  selectedRegion.value = ''
  selectedType.value = ''
  searchKeyword.value = ''
}

const exportData = () => {
  // 简单导出CSV
  const headers = ['设备编号', '设备名称', '设备类型', '所属行政区域', '详细位置', '运行状态', '安装日期']
  const rows = filteredTableData.value.map(d => [
    d.deviceCode, d.deviceName, d.deviceType, d.region, d.address, d.status, d.installDate
  ])
  const csvContent = [headers, ...rows].map(row => row.join(',')).join('\n')
  const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' })
  const link = document.createElement('a')
  const url = URL.createObjectURL(blob)
  link.href = url
  link.setAttribute('download', '设备统计报表.csv')
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  URL.revokeObjectURL(url)
}

const getTypeTagColor = (type) => {
  const map = { '智能井盖': 'success', '水位计': 'primary', '流量计': 'warning', '水质仪': 'danger', '压力计': 'info', '气体仪': '' }
  return map[type] || ''
}

const getStatusType = (status) => {
  if (status === '正常') return 'success'
  if (status === '维护') return 'warning'
  if (status === '故障') return 'danger'
  return 'info'
}
</script>

<style scoped>
.device-statistics-dashboard {
  padding: 20px;
  background: #f5f7fb;
  min-height: 100vh;
  font-family: 'Segoe UI', 'PingFang SC', Roboto, Helvetica, Arial, sans-serif;
}

.dashboard-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
  padding: 16px 24px;
  border-radius: 16px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.title-section h2 {
  margin: 0 0 4px 0;
  font-size: 22px;
  font-weight: 600;
  color: #1f2d3d;
}

.header-stats {
  display: flex;
  gap: 32px;
}

.stat-item {
  text-align: center;
}

.stat-value {
  font-size: 28px;
  font-weight: 700;
  color: #409eff;
  line-height: 1.2;
}

.stat-label {
  font-size: 13px;
  color: #909399;
  margin-top: 4px;
}

.filter-bar {
  background: white;
  padding: 12px 20px;
  border-radius: 12px;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.filter-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-label {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
}

.charts-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-bottom: 24px;
}

.chart-card {
  background: white;
  border-radius: 16px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
  overflow: hidden;
  transition: all 0.2s;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #ebeef5;
}

.card-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  font-size: 16px;
  color: #303133;
}

.chart-wrapper {
  padding: 16px;
  height: 380px;
}

.data-table-container {
  background: white;
  border-radius: 16px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
  padding: 0 16px 16px 16px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 0 12px 0;
  border-bottom: 1px solid #e9ecef;
  margin-bottom: 12px;
}

.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
  padding-top: 8px;
}

:deep(.el-table th) {
  background-color: #f8fafc;
  font-weight: 600;
  color: #2c3e50;
}
</style>