import { unref, nextTick, watch, computed, ref } from 'vue';
import { useDebounceFn, tryOnUnmounted } from '@vueuse/core';
import { useTimeoutFn } from './useTimeout';
import { useEventListener } from './useEventListener';
import { useBreakpoint } from './useBreakpoint';
import echarts from '../utils/echarts';

export const useEcharts = (elRef, theme = 'default') => {
  const getDarkMode = computed(() => {
    return theme === 'default' ? 'dark' : theme;
  });
  let chartInstance = null;
  let resizeFn = resize;
  const cacheOptions = ref({});
  let removeResizeFn = null;

  resizeFn = useDebounceFn(resize, 200);

  const getOptions = computed(() => {
    if (getDarkMode.value !== 'dark') {
      return cacheOptions.value;
    }
    return {
      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;
    const { widthRef } = useBreakpoint();
    if (unref(widthRef) <= 768 || el.offsetHeight === 0) {
      useTimeoutFn(() => {
        resizeFn();
      }, 30);
    }
  }

  function setOptions(options = {}, clear = true) {
    cacheOptions.value = options;
    if (unref(elRef)?.offsetHeight === 0) {
      useTimeoutFn(() => {
        setOptions(unref(getOptions));
      }, 30);
      return;
    }
    nextTick(() => {
      useTimeoutFn(() => {
        if (!chartInstance) {
          initCharts(getDarkMode.value ?? 'default');

          if (!chartInstance) return;
        }
        clear && chartInstance?.clear();

        chartInstance?.setOption(unref(getOptions));
      }, 30);
    });
  }

  function resize() {
    chartInstance?.resize();
  }

  /**
   * 注册地图数据
   * @param {string} mapName - 地图名称
   * @param {object} geoJSON - GeoJSON 数据
   */
  function registerMap(mapName, geoJSON) {
    if (!mapName || !geoJSON) {
      console.warn('地图名称或 GeoJSON 数据无效');
      return;
    }
    echarts.registerMap(mapName, geoJSON);
  }

  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 ?? 'default');
    }
    return chartInstance;
  }

  return {
    setOptions,
    resize,
    echarts,
    getInstance,
    registerMap,
  };
};
