<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',
  },
  Label1: {
    type: String,
    default: 'Label1',
  },
  Label2: {
    type: String,
    default: 'Label2',
  },
  Data: {
    type: Object,
    required: true,
  },
  Title: {
    type: String,
    default: 'Title',
  },
})

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

  chart.setOption({
    title: {
      text: props.Title,
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b} : {c} ({d}%)',
    },
    legend: {
      left: 'center',
      bottom: '2%',
      // orient: 'vertical',
      // data: [props.Label1, props.Label2],
    },
    series: [
      {
        name: props.Title,
        type: 'pie',
        radius: ['5%', '50%'],
        itemStyle: {
          borderRadius: 5,
          borderColor: '#fff',
          borderWidth: 1
        },
        label: {
          formatter: '{b} : {c} ({d}%)'
        },
        data: [
          { value: props.Data.d0, name: props.Label1 },
          { value: props.Data.d1, name: props.Label2 },
        ],
        animationEasing: 'cubicInOut',
        animationDuration: 2000,
      },
    ],
  })
}
function setOptions(data) {
  chart.setOption({
    series: [
      {
        data: [
          { value: data.d0, name: props.Label1 },
          { value: data.d1, name: props.Label2 },
        ],
        animationEasing: 'cubicInOut',
        animationDuration: 2000,
      },
    ],
  })
}
onMounted(() => {
  initChart()
})
window.onresize = function () {
  chart.resize()
}
watch(props.Data, (newData, oldData) => {
  setOptions(newData)
}
)
</script>
