<template>
  <div ref="distributionOfSeizureResultsChart" class="echarts" />
</template>

<script setup>
  import { onMounted, onUnmounted, ref } from 'vue';
  import * as echarts from 'echarts';
  import { executeSqlByKeyAndParam } from '@/api/system/sql.js';

  const chart = ref(null);
  const distributionOfSeizureResultsChart = ref(null);
  const chartOption = ref({
    color: [
      '#3C516A',
      new echarts.graphic.LinearGradient(0, 1, 0, 0, [{ offset: 0, color: '#0AE8FE' }, {
        offset: 1,
        color: '#47B3FE',
      }], false),
    ],
    series: [
      {
        type: 'pie',
        height: '60%',
        center: ['25%', '50%'],
        label: {
          show: false,
        },
        data: [],
      },
      {
        type: 'pie',
        height: '60%',
        center: ['75%', '50%'],
        label: {
          show: false,
        },
        data: [],
      },
    ],
  });

  const initChart = () => {
    chart.value = echarts.init(distributionOfSeizureResultsChart.value, 'macarons');
    chart.value.setOption(chartOption.value);
  };

  onMounted(() => {
    executeSqlByKeyAndParam('category_distribution', {}).then(res => {
      chartOption.value.series[0].data = res.data.map((el, idx) => {
        return {
          value: el.total_quantity,
          name: el.category_name,
        };
      });
      chartOption.value.series[1].data = chartOption.value.series[0].data;
      initChart();
    });

    window.addEventListener('resize', () => {
      chart.value.resize();
    });
  });

  onUnmounted(() => {
    if (!chart.value) {
      return;
    }
    chart.value.dispose();
    chart.value = null;
  });
</script>

<style scoped>
  .echarts {
    height: 100%;
    width: 100%;
  }
</style>
