import CryptoJS from 'crypto-js'
import http from './request';

const UrlPath = {
	// getBaseUrl() {
	// 	return "http://zyhzty.top/"
	// },
	// getBaseUrl() {
	// 	return "http://10.110.65.77:5005/"
	// }
	// getBaseUrl() {
	// 	// return "http://192.168.31.7:48080/"
	// 	return "http://192.168.31.36:98/zyzk/api/"
	// }
	getBaseUrl() {
		return "/zyzk/api/"
	}

}
//加密处理
const Encrypt = { 
	AESINFO: null,
	GetAESINFO() {//获取编码信息
		if (this.AESINFO == null) {
			this.AESINFO = JSON.parse(this.Base64Decode("eyJrZXkiOiJjaWljY2lpY2NpaWNjaWljIiwiaXYiOiJjaWljMjAyMmNpaWMyMDIyIn0="));
		}
		return this.AESINFO;
	},//如果空返回
	IsNull(WhenInfo: any, ThenInfo: any) {
		if (WhenInfo === null || WhenInfo === undefined) {
			return (ThenInfo === null || ThenInfo === undefined) ? "" : ThenInfo;
		}
		return WhenInfo;
	},//如果空返回
	IsNullOrEmpty(Info: any) {
		return this.IsNull(Info, "") === "";
	}, //Base64编码
	Base64Encode(str: string) {
		return CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(str));
	},//Base64解码
	Base64Decode(str: string) {
		return CryptoJS.enc.Base64.parse(str).toString(CryptoJS.enc.Utf8);
	},//AES编码
	AESEncode(data: string, key: string, iv: string) {
		if (typeof data === "object") {
			// 如果传入的data是json对象，先转义为json字符串
			try {
				data = JSON.stringify(data)
			} catch (error) {
				console.log("error:", error)
			}
		}
		if (this.IsNullOrEmpty(key)) {
			key = this.GetAESINFO().key;
		}
		if (this.IsNullOrEmpty(iv)) {
			iv = this.GetAESINFO().iv;
		}
		const dataHex = CryptoJS.enc.Utf8.parse(data) // 需要加密的数据
		const keyHex = CryptoJS.enc.Utf8.parse(key) // 秘钥
		const ivHex = CryptoJS.enc.Utf8.parse(iv) // 偏移量
		const encrypted = CryptoJS.AES.encrypt(dataHex, keyHex, {
			iv: ivHex,
			mode: CryptoJS.mode.CBC, // 加密模式
			padding: CryptoJS.pad.Pkcs7
		})
		return encrypted.ciphertext.toString() //  返回加密后的值
	},
	AESDecode(data: string, key: string, iv: string) {//AES解码
		if (this.IsNullOrEmpty(key)) {
			key = this.GetAESINFO().key;
		}
		if (this.IsNullOrEmpty(iv)) {
			iv = this.GetAESINFO().iv;
		}
		let encryptedHexStr = CryptoJS.enc.Hex.parse(data);
		let srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr);
		const keyHex = CryptoJS.enc.Utf8.parse(key) // 秘钥
		const ivHex = CryptoJS.enc.Utf8.parse(iv) // 偏移量
		let decrypt = CryptoJS.AES.decrypt(srcs, keyHex, {
			iv: ivHex,
			mode: CryptoJS.mode.CBC,
			padding: CryptoJS.pad.Pkcs7
		});
		return decrypt.toString(CryptoJS.enc.Utf8).toString();
	}
}
//消息功能
const Message = {
	success(content: string) {
		uni.showToast({
			title: content,
			icon: 'success',
			duration: 2000
		})
	},
	error(content: string) {
		uni.showToast({
			title: content,
			icon: 'error',
			duration: 2000
		})
	},
	info(content: string) {
		uni.showToast({
			title: content,
			icon: 'none',
			duration: 2000
		})
	}
}

