import dayjs from 'dayjs';
import { createPinia } from 'pinia';
import { createApp, h, provide } from 'vue';
import 'dayjs/locale/zh-cn';
import localeData from 'dayjs/plugin/localeData';

dayjs.extend(localeData);
dayjs.locale('zh-cn');

import { createMemoryHistory, createRouter } from 'vue-router';
import pkg from '../package.json';
import App from './App.vue';
import routes from './router/moduleRoutes';
import { formatRouterUrl } from './utils';
import { createRequest } from './utils/request';

const name = pkg.name;

const getRoutes = () => routes.map((v) => ({ ...v }));

let app = null;
let router = null;
let pinia = null;

const startup = {
  routes: getRoutes(),
};

startup.bootstrap = (hostApp) => {
  pinia = createPinia();

  if (hostApp && hostApp.$store) {
    createRequest(hostApp);
  }

  if (hostApp && hostApp.$mountRoutes) {
    hostApp.$mountRoutes(name, getRoutes());
  }
};

startup.attach = (hostApp, container = '#moduleApp', payload) => {
  const HostRouter = window.Router;

  const formattedRoutes = formatRouterUrl(routes);

  router = HostRouter
    ? new HostRouter({
        history: createMemoryHistory(),
        routes: formattedRoutes,
      })
    : createRouter({
        history: createMemoryHistory(),
        routes: formattedRoutes,
      });

  pinia = createPinia();

  app = createApp({
    render() {
      return h(App);
    },
    setup() {
      provide('modulePayload', payload);
    },
  });

  app.use(router);
  app.use(pinia);

  if (hostApp && hostApp.$store) {
    createRequest(hostApp);
  }

  if (hostApp && hostApp.$mountRoutes) {
    hostApp.$mountRoutes(name, getRoutes());
  }

  app.mount(container);

  return app;
};

startup.destroy = () => {
  if (app) {
    app.unmount();
    app = null;
  }
  router = null;
  pinia = null;
};

export default startup;
export { getRoutes };
