import * as vueRouter from 'vue-router'
import baseData from './modules/base'
import { getToken } from '~src/api/auth'
import { getRouterData } from './routers'
import NProgress from 'nprogress'
import '~src/styles/app/nprogress.scss'

//设置路由数据
const router = vueRouter.createRouter({
    history: vueRouter.createWebHashHistory(),
    routes: baseData,
})

//路由拦截
router.beforeResolve(async (to) => {
    NProgress.start()
    const token = getToken(), auth = ['/login', '/auth', '/auth-token']
    if (auth.indexOf(to.path) !== -1) {
        return true
    } else if (!token) {
        return '/login'
    } else {
        const res = await getRouterData(to.name)
        if (res) {
            return true
        } else {
            return '/login'
        }
    }
})

router.afterEach((to) => {
    if (to.path !== '/') {
        window.document.title = to.meta['title']
    } else {
        window.document.title = ''
    }
    window.scrollTo(0, 0)
    NProgress.done()
})

export function setupRouter(app) {
    app.use(router)
    return router
}

export default router
