import CryptoJS from "crypto-js";
 //秘钥
const CRYPTOJSKEY= "szhdxfiCPTh3zDaW";

// 加密
export const encrypt = plaintText => {
	try{
		var plaintText = plaintText;
		var options = {
		    mode: CryptoJS.mode.ECB,
		    padding: CryptoJS.pad.Pkcs7
		};
		var key = CryptoJS.enc.Utf8.parse(CRYPTOJSKEY);
		var encryptedData = CryptoJS.AES.encrypt(plaintText, key, options);
		var encryptedBase64Str = encryptedData.toString().replace(/\//g, "_");
		encryptedBase64Str = encryptedBase64Str.replace(/\+/g,"-");
		return encryptedBase64Str;
	}catch(e){
		return plaintText
	}
}

//解密
export const decrypt = encryptedBase64Str => {
	try{
		var vals = encryptedBase64Str.replace(/\-/g, '+').replace(/_/g, '/');
		var options = {
		    mode: CryptoJS.mode.ECB,
		    padding: CryptoJS.pad.Pkcs7
		};
		var key = CryptoJS.enc.Utf8.parse(CRYPTOJSKEY);
		var decryptedData = CryptoJS.AES.decrypt(vals, key, options);
		var decryptedStr = CryptoJS.enc.Utf8.stringify(decryptedData);
		return decryptedStr
	}catch(e){
		return encryptedBase64Str
	}
}

//type:1 姓名、2 手机号、3 身份证
export const tuomin = (value,type) => {
	if(!value) return;
	let res = '';
	if(type==1){
		let arr = Array.from(value)
		if (arr.length === 2) {
			res = arr[0] + '*'
		} else if (arr.length > 2) {
			for (let i = 1; i < arr.length - 1; i++) {
			  arr[i] = '*'
			}
			res = arr.join("")
		}else {
			res = value
		}
	}else if(type==2){
		res = value.replace(/^(.{3})(?:\d+)(.{4})$/, "$1****$2");
	}else if(type==3){
		res = value.replace(/^(.{4})(?:\d+)(.{4})$/, "$1**********$2");
	}
	
	return res;
}

export default {
	encrypt,
	decrypt,
	tuomin
}