<template>
  <div ref="main" style="width: 100%;height: 100%;"></div>
</template>

<script setup>
import * as echarts from 'echarts';
import { onMounted, ref, onUnmounted, defineProps, reactive, watch } from "vue";
const main = ref();
const myChart = ref();
const pageData = reactive({
  list: []
})
const props = defineProps({
  data: Array,
  key: Number,
  text: {
    type: String,
    default: ''
  },
  itemGap: {
    type: Number,
    default: 30
  }
})
watch(
  () => props.data,
  (val) => {
    if (val) {
      getData();
    }
  }, { deep: true }
)

// 初始化
onMounted(() => {
  getData();
});
const getData = () => {
  for (let i = 0; i < props.data.length; i++) {
    const item = props.data[i]
    pageData.list.push({
      ...item,
      itemStyle: {
        color: item.color
      }
    })
  }
  myChart.value = echarts.init(main.value);
  myChart.value.setOption(setOptions());
  // 监听窗口变化 - 多个图表同时刷新
  window.addEventListener("resize", () => {
    myChart.value.resize();
  });
}
onUnmounted(() => { });
const setOptions = () => {
  return {
    tooltip: {
      trigger: 'item'
    },
    graphic: {
      type: 'text',
      left: '57%',
      top: '40%',
      style: {
        text:
          String(
            props.text
          ).replace(/(\d)(?=(?:\d{6})+$)/g, '$1.'),
        textAlign: 'center',
        fill: '#333',
        width: 30,
        height: 30,
        fontSize: 14
      }
    },

    legend: {
      type: 'scroll',
      orient: 'vertical',
      left: 10,
      top: 20,
      bottom: 20,
      itemGap: props.itemGap,
      itemWidth: 14,
      itemHeight: 14,
      icon: "square",
      textStyle: {
        fontSize: 16
      },
      // 使用formatter自定义图例文本
      formatter: function (name) {
        var data = pageData.list;
        var total = data.reduce(function (sum, item) {
          return sum + item.value;
        }, 0);
        var target = data.find(function (item) {
          return item.name === name;
        });
        return `${name}        ${target.value}`;
      }
    },

    series: [
      {
        type: 'pie',
        radius: ['50%', '70%'],
        center: ["60%", "45%"],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: false,
          }
        },
        labelLine: {
          show: false
        },
        data: pageData.list
      }
    ]
  };
}
</script>

<style lang="scss" scoped>
::v-deep canvas {
  width: 100% !important;
  height: 100% !important;
}
</style>
