import Vue from 'vue'
import VueRouter from 'vue-router'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css'
import store from './store'
import { pages } from './views'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'index',
    redirect: '/dashboard',
    component: () => import('@/layout/index.vue'),
    children: [
      ...pages,
    ]
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/Login.vue')
  }
]

const router = new VueRouter({ routes })

// 校验用户权限
router.beforeEach((to, from, next) => {
  NProgress.start()
  if (to.name === 'login') {
    next()
    return
  }
  store.dispatch('checkLogin').then(() => {
    if (to.name === 'login') {
      next({ name: 'index' })
    } else {
      next()
    }
  }).catch(() => {
    if (to.name === 'login') {
      next()
    } else {
      next({ name: 'login', query: { from: to.name } })
    }
  })
})

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

export default router
