import Vue from 'vue'
import router from './router'
import { initSign } from './utils/index'

import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

import { getInfo } from '@/utils/auth'

NProgress.configure({
    showSpinner: false
})

export const routerCache = JSON.parse(localStorage.getItem('routerCache') || '[]')

router.beforeEach(async (to, from, next) => {
    NProgress.start()
    const ticket = getInfo()
    routerCache.push(to.name)
    if (ticket) {
        if (to.path === '/login') {
            next({ path: '/' })
        }
        else {
            if (!Vue.prototype.$signAos) {
                initSign().then(res => {
                    Vue.prototype.$signAos = res
                }).catch(_ => {})
            }
            next()
        }
    }
    else {
        if (to.path === '/login') {
            next()
        }
        else {
            next({ path: '/login' })
        }
    }
})

export function returnRouter(router, name) {
    const index = routerCache.lastIndexOf('reportList')
    const len = routerCache.length
    const goLen = len - index - 1
    routerCache.length = len - goLen
    localStorage.setItem('routerCache', JSON.stringify(routerCache))
    router.go(goLen);
}

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