export default {

	maxSize: 500,
	compress:function (file,src:HTMLImageElement | string,base64:boolean=false,useInt:boolean=true,obj:Record<string, any> | undefined = undefined,maxSize:number = 500) {
		return new Promise((resolve, reject)=>{

			if (typeof src === 'string') {
				let image:HTMLImageElement = document.createElement('img');

				image.src = src;

				image.onload = () => {
					if (obj === undefined) {
						obj = {
							width: image.offsetWidth,
							height: image.offsetHeight
						}
					}
					image.parentNode.removeChild(image);
					return this.compressTrigger(file,image,base64,useInt,obj,maxSize,resolve,reject);
				}

				image.onerror = ()=>{
					image.parentNode.removeChild(image);
					return  reject();
				};

				image.setAttribute('style','position:absolute;z-index:-9;top:0;left:0;opacity:0;visibility: hidden;');

				document.body.appendChild(image);

			} else {

				if (obj === undefined) {
					obj = {
						width: src.offsetWidth,
						height: src.offsetHeight
					}
				}

				this.compressTrigger(file,src,base64,useInt,obj,maxSize,resolve,reject);
			}



		});
	},

	compressTrigger(file,image,base64,useInt,obj,maxSize,resolve,reject){

		maxSize = maxSize || this.maxSize;

		// 判断是否需要压缩
		if (obj.width > maxSize) {
			/* 统计尺寸 */
			let width = obj.width;
			let height = obj.height;
			// 计算 宽度 是 高度的多少倍
			let radio = width / height;

			// 设置 压缩后的高度
			height -= (width - this.maxSize) / radio;
			// 设置 压缩后的宽度
			width = this.maxSize;

			// 执行格式化
			width = useInt ? parseInt(width) : width;
			height = useInt ? parseInt(height) : height;

			// 创建画布
			let canvas = document.createElement("canvas");
			// 设置画布的宽高
			canvas.width = width;
			canvas.height = height;

			// 创建 2D 的画布
			let canvas2D = canvas.getContext('2d');
			// 绘制图片
			canvas2D.drawImage(image,0,0,width,height);

			// 导出图片
			if (base64) {
				let exportImage = canvas.toDataURL(file.type, 0.7);
				// 执行成功函数
				return resolve({
					path: exportImage,
					width,
					height
				});
			} else {
				return canvas.toBlob((file)=>{

					if (file) {

						file = new File([file],'name.'+ file.type.split('/').pop(),{
							type:file.type
						})

						return resolve({
							file,
							width,
							height
						});
					} else {
						return reject();
					}

				},file.type,0.7);
			}


		} else {
			return reject();
		}
	}

}
