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 {
            console.log(to);
            if (to.matched.length === 0) {
                console.log(from.name);
                // router.push(to.path)
                next('/404') // 判断此跳转路由的来源路由是否存在，存在的情况跳转到来源路由，否则跳转到404页面
            } else {
            if (store.getters.addRouters.length === 0) {
                store.dispatch('GetUserInfo').then(() => {
                    store.dispatch('GenerateRoutes').then((res) => {
                        if (res) {
                            next({ ...to, replace: true })
                            // store.state.navActive = to.path//导航栏状态
                        } else {
                            next()
                            // store.state.navActive = '/home'//导航栏状态
                        }
                    })
                }).catch(errors => {
                    Message.error('用户信息储存报错')
                })
                
            } else {
                next()
                // store.state.navActive = to.path//导航栏状态
                // 加载进度条end
            }
            store.state.navActive = to.path//导航栏状态
            store.commit('uploadTabberLists', to)
            }
        }
    } 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();
})