/**
 * APP端图片压缩
 *  参数说明：
 *  img 图片url
 *  scale缩放比例 1-100
 *  callback 回调设置返回值 
 */
export function translateapp(img, scale, callback) {

	plus.io.resolveLocalFileSystemURL(img, (entry) => { //通过URL参数获取目录对象或文件对象
		entry.file((file) => { // 可通过entry对象操作图片 
			if (file.size > 504800) { //   如果大于500Kb进行压缩
				plus.zip.compressImage({ // 5+ plus.zip.compressImage 了解一下，有详细的示例
					src: img, //src: 压缩原始图片的路径    
					dst: img.replace('.png', 'yasuo.png').replace('.PNG',
							'yasuo.PNG').replace('.jpg', 'yasuo.jpg')
						.replace('.JPG', 'yasuo.JPG'),
					width: '40%', //dst: (String 类型 )压缩转换目标图片的路径，这里先在后面原始名后面加一个yasuo区分一下
					height: '40%', //width,height: (String 类型 )缩放图片的宽度,高度
					quality: scale, //quality: (Number 类型 )压缩图片的质量
					overwrite: true, //overwrite: (Boolean 类型 )覆盖生成新文件
					// format:'jpg'   //format: (String 类型 )压缩转换后的图片格式
				}, (event) => {
					//返回压缩后的图片路径
					callback(event.target);
				}, function(err) {
					console.log('Resolve file URL failed: ' + err.message);
				});
			} else { //else小于500kb跳过压缩，直接返回现有的src
				callback(img);

			}
		});
	}, (e) => { // 返回错误信息
		console.log('Resolve file URL failed: ' + e.message);
	});

}
/**
 * H5端图片压缩
 *  参数说明：
 *  imgSrc 图片url
 *  scale缩放比例 0-1
 *  type 返回图片类型  默认blob 
 *  callback 回调设置返回值 
 */
export function translate(imgSrc, scale, type, callback) {
	var img = new Image();
	img.src = imgSrc;
	img.onload = function() {
		var that = this;
		let yasuobi = 700 / that.width
		let h = that.height * yasuobi;
		let w = that.width * yasuobi;
		var canvas = document.createElement('canvas');
		var ctx = canvas.getContext('2d');
		var width = document.createAttribute("width");
		width.nodeValue = w;
		var height = document.createAttribute("height");
		height.nodeValue = h;
		canvas.setAttributeNode(width);
		canvas.setAttributeNode(height);
		ctx.drawImage(that, 0, 0, w, h);
		var base64 = canvas.toDataURL('image/jpeg', scale); //压缩比例
		canvas = null;
		if (type == 'base64') {
			var blob = base64ToBlob(base64);
			var blobUrl = window.URL.createObjectURL(blob); //blob地址
			callback(base64, blobUrl);
		} else {
			var blob = base64ToBlob(base64);
			var blobUrl = window.URL.createObjectURL(blob); //blob地址
			callback(base64, blobUrl);
		}
	}
}


export function translateAll(imgSrc, callback) {
	translate1(imgSrc, 0.6, 'blob', callback)
}



export function translate1(imgSrc, scale, type, callback) {
	var img = new Image();
	img.src = imgSrc;
	img.onload = function() {
		var that = this;
		let yasuobi = 700 / that.width
		let h = that.height * yasuobi;
		let w = that.width * yasuobi;
		var canvas = document.createElement('canvas');
		var ctx = canvas.getContext('2d');
		var width = document.createAttribute("width");
		width.nodeValue = w;
		var height = document.createAttribute("height");
		height.nodeValue = h;
		canvas.setAttributeNode(width);
		canvas.setAttributeNode(height);
		ctx.drawImage(that, 0, 0, w, h);
		var base64 = canvas.toDataURL('image/jpeg', scale); //压缩比例
		canvas = null;
		if (type == 'base64') {
			var blob = base64ToBlob(base64);
			var blobUrl = window.URL.createObjectURL(blob); //blob地址
			// callback(base64, blobUrl, callback1);
			uni.getFileInfo({
				filePath: blobUrl,
				success: (res) => {
					let size = res.size
					let scale = 1
					if (size / 1024 / 1024 > 0.12) {
						scale = 0.6
						translate1(blobUrl, scale, 'blob', callback)
					} else {
						callback(base64, blobUrl)
					}
				},
				fail: (err) => {
					console.log(err);
				}
			})


		} else {
			var blob = base64ToBlob(base64);
			var blobUrl = window.URL.createObjectURL(blob); //blob地址
			// callback(base64, blobUrl, callback1);

			uni.getFileInfo({
				filePath: blobUrl,
				success: (res) => {
					let size = res.size
					let scale = 1
					if (size / 1024 / 1024 > 0.12) {
						scale = 0.6
						translate1(blobUrl, scale, 'blob', callback)
					} else {
						callback(base64, blobUrl)
					}
				},
				fail: (err) => {
					console.log("err:", err);
				}
			})
		}
	}
}


// base转Blob
export function base64ToBlob(base64) {
	var arr = base64.split(','),
		mime = arr[0].match(/:(.*?);/)[1],
		bstr = atob(arr[1]),
		n = bstr.length,
		u8arr = new Uint8Array(n);
	while (n--) {
		u8arr[n] = bstr.charCodeAt(n);
	}
	return new Blob([u8arr], {
		type: mime
	});
}

// base转url
export function base64ToUrl(base64) {
	var arr = base64.split(',')
	let blob = {}
	if (arr.length < 2) {
		const arrayBuffer = uni.base64ToArrayBuffer(base64);
		// 创建Blob对象
		blob = new Blob([arrayBuffer], {
			type: 'image/jpg'
		});
	} else {
		var mime = arr[0].match(/:(.*?);/)[1]
		var bstr = atob(arr[1])
		var n = bstr.length
		var u8arr = new Uint8Array(n);
		while (n--) {
			u8arr[n] = bstr.charCodeAt(n);
		}
		blob = new Blob([u8arr], {
			type: mime
		});
	}
	return URL.createObjectURL(blob);
}


// blob 转 base64
export function blobToDataURI(blob, callback) {
	var reader = new FileReader();
	reader.readAsDataURL(blob);
	reader.onload = function(e) {
		callback(e.target.result);
	};
}


// base64转File
export function base64toFilen(dataurl, filename = 'file') {
	let arr = dataurl.split(',')
	let mime = arr[0].match(/:(.*?);/)[1]
	let suffix = mime.split('/')[1]
	let bstr = atob(arr[1])
	let n = bstr.length
	let u8arr = new Uint8Array(n)
	while (n--) {
		u8arr[n] = bstr.charCodeAt(n)
	}
	return new File([u8arr], `${filename}.${suffix}`, {
		type: mime
	})
}


// File转blob
export function fileToBlob(file, callback) {
	var reader = new FileReader();

	// 当文件读取完毕后，reader.result就会包含文件的内容
	reader.onload = function(event) {
		// 在这里，event.target.result就是文件的blob形式
		var blob = new Blob([event.target.result], {
			type: file.type
		});

		// 接下来，你可以使用这个blob对象了，例如用它来创建一个URL
		var blobURL = URL.createObjectURL(blob);
		callback(blobURL)

	};

	// 以数据URL的形式读取文件
	reader.readAsArrayBuffer(file);
}