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

<script setup lang="ts">
  import { ref, shallowReactive, watch } from "vue";
  import * as echarts from "echarts";


  const height = "220px";
  const width = "260px";
  const props = defineProps<{
    cdata: {
      xData: string[],
      seriesData: {
        value: number,
        name: string
      }[]
    };
  }>();

  // 定义 ref
  const chartRef = ref();

  // 配置项
  let options = shallowReactive({ color: null, tooltip: null, toolbox: null, calculable: null, legend: null, series: null });
  // echarts 实例
  let chartInstance: echarts.ECharts | null = null;
  watch(
    () => props.cdata,
    (val: any) => {
      options = {
        color: [
          "#37a2da",
          "#32c5e9",
          "#9fe6b8",
          "#ffdb5c",
          "#ff9f7f",
          "#fb7293",
          "#e7bcf3",
          "#8378ea"
        ],
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b} : {c} ({d}%)"
        },
        toolbox: {
          show: true
        },
        calculable: true,
        legend: {
          orient: "horizontal",
          icon: "circle",
          bottom: 0,
          x: "center",
          data: val.xData,
          textStyle: {
            color: "#fff"
          }
        },
        series: [
          {
            name: "通过率统计",
            type: "pie",
            radius: [10, 50],
            roseType: "area",
            center: ["50%", "40%"],
            itemStyle: {
              borderRadius: 5
            },
            label: {
              show: true,
              color: "#fff"
            },
            emphasis: {
              label: {
                show: false
              }
            },
            data: val.seriesData
          }
        ]
      };
      // // 手动触发更新
      // if (chartRef.value) {
      //   // 通过初始化参数打入数据
      //   chartRef.value.initChart(options)
      // }
      // 手动触发更新
      if (chartRef.value) {
        if (!chartInstance) {
          chartInstance = echarts.init(chartRef.value);
        }
        chartInstance.setOption(options);
      }
    },
    {
      immediate: true,
      deep: true
    }
  );
</script>
<style scoped lang="scss">

</style>