//  Copyright (c) 2024 Huawei Technologies Co., Ltd.
//  openUBMC is licensed under Mulan PSL v2.
//  You can use this software according to the terms and conditions of the Mulan PSL v2.
//  You may obtain a copy of Mulan PSL v2 at:
//        #  http://license.coscl.org.cn/MulanPSL2
//  THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
//  EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
//  MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
//  See the Mulan PSL v2 for more details.
import { RouterChangeReason } from '@/model/base-enum';
import { getStoreData, setStoreData } from '@/utils/composition';
import { RouteLocationNormalized } from 'vue-router';
import { checkHasPrivil, checkRouteIsValid } from '../router/routes';
import { getRandomNumber } from '@/utils/utils';

/**
 * 该守卫主要是验证进入路由是否有权限（是否登录）, 主要验证3个点
 * 1. 是否登录。
 * 2. 路由是否合法。
 * 3. 用户权限是否符合对应路由要求的权限（主要是是否有查看该页面的权限）
 */
export function authorizeGuard(to: RouteLocationNormalized): Promise<any> | boolean {
  if (to.fullPath.indexOf('login') > -1 || to.fullPath.indexOf('kvm_h5') > -1) {
    return true;
  }

  const isLogin = getStoreData('loct', 'isLogin');
  if (!isLogin) {
    setStoreData('event', 'routeChangeError', RouterChangeReason.notLogin + getRandomNumber());
    return false;
  }

  let path = to.fullPath.split('?')[0];
  const isValidRoute = checkRouteIsValid(path);
  if (!isValidRoute) {
    setStoreData('event', 'routeChangeError', RouterChangeReason.invalid + getRandomNumber());
    return false;
  }

  const hasPermission = checkHasPrivil(path);
  if (!hasPermission) {
    setStoreData('event', 'routeChangeError', RouterChangeReason.noPermission + getRandomNumber());
    return false;
  }

  return true;
}
