import VueAccessControl, {LoginMiddleware} from '@lywzx/vue.access.control';
import Vue from 'vue';
import { User } from '../service/User';

Vue.use(VueAccessControl, {
  vueRouter: true,
  globalMiddleWares: ['login?'], // 定义默认的中间件
  loginRoute: { // 登入路由
    path: '/login'
  },
  permissionDenyRedirectRoute: {  // 權限拒絕重定向路由
    path: '404'
  },
  defaultRoute: {  // 基本路由
    name: 'home'
  },
});


LoginMiddleware.handleExtend = function(next, ...arg) {
  let identity = localStorage.getItem('identity')
  let toNextPath = arg[1].path
  let userAccess, userInfo

  if(localStorage.userAccess){
    userAccess = JSON.parse(decodeURIComponent(localStorage.userAccess,"utf-8"))
  }
  if(localStorage.userInfo){
    userInfo = JSON.parse(decodeURIComponent(localStorage.userInfo,"utf-8"))
  }
  
  if (userAccess && userInfo) {
    if(toNextPath === '/login' && userAccess.isLogin){
      window.location.href = identity == 'student' ? '/studentWeb' : '/home'
    } else {
      User.freshLogin().then(() => {
        next(true);
      }).catch(() => {
        next(false);
      });        
    }      
  } else {
    next(false);
  }
};

const access = new VueAccessControl.Access({
  routes: []
  //routes: AsyncTeacherRoute.concat(AsyncStudentRoute),
});
  

User.$access = access;

export default access;