
var ImageUtil = window.ImageUtil || {};  
ImageUtil.imageUtil =  
{  

    compression:function(targetResult) {
        let image = new Image(); //新建一个img标签（还没嵌入DOM节点)
        image.src = targetResult;

        var imageQuality = localStorage.getItem("imageQuality");

        var imageWidth, imageHeight;
        if(imageQuality == 1){
            // 1080P  1920*1080
            imageWidth = 1920;
            imageHeight = 1080;
        }else if(imageQuality == 2){
            // 720P 1280x720
            imageWidth = 1280;
            imageHeight = 720;
        }else{
            imageWidth = 1024;
            imageHeight = 768;
        }
                            
        return new Promise(function(resolve, reject) {
            image.onload = function () {
                let canvas = document.createElement('canvas');
                let context = canvas.getContext('2d');
                let data = '';
                
            
                if(image.width > imageWidth || image.height > imageHeight){
                    canvas.width = imageWidth;
                    canvas.height = imageHeight;
                    context.drawImage(image, 0, 0, imageWidth, imageHeight);
                }else{
                    canvas.width = image.width;
                    canvas.height = image.height;
                    context.drawImage(image, 0, 0, image.width, image.height);
                }
        
                data = canvas.toDataURL('image/jpeg');
                resolve(data);
            }

            image.onerror = function(){
                reject();
            }
        });
    },

    /**
     * DataURL转Png Blob对象
     */
    sussesDataToPngBlob:function (dataurl) {
            const arr = dataurl.split(',');
            const bstr = atob(arr[1]);
            let n = bstr.length;
            const u8arr = new Uint8Array(n);
            while (n--) {
            u8arr[n] = bstr.charCodeAt(n);
            }
            return new Blob([u8arr], {
            type: 'image/png'
            });
    },

    /**
     * stockInResult and stockOutResult 文件上传图片至服务器
     * @param file 图片文件
     * @param className 类名
     */
    uploadStockResultImage:function (file,className) {
        const _self = this;
        // 获取图片的base64
        const imgReader = new FileReader();
        const promise = new Promise(function (resolve, reject) {
            imgReader.onload = function (evt) {
                if (!/image\/\w+/.test(file.type)) {
                    reject(new Error('请确认您选择的文件为图片类型。'));
                    return;
                }
                const eImgBase64 = evt.target.result; // 给eImgBase64赋值
                if (eImgBase64 != null) {
                   _self.compression(eImgBase64).then(function (successData) {
                        if (successData == undefined) {
                            return;
                        }
                        // 把图片上传到服务器
                        const formData = new FormData();
                        const uuid = Loading.loading.show();
                        formData.append('className', className);
                        const nameImg = new Date().getTime() + '.png';
                        const blobImg = _self.sussesDataToPngBlob(successData);
                        formData.append('uploadImage', blobImg, nameImg);
                        $.ajax({
                            url: Common.getApiURL('file/imageUpload'),
                            type: 'post',
                            beforeSend: function (request) {
                                Common.addTokenToRequest(request);
                            },
                            data: formData,
                            contentType: false,
                            processData: false,
                            success: function (data) {
                                Loading.loading.hide(uuid);
                                if (data.indexOf('success') >= 0) {
                                    const imageName = data.substring(data.indexOf(':') + 1);
                                    resolve(imageName);
                                } else {
                                    reject(new Error('图片上传失败，' + data));
                                }
                            },
                            error: function (XMLHttpRequest, textStatus, errorThrown) {
                                Loading.loading.hide(uuid);
                                reject(new Error(XMLHttpRequest.statusText));
                            }
                        });
                    }, function (errorData) {
                        console.log(errorData);
                        reject(new Error('图片压缩失败，' + errorData));
                    });
                }
            };
        });

        imgReader.readAsDataURL(file);

        return promise;
    }

}
