(function () {
    window.eku = window.eku || {
        /*
        id：指的是上传控件的名称
        hdid：上传后图片存放的隐藏控件名称,不填默认为“hd”+第一个参数（图片控件）的id
        filename：图片保存的文件夹名称 不填默认为“other”
        */
        UpPic: function(id, hdid, filename) {
            var imgQuality = 0.8;
            var imgMaxWidth = 800;
            hdid = hdid || "hd" + id;
            
            filename = filename || "other";
            var uImg = $('#' + id)
            var uHidden = $('#' + hdid)
            function uploadImg(formData) {
                console.log("uploadImg");
                jQuery.ajax({
                    type: 'POST',
                    url: '/Api/Common/UploadImg',
                    dataType: 'json',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function (res) {
                        if (res.error == 0) {
                            uImg.attr("src", res.url);
                            $('#' + hdid).val(res.url);
                        }
                        else {
                            layer.msg(res.message);
                        }
                    },
                    beforeSend: function () {
                        layer.load();
                    },
                    complete: function () {
                        layer.closeAll('loading');
                    }
                });
            }

            var uploadFileHtml = $("<input id='uploadFile" + id + "' type='file'  accept='image/*' name='file' style='display: none' >");
            var hideHtml = $("<input type='hidden' datatype='*' id='" + hdid + "' name='" + hdid + "' value=''>");
            uImg.after(hideHtml);
            uImg.after(uploadFileHtml);
            var uUploadFile = $("#uploadFile" + id);

            //data-src属性表示给控件初始赋值
            var imgInitSrc = $('#' + id).data("src");
            if (imgInitSrc) {
                $('#' + hdid).val(imgInitSrc);
                $('#' + id).attr("src", imgInitSrc);
            }
            uImg.click(function () {
                uUploadFile.click();
            });
            uUploadFile.on("change", function () {
                if ($(this).val() != "") {

                    var file = this.files[0];
                    var formData = new FormData();
                    formData.append("SaveFile", filename);

                    try {

                        if (file.size < 500 * 1024) {
                            formData.append(file.name, file, file.name);

                            uploadImg(formData);
                        }
                        else {
                            eku.photoCompress(file, { quality: imgQuality, maxWidth: imgMaxWidth },
                                function (base64Codes) {
                                    var bl = eku.convertBase64UrlToBlob(base64Codes);

                                    if (bl.size > file.size) {

                                        formData.append(file.name, file, file.name);
                                    }
                                    else {

                                        formData.append(file.name, bl, file.name);
                                    }
                                    uploadImg(formData);
                                });
                        }

                    } catch (e) {

                    }
                }
            });
        },
        vueUpload: function (file, filePath,successCallback,errorCallback) {
            function uploadImg(formData) {

                $.ajax({
                    type: 'POST',
                    url: '/Api/Common/UploadImg',
                    dataType: 'json',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function (res) {
                        if (res.error == 0) {
                            if (successCallback) {
                                successCallback(res.url);
                            }
                        }
                        else {
                            if (errorCallback) {
                                errorCallback(res.message);
                            }
                        }
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        errorCallback(textStatus);
                    },
                    beforeSend: function () {
                    },
                    complete: function () {
                    }
                });
            }

            var formData = new FormData();
            formData.append("SaveFile", filePath);
            try {
                if (file.size < 500 * 1024) {
                    formData.append(file.name, file, file.name);
                    uploadImg(formData);
                }
                else {
                    var imgQuality = 0.8;
                    var imgMaxWidth = 800;
                    eku.photoCompress(file, { quality: imgQuality, maxWidth: imgMaxWidth },
                        function (base64Codes) {
                            var bl = eku.convertBase64UrlToBlob(base64Codes);
                            if (bl.size > file.size) {

                                formData.append(file.name, file, file.name);
                            }
                            else {
                                formData.append(file.name, bl, file.name);
                            }
                            uploadImg(formData);
                        });
                }

            } catch (e) {
                console.log(e);
            }

        },

        getImgResize: function(img, opts) {
            var imgWidth = img.naturalWidth, imgHeight = img.naturalHeight,
                width = opts.width, height = opts.height,
                maxWidth = opts.maxWidth, maxHeight = opts.maxHeight;
            if (width && !height) {
                height = (imgHeight * width / imgWidth) << 0;
            } else if (height && !width) {
                width = (imgWidth * height / imgHeight) << 0;
            } else {
                width = imgWidth;
                height = imgHeight;
            }
            if (maxWidth && width > maxWidth) {
                width = maxWidth;
                height = (imgHeight * width / imgWidth) << 0;
            }
            if (maxHeight && height > maxHeight) {
                height = maxHeight;
                width = (imgWidth * height / imgHeight) << 0;
            }
            opts.width = width;
            opts.height = height;
        },
        photoCompress: function(file, w, objDiv) {
            var ready = new FileReader();
            /*开始读取指定的Blob对象或File对象中的内容. 
            当读取操作完成时,readyState属性的值会成为DONE,
            如果设置了onloadend事件处理程序,则调用之.
            同时,result属性中将包含一个data: URL格式的字符串以表示所读取文件的内容.*/
            ready.readAsDataURL(file);
            ready.onload = function () {
                var re = this.result;
                eku.canvasDataURL(re, w, objDiv);
            }
        },
        canvasDataURL: function(path, obj, callback) {
            var img = new Image();
            img.src = path;
            img.onload = function () {
                var that = this;
                // 默认按比例压缩
                var w = that.width,
                    h = that.height,
                    scale = w / h;
                w = obj.width || w;
                h = obj.height || (w / scale);

                jQuery.getScript("/Scripts/Public/exif.js", function () {
                    //生成canvas
                    EXIF.getData(img, function () {
                        var defaults = {
                            width: null,
                            height: null,
                            maxWidth: obj.maxWidth || 800,
                            quality: obj.quality || 0.8 // 默认图片质量为0.8
                        };
                        var orientation = EXIF.getTag(this, "Orientation");

                        eku.getImgResize(img, defaults);
                        var cvs = document.createElement('canvas');

                        if ("5678".indexOf(orientation) > -1) {
                            cvs.width = defaults.height;
                            cvs.height = defaults.width;
                        } else {
                            cvs.width = defaults.width;
                            cvs.height = defaults.height;
                        }
                        var ctx = cvs.getContext('2d');
                        if (!ctx) {
                            throw new Error('浏览器不支持canvas，请更换最新的360或QQ浏览器');
                        }
                        //设置为白色背景，jpg是不支持透明的，所以会被默认为canvas默认的黑色背景
                        ctx.fillStyle = "#fff";
                        ctx.fillRect(0, 0, cvs.width, cvs.height);

                        // 调整为正确方向
                        switch (orientation) {
                            case 3:
                                ctx.rotate(180 * Math.PI / 180);
                                ctx.drawImage(img, -cvs.width, -cvs.height, cvs.width, cvs.height);
                                break;
                            case 6:
                                ctx.rotate(90 * Math.PI / 180);
                                ctx.drawImage(img, 0, -cvs.width, cvs.height, cvs.width);
                                break;
                            case 8:
                                ctx.rotate(270 * Math.PI / 180);
                                ctx.drawImage(img, -cvs.height, 0, cvs.height, cvs.width);
                                break;

                            case 2:
                                ctx.translate(cvs.width, 0);
                                ctx.scale(-1, 1);
                                ctx.drawImage(img, 0, 0, cvs.width, cvs.height);
                                break;
                            case 4:
                                ctx.translate(cvs.width, 0);
                                ctx.scale(-1, 1);
                                ctx.rotate(180 * Math.PI / 180);
                                ctx.drawImage(img, -cvs.width, -cvs.height, cvs.width, cvs.height);
                                break;
                            case 5:
                                ctx.translate(cvs.width, 0);
                                ctx.scale(-1, 1);
                                ctx.rotate(90 * Math.PI / 180);
                                ctx.drawImage(img, 0, -cvs.width, cvs.height, cvs.width);
                                break;
                            case 7:
                                ctx.translate(cvs.width, 0);
                                ctx.scale(-1, 1);
                                ctx.rotate(270 * Math.PI / 180);
                                ctx.drawImage(img, -cvs.height, 0, cvs.height, cvs.width);
                                break;

                            default:
                                ctx.drawImage(img, 0, 0, cvs.width, cvs.height);
                        }


                        var base64Data = cvs.toDataURL('image/jpeg', defaults.quality);
                        // 回调函数返回base64的值
                        callback(base64Data);
                    });
                });
            }
        },
        convertBase64UrlToBlob: function(dataURI) {
            var byteString;
            if (dataURI.split(',')[0].indexOf('base64') >= 0)
                byteString = atob(dataURI.split(',')[1]);
            else
                byteString = unescape(dataURI.split(',')[1]);

            // separate out the mime component
            var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

            // write the bytes of the string to a typed array
            var ia = new Uint8Array(byteString.length);
            for (var i = 0; i < byteString.length; i++) {
                ia[i] = byteString.charCodeAt(i);
            }

            return new Blob([ia], { type: mimeString });
        }
    };

    $('img[data-ekutype="upload"]').each(function () {
        eku.UpPic($(this).attr('id'), $(this).data('hdid'), $(this).data('filepath'));
    });

})(window, jQuery);

