import router from './router'
import store from './store'
import cookie from 'js-cookie'

import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import notification from 'ant-design-vue/es/notification'

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

const whiteList = ['login'] // no redirect whitelist

router.beforeEach((to, from, next) => {
  NProgress.start() // start progress bar
  let isLogin = cookie.get('sessionid')
  if (isLogin) {
    if (to.path === '/user/login') {
      next({ name: 'dashboard' })
      NProgress.done()
    } else {
      if (store.getters.userid === '') {
        store.dispatch('GetInfo')
          .then(res => {
            const redirect = decodeURIComponent(from.query.redirect || to.path)
            next({ path: redirect })
          })
          .catch(() => {
            store.dispatch('Logout').then(() => {
              next({ path: '/user/login', query: { redirect: to.fullPath } })
            })
          })
      } else {
        next()
      }
    }
  } else {
    if (whiteList.includes(to.name)) {
      next()
    } else {
      notification.error({
        message: '错误',
        description: '登陆状态失效，请重新登陆',
        key: 'ERROR'
      })
      next({ path: '/user/login', query: { redirect: to.fullPath } })
      NProgress.done()
    }
  }
})

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