import { useTimeoutFn } from './useTimeout.js';
import { tryOnUnmounted } from '@vueuse/core';
import { unref, nextTick, watch, computed, ref } from 'vue';
import { useDebounceFn } from '@vueuse/core';
import { useEventListener } from './useEventListener.js';
import echarts from './echarts.js';
export function useECharts(elRef, theme = 'default') {
  const getDarkMode = computed(() => {
    return 'light'
  });
  let chartInstance = null;
  let resizeFn = resize;
  const cacheOptions = ref({});
  let removeResizeFn = () => { };
  resizeFn = useDebounceFn(resize, 200);
  const getOptions = computed(() => {
    if (getDarkMode.value !== 'dark') {
      return cacheOptions.value;
    }
    return Object.assign({ backgroundColor: 'transparent' }, cacheOptions.value);
  });
  function initCharts(t = theme) {
    const el = unref(elRef);
    if (!el || !unref(el)) {
      return;
    }
    chartInstance = echarts.init(el, t);
    const { removeEvent } = useEventListener({
      el: window,
      name: 'resize',
      listener: resizeFn,
    });
    removeResizeFn = removeEvent;
    // useTimeoutFn(() => {
    //   resizeFn();
    // }, 30);
  }
  function setOptions(options, clear = true) {
    var _a;
    cacheOptions.value = options;
    if (((_a = unref(elRef)) === null || _a === void 0 ? void 0 : _a.offsetHeight) === 0) {
      useTimeoutFn(() => {
        setOptions(unref(getOptions));
      }, 30);
      return;
    }
    nextTick(() => {
      useTimeoutFn(() => {
        if (!chartInstance) {
          initCharts(getDarkMode.value);
          if (!chartInstance)
            return;
        }
        clear && (chartInstance === null || chartInstance === void 0 ? void 0 : chartInstance.clear());
        chartInstance === null || chartInstance === void 0 ? void 0 : chartInstance.setOption(unref(getOptions));
      }, 30);
    });
  }
  function resize() {
    chartInstance === null || chartInstance === void 0 ? void 0 : chartInstance.resize({
      animation: {
        duration: 300,
        easing: 'quadraticIn',
      },
    });
  }
  watch(() => getDarkMode.value, (theme) => {
    if (chartInstance) {
      chartInstance.dispose();
      initCharts(theme);
      setOptions(cacheOptions.value);
    }
  });
  tryOnUnmounted(() => {
    if (!chartInstance)
      return;
    removeResizeFn();
    chartInstance.dispose();
    chartInstance = null;
  });
  function getInstance() {
    if (!chartInstance) {
      initCharts(getDarkMode.value);
    }
    return chartInstance;
  }
  return {
    setOptions,
    resize,
    echarts,
    getInstance,
  };
}
