import store from '@/store'
import router from '@/router'
import { Message, MessageBox } from 'element-ui'
import cookie from '@/utils/cookie'
import NProgress from 'nprogress';//加载进度条
import 'nprogress/nprogress.css';//加载进度条
NProgress.configure({
    showSpinner: false
});
NProgress.inc(0.2);
router.beforeEach((to, from, next) => {
    //保险起见 路由跳转时检查token是否存在
    const getToken = cookie.getCookie('token')
    // 加载进度条start
    NProgress.start();
    if (getToken) {
        if (to.path === '/login') {
            next({ path: '/' })//重定向回主页
            // 加载进度条end
        } else {
            if (store.getters.userInfo.length === 0) {
                store.dispatch('GetUserInfo').then(() => {
                    store.dispatch('GenerateRoutes').then(res => {
                        router.addRoutes(res)
                        next({ ...to, replace: true })
                    })
                }).catch(err => {
                    store.dispatch('outLogin').then(() => {
                        Message.error(err)
                        next({ path: '/' })
                    })
                })
            } else {
                if (to.matched.length === 0) {
                    Message.error('未找到该页面')
                    next({ path: '/404', replace: true })
                } else {
                    store.state.navActive = to.path//导航栏状态
                    store.commit('uploadTabberLists', to)
                    next()
                }
            }
        }
    } else {
        if (to.path === '/login') {
            next()
            // 加载进度条end
        } else {
            localStorage.clear()
            store.state.tabberLists = []
            store.state.routes = []
            store.state.allRoutes = []
            next('/login')
            Message({
                type: 'info',
                message: '请重新登入'
            });
            // 加载进度条end
        }
    }
})
router.afterEach((to, from) => {
    NProgress.done();
})