import { install as installCore } from '@ibiz-template/core';
import { install as installRuntime } from '@ibiz-template/runtime';
import { install as installDefaultViewLayout } from '@ibiz-template/mob-theme';
import {
  LoadingUtil,
  MessageUtil,
  ModalUtil,
  NotificationUtil,
  OpenViewUtil,
  ConfirmUtil,
  OverlayController,
} from '@ibiz-template/mob-vue3-components';
import { OverlayContainer, PluginFactory } from '@ibiz-template/vue3-util';
import App from './App';
import { attachEnvironmentConfig } from './attach-environment-config';
import { createVueApp } from './create-vue-app';
import { AppRouter } from '@/router';
import { UnauthorizedHandler } from './util';

async function createApp(): Promise<void> {
  OverlayContainer.createVueApp = createVueApp;

  installCore();
  installRuntime();

  // 插件对象初始化放置在创建 app 之前
  ibiz.plugin = new PluginFactory();

  const app = createVueApp(App);

  // 全局 window 异常处理
  window.onerror = function (
    _event: Event | string,
    _source?: string,
    _lineno?: number,
    _colno?: number,
    error?: Error,
  ) {
    if (error) {
      ibiz.util.error.handle(error);
    }
  };

  // 全局 promise 异常处理
  window.addEventListener('unhandledrejection', function (event) {
    // 阻止继续冒泡
    event.preventDefault();
    // 获取到未处理的promise对象
    event.promise.catch(err => {
      ibiz.util.error.handle(err);
    });
  });

  await attachEnvironmentConfig();

  const router = AppRouter.getRouter();

  app.use(router);

  ibiz.openView = new OpenViewUtil(router);
  ibiz.message = new MessageUtil();
  ibiz.modal = new ModalUtil();
  ibiz.confirm = new ConfirmUtil();
  ibiz.notification = new NotificationUtil();
  ibiz.loading = new LoadingUtil();
  ibiz.overlay = new OverlayController();
  ibiz.util.error.register(new UnauthorizedHandler());
  installDefaultViewLayout((key, model) => {
    ibiz.util.layoutPanel.register(key, model);
  });
  await ibiz.i18n.init();

  app.mount('#app');
}

createApp();
