import {
  computed,
  getCurrentInstance,
  onActivated,
  onBeforeUnmount,
  onDeactivated,
  onMounted,
} from 'vue';
import bus from '@/utils/bus';
import { getInfo, ICP_CONFIG } from '@/utils/commMethods';
/**
 * 注册某模块文件夹下的组件为全局组件
 * @param modules 引入当前文件夹下的vue文件  app: 一般在main.ts引用是需要传入
 */
export const registerComponents = (modules: any, app?: any) => {
  const appContext = app ? app : getCurrentInstance()?.appContext?.app;
  for (const path in modules) {
    modules[path]().then(file => {
      const name = file.default?.name;
      appContext.component(name, file.default);
    });
  }
};

export const handleCommonInstance = (buttonClick: any) => {
  const commonParams = computed(() => {
    return getInfo(ICP_CONFIG);
  });
  const busFlag = commonParams.value.keepalive;
  onMounted(() => {
    if (!busFlag) {
      bus.on('getInstance', buttonClick);
    }
  });
  onActivated(() => {
    bus.on('getInstance', buttonClick);
  });
  onDeactivated(() => {
    bus.off('getInstance');
  });
  onBeforeUnmount(() => {
    bus.off('getInstance');
  });
};
