$(function () {
    setTimeout(uploaderInput,1000);
    function uploaderInput(){
        // 允许上传的图片类型
        var allowTypes = ['image/jpg', 'image/jpeg', 'image/png', 'image/gif'];
        var maxSize = 1024 * 1024*20; // 10240KB，也就是 10MB
        var maxWidth = 1900;  // 图片最大宽度
        //
        var $gallery = $("#gallery"),
            $galleryImg = $("#galleryImg"),
            $uploaderInput = $("#uploaderInput"),
            $uploaderFiles = $("#uploaderFiles");
        $uploaderInput.on("change",function (e) {
            files = e.target.files;
            // 如果没有选中文件，直接返回
            if (files.length === 0) {
                return;
            }
            for (var i = 0, len = files.length; i < len; ++i) {
                var file = files[i];
                var imgID = genGUID();
                var reader = new FileReader();
                var fileType = file.type;
                // 如果类型不在允许的类型范围内
                if (allowTypes.indexOf(file.type) === -1) {

                    $.toast('该类型不允许上传' + fileType);
                    continue;
                }

                if (file.size > maxSize) {
                    $.toast("图片太大，不允许上传");
                    continue;
                }

                // if ($('.weui-uploader__file').length >= maxCount) {
                //     $.toast('最多只能上传' + maxCount + '张图片', "forbidden");
                //     return;
                // }
                var base64;
                reader.onload = function (e) {
                    $.showLoading("上传中");
                    var img = new Image();
                    img.onload = function () {
                        // 不要超出最大宽度
                        var w = Math.min(maxWidth, img.width);
                        // 高度按比例计算
                        var h = img.height * (w / img.width);
                        var canvas = document.createElement('canvas');
                        var ctx = canvas.getContext('2d');
                        // 设置 canvas 的宽度和高度
                        canvas.width = w;
                        canvas.height = h;
                        ctx.drawImage(img, 0, 0, w, h);
                        base64 = canvas.toDataURL(fileType,0.6); //0.6指的是压缩60%
                        // 插入到预览区
                        // $uploaderFiles.find('.upload_imgs').before($(tmpl.replace('#url#', base64).replace('#ImgID#', imgID)));
                        // var num = $('.weui-uploader__file').length;
                        // $('#uploadCount').text(num);
                        // 模拟上传进度
                        // var progress = 0;
                        // function uploading() {
                        //     $uploaderFiles.find('.weui_uploader_status_content').text(++progress + '%');
                        //     if (progress < 100) {
                        //         setTimeout(uploading, 30);
                        //     } else {
                        //         $uploaderFiles.removeClass('weui_uploader_status').find('.weui_uploader_status_content').remove();//清除上传进度图标
                        //     }
                        // }
                        // setTimeout(uploading, 30);
                    };

                    img.src = e.target.result;
                    var FormDatas = new FormData();
                    FormDatas.append("file", file);
                    //这里实现上传
                    $.ajax({
                        url: uploadUrl,
                        type: 'POST',
                        data: FormDatas,
                        contentType: false,
                        processData: false,
                        success: function (res) {
                            if (res.code === '200') {
                                var str = `
                            <li class="weui-uploader__file" img-Url="${res.data.fullURL}" id="${imgID}" style="background-image:url(${base64})"><div class="weui_uploader_status_content">0%</div></li>`;
                                $uploaderFiles.find('.upload_imgs').before(str);
                                var num = $('.weui-uploader__file').length;
                                $('#uploadCount').text(num);
                                var progress = 0;
                                function uploading() {
                                    $uploaderFiles.find('.weui_uploader_status_content').text(++progress + '%');
                                    if (progress < 100) {
                                        setTimeout(uploading, 30);
                                    } else {
                                        $uploaderFiles.removeClass('weui_uploader_status').find('.weui_uploader_status_content').remove();//清除上传进度图标
                                        $.toast("上传成功")
                                        $.hideLoading();
                                    }
                                }
                                setTimeout(uploading, 30);
                            }else {
                                $.toast("上传失败",'forbidden');
                                $.hideLoading();
                            }
                        },
                        error:function () {
                            $.toast("上传失败,请检查网络！",'forbidden');
                            $.hideLoading();
                        }
                    })

                };
                reader.readAsDataURL(file);
            }
        });
        function genGUID() {
            var G1 = (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1) + (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
            var G2 = (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1) + (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
            return (G1 + G2);
        }
        var index; //第几张图片
        $uploaderFiles.on("click", ".weui-uploader__file", function () {
            index = $(this).index();
            $galleryImg.attr("style", this.getAttribute("style"));
            $gallery.fadeIn(100);
        });
        $gallery.on("click", function () {
            $gallery.fadeOut(100);
        });

        //删除图片
        $(".weui-gallery__del").click(function () {
            $uploaderFiles.find("li").eq(index).remove();
            var num = $('.weui-uploader__file').length;
            $('#uploadCount').text(num);
        });
    }
});