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';//加载进度条
// const TenantId = '867735392558919680'
NProgress.configure({
    showSpinner: false
});
NProgress.inc(0.2);
router.beforeEach((to, from, next) => {
    //保险起见 路由跳转时检查token是否存在
    // if (router.history.pending.query.TenantId !== undefined) {
    //     sessionStorage.TenantId = router.history.pending.query.TenantId
    // }
    // if(sessionStorage.TenantId == 'undefined'){
    //     sessionStorage.removeItem("TenantId");
    // }
    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)
                    if(!to.query.TenantId){
                            to.query.TenantId = sessionStorage.TenantId
                        next(to)
                    }else{
                        next()
                    }
                }
            }
        }
    } else {
        if (to.path === '/login') {
            // if(!to.query.TenantId){
            //     sessionStorage.TenantId = TenantId;
            //     to.query.TenantId = TenantId
            //     next(to)
            // }else{
                next()
            // }
            // 加载进度条end
        } else {
            let TenantId = 0
            if(router.history.current){
                TenantId = router.history.current.query.TenantId
            }
            localStorage.clear()
            store.state.tabberLists = []
            store.state.routes = []
            store.state.allRoutes = []
            next({path:'/login',query:{
                TenantId: TenantId
            }})
            Message({
                type: 'info',
                message: '登录已过期，请重新登录'
            });
            // 加载进度条end
        }
    }
})
router.afterEach((to, from) => {
    NProgress.done();
})
