<!--监测设备统计分析-->
<template>
  <div class="device-statistics-dashboard">
    <!-- 图表展示区域：左右两列 -->
    <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 ref="regionBarRef" class="chart-wrapper"></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 ref="typePieRef" class="chart-wrapper"></div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, nextTick, onMounted, onBeforeUnmount } from 'vue'
import { Location, PieChart } from '@element-plus/icons-vue'
import { getManholeDeviceStatistics } from '@/api/pipeNetwork/basic'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'

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

// 统计数据（来自接口）
const regionDistribution = ref([])
const typeDistribution = ref([])

// 图表实例
let regionBarChart = null
let typePieChart = null
const regionBarRef = ref(null)
const typePieRef = ref(null)

// 加载统计数据（默认全部窨井设备）
async function loadStatistics() {
  try {
    const res = await getManholeDeviceStatistics({})
    regionDistribution.value = res.data?.regionDistribution || []
    typeDistribution.value = res.data?.typeDistribution || []
  } catch (e) {
    ElMessage.error('统计数据加载失败')
  }
}

// 柱状图配置：设备区域分布（数量/占比）
const regionBarOption = computed(() => {
  const regions = regionDistribution.value.map(item => item.name)
  const counts = regionDistribution.value.map(item => item.count)
  const percentages = regionDistribution.value.map(item => item.percent)

  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 typePieOption = computed(() => {
  const pieData = typeDistribution.value.map(item => ({
    name: item.name,
    value: item.count
  }))

  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']
      }
    ]
  }
})

// 图表配置变化时刷新
watch([regionBarOption, typePieOption], () => {
  if (regionBarChart) regionBarChart.setOption(regionBarOption.value, true)
  if (typePieChart) typePieChart.setOption(typePieOption.value, true)
}, { deep: true })

// 窗口变化自适应（防抖）
let resizeTimer = null
const handleResize = () => {
  clearTimeout(resizeTimer)
  resizeTimer = setTimeout(() => {
    regionBarChart && regionBarChart.resize()
    typePieChart && typePieChart.resize()
  }, 100)
}

onMounted(async () => {
  await nextTick()
  regionBarChart = echarts.init(regionBarRef.value)
  typePieChart = echarts.init(typePieRef.value)
  window.addEventListener('resize', handleResize)
  loadStatistics()
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
  clearTimeout(resizeTimer)
  regionBarChart && regionBarChart.dispose()
  typePieChart && typePieChart.dispose()
})
</script>

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

.charts-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  /* 随视口高度自适应，占满剩余空间 */
  height: calc(100vh - 40px);
  min-height: 420px;
}

.chart-card {
  background: white;
  border-radius: 16px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
  overflow: hidden;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

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

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

/* 图表容器占满卡片剩余高度 */
.chart-wrapper {
  flex: 1;
  min-height: 0;
  width: 100%;
}
</style>
