//  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 { traduction } from '@/utils/language';
import { IRule } from '@/model/Service/vnc-interface';
import { pwdLevelFn } from '@/validators/get-security-level';
import { USERNAME_LENGTH_AND_SPECIAL_WORD } from '@/utils/regular';

import {
  strLengthVerification,
  atLeastContainVerification,
  containSpecialStrVerification,
  securityVerification
} from '@/validators/password-rules';
import { getStoreData } from '@/utils/composition';
import { regVerification } from '@/validators/password-rules';
import { strVerification, setCircleAndLineStyle } from '@/validators/validation-functions';

// 没有开启 密码检查的时候的校验规则
const ordinaryRule = (
  minLength: number,
  maxLength: number,
  message: string,
  required: boolean,
  trigger?: string,
  containsEmptyString?: boolean
): IRule => {
  return {
    type: 'password',
    required: required,
    minLength: minLength,
    maxLength: maxLength,
    containsEmptyString: containsEmptyString || false,
    tipText: traduction('VALIDATOR_PWD_STANDARD', [1, 20]),
    validator: strVerification,
    message: message,
    trigger: trigger || 'blur'
  };
};

// 不能和用户名或者倒序的用户名相同
function notEquireAndBackEquire(editData: any) {
  return {
    // 是否展示前面的验证正确或者错误的icon
    icon: true,
    // 验证方法
    validator: (rule: any, val: string) => {
      const str = editData.userName.split('').reverse().join('');
      const condition = editData.userName && (editData.userName === val || str === val);
      if (!val || condition) {
        return false;
      }
      return true;
    },
    // 提示文本
    label: traduction('VALIDATOR_PWD_VALIDATOR4'),
    // 验证结果
    state: false
  };
}

