import '@ibiz-template/theme/style/index.scss';
import Vue from 'vue';
import Router from 'vue-router';
import { PiniaVuePlugin } from 'pinia';
import router from './router';
import App from './App';
import { AppRegister } from './app-register';
import UserRegister from './user-register';
import {
  MessageUtil,
  OpenViewUtil,
  ModalUtil,
  NotificationUtil,
  LoadingUtil,
  ErrorHandler,
  OverlayController,
} from './util';
import { piniaInstance } from './store';
import { attachEnvironmentConfig } from './attach-environment-config';
import { PluginFactory } from './plugin';

Vue.use(Router);
Vue.use(PiniaVuePlugin);
Vue.use(AppRegister);

/** 异常处理：start */
Vue.config.errorHandler = function (err: Error, _vm) {
  ErrorHandler.handlerError(err);
};

window.onerror = function (
  event: Event | string,
  source?: string,
  lineno?: number,
  colno?: number,
  error?: Error,
) {
  if (error) {
    ErrorHandler.handlerError(error);
  }
};

window.addEventListener('unhandledrejection', function (event) {
  // 阻止继续冒泡
  event.preventDefault();
  // 获取到未处理的promise对象
  event.promise.catch(err => {
    ErrorHandler.handlerError(err);
  });
});
/** 异常处理：end */

async function createApp(): Promise<void> {
  await attachEnvironmentConfig();

  const app = new Vue({
    created() {
      ibiz.openView = new OpenViewUtil();
      ibiz.message = new MessageUtil();
      ibiz.modal = new ModalUtil();
      ibiz.notification = new NotificationUtil();
      ibiz.loading = new LoadingUtil();
      ibiz.overlay = new OverlayController();
      ibiz.plugin = new PluginFactory();
      Vue.use(UserRegister);
    },
    router,
    pinia: piniaInstance,
    render: h => h(App),
  });

  app.$mount('#app');
}

createApp();
