<template>
  <div class="chart-main" ref="ref_main">
    <div class="chart-ref" ref="ref_chart" />
  </div>
</template>

<script setup lang="ts">
import {
  getCurrentInstance,
  reactive,
  ref,
  onMounted,
  watch,
  nextTick,
} from 'vue'
import * as echarts from 'echarts'

const props = defineProps({
  data: <any>{},
})

const { proxy } = getCurrentInstance()
const state = reactive({
  resizeObserver: <any>null,
  chart: <any>null,
})
const ref_chart = ref()
const ref_main = ref()
const colors = ['58, 136, 255', '96, 217, 169', '31, 182, 221', '255, 116, 44']
const initChart = () => {
  echarts.dispose(ref_chart.value)
  const chart = echarts.init(ref_chart.value)
  const padAngle = 1
  const option = {
    tooltip: {
      trigger: 'item',
    },
    series: [
      {
        type: 'pie',
        data: props.data,
        radius: ['68%', '70%'],
        padAngle: padAngle,
        itemStyle: {
          borderRadius: 10,
          color: (p) => {
            const colorRgb = colors[p.dataIndex % (colors.length - 1)]
            return `rgba(${colorRgb}, 1)`
          },
        },
        label: {
          formatter: '{b}\n{d}%',
          color: '#606266',
          fontSize: 16,
          fontFamily: 'PingFang SC',
          fontWeight: 'bold',
        },
        labelLine: {
          length2: 100,
        },
        emphasis: {
          disabled: true,
        },
      },
      {
        type: 'pie',
        data: props.data,
        radius: ['52%', '62%'],
        padAngle: padAngle,
        itemStyle: {
          borderRadius: 10,
          color: (p) => {
            const colorRgb = colors[p.dataIndex % (colors.length - 1)]
            return {
              type: 'linear',
              x: 1,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                {
                  offset: 0,
                  color: `rgba(${colorRgb}, 0.3)`, // 0% 处的颜色
                },
                {
                  offset: 1,
                  color: `rgba(${colorRgb}, 1)`, // 100% 处的颜色
                },
              ],
              global: false, // 缺省为 false
            }
          },
        },
        emphasis: {
          disabled: true,
        },
        label: {
          show: false,
        },
      },
    ],
  }
  chart.setOption(option)
  state.resizeObserver = new ResizeObserver((entries) => {
    for (const entry of entries) {
      chart && chart.resize()
    }
  })
  state.resizeObserver.observe(ref_main.value)
  return chart
}
watch(
  () => props.data,
  () => {
    state.chart = initChart()
  },
)
onMounted(() => {
  nextTick(() => {
    state.chart = initChart()
  })
  return () => {
    state.resizeObserver?.unobserve(ref_main?.value)
    state.resizeObserver?.disconnect()
  }
})
</script>

<style lang="scss" scoped>
.chart-main {
  flex: 1;
  width: 100%;
  height: 100%;
  .chart-ref {
    width: 100%;
    height: 100%;
  }
}
</style>
