import router, { constantRoutes, staticRoutes, dynamicRoutes } from './router'
import request from "@/utils/request"
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import store from './store'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login'] // no redirect whitelist

router.beforeEach(async (to, from, next) => {
    NProgress.start()
    document.title = getPageTitle(to.meta.title)
    if (store.getters.token != null) {
        if (store.getters.hasRoute == false) {
            //获取路由表
            request({
                url: "/user/getRoutesById",
                method: "post",
                params: {
                    id: store.getters.token
                }
            })
            .then(response => {
            //在这里组装动态路由
                store.commit('permission/SET_HAS_ROUTE', true)
                store.commit('permission/SET_AUTHORIZATION', true)
                next()
            })
            .catch(error => {
                console.log(error)
            })
        } else {
            if (to.path === '/login') {
                next({ path: '/' })
                NProgress.done()
            } else {
                next();
            }
        }

    } else {
        if (whiteList.indexOf(to.path) !== -1) {
            next()
        } else {
            next('/login')
            NProgress.done()
        }
    }
})

router.afterEach(() => {
    NProgress.done()
})
