import router from '@/router';
import pinia, { useFlowStore } from '@/stores';

const components = import.meta.glob('@/pages/**/*.vue');

export default function launchLoader(container = '#app'): DEV.Loader {
  return async function (app, config) {

    let currentRoute = router.currentRoute.value.fullPath;
    if (currentRoute === '/') currentRoute = '/screen';

    if (config.image.com) {
      const component = components[`/src/pages/${config.image.com}.vue`];
      if (!component) throw { message: `配置 ${config.image.com} 组件未找到` };
      const path = '/screen';
      router.addRoute({
        name: 'screen',
        path,
        component,
        meta: { scan: true },
      });
      if (currentRoute === path) await router.replace(path);
    }

    if (config.image.page && config.image.page !== currentRoute) await router.replace(config.image.page);
    useFlowStore().$init(config.flowConfig)

    app.mount(container);
  };
}
