<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' }),
    legend: createLegend(
      { bottom: 10, itemWidth: 12, itemHeight: 12 },
      data.map((item) => item.name)
    ),
    series: [
      {
        name: '设备状态',
        type: 'pie',
        center: ['50%', '44%'],
        radius: ['50%', '70%'],
        minAngle: 5,
        label: {
          show: false,
          position: 'center',
          formatter(params: any) {
            return `{name|${params.name}}\n{value|${params.value}}`
          },
          rich: {
            name: {
              color: THEME.text.regular,
              fontSize: 14,
              fontWeight: 500,
              lineHeight: 24,
              fontFamily: FONT_FAMILY
            },
            value: {
              color: THEME.text.strong,
              fontSize: 28,
              fontWeight: 700,
              lineHeight: 36,
              fontFamily: FONT_FAMILY
            }
          }
        },
        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('ry')
    chartData.value = Array.isArray(res) ? res : []
    renderChart()
  } catch (error) {
    console.error('获取设备状态失败:', error)
    chartData.value = []
    renderChart()
  }
}

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

onUnmounted(() => {
  window.removeEventListener('resize', resizeChart)
  window.removeEventListener('rykb: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>
