<!-- 饼图 -->
<template>
  <el-card>
    <div :id="id" :class="className" :style="{ height, width }"></div>
  </el-card>
</template>

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

const props = defineProps({
  id: {
    type: String,
    default: "pieChart",
  },
  className: {
    type: String,
    default: "",
  },
  width: {
    type: String,
    default: "200px",
    required: true,
  },
  height: {
    type: String,
    default: "200px",
    required: true,
  },
  list: {
    type: Array,
    default: [],
    required: true
  }
});
const options = {
  title : {
    text: '订单准时完成率',
    x:'center'
  },
  tooltip : {
    trigger: 'item',
    formatter: "{b} : {c} ({d}%)"
  },
  legend: {
    orient : 'vertical',
    x : 'left',
    data:['直接访问','邮件营销','联盟广告','视频广告','搜索引擎']
  },
  calculable : true,
  series : [
    {
      name:'访问来源',
      type:'pie',
      radius : '75%',
      center: ['50%', '50%'],
      data:[
        { name:'直接访问',value:70},
        {value:30, name:'邮件营销'},
      ]
    }
  ]
};

const chart = ref<any>("");
watch?.(
    () => props.list,
    (newVal) => {
      options.series[0].data = props.list
      options.legend.data = []
      props.list.forEach(item=>{
        options.legend.data.push(item.name)
      })
      handle()
    }
);

const handle=()=>{
  chart.value = markRaw(
      echarts.init(document.getElementById(props.id) as HTMLDivElement)
  );

  chart.value.setOption(options);

  window.addEventListener("resize", () => {
    chart.value.resize();
  });
}
onMounted(() => {
 handle();
});

onActivated(() => {
  if (chart.value) {
    chart.value.resize();
  }
});
</script>
