import Vue from 'vue'
import Router from 'vue-router'
import routes from './routers'
import store from '@/store'
import iView from 'iview'
import { getToken, canTurnTo, setTitle } from '@/libs/util'
import config from '@/config'
import { asynRouters_copy } from '@/router/aysnRouters.js'
const { homeName } = config

const baseUrl = process.env.NODE_ENV === 'production' ? '/admin/' : '/'

Vue.use(Router)
const router = new Router({
  routes,
  base: baseUrl,
  mode: 'history'
})
const LOGIN_PAGE_NAME = 'login'
// const REGISTER_PAGE_NAME = 'register'

// 判断是否为动态路由的页面
const IsAsynPath = (path) => {
  return canTurnTo(path, asynRouters_copy)
}

const turnTo = (to, next, access) => {
  if (canTurnTo(to.path, access)) {
    next() // 有权限，可访问
  } else if (IsAsynPath(to.path)) {
    next({ replace: true, name: 'error_401' }) // 地址正确但无权限，重定向到401页面
  } else {
    next({ replace: true, name: 'error_404' }) // 错误地址，重定向到404页面
  }
}

router.beforeEach((to, from, next) => {
  // console.log('hi', to)
  iView.LoadingBar.start()
  const token = getToken()

  if (!token && to.name !== LOGIN_PAGE_NAME) {
    // 未登录且要跳转的页面不是登录页
    next({
      name: LOGIN_PAGE_NAME // 跳转到登录页
    })
  } else if (!token && to.name === LOGIN_PAGE_NAME) {
    // 未登陆且要跳转的页面是登录页
    next() // 跳转
  } else if (token) {
    // 判断是否获得路由权限
    if (!store.state.app.gotPermission) {
      // console.log('1', to.path)
      store.dispatch('getPermission').then(() => {
        const newRoutes = routes.concat(store.state.user.permission)
        store.commit('setMenuList', newRoutes)
        // 通过刷新或者输入地址访问页面时，直接next()无法根据router访问， 需重新通过vueRouter跳转
        next({ name: homeName })
        setTimeout(() => {
          next({
            path: to.path,
            query: to.query
          })
        }, 0)
      })
    } else if (store.state.app.gotPermission) {
      if (to.name === LOGIN_PAGE_NAME) {
        // 已登录且要跳转的页面是登录页
        next({
          name: homeName // 跳转到homeName页
        })
      } else if (to.name === homeName) {
        next()
      } else {
        // console.log('2')
        const newRoutes = routes.concat(store.state.user.permission)
        turnTo(to, next, newRoutes)
      }
    }
  }
})

router.afterEach(to => {
  setTitle(to, router.app)
  iView.LoadingBar.finish()
  window.scrollTo(0, 0)
})

export default router
