<template>
  <div id="device-overview-container" style="height: 228px"></div>
</template>

<script setup>
import { computed, onMounted, ref, watchEffect } from 'vue';
import { useStore } from 'vuex';
import { Pie } from '@antv/g2plot';
import isEmpty from 'lodash/isEmpty';
import { generateChartData } from 'utils/overview';

const store = useStore();
const count = computed(() => store.state.device.count);
const isMounted = ref(false);
let piePlot = null;

watchEffect(() => {
  if (isEmpty(count.value) || !isMounted.value) return;
  if (!piePlot) {
    render(count.value);
  } else {
    // TODO: 更新图表数据
    piePlot.destroy();
    render(count.value);
  }
});

function render(rawCount) {
  const data = generateChartData(rawCount);
  piePlot = new Pie('device-overview-container', {
    legend: false,
    appendPadding: 10,
    data,
    angleField: 'value',
    colorField: 'type',
    radius: 1,
    innerRadius: 0.64,
    label: {
      type: 'inner',
      offset: '-50%',
      autoRotate: false,
      style: { textAlign: 'center' },
    },
    statistic: {
      title: {
        offsetY: -12,
        content: '设备总数',
      },
      content: { offsetY: 0 },
    },
    // 添加 中心统计文本 交互
    interactions: [
      { type: 'element-selected' },
      { type: 'element-active' },
      {
        type: 'pie-statistic-active',
        cfg: {
          start: [
            {
              trigger: 'element:mouseenter',
              action: 'pie-statistic:change',
            },
            {
              trigger: 'legend-item:mouseenter',
              action: 'pie-statistic:change',
            },
          ],
          end: [
            {
              trigger: 'element:mouseleave',
              action: 'pie-statistic:reset',
            },
            {
              trigger: 'legend-item:mouseleave',
              action: 'pie-statistic:reset',
            },
          ],
        },
      },
    ],
  });
  piePlot.render();
}

onMounted(() => {
  isMounted.value = true;
});
</script>
