
/**安全相关工具 */
import CryptoJS from 'crypto-js';

const dk = 'abacuscommon2025'; // 密钥 后端提供 
const iv = CryptoJS.enc.Utf8.parse(); // 偏移量
/**
 * 加密
 * @param content 加密内容
 * @param encryptKey 加密密钥(16字节)，为空则使用默认密钥
 */
export function encrypt(content,key) {
  if(!content){
    return content
  }
  if(!key){
    key=dk
  }
  key=CryptoJS.enc.Utf8.parse(key)
  const srcs = CryptoJS.enc.Utf8.parse(content);
  const encrypted = CryptoJS.AES.encrypt(srcs, key, {
    iv: iv,
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7,
  });
  return CryptoJS.enc.Base64.stringify(encrypted.ciphertext);
}

/**
 * 解密
 * @param content 解密内容
 * @param encryptKey 解密密钥(16字节)，为空则使用默认密钥
 */
export function decrypt(content,key) {
  if(!content){
    return content
  }
  if(!key){
    key=dk
  }
  key=CryptoJS.enc.Utf8.parse(key)
  const base64 = CryptoJS.enc.Base64.parse(content);
  const src = CryptoJS.enc.Base64.stringify(base64);

  const decrypt = CryptoJS.AES.decrypt(src, key, {
    iv: iv,
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7,
  });
  return CryptoJS.enc.Utf8.stringify(decrypt);
}

export enum DesensitizationType {
  CUSTOMIZE=0,
  ALL=1,
  CHINESENAME = 2,
  IDCARD = 3,
  BANKCARD = 4,
  PHONE=5,
}

/**
 * 脱敏
 * @param content 脱敏内容
 * @param type 脱敏类型
 */
export function desensitize(content:String,type:DesensitizationType,custEvent:Function) {
  if(type===DesensitizationType.CUSTOMIZE){
    return custEvent(content)
  }else if(type===DesensitizationType.ALL){
    return "******"
  }else if(type===DesensitizationType.CHINESENAME){
    if (content.length <= 1) 
      return content;
    return content.charAt(0) + "*" + (content.length > 2 ? content.charAt(content.length-1) : "");
  }else if(type===DesensitizationType.IDCARD){
    if (content.length < 8) 
      return content;
    return content.substring(0, 4) + "********" + content.substring(content.length-4);
  }else if(type===DesensitizationType.BANKCARD){
    if (content.length < 8) 
      return content;
    return content.substring(0, 4) + " **** **** " + content.substring(content.length-4);
  }else if(type===DesensitizationType.PHONE){
    if (content.length != 11) 
      return content;
    return content.substring(0, 3) + "****" + content.substring(7);
  }else{
    if (content.length <= 2) return "******";
        return content.charAt(0) + "****" + content.charAt(content.length-1);
  }
}











