//  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 { keepAlive } from '@/utils/common-api';
import { saveStoreToLocal } from '@/utils/common-service';
import { setStoreData } from '@/utils/composition';
import { RouteLocationNormalized, NavigationGuardNext, RouteLocationRaw } from 'vue-router';

export function kvmGuard(
  to: RouteLocationNormalized,
  from: RouteLocationNormalized,
  next: NavigationGuardNext,
): void | Error | RouteLocationRaw | boolean | Promise<any> {
  // 若是预览功能要进入登录页，直接放行
  if (localStorage.getItem('previewFlag')) {
    next();
  } else {
    // 处理KVM直连等操作
    const loct = localStorage.getItem('loct') as string;
    const loctJson = JSON.parse(loct);
    if (loctJson?.rn) {
      keepAlive('Activate').then(
        () => {
          if (sessionStorage.getItem('kvmConnect')) {
            // 该场景是已经登录的情况下，通过remoteconsole,kvmvmm.asp的方式打开KVM(具体写入存储的信息在 kvmParamInit 方法内)
            next();
          } else {
            next('/navigate/home');
          }
        },
        () => {
          // 该场景是通过SSO跳转或URL参数拼接的方式打开KVM
          const result = isDirectConnectKvm();
          if (result) {
            next({ path: '/kvm_h5' });
          } else {
            setStoreData('loct', 'rn', '');
            setStoreData('loct', 'to', '');
            saveStoreToLocal();
            next();
          }
        },
      );
    } else {
      const result = isDirectConnectKvm();
      const ssoError = localStorage.getItem('ssoError');
      // 获取sso登录kvm的错误，并让其跳转到登录页
      if (result && ssoError !== 'error') {
        next({ path: '/kvm_h5' });
      } else {
        next();
      }
    }
  }
}

// 检测是否是KVM直连
function isDirectConnectKvm() {
  const localKvmH5Info = JSON.parse(localStorage.getItem('kvmHtml5Info') as string);
  const sessionKvmH5Info = JSON.parse(sessionStorage.getItem('kvmHtml5Info') as string);
  if (localKvmH5Info || sessionKvmH5Info) {
    return true;
  }
  return false;
}
