//  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 $http from '@/utils/http-service';
import { traduction } from '@/utils/language';
import useStore from '@/stores';
import { UI_REST_FIRMWAREINVENTORY } from '@/api/api';


// 获取双因素认证配置信息
export function getTwoFactoryData() {
  return $http.get('/UI/Rest/AccessMgnt/TwoFactorAuthentication');
}

// 设置双因素认证配置信息
export function setTwoFactoryData(data: any) {
  return $http.patch('/UI/Rest/AccessMgnt/TwoFactorAuthentication', data);
}

// 删除根证书/客户端证书
export function delRootCert(param: any) {
  return $http.post('/UI/Rest/AccessMgnt/TwoFactorAuthentication/DeleteCertificate', param);
}

export function rootCertInfoAssemble(data: any) {
  const rootCertificate = data?.RootCertificateMembers;
  const certificates = [];
  if (rootCertificate && JSON.stringify(rootCertificate) !== '{}') {
    for (const item of rootCertificate) {
      const issueByTarget = item.IssueBy;
      const regCN = /(?<=CN=).*?(?=,)/;
      const issueByCNTarget = issueByTarget.match(regCN)[0];
      const issueToTarget = item.IssueTo;
      const issueToCNTarget = issueToTarget.match(regCN)[0];
      let crlValidFromTo = '--';
      if (item.CrlValidFrom && item.CrlValidTo) {
        crlValidFromTo = `${item.CrlValidFrom} - ${item.CrlValidTo}`;
      }
      let validFromTo = '--';
      if (item.ValidFrom && item.ValidTo) {
        validFromTo = `${item.ValidFrom} - ${item.ValidTo}`;
      }
      certificates.push({
        certId: item.ID,
        issueBy: issueByTarget,
        issueByCN: issueByCNTarget,
        issueTo: issueToTarget,
        issueToCN: issueToCNTarget,
        validFrom: item.ValidFrom,
        validTo: item.ValidTo,
        valid: validFromTo,
        crlValidFrom: item.CrlValidFrom,
        crlValidTo: item.CrlValidTo,
        crlValid: crlValidFromTo,
        isImportCrl: item.CrlState,
        serialNumber: item.SerialNumber,
        isCRLUpload: false,
      });
    }
  }
  return certificates;
}
export function getRoleName(id: string) {
  let roleName = '';
  switch (id) {
    case 'Administrator':
      roleName = traduction('COMMON_ROLE_ADMINISTRATOR');
      break;
    case 'Operator':
      roleName = traduction('COMMON_ROLE_OPERATOR');
      break;
    case 'CommonUser':
      roleName = traduction('COMMON_ROLE_COMMONUSER');
      break;
    case 'NoAccess':
      roleName = traduction('COMMON_ROLE_NOACCESS');
      break;
    case 'CustomRole1':
      roleName = traduction('COMMON_ROLE_CUSTOMROLE1');
      break;
    case 'CustomRole2':
      roleName = traduction('COMMON_ROLE_CUSTOMROLE2');
      break;
    case 'CustomRole3':
      roleName = traduction('COMMON_ROLE_CUSTOMROLE3');
      break;
    case 'CustomRole4':
      roleName = traduction('COMMON_ROLE_CUSTOMROLE4');
      break;
    default:
      roleName = traduction('COMMON_ROLE_NOACCESS');
      break;
  }
  return roleName;
}

// 客户端证书查询
export function clientCertInfoAssemble(data: any) {
  const clientCertData = [];
  for (const item of data.ClientCertificateMembers) {
    let fingerPrint = '--';
    let revokedTime = '--';
    let revokedStatus = null;
    let uploadState = true;
    let rootState = traduction('COMMON_NOT_UPLOADED');
    let revokedStatusValue = traduction('COMMON_NOT_UPLOADED');
    let roleID = '';
    const next = item;
    if (next) {
      if (next.RootCertUploadedState) {
        rootState = traduction('COMMON_UPLOADED');
      } else {
        rootState = traduction('COMMON_NOT_UPLOADED');
      }
      if (next.Fingerprint !== undefined && next.Fingerprint !== null && next.Fingerprint !== '') {
        fingerPrint = next.Fingerprint;
        uploadState = false;
      }
      // 证书已吊销情况下，吊销时间也可能为 null , 未吊销的情况下，吊销时间为 null
      revokedTime = next.RevokedDate !== null ? next.RevokedDate : '--';
      revokedStatus = next.RevokedState;
      if (next.RevokedState) {
        revokedStatusValue = traduction('TWO_FACTORS_REVOKED');
      } else {
        revokedStatusValue = traduction('TWO_FACTORS_UNREVOKED');
      }
      roleID = next.RoleID.replace(/\s+/g, '');
    }

    const certInfo = {
      id: item.UserId,
      userName: item.UserName,
      user: getRoleName(roleID),
      issueBycertificateStatus: rootState,
      clientCertificateFingerprint: fingerPrint,
      revokedState: revokedStatus,
      revokedStateValue: revokedStatusValue,
      revokedDate: revokedTime,
      isUpload: uploadState,
      isClientUpload: false,
    };
    clientCertData.push(certInfo);
  }
  return clientCertData;
}

export function alertMessage(type: string, message: string) {
  return useStore().state.event.setEventState({
    type: 'alertMessage',
    value: { type: type, message: traduction(message) },
  });
}

// 上传客户端证书文件
export function uploadClientCertFile(formData: FormData) {
  return $http.post(UI_REST_FIRMWAREINVENTORY, formData);
}

// 导入客户端证书文件
export function importClientCertificate(fileName: string, userId: number) {
  let data = { Content: `/tmp/web/${fileName}`, UserId: userId };
  return new Promise((resolve, reject) => {
    const url = '/UI/Rest/AccessMgnt/TwoFactorAuthentication/ImportClientCertificate';
    $http
      .post(url, data)
      .then((res: any) => {
        resolve(res);
      })
      .catch(error => {
        reject(error);
      });
  });
}

