import * as echarts from "echarts";
import { Ref, watch, unref } from "vue";
import chinaMapData from "./../data/china.json";
import { tryOnUnmounted, useDebounceFn } from "@vueuse/core";

echarts.registerMap("china", chinaMapData);

export const useEchart = (
  elRef: Ref<HTMLDivElement>,
  theme: "light" | "dark" = "light"
) => {
  let echartInstance: echarts.ECharts | null = null;
  const resize = () => {
    echartInstance!.resize();
  };

  const resizeFn = useDebounceFn(resize, 200);

  //初始化
  const init = (t = theme) => {
    const el = unref(elRef);
    if (!el) return;
    echartInstance = echarts.init(el, t);

    window.addEventListener("resize", resizeFn);
  };

  const setOption = (options: echarts.EChartsOption) => {
    echartInstance?.setOption(options);
  };

  tryOnUnmounted(() => {
    window.removeEventListener("resize", resizeFn);
  });

  watch(
    elRef,
    () => {
      init();
    },
    {
      immediate: true
    }
  );

  return {
    setOption,
    updateResize: resize,
    debounceResize: resizeFn,
    echartInstance
  };
};
