<template>
  <v-chart class="chart" :option="option" :autoresize="autoresize" />
</template>

<script setup lang="ts">
import VChart from 'vue-echarts'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { PieChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GraphicComponent,
} from 'echarts/components'
import type { EChartsOption } from 'echarts'
import { useTheme } from '@/utils/useTheme'
use([
  CanvasRenderer,
  PieChart,
  TitleComponent,
  TooltipComponent,
  GraphicComponent,
  LegendComponent,
])

interface Props {
  data: any[]
}
const { chartGraphicTextColor } = useTheme()

const props = withDefaults(defineProps<Props>(), {
  data: () => [],
})

const updateTrigger = ref(0)
const autoresize = {
  throttle: 2500,
  onResize: () => {
    updateTrigger.value++
  },
}

// 数据总数
const total = computed(() => props.data.reduce((acc, cur) => acc + cur.value, 0))

const option = computed(() => {
  const trigger = updateTrigger.value
  const res: EChartsOption = {
    tooltip: {
      show: false,
    },
    graphic: {
      elements: [
        {
          type: 'text',
          left: 'center',
          top: '30%',
          style: {
            text: total.value.toString(),
            fill: chartGraphicTextColor.value,
            fontSize: 20,
            fontWeight: 700,
          },
        },
        {
          type: 'text',
          left: 'center',
          top: '42%',
          style: {
            text: '设备总数',
            fill: chartGraphicTextColor.value,
            fontSize: 16,
          },
        },
      ],
    },
    legend: {
      show: true,
      bottom: '3%',
      itemWidth: 20,
      itemHeight: 15,
      itemGap: 10,
      textStyle: {
        fontSize: 16,
      },
      selectedMode: false,
    },
    color: ['#4CAF50', '#2196F3', '#FBB852', '#FF9800', '#F44336', '#ccc'],
    series: [
      {
        type: 'pie',
        radius: ['40%', '55%'],
        center: ['50%', '40%'],
        data: props.data,
        avoidLabelOverlap: false,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 1,
            shadowColor: 'rgba(0, 0, 0, 0.5)',
          },
        },
        label: {
          show: true,
          position: 'outside',
          // formatter: '{b}: {c} ({d}%)',
          formatter: ' {c}',
        },
        labelLine: {
          show: true,
        },
      },
    ],
  }
  return res
})
</script>

<style scoped lang="scss">
.chart {
  width: 100%;
  height: 100%;
}
</style>
