<template>
  <div class="bdlite-chart-item" :id="`chart-${id}`" ref="visualItemRef"></div>
</template>
<script>
// 图表组件库
import {
  defineComponent,
  onMounted,
  onUnmounted,
  nextTick,
  ref,
  watch,
} from "@vue/composition-api";
import { initCard, updateEchartsCom } from "@/utils/cardManager";

export default defineComponent({
  name: "EchartComp",
  emits: ["loaded", "change"],
  props: {
    chartData: {
      type: Object,
      default: () => {},
    },
    id: {
      type: String | Number,
    },
  },
  setup(props, vm) {
    const visualItemRef = ref(null);
    let resizeObserver = null;
    let instance = null;
    const renderEchartDom = async () => {
      nextTick(() => {
        instance = initCard(visualItemRef.value, props.chartData);
        // 监听图表是否渲染完成
        // watchChartRenderFinished(instance, () => vm.emit("loaded", id));
      });
    };

    const init = async () => {
      props.chartData && renderEchartDom();
    };
    const renderEchartConfig = (component) => {
      component && updateEchartsCom(instance, component);
      chartResize();
    };
    const chartResize = () => {
      setTimeout(() => {
        if (instance) {
          instance.resize({
            animation: {
              duration: 300,
              easing: "quadraticOut",
            },
          });
        } else {
          init();
        }
      }, 100);
    };
    const observerDom = () => {
      resizeObserver = new ResizeObserver(() => {
        renderEchartConfig(props.chartData);
      });
      resizeObserver.observe(visualItemRef.value);
    };
    watch(
      () => props.chartData,
      () => {
        console.log("更新 echarts");
        renderEchartConfig(props.chartData);
      },
      {
        deep: true,
      }
    );
    onMounted(() => {
      observerDom();
      init();
      vm.emit("change");
    });

    onUnmounted(() => {
      resizeObserver && resizeObserver.unobserve(visualItemRef.value);
      instance && instance.dispose();
    });
    return {
      visualItemRef,
    };
  },
});
</script>
<style lang="less">
:host .bdlite-chart-item {
  width: 100%;
  height: 100%;
}
</style>
