<script setup lang="ts">
import { $font_color } from '@/styles/variate'
import * as echarts from 'echarts'

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

const widthRate = window.screen.width / 1920

const chartContainer = ref<HTMLDivElement | null>(null)

let myChart = reactive<anyObj>({})

const option = reactive<anyObj>({
  title: {
    text: '',
    textStyle: {
      color: $font_color,
      fontSize: widthRate * 28,
      fontWeight: 'normal',
    },
    top: 0,
    left: 'center',
  },
  legend: {
    bottom: 0,
    left: 'center',
    icon: 'circle',
    itemWidth: widthRate * 8,
    textStyle: {
      fontSize: widthRate * 20,
      color: '#666',
    },
    data: [],
  },

  series: {
    type: 'pie',
    radius: ['30%', '70%'],
    avoidLabelOverlap: false,
    legendHoverLink: false,
    emphasis: {
      label: {
        show: false,
      },
    },
    label: {
      position: 'outer',
      alignTo: 'labelLine',
      formatter: (params: anyObj) => Math.round(params.percent) + '%',
      color: 'inherit',
      fontSize: widthRate * 22,
      distanceToLabelLine: widthRate * -50,
    },
    labelLine: {
      length: widthRate * 22,
      length2: widthRate * 75,
      maxSurfaceAngle: 80,
    },
    labelLayout: {
      verticalAlign: 'bottom',
    },
    data: [],
    // width: '85%',
    // height: '85%',
    left: 'center',
    top: 'center',
  },
})

async function drawGraph() {
  await nextTick()
  if (myChart) {
    myChart.dispose?.() // 清除上一次已经画过得图，这样才能实时才到最新数据的图
    myChart = echarts.init(chartContainer.value)
  }
  option.series.data = props.data
  option.legend.data = props.data
  option.title.text = props.title
  myChart.setOption(option)
  myChart.resize()
}

onMounted(() => {
  drawGraph()
})
</script>
<template>
  <div ref="chartContainer" class="echarts-pie"></div>
</template>
<style scoped lang="scss">
.echarts-pie {
  width: 100%;
  height: 100%;
}
</style>
