import { createRouter,createWebHistory } from 'vue-router'
import routes from './routers'
import store from '../bc-store'
import iView from 'view-ui-plus'
import { canTurnTo, setTitle } from '../bc-libs/util'
import { setToken, getToken } from '../bc-libs/token-util'
import config from '@/config'
const { homeName,PThomeName } = config


const router =createRouter({
  routes,
  history: createWebHistory()
})
const LOGIN_PAGE_NAME = 'login'
const BOCHU_PRINT_NAME = 'bochu-print'


router.reLoad= () => {

}

const turnTo = (to, access, next) => {
  let paramsRoutes = routes;
  //首先看看缓存里有没有路由,有的话优先加载缓存中的,
  // 后面的组件会有逻辑更新缓存的,这里是一次性使用,主要应对浏览器刷新
  //let caCheRoutes = getRouteListFromLocalstorage();
  //if (caCheRoutes.length>0) paramsRoutes = caCheRoutes;
  //console.log(this.$store.state.app.realRoutes)
  //debugger
  if (canTurnTo(to.name, access, paramsRoutes)) next() // 有权限，可访问
  else if (to.name == null || to.name == '')  next({ replace: true, name: homeName });//这是刷新了浏览器,路由重置了
  else next({ replace: true, name: 'error_401' }) // 无权限，重定向到401页面
}

router.beforeEach((to, from, next) => {
  iView.LoadingBar.start()
  const token = getToken()
  const needLogin = to.meta.requireLogin
  if (!token && to.name !== LOGIN_PAGE_NAME && needLogin!==false) {
    // 未登录且要跳转的页面不是登录页
    if (config.deploymentStandAlone || config.systemCode === 'cas-new'){
      next({
        name: LOGIN_PAGE_NAME // 跳转到登录页
      })
    }else {
      window.location.href= config.logout_url;//接入平台或不接入,登出地址不一样
    }
  } else if (!token && to.name === LOGIN_PAGE_NAME) {
    // 未登陆且要跳转的页面是登录页
    next() // 跳转
  } else if (token && to.name === LOGIN_PAGE_NAME) {
    // 已登录且要跳转的页面是登录页
    next({
      name: PThomeName // 跳转到homeName页
    })
  } else {
    if(needLogin == false){ //不需要登陆
      next()
    } else {
      if (store.state.user.hasGetInfo) {
        turnTo(to, store.state.user.access, next)
      } else {
        store.dispatch('getUserInfo').then(user => {
          // 拉取用户信息，通过用户权限和跳转的页面的name来判断是否有权限访问;access必须是一个数组，如：['super_admin'] ['super_admin', 'admin']
          turnTo(to, user.access, next)
        }).catch(() => {
          setToken('')
          /*if (config.deploymentStandAlone){
            next({
              name: LOGIN_PAGE_NAME // 跳转到登录页
            })
          }else {
            window.location.href= config.logout_url;//接入平台或不接入,登出地址不一样
          }*/
        })
      }
    }
  }
})

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

export default router
