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

<script setup>
import * as echarts from 'echarts'
import { inject } from 'vue'
const { proxy } = getCurrentInstance()
const data = inject('groupByKey')
let chart = null
const props = defineProps({
  className: {
    type: String,
    default: 'chart',
  },
  width: {
    type: String,
    default: '100%',
  },
  height: {
    type: String,
    default: '300px',
  },
})

function initChart() {
  chart = echarts.init(proxy.$refs.chartRef)

  chart.setOption({
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b} : {c} ({d}%)',
    },
    legend: {
      left: 'center',
      bottom: '1%',
      data: ['关键件', '非关键件'],
    },
    series: [
      {
        name: '关键件占比',
        type: 'pie',
        radius: ['10%', '70%'],
        itemStyle: {
          borderRadius: 7,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          formatter: '{b} : {c} ({d}%)'
        },
        data: [
          { value: data.key, name: '关键件' },
          { value: data.unkey, name: '非关键件' },
        ],
        animationEasing: 'cubicInOut',
        animationDuration: 2000,
      },
    ],
  })
}
function setOptions(data) {
  chart.setOption({
    series: [
      {
        data: [
          { value: data.key, name: '关键件' },
          { value: data.unkey, name: '非关键件' },
        ],
        animationEasing: 'cubicInOut',
        animationDuration: 2000,
      },
    ],
  })
}
onMounted(() => {
  initChart()
})
window.onresize = function () {
  chart.resize()
}
watch(data, (newData, oldData) => {
  setOptions(newData)
}
)
</script>
