/*
 *公共方法 
 *图片处理
 *
 *
 */

let ImageUtil = {
    reg:/image\/[jpg|png|gif]/i,
    //压缩
    canvasDataURL:(path, obj,callback)=>{
        let canvasSize = obj.canvasSize || 800 ;//画布大小
        var img = new Image();
        img.src = path;
        img.onload = function() {
            var that = this;
            // 默认按比例压缩
            var w = that.width,
                h = that.height,
                scale = w / h;
            if (w > h && w > canvasSize) {
                w = canvasSize;
                h = canvasSize / scale;
            } else if (w < h && h > canvasSize) {
                h = canvasSize;
                w = canvasSize * scale;
            }

            var quality = 0.9; // 默认图片质量为0.9
            //生成canvas
            var canvas = document.createElement("canvas");
            var ctx = canvas.getContext("2d");
            // 创建属性节点
            var anw = document.createAttribute("width");
            anw.nodeValue = w;
            var anh = document.createAttribute("height");
            anh.nodeValue = h;
            canvas.setAttributeNode(anw);
            canvas.setAttributeNode(anh);
            ctx.drawImage(that, 0, 0, w, h);
            // 图像质量
            if (obj.quality && obj.quality <= 1 && obj.quality > 0) {
                quality = obj.quality;
            }
            // quality值越小，所绘制出的图像越模糊
            var base64 = canvas.toDataURL("image/jpeg", quality);
            // 回调函数返回base64的值
            callback(base64);
        };
    },
    //调用压缩
    photoCompress:function(file, w){
        let _this = this;
        return new Promise(resolve => {
            var ready = new FileReader();
            /*开始读取指定的Blob对象或File对象中的内容. 当读取操作完成时,readyState属性的值会成为DONE,如果设置了onloadend事件处理程序,则调用之.同时,result属性中将包含一个data: URL格式的字符串以表示所读取文件的内容.*/
            ready.onload = function() {
                var re = this.result;
                _this.canvasDataURL(re, w, base64 => {
                    resolve(base64);
                });
            };
            ready.readAsDataURL(file);
        });
    },
    //压缩后的base64 转回file格式 用于上传。。。
    convertBase64UrlToFile:function(urlData,filename){
        var arr = urlData.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 File([u8arr],filename, { type: mime });
    },
    //将超过限制的图片  循环调用压缩图片
    compressPromis :function(sourcefiles,maxSize,canvasSize){
        console.log(sourcefiles)
        let userAgent = navigator.userAgent
        let isIE11 = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1; // ie11<11
       
        let resFileArr = []
        let len = sourcefiles.length;
        return new Promise((resolve, reject) => {
            let promiseList = [];
            for(let i = 0 ; i<len;i++){
                let file = sourcefiles[i].file;
                console.log(file)
                if(file && file.size > maxSize * 1024 && !isIE11){
                    let promise = new Promise((_resolve, _reject) => {
                        this.photoCompress(file, { quality: 0.5 , canvasSize:canvasSize}).then(base64 => {
                            let compressFile = this.convertBase64UrlToFile(base64,file.name);
                            _resolve(compressFile);
                        });
                    });
                    promiseList.push(promise);
                }
                
            }
            //压缩所有图片后回调
            Promise.all(promiseList).then(values => {
                console.log(values)
                resolve(values);
            });
        })
    },
    //页面触发 传入file 图片大小限制 压缩画布大小
    handleChangeMasterImg:function(sourcefiles,maxSize,canvasSize,callback){
        console.log("sourcefiles",sourcefiles)
        let userAgent = navigator.userAgent
        let isIE11 = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1; // ie11<11
   
       this.compressPromis(sourcefiles,maxSize,canvasSize).then(res => {
        console.log(res)
            let resArr = res || []
            let len = sourcefiles.length;
            for(let i = 0 ; i<len;i++){
                let file = sourcefiles[i].file;
                console.log(file.size,maxSize * 1024)
                if(file.size <= maxSize * 1024){
                    resArr.push(file)
                }
            }
            console.log(resArr)
            callback(resArr)
        });
    }

}

export {
    ImageUtil
};