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

const { getToken } = useLoginStore()

const routes: Array<RouteRecordRaw> = [
    {
        path: '/',
        redirect: () => getToken() ? '/home' : '/login', // 重定向到默认页面
    },
    {
        path: '/login',
        name: 'login',
        component: () => import('../views/sign/login/index.vue'),
        meta: {
            title: "登陆",
        },
    },
    {
        path: '/boot',
        name: 'boot',
        component: () => import('../views/boot/index.vue'),
        meta: {
            title: "初始化",
        },
    },
    {
        path: '/system',
        name: 'system',
        component: () => import('../views/system/index.vue'),
        meta: {
            title: "系统管理",
        },
        children: [
            {
                path: '',
                name: 'system_menu',
                component: () => import('../views/system/menu/index.vue'),
                meta: {
                    title: "菜单管理",
                },
            }
        ]
    },
]

const router = createRouter({
    history: createWebHashHistory(),
    routes
})

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

    // 判断服务是否加载完成
    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
