import ObsClient from "esdk-obs-browserjs"
import CryptoJS from "crypto-js"
export function upload(data, cb) {
	return uni.$u.http.upload('/file/upload', {
		filePath: data.url,
		name: 'file',
		timeout: 60000,
		getTask: (task, options) => {
			task.onProgressUpdate((res) => {
				cb(res)
			});
		},
	})
}

export function OBS() {
	return uni.$u.http.get('/file/getStsToken')
}

export function obsJiami(file) {
	return new Promise((res, rej) => {
		var reader = new FileReader();
		reader.readAsArrayBuffer(file);
		reader.onload = () => {
			var key = 'a63f22e7c4a5e167';
			var wordArray = CryptoJS.lib.WordArray.create(reader
				.result); // Convert: ArrayBuffer -> WordArray
			var encrypted = CryptoJS.AES.encrypt(wordArray, CryptoJS.enc.Utf8.parse(key), {
				mode: CryptoJS.mode.ECB,
				padding: CryptoJS.pad.Pkcs7
			}).toString();
			// var fileEnc = encrypted
			// console.log(fileEnc)
			// return
			res(encrypted)
		};
		reader.onerror = (e) => {
			rej(e)
		}
	})
};

function convertWordArrayToUint8Array(wordArray) {
	var arrayOfWords = wordArray.hasOwnProperty("words") ? wordArray.words : [];
	var length = wordArray.hasOwnProperty("sigBytes") ? wordArray.sigBytes : arrayOfWords.length * 4;
	var uInt8Array = new Uint8Array(length),
		index = 0,
		word, i;
	for (i = 0; i < length; i++) {
		word = arrayOfWords[i];
		uInt8Array[index++] = word >> 24;
		uInt8Array[index++] = (word >> 16) & 0xff;
		uInt8Array[index++] = (word >> 8) & 0xff;
		uInt8Array[index++] = word & 0xff;
	}
	return uInt8Array;
}

export function obsJiemi(url,flag = false) {
	if(url.includes('myhuaweicloud'))
	return new Promise((res, rej) => {
		let xhr = new XMLHttpRequest()
		let blob;
		xhr.open('get', url)
		xhr.setRequestHeader('Accept', getFileType(url))
		xhr.responseType = 'blob'
		xhr.onload = () => {
			blob = xhr.response
			let file;
				file = new File([blob], url, {
					type: getFileType(url)
				})
			var reader = new FileReader();
			reader.readAsText(file);
			reader.onload = () => {
				var key = 'a63f22e7c4a5e167';
				var decrypted = CryptoJS.AES.decrypt(reader.result, CryptoJS.enc.Utf8.parse(key), {
					mode: CryptoJS.mode.ECB,
					padding: CryptoJS.pad.Pkcs7
				}); // Decryption: I: Base64 encoded string (OpenSSL-format) -> O: WordArray
				var typedArray = convertWordArrayToUint8Array(
				decrypted); // Convert: WordArray -> typed array
				var fileDec = new Blob([typedArray]); // Create blob from typed array
				let url = URL.createObjectURL(fileDec)
				if((file.type != 'image/*' && file.type != 'video/*') && flag){
					var a = document.createElement("a");
					var filename = file.name;
					a.href = url;
					a.download = filename.substring(filename.lastIndexOf('/')+1);
					a.click();
					window.URL.revokeObjectURL(url);
				}
				let param = {url:url,type:file.type}
				res(param)
			};
		}
		xhr.onerror = (error) => {
			rej(error)
		}
		xhr.send()
	})
	else{
		return new Promise((res,rej)=>{
			let param = {url:url,type:getFileType(url)}
			res(param)
		})
	}
}

function getFileType(url){
	let arr = 'bmp,jpg,png,tif,gif,pcx,tga,exif,fpx,svg,psd,cdr,pcd,dxf,ufo,eps,ai,raw,WMF,webp,avif,apng'
	let videoArr = 'asf,avi,mov,mpeg,mpg,vob,wmv,rm,rmvb,ogm,mkv,ifo,mp4,3gp,ts,mid,mp3,wav,wma,ra,ogg,flac,aac,ape,mpc,ac3,cda,m4a,mka,mp2,mpa,ofr,dts'
	arr = arr.split(',')
	videoArr = videoArr.split(',')
	for(let i in arr){
		if(url.includes(arr[i]) || url.includes(arr[i].toUpperCase()))
		return 'image/*'
	}
	for(let i in videoArr){
		if(url.includes(videoArr[i]) || url.includes(videoArr[i].toUpperCase()))
		return 'video/*'
	}
	if(url.includes('txt') || url.includes('TXT')){
		return "text/html,text/plain"
	}
	if(url.includes('pdf') || url.includes('PDF')){
		return "application/pdf"
	}
	if(url.includes('doc') || url.includes('DOC')){
		return "application/msword"
	}
}

export function initObs(param) {
	return new ObsClient({
		access_key_id: param.accessKey,
		secret_access_key: param.secretKey,
		security_token: param.sessionToken,
		server: param.endPoint
	});
}