// 用户名的校验规则
export function userNameVerification(rule: any, value: string, callback: any) {
  const errMsg = traduction('VALIDTOR_FORMAT_ERROR');
  if (!value) {
    callback(new Error());
    return false;
  }
  if (rule.pattern) {
    if (!new RegExp(rule.pattern).test(value)) {
      callback(new Error(errMsg));
      return false;
    }
  } else {
    if (
      !USERNAME_LENGTH_AND_SPECIAL_WORD.test(value) ||
      !/^[^#+-].*$/.test(value) ||
      value === '.' ||
      value === '..'
    ) {
      callback(new Error(errMsg));
      return false;
    }
  }

  callback();
  return true;
}

// 必传和安全校验
function requiredAndSecurity(
  val: string,
  callback: any,
  verificationList: any,
  security: boolean,
  errorMessage: string[],
  required?: boolean
): boolean {
  // 如果不是必传且没有输入内容
  if (!required && !val) {
    callback();
    return true;
  } else {
    let num = 0;
    let msg = '';
    verificationList.forEach((item: any, index: number) => {
      if (item.state) {
        num++;
      } else if (!msg) {
        // 因为必传和长度校验是在同一个函数的
        msg = errorMessage[index === 0 ? 1 : index];
      }
    });

    // 根据满足条件个数来判断是否返回校验错误
    // 如果有安全程度
    if (security) {
      if (num === verificationList.length - 1) {
        callback();
        return true;
      }
    } else {
      // 如果没有安全程度
      if (num === verificationList.length) {
        callback();
        return true;
      }
    }

    callback(new Error(msg));
    return false;
  }
}

// 密码检查
export function passwordVerification(rule: IRule, val: string, callback: any) {
  const { errorMessage, required } = rule;
  // 为空校验
  if (required && !val) {
    callback(new Error(errorMessage[0]));
    return false;
  }

  let security = false;
  const { verificationList } = rule;
  if (
    verificationList &&
    typeof verificationList === 'object' &&
    verificationList instanceof Array
  ) {
    verificationList.forEach((item: any) => {
      const { validator } = item;
      if (validator && typeof validator === 'function' && validator instanceof Function) {
        // 对每一项进行校验,设置其验证结果
        item.state = validator(item, val);
        // 如果有安全程度
        if (item.security) {
          security = true;
          // 0、1、2
          const level = pwdLevelFn(val, verificationList);
          setCircleAndLineStyle(level, item, val);
        }
      }
    });
  } else {
    // 没有设置校验规则
    callback();
    return false;
  }

  return requiredAndSecurity(val, callback, verificationList, security, errorMessage, required);
}

export const specialRule = (
  minLength: number,
  maxLength: number,
  editData: any,
  required: boolean,
  errorMessage: string[],
  trigger?: string,
  containsEmptyString?: boolean
): IRule => {
  const localAccountPasswordRulePolicy = getStoreData('glob', 'localAccountPasswordRulePolicy');
  const localAccountPasswordPattern = getStoreData('glob', 'localAccountPasswordPattern');
  let verificationList: IRule = [];
  if (localAccountPasswordRulePolicy === 'Customized') {
    verificationList = [
      strLengthVerification({
        rangeSize: [minLength, maxLength],
        label: traduction('VALIDATOR_PWD_VALIDATOR1', [minLength, maxLength])
      }),
      regVerification(localAccountPasswordPattern, 'local'),
      securityVerification()
    ];
  } else if (localAccountPasswordRulePolicy === 'Hybrid') {
    verificationList = [
      strLengthVerification({
        rangeSize: [minLength, maxLength],
        label: traduction('VALIDATOR_PWD_VALIDATOR1', [minLength, maxLength])
      }),
      atLeastContainVerification(),
      containSpecialStrVerification(),
      notEquireAndBackEquire(editData),
      regVerification(localAccountPasswordPattern, 'local'),
      securityVerification()
    ];
  } else {
    verificationList = [
      strLengthVerification({
        rangeSize: [minLength, maxLength],
        label: traduction('VALIDATOR_PWD_VALIDATOR1', [minLength, maxLength])
      }),
      atLeastContainVerification(),
      containSpecialStrVerification(),
      notEquireAndBackEquire(editData),
      securityVerification()
    ];
  }

  return {
    type: 'password',
    required: required,
    containsEmptyString: containsEmptyString ? containsEmptyString : false,
    verificationList: verificationList,
    validator: passwordVerification,
    errorMessage,
    trigger: trigger || 'blur'
  };
};

// 检查密码是否由重复子串组成
export function computeRepeatTimes(value: string = ''): number {
  let str1 = '';
  let str2 = '';
  const vLength = value.length;
  for (let i = 1; i <= vLength; i++) {
    if (vLength % i === 0) {
      for (let m = i; m < vLength; m += i) {
        str1 = value.substring(0, i);
        str2 = value.substring(m, m + i);
        if (str1 !== str2) {
          break;
        } else if (m + i === vLength) {
          return vLength / i;
        }
      }
    }
  }
  return 1;
}

// 失败提示词解析方法
export function errorTip(msgId: string): any {
  let alertObj = {
    type: 'error',
    label: 'COMMON_FAILED'
  };
  // 如果是授权失败错误,则不提示
  if (msgId === 'AuthorizationFailed') {
    return null;
  }

  const successTips = traduction(`${msgId}.successTips`);
  const errorMessage = traduction(`${msgId}.errorMessage`);

  // 翻译如果没有找到会返回原字符串,这里通过和原字符串比较是否相等来判断是否成功
  if (successTips !== `${msgId}.successTips`) {
    alertObj = {
      type: 'success',
      label: successTips
    };
  } else {
    if (msgId === 'InsufficientFreeSpace') {
      alertObj = {
        type: 'error',
        label: traduction('COMMON_FREE_SPACE')
      };
    } else {
      alertObj = {
        type: 'error',
        label: errorMessage || traduction('COMMON_FAILED')
      };
    }
  }
  return alertObj;
}

// 从响应信息获取错误ID
export function getMessageId(error: any) {
  let errorObject = '';
  const errorIdArr: any = [];

  if (typeof error === 'string') {
    try {
      errorObject = JSON.parse(error);
    } catch (err) {
      return errorIdArr;
    }
  } else {
    errorObject = error.data || error;
  }
  if ((errorObject as any).error && Array.isArray((errorObject as any).error)) {
    (errorObject as any).error.forEach((errorItem: any) => {
      // 自定义的错误类型,errorId, ralation:表示此错误关联的属性值
      errorIdArr.push({
        errorId: errorItem.code,
        description: errorItem.message,
        relation: ''
      });
    });
  } else if ((errorObject as any).error && (errorObject as any).error['@Message.ExtendedInfo']) {
    (errorObject as any).error['@Message.ExtendedInfo'].forEach((item: any) => {
      const oldErrorId = item.MessageId.split('.').reverse().shift();
      errorIdArr.push({
        errorId: oldErrorId,
        description: item.Message,
        relation: item.relatedProperties
      });
    });
  } else {
  }
  return errorIdArr;
}

/**
 * 根据是否开启密码检查初始化password类型输入框的校验规则
 * passwordCheck:是否启用密码检查(用户&安全-安全配置-密码检查)
 */
export function initPasswordRules(
  passwordCheck: boolean,
  minPwdLength: number,
  editData: any,
  required: boolean,
  errorMessage: string[],
  trigger?: string,
  containsEmptyString?: boolean
) {
  if (passwordCheck) {
    return specialRule(
      minPwdLength,
      20,
      editData,
      required,
      errorMessage,
      trigger,
      containsEmptyString
    );
  } else {
    return ordinaryRule(
      1,
      20,
      traduction('VALIDTOR_FORMAT_ERROR'),
      required,
      trigger,
      containsEmptyString
    );
  }
}