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

<script setup>
import { computed, onMounted, ref, watchEffect } from 'vue';
import { useStore } from 'vuex';
import isEmpty from 'lodash/isEmpty';
import { generateChartOption } from 'utils/overview';
import * as echarts from 'echarts/core';
import { TitleComponent, TooltipComponent } from 'echarts/components';
import { PieChart } from 'echarts/charts';
import { LabelLayout } from 'echarts/features';
import { CanvasRenderer } from 'echarts/renderers';

echarts.use([TitleComponent, TooltipComponent, PieChart, CanvasRenderer, LabelLayout]);

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

watchEffect(() => {
  if (isEmpty(count.value) || !isMounted.value) return;
  if (!myChart) {
    initChart();
    render(count.value);
  } else {
    render(count.value);
  }
});

// 初始化chart
function initChart() {
  const chartDom = document.getElementById('device-overview-container');
  myChart = echarts.init(chartDom);
}

// 渲染chart
function render(rawCount) {
  const option = generateChartOption(rawCount);
  option && myChart.setOption(option);
}

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