//文件上传
const FileInfo = {
	Upload(CallBackEvent: Function, FileList: Array<any>, ExtendParameter: any) {
		this.defaults = {
			Async: true,
			ShowWaiting: true,
			Later: false,
			Encrypt: false,
			Timeout: 120000,
			Tip: null,
			Folder: "Temp",
			MedID: "",
			IsFileServer: true,
			Url: UrlPath.getBaseUrl() + "ExecuteSystemUpLoadFile"
		};
		const formData = { files: [], formData: null }
		let allowfiles: Array<string> = []
		let temp_extend: Array<string> = []
		if (FileList == null || FileList.length == 0) {
			Message.error("没有需要上传的文件!");
			return;
		}
		for (let i = 0; i < FileList.length; i++) {
			temp_extend = FileList[i].name.split('.')
			allowfiles.push(temp_extend[temp_extend.length - 1])
			formData.files.push({
				name: "file:" + FileList[i].url,
				uri: FileList[i].url
			});
		}
		var Parameters = Object.assign(this.defaults, ExtendParameter);
		if (Parameters.IsFileServer === true) {
			var cur = null;//state.getters.userinfo;
			if (cur == null) {
				let uinfo = Utility.GetStorage("userinfo");
				if (uinfo == null || uinfo == "") {
					Message.error("未获取到登录信息!");
					return;
				}
				cur = JSON.parse(uinfo);
			}
			if (!Encrypt.IsNullOrEmpty(cur.LoadBalancingFileUrl)) {
				Parameters.Url = cur.LoadBalancingFileUrl.replace("[LOCALPATH]", location.protocol + "//" + location.host) + 'Api/File/UploadFilesAsync';
			}
			Parameters.MedID = cur.MedicalInstitutionID;
			Parameters.HttpPath = cur.ResourcePath;
		}
		formData.formData = { SaveFileInfo: "{\"data\":\"" + Encrypt.AESEncode(JSON.stringify({ IsSystem: false, Folder: Parameters.Folder, AllowFiles: allowfiles.join(","), MedID: Parameters.MedID, Token: Utility.GetStorage("Token"), HttpPath: Parameters.HttpPath }), "", "") + "\"}" }

		http.upload(Parameters.Url, formData).then(res => {
			CallBackEvent(res);
		});
	}
}

//通用方法
const Utility = {
	//校验密码强度
	ValidPassWord(value: string) {
		var level = 0;
		if (value.length < 6) {
			return level;
		}
		if (/\d/.test(value)) {
			level++;
		}
		if (/[a-z]/.test(value)) {
			level++;
		}
		if (/[A-Z]/.test(value)) {
			level++;
		}
		if (/[\W_!@#$%^&*`~()-+=]/.test(value)) {
			level++;
		}
		return level;
	},
	//校验手机号
	ValidMobild(value: string) {
		return /^(((1[3456789][0-9]{1})|(15[0-9]{1}))+\d{8})$/.test(value);
	},
	SetStorage(key: string, value: string) {
		uni.setStorageSync(key, value)
	},
	GetStorage(key: string) {
		return uni.getStorageSync(key)
	},
	SetStorageJson(key: string, value: object) {
		uni.setStorageSync(key, JSON.stringify(value))
	},
	GetStorageJson(key: string) {
		let value = uni.getStorageSync(key)
		if (value != null && value != "") {
			return JSON.parse(value)
		}
		return null
	},
	GetPlatform() {//ios android devtools
		return uni.getSystemInfoSync().platform
	},
	GetRuntime() {
		const sysinfo = uni.getSystemInfoSync()
		switch (sysinfo.uniPlatform) {
			case "app":
				return "app";
			case "web":
			case "h5":
				return "web"
			default:
				return "mp"
		}
	},
	IsWeChat() {//是否微信小程序
		return this.GetRuntime() === "mp";
	},
	TrimEnd(text: string, content: string) {
		if (text == null || text == "") {
			return "";
		}
		var str = text.substring(text.length - content.length, text.length);
		if (content === str) {
			return text.substring(0, text.length - content.length);
		}
		return text;
	}
}
export { Encrypt, Message, FileInfo, Utility, UrlPath } 
