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

const { token } = loginStore.$mapGetters()

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

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 ? `推广查询系统 - ${title}` : '推广查询系统'

    // 判断服务是否加载完成
    if (service.isReady) {
        if (token.value) {
            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' || to.name === 'login') {
            next()
        } else {
            next({
                name: 'boot',
                query: { redirect: to.fullPath },
            })
        }
    }
})

export default router
