/**
 * [OElove] (C)2010-2099 oelove.com Inc.biz
 * Email: service@phpcoo.com，phpcoo@qq.com
 * This is not a freeware, use is subject to license terms
 * $ LastTime 2020.04.17 Update by OE/CL $
*/
var _inst_wx_upload = null; //微信公众号上传图片
$(function () {
    //微信上传类
    function OEWxUpload () {
        this.wx_appid = ''; //JSAPI
        this.wx_timestamp = ''; //JSAPI timestamp 时间戳
        this.wx_noncestr = ''; //JSAPI nonceStr 签名随机符
        this.wx_signature = ''; //JSAPI signature 签名
        this.wx_jsApiList = ["chooseImage", "previewImage", "uploadImage", "downloadImage"]; //JSAPI权限
        this.wx_debug = false; //是否开启调试
        
        this.wx_choose_count = 9; //可选图片9张
        this.can_upload_nums = 0; //可上传数量
        this.max_select_nums = 0; //最多可选数量 
        
        this.localIds = []; //手机本地图片
        
        this.input_module = ''; //模块 如头像、LOGO，图集等不同的模块对应的不同的api_url
        this.input_name = ''; //图片预览name
        this._callback = ''; //回调
        this.input_thumb = ''; //是否生成缩略图
        this.input_forbidcom = ''; //是否禁止压缩
        this.input_forbidwater = ''; //是否禁止生成水印
        this.input_forbid_tip = ''; //是否禁止弹出上传成功提示
        this.api_urlpath = _ROOT_PATH+"index.php?m=wap&c=wxapi";

        this.attid = []; 
        this.tip_num = 0; //上传总数量
        this.download_num = 0; //从微信服务器下载的数量
        
        this.getWxJsToken(); //初始化
    }
    OEWxUpload.prototype = {
        //获取微信js token
        getWxJsToken:function() {
            var _this = this;
            var $local_page_url =  window.location.href; //获取当前url
            
            $.ajax({
                type: "POST",
                url: _this.api_urlpath,
                cache: false,
                data: {
                    a:"getwxjstoken", page_url:$local_page_url
                },
                dataType: "json",
                success: function($data) {
                    var $json = eval($data);
                    var $response = $json.response;
                    var $result = $json.result;
                    if ($response == 1) {
                        _this.wx_appid = $result.appid;
                        _this.wx_timestamp = $result.timestamp;
                        _this.wx_noncestr = $result.noncestr;
                        _this.wx_signature = $result.signature;
                        
                        //初始化微信
                        wx.config({
                            debug: _this.wx_debug, //调试模式
                            appId: _this.wx_appid, //公众号
                            timestamp: _this.wx_timestamp, //时间戳
                            nonceStr: _this.wx_noncestr, //签名随机符
                            signature: _this.wx_signature,//签名
                            jsApiList: _this.wx_jsApiList //可用的jsapi
                        });
                        _this.wakeReady(); //唤醒操作按钮
                        wx.error(function (res) {
                            if (_this.wx_debug == true) {
                                alert(JSON.stringify(res));
                            }
                　　　　});
                    }
                    else {
                        if (_this.wx_debug == true) {
                            OEUI.toast({
                                type: 'bottom', 
                                text: '获取微信jsapi token 错误'
                            });
                        }
                    }
                },
                error: function() {
                    if (_this.wx_debug == true) {
                        OEUI.toast({
                            type: 'bottom', 
                            text: '网络繁忙，请稍后再试'
                        });
                    }
                }
            });
        },
        //唤醒
        wakeReady:function() {
            var _this = this;
            
            wx.ready(function () {
                //点击上传按钮
                $(document).on("click", "[f='but_upload_wximage']", function(){
                    if (_this.wx_appid == '') {
                        OEUI.toast({
                            type: 'bottom', 
                            text: '微信公众号无法使用上传操作，请联系管理员处理。'
                        });
                        return;
                    }
                    //校验数量
                    _this.can_upload_nums = parseInt($("#remain_photos").val());
                    if (_this.can_upload_nums == 0){
                        if (_inst_photo) {
                            _inst_photo.openVipDialog();
                        }
                        else {
                            OEUI.toast({
                                type: 'bottom',
                                text: '相册已满，请升级VIP'
                            }); 
                        }
                        return;
                    }
                    if (_this.can_upload_nums > 9) {
                        _this.max_select_nums = 9;
                    }
                    else {
                        _this.max_select_nums = _this.can_upload_nums;
                    }
                    _this.wx_choose_count = _this.max_select_nums;
                    
                    _this.getProp($(this));
                    wx.checkJsApi({
                        jsApiList: _this.wx_jsApiList,
                        success: function (res) {
                            //alert(JSON.stringify(res));
                            //alert(JSON.stringify(res.checkResult.getLocation));
                            if (res.checkResult.getLocation == false) {
                                alert('你的微信版本太低，请升级到最新的微信版本！');
                                return;
                            }
                            else{
                                _this.chooseImage();
                            }
                        }
                    });
                });
            });
        },
        //获取参数
        getProp: function (el) {
            var _this = this;
            //接收参数
            _this.input_name = el.attr("data-name");
            if (typeof(_this.input_name) == 'undefined') {
                _this.input_name = '';
            }
            _this.input_module = el.attr("data-module");
            if (typeof(_this.input_module) == 'undefined') {
                _this.input_module = '';
            }
            _this.input_thumb = el.attr("data-thumb");
            if (typeof(_this.input_thumb) == 'undefined') {
                _this.input_thumb = '';
            }
            _this.input_forbidcom = el.attr("data-forbidcom");
            if (typeof(_this.input_forbidcom) == 'undefined') {
                _this.input_forbidcom = '';
            }
            _this.input_forbidwater = el.attr("data-forbidwater");
            if (typeof(_this.input_forbidwater) == 'undefined') {
                _this.input_forbidwater = '';
            }
            _this.input_forbid_tip = el.attr("data-forbidtip");
            if (typeof(_this.input_forbidwater) == 'undefined') {
                _this.input_forbidwater = '';
            }
            
            //回调
            _this._callback = el.attr("data-callback");
            if (typeof(_this._callback) == 'undefined') {
                _this._callback = '';
            }
        },
        //选择图片
        chooseImage:function() {
            var _this = this;
            
            wx.chooseImage({
                count:_this.wx_choose_count, //可选择张数
                sizeType: ['original', 'compressed'], //尺寸 默认为原图和压缩
                sourceType: ['album', 'camera'], //资源类型 可选相册和拍照
                
                success: function(data) {
                    _this.localIds = data.localIds;
                    if (_this.localIds.length == 0) {
                        OEUI.toast({
                            type: 'bottom', 
                            text: '请选择照片'
                        });
                        return;
                    }

                    //弹窗进度条
                    $("#up_progress").show();
                    $("#order_i").html(0);
                    $("#order_nums").html(_this.localIds.length);
                    _this.tip_num = _this.localIds.length;
                    _this.download_num = 0;
                    _this.uploadImage();
                }
            });
        },
        //执行上传
        uploadImage: function () {
            var _this = this;
            //发送
            if(_this.localIds.length == 0) {
                $("#order_i").html(_this.tip_num - _this.localIds.length);
                return;
            }
            var i_localId = _this.localIds.pop();
            wx.uploadImage({
                localId: i_localId,
                success: function(res) {
                    var i_serverId = res.serverId; //上传到微信端，保存返回的server_id
                    if (i_serverId.length > 0 || i_serverId != '') {
                      _this.uploadImage(); 
                      $("#order_i").html(_this.tip_num - _this.localIds.length);
                      _this.downloadImage(i_serverId).then(function (data) {
                          _this.render(data);
                          _oeloveFileSynYun(data.attid); //同步云存储

                          _this.attid.push(data.attid);
                          _this.download_num++
                          if(_this.download_num >= _this.tip_num) {
                              _this.sendAdd(_this.attid.join(','));
                          }
                      }).catch(function (res) {
                          $("#up_progress").hide();
                          if(res) {
                              OEUI.toast({
                                  text: res
                              });
                          } else {
                              OEUI.toast({
                                  text: '上传失败'
                              });
                          }
                          setTimeout(function () {
                              location.reload();
                          }, 800);
                      });
                    }
                },
                fail: function(res) {
                    if (_this.wx_debug == true) {
                        alert(JSON.stringify(res));
                    }
                }
            });
            
        },
        //下载微信端图片
        downloadImage: function (i_serverId) {
            var _this = this;
            return new Promise(function (resolve, reject) {
                $.ajax({
                    type: "POST",
                    url: _this.api_urlpath,
                    cache: false,
                    data: {
                        a:"getwximage", mediaid: i_serverId,
                        module:_this.input_module, thumb:_this.input_thumb, 
                        forbidcom:_this.input_forbidcom, forbidwater:_this.input_forbidwater
                    },
                    dataType: "json",
                    success: function($data) {
                        var $json = eval($data);
                        var $response = $json.response;
                        var $result = $json.result;
                        if ($response == '1') {
                            resolve($json);
                        } else {
                            reject($result);
                        }
                    },
                    error: function() {
                        reject();
                    }
                });
            })
        },
        //渲染图片到页面
        render: function ($json) {
            var _this = this;
            //图片
            var $thumbimg = $json.thumbimg;
            var $drawimg = $json.drawimg;
            var $base64img = $json.base64img;
            if (typeof($base64img) == 'undefined') {
                $base64img = '';
            }
            var $attid = $json.attid;
            if (typeof($attid) == "undefined") {
                $attid = "";
            }
            var $imgwidth = $json.imgwidth;
            if (typeof($imgwidth) == 'undefined') {
                $imgwidth = '0';
            }
            var $imgheight = $json.imgheight;
            if (typeof($imgheight) == 'undefined') {
                $imgheight = '0';
            }
            
            if (_this.input_name != '') {
                if ($("#"+_this.input_name+"_thumb").length > 0) {
                    $("#"+_this.input_name+"_thumb").val($thumbimg);
                }
                if ($("#"+_this.input_name+"_url").length > 0) {
                    $("#"+_this.input_name+"_url").val($drawimg);
                }
                
                if (_this.module != 'tmp') {
                    if ($("#"+_this.input_name+"_preview").length > 0) {
                        $img = _ROOT_PATH+$drawimg+"?r="+new Date().getTime();
                        $("#"+_this.input_name+"_preview").attr("src", $img);
                        $("#"+_this.input_name+"_preview").show();
                    }
                }
            }
        },
        //发送保存
        sendAdd:function($attids) {
            var _this = this;
            $.ajax({
                type: 'POST',
                url: WAP_APPFILE+'&c=photo',
                data: {
                    a:'saveadd', 'ids':$attids
                },
                dataType: "json",
                success: function($data) {
                    $("#up_progress").hide();
                    var $json = eval($data);
                    var $response = $json.response;
                    var $result = $json.result;
                    if ($response == '1') {
                        OEUI.toast({
                            type: 'bottom',
                            text: '上传完成'
                        });
                        setTimeout(function () {
                            location.reload();
                        }, 800);
                    }
                    else if ($response == '2') {
                        OEUI.toast({
                            type: 'bottom',
                            text: '上传完成，请等待审核'
                        });
                        setTimeout(function () {
                            location.reload();
                        }, 800);
                    }
                    else {
                        if ($result.length == 0 || $result == '') {
                            $result = '上传失败，请检查';
                        }
                        OEUI.toast({
                            type: 'bottom',
                            text: $result
                        }); 
                    }
                },
                error: function () {
                    $("#up_progress").hide();
                    OEUI.toast({
                        type: 'bottom',
                        text: '网络繁忙，请稍后再试！'
                    });
                }
            });
        },
    }
    _inst_wx_upload = new OEWxUpload();
});