/**
 * [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.02.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 = 1; //可选图片1张
        
        this.i_localId = ''; //手机本地图片
        this.i_serverId = ''; //已上传到微信端图片
        
        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.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.input_name = $(this).attr("data-name");
                    if (typeof(_this.input_name) == 'undefined') {
                        _this.input_name = '';
                    }
                    _this.input_module = $(this).attr("data-module");
                    if (typeof(_this.input_module) == 'undefined') {
                        _this.input_module = '';
                    }
                    _this.input_thumb = $(this).attr("data-thumb");
                    if (typeof(_this.input_thumb) == 'undefined') {
                        _this.input_thumb = '';
                    }
                    _this.input_forbidcom = $(this).attr("data-forbidcom");
                    if (typeof(_this.input_forbidcom) == 'undefined') {
                        _this.input_forbidcom = '';
                    }
                    _this.input_forbidwater = $(this).attr("data-forbidwater");
                    if (typeof(_this.input_forbidwater) == 'undefined') {
                        _this.input_forbidwater = '';
                    }
                    _this.input_forbid_tip = $(this).attr("data-forbidtip");
                    if (typeof(_this.input_forbidwater) == 'undefined') {
                        _this.input_forbidwater = '';
                    }
                    
                    //回调
                    _this._callback = $(this).attr("data-callback");
                    if (typeof(_this._callback) == 'undefined') {
                        _this._callback = '';
                    }
                
                    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.uploadImage();
                            }
                        }
                    });
                });
            });
            
        },
        
        //执行上传
        uploadImage:function() {
            var _this = this;
            
            wx.chooseImage({
                count:_this.wx_choose_count, //可选择张数
                sizeType: ['original', 'compressed'], //尺寸 默认为原图和压缩
                sourceType: ['album', 'camera'], //资源类型 可选相册和拍照
                
                success: function(data) {
                    _this.i_localId = data.localIds[0];
                    if (typeof(_this.i_localId) == 'undefined') {
                        _this.i_localId = '';
                    }
                    if (_this.i_localId.length == 0 || _this.i_localId == '') {
                        OEUI.toast({
                            type: 'bottom', 
                            text: '请选择照片'
                        });
                        return;
                    }
                    
                    //发送
                    wx.uploadImage({
                        localId: _this.i_localId,
                        success: function(res) {
                            _this.i_serverId = res.serverId; //上传到微信端，保存返回的server_id
                            if (_this.i_serverId.length > 0 || _this.i_serverId != '') {
                                
                                var loading = null;
                                var timer = setTimeout(function () {
                                    loading = OEUI.showLoading({
                                        type:2
                                    });
                                }, 200);
                                
                                //下载微信端图片
                                $.ajax({
                                    type: "POST",
                                    url: _this.api_urlpath,
                                    cache: false,
                                    data: {
                                        a:"getwximage", mediaid:_this.i_serverId,
                                        module:_this.input_module, thumb:_this.input_thumb, 
                                        forbidcom:_this.input_forbidcom, forbidwater:_this.input_forbidwater
                                    },
                                    dataType: "json",
                                    success: function($data) {
                                        
                                        clearTimeout(timer);
                                        time = null;
                                        loading && loading.hideLoading();
                                        
                                        var $json = eval($data);
                                        var $response = $json.response;
                                        var $result = $json.result;
                                        
                                        if ($response == '1') {
                                            if (_this.input_forbid_tip != '1') {
                                                OEUI.toast({
                                                    type: 'bottom', 
                                                    text: '上传成功'
                                                });
                                            }
                            
                                            //图片
                                            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();
                                                    }
                                                }
                                            }
                                            
                                            _oeloveFileSynYun($attid); //同步云存储
                                            //回调
                                            if (_this._callback && _this._callback != '') {
                                                //var $callback = eval(_this._callback);
                                                if (typeof(window[_this._callback]) == 'function') {
                                                    window[_this._callback]($json);
                                                }
                                            }
                                        }
                                        else {
                                            if ($result.length == 0 || $result == '') {
                                                $result = '上传失败，请检查';
                                            }
                                            OEUI.toast({
                                                type: 'bottom',
                                                text: $result
                                            });
                                        }
                                        
                                    },
                                    error: function() {
                                        clearTimeout(timer);
                                        time = null;
                                        loading && loading.hideLoading();
                                        OEUI.toast({
                                            type: 'bottom',
                                            text: '下载微信图片失败，请检查！'
                                        });
                                    }
                                });
                            }
                        },
                        fail: function(res) {
                            if (_this.wx_debug == true) {
                                alert(JSON.stringify(res));
                            }
                        }
                    });   
                }
            });
        }
        
        
    }
    
    _inst_wx_upload = new OEWxUpload();
});