export class User {

    static model = {
        login: null,
        logout: null,
        userInfo: null
    }

    /**
     * @type Access
     */
    static $access;

    static async login(userInfo) {
      let userAccess = {
          userId: userInfo.id,
          roles: userInfo.roles,
          permissions: userInfo.permissions,
          isLogin: true
      }

      localStorage.setItem('userAccess', encodeURIComponent(JSON.stringify(userAccess), 'utf-8')); // 權限
      localStorage.setItem('userInfo', encodeURIComponent(JSON.stringify(userInfo), 'utf-8')); // 基本信息

      return new Promise(function(resolve, reject) {
          User.$access.reset();
      //     // 配置登录用户的角色用对应的权限信息
          User.$access.setLoginUserInfo(userAccess);
      //     // 配置角色基本信息
          User.$access.setExtendInfo({
              'userAccess': userAccess,
              'userInfo' : userInfo
            });
          resolve(true);
      });
    }
    
    // 刷新登录信息，这个方法可以获取至当前登录用户的角色及权限等信息
    static freshLogin() {        
      return new Promise(function(resolve, reject) {
          // 把信息放到access当中，类似vuex状态管理，在组件中，可以通过`computed`再获取到信息 
            // computed: {
            //    user() { return this.$access.getExtendInfo('userInfo');}
            // }
            //
          let userAccess = JSON.parse(decodeURIComponent(localStorage.userAccess,"utf-8"));
          let userInfo = JSON.parse(decodeURIComponent(localStorage.userInfo,"utf-8"));

          setTimeout(() => {
            User.$access.reset();
            // 配置角色基本信息
            User.$access.setExtendInfo({
              'userAccess': userAccess,
              'userInfo' : userInfo
            });
            // 配置登录用户的角色用对应的权限信息
            User.$access.setLoginUserInfo(userAccess);
            resolve();
        }, 100);
      });
    }
    
    // 用户退出登录
    static logout() {
      return new Promise(function(resolve) {
        setTimeout(() => {
          localStorage.removeItem('token');
          localStorage.removeItem('userAccess');
          localStorage.removeItem('userInfo');
          localStorage.removeItem('login_schoolCode')
          localStorage.removeItem('user_details')
          localStorage.removeItem('access_token')
          localStorage.removeItem('expires_in')
          localStorage.removeItem('id_token')
          localStorage.removeItem('auth_token')
          localStorage.removeItem('user_profile')
          localStorage.removeItem('school_profile')
          localStorage.removeItem('student_profile')
          localStorage.removeItem('filterConditions')
          localStorage.removeItem('cacheSchoolFiles')
          localStorage.removeItem('cachePrivFiles')
          
          // 重置登录状态
          User.$access.reset();
          // 清空登录信息
          User.$access.setExtendInfo({
            'userAccess': {},
            'userInfo' : {}
          });          
          // window.location.href = '/'
          resolve(true);
        }, 100);
      });
    }
}