import NProgress from 'nprogress'
import '~src/styles/app/nprogress.scss'

//路由插件
import * as vueRouter from 'vue-router'
import baseData from './modules/base'

//其它工具
import { getStore } from '~src/utils/storage'
import config from '~src/config/index'
import { isNullES } from 'js-fast-way'

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

//路由拦截
router.beforeResolve(async (to) => {
    NProgress.start()
    const token = getStore('access-token')
    if (to.path === '/login') {
        return true
    } else if (isNullES(token)) {
        return '/login'
    } else {
        return true
    }
})

router.afterEach((to) => {
    //根据当前跳转的路由设置显示在浏览器标签的title
    let pageTitle = to.meta['title'], title = config.title
    if (to.path !== '/') {
        window.document.title = pageTitle ? `${pageTitle} - ${title}` : title
    } else {
        window.document.title = title
    }
    window.scrollTo(0, 0)
    NProgress.done()
})

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

export default router
