/**
 * 初始化路由权限
 */
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import Cookies from 'js-cookie'

import router from './router'
import store from './store'

// 免登陆白名单
const whiteList = [
    '/',
    // led
    '/led',
    '/led/stationOne',
    '/led/stationTwo',
    '/led/stationThree',
    '/led/stationFour',
    '/led/stationFive',
    '/led/stationSix',
    '/led/stationSeven',
    '/led/workShopPaintingWorkShop',
    '/led/stationVoc',
    // avi
    '/monitor/monitorIndex',
    '/monitor/monitorElectrophoresis',
    '/monitor/monitorSheetMetalCar',
    '/monitor/monitorSealedAnticorrosion',
    '/monitor/monitorPutty',
    '/monitor/monitorMiddleCoat',
    '/monitor/monitorComplexionPaint',
    '/monitor/monitorFinishedCar',
    // pc avi 轮播
    '/carouselAvi/index',
    // Led avi 轮播
    '/ledCarouselAvi/index'
]

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

router.beforeEach((to, from, next) => {
    NProgress.start() // start progress bar
    // token没有用户信息，代表没有登录过
    if (!window.sessionStorage.getItem('Admin-Token')) {
        // 在免登录白名单，直接进入
        if (whiteList.indexOf(to.path) !== -1) {
            next()
            NProgress.done()
        } else {
            // 否则全部重定向到登录页
            // next(`/?redirect=${to.path}`)
            // !重新登陆 重定向到首页
            next(`/`)
        }
    } else {
        // 如果store中没有路由数据，就初始化路由
        if (!store.state.Permission.initFlag) {
            // 初始化菜单路由
            store.dispatch('Permission/initRouters').then(() => {
                // 动态添加可访问路由表
                router.addRoutes(store.state.Permission.routers)
                // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
                next({
                    ...to,
                    replace: true
                })
            }).catch((error) => {
                console.error(error)
                next()
            });
        } else {
            // 如果有，直接next
            next()
        }
    }
})

router.afterEach(() => {
    NProgress.done() // finish progress bar
})
