<script lang="ts" setup>
import * as echarts from 'echarts'
import { ANIMATION, ChartItem, createLegend, createTooltip, FONT_FAMILY, THEME } from '@/utils/kb'
import { IotStatApi } from '@/api/pms/stat'

const chartData = ref<ChartItem[]>([])

const chartRef = ref<HTMLDivElement>()
let chart: echarts.ECharts | null = null

function getChartOption(data: ChartItem[]): echarts.EChartsOption {
  return {
    ...ANIMATION,
    grid: THEME.grid,
    tooltip: createTooltip({
      trigger: 'item',
      formatter(params: any) {
        return `
          <div style="font-weight: 600; margin-bottom: 6px;">${params.seriesName}</div>
          <div style="display: flex; align-items: center; gap: 8px;">
            <span style="display: inline-block; width: 8px; height: 8px; border-radius: 50%; background: ${params.color};"></span>
            <span>${params.name}</span>
            <span style="font-weight: 700; color: ${THEME.text.strong};">${params.value}</span>
            <span style="color: ${THEME.text.strong};">${Number(params.percent ?? 0).toFixed(0)}%</span>
          </div>
        `
      }
    }),
    legend: createLegend(
      { bottom: 4, itemWidth: 8, itemHeight: 8 },
      data.map((item) => item.name)
    ),
    series: [
      {
        name: '设备状态',
        type: 'pie',
        center: ['50%', '45%'],
        radius: ['44%', '63%'],
        minAngle: 5,
        label: {
          show: true,
          position: 'outside',
          alignTo: 'edge',
          edgeDistance: 12,
          distanceToLabelLine: 5,
          formatter(params: any) {
            return `{name|${params.name}} {percent|${Number(params.percent ?? 0).toFixed(0)}%}`
          },
          rich: {
            name: {
              color: THEME.text.primary,
              fontSize: 11,
              fontWeight: 500,
              lineHeight: 16,
              fontFamily: FONT_FAMILY
            },
            percent: {
              color: THEME.text.strong,
              fontSize: 12,
              fontWeight: 700,
              lineHeight: 16,
              fontFamily: FONT_FAMILY
            }
          }
        },
        labelLine: {
          show: true,
          length: 10,
          length2: 6,
          smooth: 0.15,
          lineStyle: {
            width: 1
          }
        },
        labelLayout: {
          hideOverlap: true
        },
        emphasis: {
          label: {
            show: true
          },
          itemStyle: {
            shadowBlur: 14,
            shadowColor: THEME.color.blue.shadow
          }
        },
        data
      }
    ]
  }
}

function initChart() {
  if (!chartRef.value) return
  if (chart) {
    chart.dispose()
  }
  chart = echarts.init(chartRef.value, undefined, {
    renderer: 'svg'
  })
  renderChart()
}

function renderChart() {
  if (!chart) return

  const data = chartData.value || []

  chart.setOption(getChartOption(data), true)
}

function resizeChart() {
  chart?.resize()
}

function destroyChart() {
  if (chart) {
    chart.dispose()
    chart = null
  }
}

async function loadChart() {
  try {
    const res = await IotStatApi.getDeviceStatusCount('rh')
    chartData.value = Array.isArray(res) ? res : []
    renderChart()
  } catch (error) {
    console.error('获取设备状态失败:', error)
    chartData.value = []
    renderChart()
  }
}

onMounted(() => {
  initChart()
  loadChart()
  window.addEventListener('resize', resizeChart)
  window.addEventListener('rhkb:resize', resizeChart)
})

onUnmounted(() => {
  window.removeEventListener('resize', resizeChart)
  window.removeEventListener('rhkb:resize', resizeChart)
  destroyChart()
})
</script>

<template>
  <div class="panel flex flex-col">
    <div class="panel-title">
      <div class="icon-decorator">
        <span></span>
        <span></span>
      </div>
      设备状态统计
    </div>
    <div ref="chartRef" class="flex-1 min-h-0"></div>
  </div>
</template>

<style lang="scss" scoped>
@import url('@/styles/kb.scss');
</style>
