/* eslint-disable import/prefer-default-export */
import {
  reactive,
  getCurrentInstance,
  nextTick,
  inject,
  watch,
  onBeforeMount,
} from 'vue'; // expose public api

export function useExpose(apis) {
  const instance = getCurrentInstance();

  if (instance) {
    Object.assign(instance.proxy, apis);
  }
}
/**
 * @description: timeout定时器
 * @param {Function} fn 回调方法
 * @param {Number} time 执行间隔
 * @param {Object} options 配置项
 * @param {Boolean} options.manual 是否手动执行，默认false
 * @return {Function} 返回可终止定时器方法
 */
export const useTimeout = (fn, time, options = { manual: false }) => {
  let timer = null;
  const run = (...args) => {
    timer = setTimeout(() => fn.call(null, ...args), time);
  };
  if (!options.manual) run();
  const stop = () => clearTimeout(timer);
  onBeforeMount(stop);
  return {
    run,
    stop,
  };
};

export function usePopupState() {
  const state = reactive({
    show: false,
  });

  const toggle = (show) => {
    state.show = show;
  };

  const open = (props) => {
    Object.assign(state, props);
    nextTick(() => toggle(true));
  };

  const close = () => toggle(false);

  useExpose({
    open,
    close,
    toggle,
  });
  return {
    open,
    close,
    state,
    toggle,
  };
}

export function useDicts(type, callback) {
  console.log('useDicts', type);
  const $store = inject('store');
  const { dicts } = $store.state.app;
  if (!dicts[type]?.length && !dicts[`${type}Loading`]) {
    $store.dispatch('app/getDict', [type]);
  }

  watch(dicts, () => {
    if (callback && dicts[type]) {
      callback(dicts[type]);
    }
  });
}
