<template>
  <div :style="{ width: width, height: height }" ref="pieChart"></div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, onActivated } from "vue";
import * as echarts from "echarts";

const props = defineProps({
  chartData: {
    type: Object,
    required: true,
  },
  width: {
    type: String,
    default: "100%",
  },
  height: {
    type: String,
    default: "400px",
  },
});
const pieChart = ref(null);
const myChart = ref(null);

// 图表初始化
function initChart() {
  setTimeout(() => {
    if (myChart.value === null) {
      myChart.value = echarts.init(pieChart.value);
    }
    myChart.value.setOption(getChartData());
  }, 200);
}
// 处理图表数据
function getChartData() {
  let optionData = {
    title: {
      text: props.chartData.title,
      left: "center",
    },
    tooltip: {
      trigger: "item",
      formatter: props.chartData.tooltipFormatter,
    },
    legend: {
      bottom: "5%",
      left: "center",
    },
    series: [
      {
        name: props.chartData.seriesName,
        type: "pie",
        radius: props.chartData.pieRadius,
        data: props.chartData.seriesData,
        label: {
          show: false,
          position: "center",
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: "rgba(0, 0, 0, 0.5)",
          },
        },
      },
    ],
  };
  return optionData;
}
window.addEventListener("resize", function () {
  if (myChart.value) {
    myChart.value.resize();
  }
});
watch(
  () => props.chartData,
  (val) => {
    if (val) {
      initChart();
    }
  },
  {
    immediate: true,
    deep: true,
  }
);
onMounted(() => {
  initChart();
});
onActivated(() => {
  if (myChart.value) {
    myChart.value.resize();
  }
});
onBeforeUnmount(() => {
  if (myChart.value) {
    // 销毁echarts实例
    myChart.value.dispose();
    myChart.value = null;
  }
});
</script>

<style></style>
