import {
  ref,
  shallowRef,
  unref,
  onMounted,
  onDeactivated,
  onBeforeUnmount,
  Ref,
} from "vue";
import * as echarts from "echarts";
import type { EChartsOption } from "echarts";

const useCharts = (elRef: Ref<HTMLElement | null>, options: EChartsOption) => {
  const charts = shallowRef<echarts.ECharts>();

  const setOptions = (options: EChartsOption) => {
    charts.value && charts.value.setOption(options);
  };

  // 初始化
  const initCharts = (themeColor?: string[]) => {
    const el = unref(elRef);
    if (!el || !unref(el)) {
      return;
    }
    charts.value = echarts.init(el);
    if (themeColor) {
      options.color = themeColor;
    }
    setOptions(options);
  };

  // 重置大小, 重新计算
  const resize = () => {
    charts.value && charts.value.resize();
  };

  onMounted(() => {
    window.addEventListener("resize", resize);
  });

  // 页面卸载时，移除事件
  onDeactivated(() => {
    console.log("component deactivated");
    window.removeEventListener("resize", resize);
  });

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

  return {
    initCharts,
    setOptions,
    resize,
  };
};

export default useCharts;
