import { createWebHashHistory, RouteRecordRaw } from 'vue-router'
import { useLoginStore } from '@/stores'
import dynamicRouter from './dynamicRouter'
import historyRouter from './historyRouter'
import service from '@/services'

const { getToken } = useLoginStore()

const routes: Array<RouteRecordRaw> = [
    {
        path: '/',
        redirect: () => getToken() ? '/home/main' : '/login', // 重定向到默认页面
    },
    {
        path: '/login',
        name: 'login',
        component: () => import('../views/user/login/index.vue'),
        meta: {
            title: "登陆",
        },
    },
    {
        path: '/boot',
        name: 'boot',
        component: () => import('../views/boot/index.vue'),
        meta: {
            title: "初始化",
        },
    },
]

const router = historyRouter.create({
    history: createWebHashHistory(),
    routes
})

// 路由跳转拦截
router.beforeEach((to, from, next) => {
    const isLoginOrRegister = to.name === 'login' || to.name === 'register';
    const title = to.meta.title;
    document.title = title ? `MTP - ${title}` : 'MTP';

    // 判断服务是否加载完成
    if (service.isReady) {
        if (getToken()) {
            if (dynamicRouter.isReady) {
                if (isLoginOrRegister) {
                    next('/');
                } else {
                    next();
                }
            } else {
                // 注册动态路由
                dynamicRouter.registerRoutes();
                next({ ...to, replace: true });
            }
        } else {
            dynamicRouter.isReady = false;
            if (isLoginOrRegister) {
                next();
            } else {
                next({
                    name: 'login',
                    query: { redirect: to.fullPath },
                });
            }
        }
    } else {
        if (to.name === 'boot') {
            next();
        } else {
            next({
                name: 'boot',
                query: { redirect: to.fullPath },
            });
        }
    }
})

export default router
