/**
1.安装apidoc，参考链接：
	http://apidocjs.com
2.按照格式弄好后，执行命令
    apidoc -i ./apiTest/assets/Sdk -o api/
    
    在小程序后台添加合法域名：
        https://game.llewan.com:1899
        https://login.llewan.com:1799
        https://log.llewan.com:1999
        https://res.llewan.com:2099

        https://glog.aldwx.com
 */

var md5 = require("md5");
var sdk_conf = require("sdk_conf");


var sdk = { 
    md5: md5,
    ip1: "https://login.llewan.com:1799",
    ip2: "https://game.llewan.com:1899",
    ip3: "https://log.llewan.com:1999",
    ip4: "https://res.llewan.com:2099",
    
    loginBg: "https://res.g.llewan.com/uploadfile/common/20180831/20180831173032_3279.png",
    loginBt: "https://res.g.llewan.com/uploadfile/common/20180831/20180831180006_1583.png",

    debug: false,//是否开启调试

    login: '/Login/common',
    modify: '/Login/modify',
    Config: '/Config/common',
    //游戏数据存储/获取
    set: "/game/set",
    get: "/game/get",
    time: "/game/time",
   

    ConfigData: { 
        "config1": {},
        "config2": {},
        "config3": {},
        "config4": {},
    },
    Share: "/Share/common",
    ShareList: [],
    Logcommon: "/Log/common",

    BannerAd: null,
    VideoAd: null,

    //.即将废弃，请不要操作此变量。
    userid: 0,
    initFlag:0,

    //视频成功回调 
    videoSuccess:null,
    //视频失败回调 
    videoFail:null,

    //视频失败回调 
    videoError:null,

    isGameStart:false,
    gameOnlineKey:"游戏在线",

    shareCancelCallback:false,
    
    shareStartTime:-1,
    shareInfo:null,

    /**
     * @apiGroup A
     * @apiName init
     * 从v1.006版本的sdk已经废弃改方法,只需要调用sdk.WeChatLogin方法就可以了
     * 
     * sdk.WeChatLogin((d)=>{
     *      var config1 = sdk.getConfig1();
     *      if(config1.hz2==1)
     *      {
     *          //显示
     *          xxx.active = true;
     *          xxx.addClickListener(() => {
     *              var d = sdk.getButtonConfig('hz2');
     *              //跳转到对应的小程序或者游戏
     *              sdk.navigateToMiniProgram(d);
     *          });
     *      }else
     *      {
     *          //隐藏
     *      }
     * 
     * });
     */
    init(args, callback){
        var self = this;
    
        if(!self.ip1)
        {
            console.error("sdk 请调用WechatLogin!");
            wx.showToast({title: '请先登录',icon:'loading',duration: 8});
            return;
        }
        if(args.debug){
            this.debug = args.debug;
        }
        if(args.userid){
            this.userid = args.userid;
        }
        
        this.checkUpdate();
        
        if (cc.sys.platform === cc.sys.WECHAT_GAME) {
            //1.初始化后台配置信息
            this.Post(this.ip2 + this.Config, {}, function (d) {
                if (d && d.c == 1) {
                    self.ConfigData = d.d;
                    
                    //2.初始化分享信息
                    self.Post(self.ip2 + self.Share, {}, function (d2) {
                        // console.log("初始化分享信息：",d2)
                        if (d2 && d2.c == 1) {
                            self.ShareList = d2.d;
                        }else{
                            console.log("sdk 初始化分享信息失败：",d2)
                        }
                        callback(true);
                    });
                }else{
                    if(self.debug){
                        console.log("sdk 后台配置信息初始化失败,再次初始化：",d)
                    }
                    self.init(args, callback);
                   // return;
                }
            });
            
 
            //为了方便技术在浏览器中调试
            this.setWeChatListener();


        }
        
        
    },
    /**
     * @apiGroup C
     * @apiName WeChatLogin
     * @api {新增、授权、登陆} 微信登录 WeChatLogin 对外提供新增、授权、登陆调用以及初始化
     * 注意v1.006版本sdk 只需要调用登录就可以了不在需要调用init了，sdk内部已经做了init操作了
     * 
     * @apiSuccessExample {json} 示例:
     * sdk.WeChatLogin((d)=>{
     *      var config1 = sdk.getConfig1();
     *      if(config1.hz2==1)
     *      {
     *          //显示
     *          xxx.active = true;
     *  
     *          xxx.addClickListener(() => {
     *              var d = sdk.getButtonConfig('hz2');
     *              //跳转到对应的小程序或者游戏
     *              sdk.navigateToMiniProgram(d);
     *          });
     *      }else
     *      {
     *          //隐藏
     *      }
     * 
     * });
     * 
     */
    WeChatLogin(callback){

        //根据sdk_conf初始化api
        this.init_api();
        var self = this;
        if (cc.sys.platform === cc.sys.WECHAT_GAME) {
       
            var userinfo = this.getUser();

            var wxauth = this.getItem("wxauth");     //记录微信是否授权
            if(userinfo&&wxauth){
                console.log("sdk 直接进入游戏");
                //用户信息获取到并且授权了
                
                self.init({},(config)=>{
                    console.log('sdk 初始化结果：', config);
                    callback(userinfo);
                
                });
            }else if(userinfo&&!wxauth)
            {
                //用户信息存在但是没有授权,就应该去授权后调用服务端member/update用户信息
                this.WxAuthLogin((userData) => {
         
                    
                    self.init({},(config)=>{
                        console.log('sdk 初始化结果：', config);
                        callback(userData);
                    });
                });

            }else if(!userinfo&&wxauth)
            {
                //用户信息没有但是有授权，就应该去登陆并且去授权后调用服务端member/update用户信息
                this.WxAuthLogin((userData) => {
    
                    //callback(d);

                    self.init({},(config)=>{
                        console.log('sdk 初始化结果：', config);
                        callback(userData);
                    } );

                });
            }
            else{
                //没有用户信息，也没有授权，就应该去登陆并且去授权后调用服务端member/update用户信息
                self.WxLogin((d) => {

                    //if(d.c==1)
                    //{
                    
                        self.WxAuthLogin((userData) => {
            
                        
                            self.init({},(config)=>{
                             console.log('sdk 初始化结果：', config);
                             callback(userData);
                            
                            });
    
                        });
                    //}else
                    //{
                    //    console.error("sdk 登陆失败",d);
                    //}
                    

                });
                
            }

            
        }
    },

    setWeChatListener()
    {
        let self =this;
        wx.onHide(function(res){
            //监听小游戏隐藏到后台事件。锁屏、按 HOME 键退到桌面、显示在聊天顶部等操作会触发此事件。
            console.log("sdk 小游戏隐藏到后台");
            self.uploadSceneEvent(null,'隐藏小游戏到后台',null);

            if(self.isGameStart&&sdk_conf.game_online)
            {
                // var data = JSON.parse(this.getItem("游戏在线"));
                // var nowTime = new Date().getTime();
                // data.take_time = data.take_time+ ((nowTime/1000)-data.last_time);
    
                // data.last_time = nowTime/1000;
    
                // this.setItem("游戏在线",JOSN.stringify(data));
                self.setSceneEnd(self.getGameOnlineKey(),{});
    
            }

            if(self.shareStartTime>0)
            {
                //隐藏发生在分享调起
                console.log("sdk 隐藏发生在分享调起");
            }
            
        });


        wx.onShow(function(res){
            //监听小游戏回到前台的事件
            console.log("sdk 监听小游戏回到前台的事件");
            var nowTime = new Date().getTime(); 
            if(self.isGameStart&&sdk_conf.game_online)
            {
                var onlineKey = self.getGameOnlineKey();

                var dataString = self.getItem(onlineKey);

                
                var data = JSON.parse(dataString);

                     
                data.last_time = nowTime/1000;

                console.log("onShow->"+onlineKey,JSON.stringify(data));

                self.setItem(onlineKey,JSON.stringify(data));
            }

            if(self.shareStartTime>0)
            {

                setTimeout(function(){

                    if(!self.shareCancelCallback)
                    {
                        //分享成功 调用api记录分享数据
                        self.shareInfo.successCallback();
                        var option = {'uid': sdk.userid, 'share_id': self.shareInfo.sysid };

                        self.Post(self.ip3 + self.Logcommon, { log_type: "ShareClick", data: JSON.stringify(option) }, function (d) {
                            console.log("sdk 分享成功记录到服务器");
                        });
                        console.log("分享成功!!!");
                    }else
                    {
                        self.shareCancelCallback = false;
                        console.log("分享失败!!!");
                    }

                    //重置分享数据
                    self.shareStartTime = -1;
                    self.shareInfo =null;
                    console.log("sdk 清空分享数据记录");

                }.bind(self),100);

                
                

            }



        });


    },
    log()
    {
        var self = this;
        if(this.getUser()){
            this.userid = this.getUser().uid;
        }
        if(this.userid&&self.initFlag===0){ 

            var option = wx.getLaunchOptionsSync();
         
            if(option.query.share_id && option.query.uid){
                option.query.share_uid = option.query.uid;
                option.query.uid = this.userid;
         
               
                this.Post(this.ip3 + this.Logcommon, { log_type: "ShareEnter", data: JSON.stringify(option) }, function (d) {
                  
                });
            }
            wx.onShow((option)=>{
     
                if(option.query.uid){
                    option.query.share_uid = option.query.uid;
                    option.query.uid = self.userid;
    
                    self.Post(self.ip3 + self.Logcommon, { log_type: "ShareEnter", data: JSON.stringify(option) }, function (d) {
                   
                    });
                }
            })

            
                //5.统计：每次打开小游戏调用
                wx.getSystemInfo({
                    success(res){
                        var loginData = res;
                        loginData.uid = self.userid;
                        loginData.share_uid = option.query.share_uid;
                        loginData.scene = option.scene;
                        loginData.source_id = option.query.source_id;
                        loginData.source_id2 = option.query.source_id2;
                        loginData.special_flag = option.query.special_flag;
                        self.setItem("deviceModel",res.model);

                        if(sdk_conf.game_online)
                        {
                            //开启游戏统计情况下
                            self.gameStart({},null);
                        }
                        
                        wx.getNetworkType({
                            success(res2){
                                loginData.network_type = res2.networkType;
                                console.log("sdk LoginData", loginData)
                                self.Post(self.ip3 + self.Logcommon, { log_type: "LoginData", data: JSON.stringify(loginData) }, function (d) {
                                    //很重要防止因为配置获取失败，重复调用
                                    self.initFlag = 1;
                                });
                            }
                        })
                    }
                })

            
        }
    },
    WeChatLoginNoAuth(callback){

        //根据sdk_conf初始化api
        this.init_api();
        var self = this;
        if (cc.sys.platform === cc.sys.WECHAT_GAME) 
        {
        var userinfo = this.getUser();
        
        if(userinfo){
            console.log("sdk 直接进入游戏");
            //用户信息获取到并且授权了
            self.init({},(config)=>{
                //console.log('sdk 初始化结果：', config);
                callback(userinfo);
            });
            self.log();
        
        }
        else{
            //没有用户信息，也没有授权，就应该去登陆并且去授权后调用服务端member/update用户信息
            self.WxLogin((userData) => {
            
            
                self.init({},(config)=>{
                    console.log('sdk 初始化结果：', config);
                    callback(userData);
                });
                self.log();
            });
        }
        
        
        }
        },
        
     /**
     * @apiGroup C
     * @apiName wxLogin
     * @api {新增} 获取设备信息新增用户 wxLogin 不对外提供调用
     * 
     */
    WxLogin(callback){
        var self = this;
        if (cc.sys.platform === cc.sys.WECHAT_GAME) {
            var options = wx.getLaunchOptionsSync();
            
            var referee_id = options.query.uid;             //.推荐人id
            var source_id = options.query.source_id;        //.用户来源id
            var source_id2 = options.query.source_id2;      //.用户来源子id
            var share_id = options.query.share_id;          //.分享素材ID
            var special_flag = options.query.special_flag;
            //wx.getSystemInfo({
            //    success(res){

                    wx.login({
                        success(res2){ 
    
                            var reqData = {   
                                code: res2.code,
                                referee_id: referee_id,
                                source_id: source_id,
                                source_id2: source_id2,
                                share_id: share_id,
                                special_flag:special_flag
                                // model: res.model,
                                // platform: res.platform,
                                // wx_version: res.version,
                                // network_type: res.networkType,
                                // scene_value: res.scene,
                                // brand: res.brand,
                                // sdk_version: res.SDKVersion,
                              
                            }
                            console.log('sdk 注册参数', reqData)
                            self.Post(self.ip1 + self.login, reqData, function(data){
                                console.log('sdk 新增登陆结果', data);
                                if(data.c == 1){
                                    self.setItem('userinfo', JSON.stringify(data.d));
                                    callback(data.d);
                                }else{
                                    console.log('sdk 登录接口请求失败', data)
                                    wx.showToast({title: '登录失败请重试1'});
                                }                
                            });
                        },
                        fail(){
                            wx.showToast({title: '登录失败请重试2'});
                            //console.error("systemInfo",res);
                            callback(false)
                        },
                    });
                //}
            //});
         
        }
    },
    /**
     * @apiGroup C
     * @apiName wxAuth
     * @api {微信授权} 微信授权登录 WxAuthLogin（授权）不对外提供调用
     * 
     */
    WxAuthLogin(callback){
        var self = this;
        if (cc.sys.platform === cc.sys.WECHAT_GAME) {
            var options = wx.getLaunchOptionsSync();
            
            var referee_id = options.query.share_uid;             //.推荐人id
            var source_id = options.query.source_id;        //.用户来源id
            var source_id2 = options.query.source_id2;      //.用户来源子id
            var share_id = options.query.share_id;          //.分享素材ID
            var special_flag = options.query.special_flag;
            var userinfo = this.getUser();

                //.登录遮罩背景
                var maskNode = new cc.Node('Sprite');
                maskNode.parent = cc.director.getScene().getChildByName('Canvas');
                maskNode.addComponent(cc.BlockInputEvents)
                var sp = maskNode.addComponent(cc.Sprite);
                maskNode.opacity = 178;
                maskNode.color = new cc.Color(25,88,95,255);
                sp.sizeMode = cc.Sprite.SizeMode.CUSTOM;
                self.createImage(sp, self.loginBg);
                maskNode.width = cc.view.getVisibleSize().width;
                maskNode.height = cc.view.getVisibleSize().height;
                // console.log(maskNode.width, maskNode.height)

                //.微信登录按钮
                if(self.button){
                    self.button.show();
                }else{


                    wx.getSystemInfo({
                        success(res){
                            var width = 507/2;
                            var height = 464/2;
                            self.button = wx.createUserInfoButton({
                                type: 'image',
                                image: self.loginBt,
                                style: {  width: width, height: height, left: res.screenWidth/2-width/2, top: res.screenHeight/2-height/2 }
                            })
                            self.button.onTap((res1) => {
                                // 处理用户拒绝授权的情况
                                // if (res1.errMsg.indexOf('auth deny') > -1 || res1.errMsg.indexOf('auth denied') > -1 ) {
                                //     wx.showToast();
                                // }
                                wx.showToast({title: '登录中...',icon:'loading',duration: 8});
                                wx.getSetting({
                                    success(auths){
                                        if(auths.authSetting["scope.userInfo"]){
                                            self.setItem("wxauth",1);
                                            console.log('sdk 用户已经授权');

                                            var reqData = {
                                                rawData: res1.rawData,
                                                iv: res1.iv,
                                                encryptedData: res1.encryptedData,
                                                signature: res1.signature,

                                                referee_id: referee_id,
                                                source_id: source_id,
                                                source_id2: source_id2,
                                                share_id: share_id,
                                                special_flag:special_flag,
                                                
                                            }
                                            // console.log('==登录参数==', reqData)
                                            self.Post(self.ip1 + self.modify, reqData, function(data){
                                                console.log('sdk 更新用户信息结果', data)
                                                if(data.c == 1){
                                                    self.setItem('userinfo', JSON.stringify(data.d));
                                                    wx.hideToast();
                                                    maskNode.destroy();
                                                    self.button.hide();
                                                    //.登录成功，重新初始化
                                                    self.userid = data.d.uid;
                                                    //self.init({},(d)=>{})

                                                    callback(data.d);
                                                }else{
                                                    console.log(' sdk 登录接口请求失败', data)
                                                    wx.showToast({title: '登录失败请重试3'});
                                                }                
                                            });

                                        }else{
                                            callback(false)
                                        }
                                    }
                                })        
                            })
                            self.button.show()
                        }
                    })
                }


        }
    },
    /**
      * 微信授权
      * 
      * 用户点击游戏中授权按钮之后将授权的数据res传递进来
      * 
      *  self.button = wx.createUserInfoButton({
                               
         })

      * self.button.onTap((res) => {
      *     sdk.WechatAuth(res,function (d) {
      *             
      *     })
      * });
      */
     WechatAuth(res,callback){

        if (cc.sys.platform === cc.sys.WECHAT_GAME) 
        {
            var options = wx.getLaunchOptionsSync();
            
            var referee_id = options.query.share_uid;             //.推荐人id
            var source_id = options.query.source_id;        //.用户来源id
            var source_id2 = options.query.source_id2;      //.用户来源子id
            var share_id = options.query.share_id;          //.分享素材ID
            var special_flag = options.query.special_flag;
            self.setItem("wxauth",1);
            console.log('sdk 用户已经授权');

            var reqData = {
                rawData: res.rawData,
                iv: res.iv,
                encryptedData: res.encryptedData,
                signature: res.signature,

                referee_id: referee_id,
                source_id: source_id,
                source_id2: source_id2,
                share_id: share_id,
                special_flag:special_flag,
                
            }
            console.log('sdk 授权参数', reqData)
            self.Post(self.ip1 + self.modify, reqData, function(data){
                console.log('sdk 更新用户信息结果', data)
                if(data.c == 1){
                    self.setItem('userinfo', JSON.stringify(data.d));
                
                    //.登录成功，重新初始化
                    self.userid = data.d.uid;
                    //self.init({},(d)=>{})

                    callback(data.d);
                }else{
                    console.log(' sdk 授权接口请求失败', data)
                    wx.showToast({title: '授权失败请重试3'});
                }                
            });
        }


     },

     

    /**
     * @apiGroup C
     * @apiName WxAuthLoginOpacity
     * 将透明图片附着在游戏中功能按钮之上，点击弹出授权按钮
     * @apiParam {Object} [obj] 传递按钮位置信息 width height left top
     * 
     * @api {微信授权} 微信授权登录 WxAuthLoginOpacity（授权）不对外提供调用
     * 
    */
    WxAuthLoginOpacity(obj,callback){
        var self = this;
        if (cc.sys.platform === cc.sys.WECHAT_GAME) {
            if(self.getItem('wxauth'))return;//已授权
            var options = wx.getLaunchOptionsSync();
            
            var referee_id = options.query.share_uid;             //.推荐人id
            var source_id = options.query.source_id;        //.用户来源id
            var source_id2 = options.query.source_id2;      //.用户来源子id
            var share_id = options.query.share_id;          //.分享素材ID
            var special_flag = options.query.special_flag;
                //.微信登录按钮
                if(self.button){
                    self.button.show();
                }else{


                    wx.getSystemInfo({
                        success(res){
                            var ratio = 750/res.screenWidth;//设计与真实尺寸缩放比例,这里默认设计分辨率为750x1334
                            if(!obj){
                                var width = 120;
                                var height = 40;
                                var left = res.screenWidth/2-width/2;
                                var top = res.screenHeight/2-height/2;
                            }else{
                                var width = obj.width/ratio;
                                var height = obj.height/ratio;
                                var left = obj.left/ratio;
                                var top = obj.top?obj.top/ratio:obj.bottom?res.screenHeight - obj.bottom/ratio - height:0;//如果以底部为定位基线要使用bottom计算
                            }
                            self.button = wx.createUserInfoButton({
                                type: 'text',
                                text: '获取用户信息',
                                style: {
                                    left: left,
                                    top: top,
                                    width: width,
                                    height: height,
                                    lineHeight: height,
                                    backgroundColor: 'rgba(0,0,0,0)',
                                    color: 'rgba(0,0,0,0)',
                                    textAlign: 'center',
                                    fontSize: 16,
                                    borderRadius: 4
                                }
                            })
                            self.button.onTap((res1) => {

                                if(!self.getItem("wxauth"))
                                {
                                    wx.showToast({title: '登录中...',icon:'loading',duration: 8});
                                }else
                                {
                                    callback && callback(data.d);
                                    return;
                                }
                                // 处理用户拒绝授权的情况
                                console.log('授权按钮',res1);
                                if (res1.errMsg.indexOf('auth deny') > -1 || res1.errMsg.indexOf('auth denied') > -1 ) {
                                    // self.button.hide();
                                    // callback && callback(false)
                                    return;
                                }
                                
                                wx.getSetting({
                                    success(auths){
                                        if(auths.authSetting["scope.userInfo"]){
                                            self.setItem("wxauth",1);
                                            console.log('sdk 用户已经授权');

                                            var reqData = {
                                                rawData: res1.rawData,
                                                iv: res1.iv,
                                                encryptedData: res1.encryptedData,
                                                signature: res1.signature,

                                                referee_id: referee_id,
                                                source_id: source_id,
                                                source_id2: source_id2,
                                                share_id: share_id,
                                                special_flag:special_flag,
                                                
                                            }
                                            // console.log('==登录参数==', reqData)
                                            self.Post(self.ip1 + self.modify, reqData, function(data){
                                                console.log('sdk 更新用户信息结果', data)
                                                if(data.c == 1){
                                                    self.setItem('userinfo', JSON.stringify(data.d));
                                                    wx.hideToast();
                                                    self.button.hide();
                                                    //.登录成功，重新初始化
                                                    self.userid = data.d.uid;
                                                    //self.init({},(d)=>{})

                                                    callback && callback(data.d);
                                                }else{
                                                    console.log(' sdk 登录接口请求失败', data)
                                                    wx.showToast({title: '登录失败请重试3'});
                                                }                
                                            });

                                        }else{
                                            callback && callback(false)
                                        }
                                    }
                                })        
                            })
                            self.button.show()
                        }
                    })
                }
        }
    },
     /**
      * 初始化接口
      */
     init_api(){
        if(sdk_conf.env==='prod')
        {
            this.ip1 = sdk_conf.env_apis.prod.ip1;
            this.ip2 = sdk_conf.env_apis.prod.ip2;
            this.ip3 = sdk_conf.env_apis.prod.ip3;
            this.ip4 = sdk_conf.env_apis.prod.ip4;   

        }else
        {
        
            this.ip1 = sdk_conf.env_apis.test.ip1;
            this.ip2 = sdk_conf.env_apis.test.ip2;
            this.ip3 = sdk_conf.env_apis.test.ip3;
            this.ip4 = sdk_conf.env_apis.test.ip4;
        }

        console.log("sdk ip1",this.ip1);
        console.log("sdk ip2",this.ip2);
        console.log("sdk ip3",this.ip3);
        console.log("sdk ip4",this.ip4);
    
    },

    //.根据权重随机获取指定type类型的分享信息。（没有this.ShareList数据不能调用）
    getShareByWeight(type){
        if(this.ShareList.length > 0){
            //1.获取某种type的集合
            var tArray = [];
            for (var i = 0; i < this.ShareList.length; i++) {
                if (type == this.ShareList[i].type) {
                    this.ShareList[i].weight = parseInt(this.ShareList[i].weight);
                    tArray.push(this.ShareList[i]);
                }
            }
            //2.根据权重配比：从i集合（权重越大占比越多）中随机获取。
            var iArray = [];
            for (var i = 0; i < tArray.length; i++) {
                for (var j = 0; j < tArray[i].weight; j++) {
                    iArray.push(i);
                }
            }
            var i = iArray[parseInt(Math.random() * iArray.length)];
            //3.结果处理：正则替换昵称
            var item = tArray[i];
            if(item.title.indexOf("&nickName") != -1){
                item.title = item.title.replace(/&nickName/g, this.getUser().nickName);
            }
            return JSON.parse(JSON.stringify(item));
        }else{
            return null;
        }
    },
    /**
     * @apiGroup C
     * @apiName onShareAppMessage
     * @api {分享} 注册微信右上角分享 onShareAppMessage(分享)
     * @apiParam {int} type=0 后台自定义的分享类型；例如：0：右上角分享、1：普通分享 2：分享加金币
     * @apiParam {int} specialFlag=0 特殊标记,例如0:默认、1：邀新好友、2:邀旧好友
     * @apiParam {String} [title] 转发标题
     * @apiParam {String} [imageUrl] 转发显示图片的链接
     * @apiParam {String} [query] 必须是 key1=val1&key2=val2 的格式。
     * @apiParam {callback} [success] 成功回调
     * @apiParam {callback} [fail] 失败回调
     * @apiParam {callback} [cancel] 点击取消分享按钮回调 
     * 
     * @apiSuccessExample {json} 示例:
     * sdk.shareAppMessage({type: 1,query: "",success:xxx,cancel:xxx,fail:xxx });
     */
    onShareAppMessage(obj){
        var self = this;
        if (cc.sys.platform === cc.sys.WECHAT_GAME) {
            //.微信右上角分享
            var specialFlag =0;
            wx.showShareMenu({withShareTicket:true})

      


            wx.onShareAppMessage(function(res){
                //.默认0：右上角分享
                var tpye = 0;
                if(obj.type){
                    tpye = obj.type;
                }

                // if(self.getConfig4().cityLimit==1)
                // {
                //     //如果在限制的ip或者城市则调用起100分类类型素材
                //     tpye = 100;
                // }

                if(obj.specialFlag){
                    specialFlag = obj.specialFlag;
                }
                
                var shareInfo = self.getShareByWeight(tpye)

                if(obj.title){
                    shareInfo.title = obj.title;
                }
                if(obj.imageUrl){
                    shareInfo.imageUrl = obj.imageUrl;
                }
                if(shareInfo.query){
                    shareInfo.query += obj.query + "&share_id="+shareInfo.sysid + "&uid="+self.userid+"&special_flag="+specialFlag;
                }else{
                    if(obj.query){
                        shareInfo.query = "share_id="+shareInfo.sysid+"&uid="+self.userid+"&special_flag="+specialFlag +"&" + obj.query;
                    }else{
                        shareInfo.query = "share_id="+shareInfo.sysid + "&uid="+self.userid+"&special_flag="+specialFlag;
                    }
                }
                if(obj.success){
                    shareInfo.successCallback = obj.success;
                }
                if(obj.fail){
                    shareInfo.failCallback = obj.fail;
                }

                if(obj.cancel){
                    shareInfo.cancel = function(){
                        self.shareCancelCallback=true;
                        obj.cancel();
                        console.log("分享取消了");
                    }
                }

 
                var nowTime = new Date().getTime();
                self.shareStartTime = nowTime/1000;
                self.shareInfo = shareInfo;



                return shareInfo;
            })
        }
    },
    /**
     * @apiGroup C
     * @apiName shareAppMessage
     * @api {分享} 主动拉起微信分享 shareAppMessage(分享)
     * @apiParam {int} type=1 后台自定义的分享类型；例如：0：右上角分享、1：普通分享 2：分享加金币
     * @apiParam {int} specialFlag=0 特殊标记,例如0:默认、1：邀新好友、2:邀旧好友
     * @apiParam {String} [title] 转发标题
     * @apiParam {String} [imageUrl] 转发显示图片的链接
     * @apiParam {String} [query] 必须是 key1=val1&key2=val2 的格式。
     * @apiParam {callback} [success] 成功回调
     * @apiParam {callback} [fail] 失败回调
     * @apiParam {callback} [cancel] 点击取消分享按钮回调 
     * 
     * @apiSuccessExample {json} 示例:
     * sdk.shareAppMessage({type: 1,query: "",success:xxx,cancel:xxx,fail:xxx });
     */
    shareAppMessage(obj){
        var self = this;
        //.默认1：普通分享
        var tpye = 1;
        var specialFlag =0;
        if(obj.type){
            tpye = obj.type;
        }
        // if(self.getConfig4().cityLimit==1)
        // {
        //     //如果在限制的ip或者城市则调用起100分类类型素材
        //     tpye = 100;
        // }

        if(obj.specialFlag){
            specialFlag = obj.specialFlag;
        }

        var shareInfo = this.getShareByWeight(tpye);
        if(obj.title){
            shareInfo.title = obj.title;
        }
        if(obj.imageUrl){
            shareInfo.imageUrl = obj.imageUrl;
        }
        if(shareInfo.query){
            shareInfo.query += obj.query + "&share_id="+shareInfo.sysid + "&uid="+self.userid+"&special_flag="+specialFlag;
        }else{
            if(obj.query){
                shareInfo.query = "share_id="+shareInfo.sysid+"&uid="+self.userid+"&special_flag="+specialFlag +"&" + obj.query;
            }else{
                shareInfo.query = "share_id="+shareInfo.sysid + "&uid="+self.userid+"&special_flag="+specialFlag;
            }
        }
        if(obj.success){
            shareInfo.successCallback = obj.success;
        }
        if(obj.fail){
            shareInfo.failCallback = obj.fail;
        }
        if(obj.cancel){
            shareInfo.cancel = function(){
                self.shareCancelCallback=true;
                obj.cancel();
                console.log("分享取消了");
            }
        }

        console.log("sdk 微信分享", shareInfo);
        if (cc.sys.platform === cc.sys.WECHAT_GAME) {


            wx.shareAppMessage(shareInfo);

            var nowTime = new Date().getTime();
            self.shareStartTime = nowTime/1000;
            self.shareInfo = shareInfo;
       
        }
    },

   

    /**
     * @apiGroup C
     * @apiName Get
     * @api {Get} 发起网络请求 Get（发起Get请求）
     * 
     * @apiParam {String} url 请求地址
     * @apiParam {Object} reqData 请求参数
     * @apiParam {Object} callback 不存在返回null
     * @apiSuccessExample {json} 示例:
     * sdk.Get("https://xxx.xxx", { user_id: user_id }, function (d) {
     *     console.log(d)
     * });
     */
    Get(url, reqData, callback) {
        var self = this;

        reqData.game = sdk_conf.game;
        reqData.version = sdk_conf.version;
        reqData.dev_platform = sdk_conf.dev_platform;
        reqData.llewan_sdk_version = sdk_conf.llewan_sdk_version;
        var ts = new Date().getTime();
        reqData.ts = ts;
        var token = "";
        if(this.getUser()&&this.getUser()!=null)
        {
            token = this.getUser().token;
        }
        var options = wx.getLaunchOptionsSync();
        
        var source_id = options.query.source_id;   
        //数据验证签名。规则为：MD5(ts.substr(9,4)+game.substr(0,2)+version.substr(0,1)+key),时间戳后4位、data前3位、key（服务端提供）然后进行MD5加密
        reqData.sign = md5(ts.toString().substr(9,4)+sdk_conf.game.substr(0,2)+sdk_conf.version.substr(0,1)+ sdk_conf.md5_key);
        
        url += "?";
        for (var item in reqData) {
            url += item + "=" + reqData[item] + "&";
        }
        url += "token="+token+"&";

        url += "source_id="+source_id+"&";

        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                if (xhr.status >= 200 && xhr.status < 400) {
                    var response = xhr.responseText;
                    if (response) {
                        var responseJson = JSON.parse(response);
                        callback(responseJson);
                    } else {
                        if(self.debug){
                            console.log("sdk 返回数据不存在",url)
                        }
                        callback(null);
                    }
                } else {
                    if(self.debug){
                        console.log("sdk 请求失败",url)
                    }
                    callback(null);
                }
            }
        };
        //console.log("get url is :",url);
        xhr.open("GET", url, true);
        xhr.send();
    },
    
    /**
     * @apiGroup C
     * @apiName Post
     * @api {Post} 发起网络请求 Post（发起Post请求）
     * 
     * @apiParam {String} url 请求地址
     * @apiParam {Object} reqData 请求参数
     * @apiParam {Object} callback 不存在返回null
     * @apiSuccessExample {json} 示例:
     * sdk.Post(sdk.ip + sdk.common, { user_id: user_id }, function (d) {
     *     console.log(d)
     * });
     */
    Post: function (url, reqData, callback) {
        var self = this;
        
        reqData.game = sdk_conf.game;
        reqData.version = sdk_conf.version;
        reqData.dev_platform = sdk_conf.dev_platform;
        reqData.llewan_sdk_version = sdk_conf.llewan_sdk_version;
        var ts = new Date().getTime();
        var token = "";
        if(this.getUser()&&this.getUser()!=null)
        {
            token = this.getUser().token;
        }
        var options = wx.getLaunchOptionsSync();
        var source_id = options.query.source_id;   

        reqData.ts = ts;
        reqData.sign = md5(ts.toString().substr(9,4)+sdk_conf.game.substr(0,2)+sdk_conf.version.substr(0,1)+ sdk_conf.md5_key);
        
        //1.拼接请求参数
        var param = "";
        for (var item in reqData) {
            param += item + "=" + reqData[item] + "&";
        }
        param +="token="+token+ "&";
        param += "source_id="+source_id+"&";
      

        //2.发起请求
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                if (xhr.status >= 200 && xhr.status < 400) {
                    var response = xhr.responseText;
                    // console.log(response)
                    if (response) {
                        var responseJson = JSON.parse(response);
                        callback(responseJson);
                    } else {
                        if(self.debug){
                            console.log("sdk 返回数据不存在")
                        }
                        callback(null);
                    }
                } else {
                    if(self.debug){
                        console.log("sdk 请求失败",xhr)
                    }
                    callback(null);
                }
            }
        };
        xhr.open("POST", url, true);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.send(param);//reqData为字符串形式： "key=value"
    },
    /**
     * @apiGroup C
     * @apiName checkUpdate
     * @api {检测版本更新} 微信小游戏（冷启动的时候会检查，如果有更新则会重启小游戏进行更新） checkUpdate（版本更新）
     * 
     * @apiSuccessExample {json} 示例:
     * sdk.checkUpdate();
     */
    checkUpdate() {
        var self = this;
        if (cc.sys.platform === cc.sys.WECHAT_GAME && typeof wx.getUpdateManager === 'function') {
            const updateManager = wx.getUpdateManager()
            updateManager.onCheckForUpdate(function (res) {
                if(self.debug){
                    console.log("sdk 请求完新版本信息的回调", res.hasUpdate)
                }
            })
            updateManager.onUpdateReady(function () {
                if(self.debug){
                    console.log("sdk 新的版本已经下载好，调用 applyUpdate 应用新版本并重启")
                }
                updateManager.applyUpdate()
            })
            updateManager.onUpdateFailed(function () {
                if(self.debug){
                    console.log("sdk 新的版本下载失败")
                }
            })
        }
    },
    /**
     * @apiGroup C
     * @apiName getConfig1
     * @api {运营配置} 游戏后台配置信息，运营人员使用的通用配置开关 getConfig1（运营配置）
     * @apiParam {Object} callback 不存在返回null
     * 
     * @apiSuccessExample {json} 示例:
     * var d = sdk.getConfig1();
     */
    getConfig1(){
        return JSON.parse(this.ConfigData.config1);
    },
    
    /**
     * @apiGroup C
     * @apiName getConfig2
     * @api {程序配置} 游戏后台配置信息，程序员使用的游戏数据开关，可随便自定义数据：例如复活次数等 getConfig2（程序配置）
     * @apiParam {Object} callback 不存在返回null
     * 
     * @apiSuccessExample {json} 示例:
     * var d = sdk.getConfig2();
     */
    getConfig2(){
        return JSON.parse(this.ConfigData.config2);
    },

     /**
     * @apiGroup C
     * @apiName getConfig3
     * @api {运营配置} 游戏后台配置信息，运营人员使用的通用配置开关 相关按钮根据时间来配置以及跳转方式按钮属性getConfig3（运营配置）
     * @apiParam {Object} callback 不存在返回null
     * 
     * @apiSuccessExample {json} 示例:
     * var d = sdk.getConfig3();
     */
    getConfig3(){
        return JSON.parse(this.ConfigData.config3);
    },

     /**
     * @apiGroup C
     * @apiName getConfig4
     * @api {技术程序控制} 游戏服务端控制一些需要服务端判断的比如：ip地区配置，getConfig4（技术程序）
     * @apiParam {Object} callback 不存在返回null
     * 
     * @apiSuccessExample {json} 示例:
     * var d = sdk.getConfig4();
     */
    getConfig4(){
        return JSON.parse(this.ConfigData.config4);
    },
    
    /**
     * @apiGroup C
     * @apiName createImage
     * @api {显示网络图片} 微信小游戏加载图片 createImage（显示图片）
     * @apiParam {cc.Sprite} sprite 显示图片的Sprite
     * @apiParam {String} url 需要加载的图片地址
     * @apiParam {callback} cb 添加缓存逻辑
     * 
     * @apiSuccessExample {json} 示例:
     * var data = sdk.createImage(advs);
     * 或
     * sdk.createImage(itemNode.getComponent(cc.Sprite), imageUrl, 
     *           (spriteFrame) => {
     *              console.log("set to cache!");
     *               //spriteFrame既是请求下来的图片，可用于缓存
     *               Global.CacheManager.setObject(imageUrl,spriteFrame);
     *           });
     */
    createImage(sprite, url, cb = null) {
        if (cc.sys.platform === cc.sys.WECHAT_GAME) {
            let image = wx.createImage();
            image.onload = function () {
                let texture = new cc.Texture2D();
                texture.initWithElement(image);
                texture.handleLoadedTexture();
                sprite.spriteFrame = new cc.SpriteFrame(texture);

                if(cb){
                    cb(sprite.spriteFrame);
                }

            };
            image.src = url;
        }
        
    },

    /**
     * @apiGroup C
     * @apiName getUser
     * @api {获取本地用户信息} 获取本地用户信息（登录成功后，会在本地存储用户信息） getUser（获取用户信息）
     * 
     * @apiSuccessExample {json} 示例:
     * //.不存在返回null
     * var user = sdk.getUser();
     */
    getUser(){
        var userinfo = this.getItem('userinfo');
        if(userinfo){
            return JSON.parse(userinfo);
        }else{
            return null;
        }
    },
    /**
     * @apiGroup C
     * @apiName setItem
     * @api {set} 数据存储 setItem（存）
     * @apiParam {String} key 键
     * @apiParam {String} value 值
     * 
     * @apiSuccessExample {json} 示例:
     * sdk.setItem("nick","hello")
     */
    setItem(key, value){
        cc.sys.localStorage.setItem(key, value);
    },
    /**
     * @apiGroup C
     * @apiName getItem
     * @api {数据存储} 数据存储 getItem（取）
     * @apiParam {String} key 键
     * @apiParam {String} value 值
     * 
     * @apiSuccessExample {json} 示例:
     * var nick = sdk.getItem("nick")
     */
    getItem(key){
        return cc.sys.localStorage.getItem(key);
    },
    /**
     * @apiGroup C
     * @apiName removeItem
     * @api {数据存储} 数据存储 removeItem(删)
     * @apiParam {String} key 键
     * 
     * @apiSuccessExample {json} 示例:
     * sdk.removeItem("nick")
     */
    removeItem(key){
         cc.sys.localStorage.removeItem(key);
    },
    /**
     * @apiGroup C
     * @apiName onMessage
     * @api {主域监听子域发送的消息} 主域监听子域发送的消息 onMessage（监听消息）
     * @apiParam {callback} callback 回调函数
     * 
     * @apiSuccessExample {json} 示例:
     * sdk.onMessage((d)=>{
     *     console.log(d)
     * })
     */
    onMessage(callback){
        if (cc.sys.platform === cc.sys.WECHAT_GAME) {
            wx.onMessage(function(d){
                // if(d.message == "common_back"){//.子域: 返回子域首页
                //     cc.director.loadScene("common_children")
                // }
                callback(d)
            });
        }
    },
    /**
     * @apiGroup C
     * @apiName postMessage
     * @api {主域向子域发送消息} 主域向子域发送消息 postMessage（发送消息）
     * @apiParam {String} msg 发送给子域的消息
     * 
     * @apiSuccessExample {json} 示例:
     * sdk.postMessage("hello")
     */
    postMessage(msg){
        if (cc.sys.platform === cc.sys.WECHAT_GAME) {
            wx.postMessage({ message: msg });
        }
    },
    //.主域上报数据:    对用户托管数据进行写数据操作，允许同时写多组 KV 数据。
    setUserCloudStorage(kvDataList, callback){
        if (cc.sys.platform === cc.sys.WECHAT_GAME) {
            wx.setUserCloudStorage({
                KVDataList: kvDataList,
                success(res){
                    callback(res)
                },
                fail(res){
                    callback(res)
                }
            })
        }
    },
    //.获取当前用户托管数据当中对应 key 的数据。该接口只可在开放数据域下使用
    getUserCloudStorage(keyList, callback){
        if (cc.sys.platform === cc.sys.WECHAT_GAME) {
            wx.getUserCloudStorage({
                keyList: keyList,
                success(res){
                    callback(res)
                },
                fail(res){
                    callback(res)
                }
            })
        }
    },
    //.在小游戏是通过群分享卡片打开的情况下，可以通过调用该接口获取群同玩成员的游戏数据。该接口只可在开放数据域下使用。
    getGroupCloudStorage(shareTicket, keyList, callback){
        if (cc.sys.platform === cc.sys.WECHAT_GAME) {
            wx.getGroupCloudStorage({
                shareTicket: shareTicket,
                keyList: keyList,
                success(res){
                    callback(res)
                },
                fail(res){
                    callback(res)
                }
            })
        }
    },
    //.拉取当前用户所有同玩好友的托管数据。该接口只可在开放数据域下使用
    getFriendCloudStorage(keyList, callback){
        if (cc.sys.platform === cc.sys.WECHAT_GAME) {
            wx.getFriendCloudStorage({
                keyList: keyList,
                success(res){
                    callback(res)
                },
                fail(res){
                    callback(res)
                }
            })
        }
    },
    /**
     * @apiGroup C
     * @apiName sortList
     * @api {对子域数据进行排序} 对子域数据进行排序 sortList（子域排序）
     * @apiParam {String} ListData 要排序的微信子域数据
     * @apiParam {String} field 排序字段
     * @apiParam {String} order 正序：true  ； 倒序：false
     * 
     * @apiSuccessExample {json} 示例:
     * wx.getFriendCloudStorage({
     *       keyList: ["score"],
     *       success(res){
     *           var ListData = sdk.sortList(res.data, 'score', true));
     *           console.log("=排序后的数据=", ListData);
     *       },
     *       fail(){
     *           console.log(res)
     *       }
     *})
     */
    sortList(ListData, field, order){
        ListData.sort(function(a,b){
            var AMaxScore = 0;
            var KVDataList = a.KVDataList;
            for(var i=0; i<KVDataList.length; i++){
                if(KVDataList[i].key == field){
                    AMaxScore = KVDataList[i].value;
                }
            }

            var BMaxScore = 0;
            KVDataList = b.KVDataList;
            for(var i=0; i<KVDataList.length; i++){
                if(KVDataList[i].key == field){
                    BMaxScore = KVDataList[i].value;
                }
            }

            if(order){
                return parseInt(AMaxScore) - parseInt(BMaxScore);
            }else{
                return parseInt(BMaxScore) - parseInt(AMaxScore);
            }
        });
        return ListData;
    },
    /**
     * @apiIgnore
     * @apiGroup C
     * @apiName getMyRank3
     * @api {排名与我相邻的3位玩家信息} 排名与我相邻的3位玩家信息 getMyRank3（Top3）
     * @apiParam {String} ListData 要排序的微信子域数据
     * @apiParam {String} me 我的子域信息
     * 
     * @apiSuccessExample {json} 示例:
     * wx.getUserInfo({
     *       openIdList: ['selfOpenId'],
     *       lang: 'zh_CN',
     *       success(res){
     *          //.Top3
     *          var dList = sdk.getMyRank3(dataList,res.data[0]);
     *          console.log(dList)
     *       },
     *       fail(error) {
     *          console.log(error)
     *       }
     * })
     * 
     * 
     */
    getMyRank3(ListData,me){
        var dataList = [];
        for(var i=0; i<ListData.length; i++){
            if(ListData.length <= 3){
                //.只有3个人或以下
                if(ListData[i].avatarUrl == me.avatarUrl && ListData[i].nickname == me.nickName){
                    ListData[i].isSelf = true;//.标记自己
                }
                dataList = ListData;
                for(var i=0; i<dataList.length; i++){
                    dataList[i].rank = i;
                }                 
            }else{
                if(ListData[i].avatarUrl == me.avatarUrl && ListData[i].nickname == me.nickName){
                    ListData[i].isSelf = true;//.标记自己
                    if(i == ListData.length-1){
                        //.自己分数最低
                        ListData[i].rank = i;
                        ListData[i-1].rank = i-1;
                        ListData[i-2].rank = i-2;
                        dataList.push(ListData[i-2])
                        dataList.push(ListData[i-1])
                        dataList.push(ListData[i])
                    }else if(i==0){
                        //.自己分数最高
                        ListData[i].rank = i;
                        ListData[i+1].rank = i+1;
                        ListData[i+2].rank = i+2;
                        dataList.push(ListData[i])
                        dataList.push(ListData[i+1])
                        dataList.push(ListData[i+2])
                    }else{
                        //.居中
                        ListData[i-1].rank = i-1;
                        ListData[i].rank = i;
                        ListData[i+1].rank = i+1;
                        dataList.push(ListData[i-1])
                        dataList.push(ListData[i])
                        dataList.push(ListData[i+1])
                    }
                    break;        
                }
            }
               
        }
        return dataList;
    },
   
    
   
 
     /**
     * @apiGroup C
     * @apiName Screenshot
     * @api {微信小游戏截图保存} 微信小游戏截图保存 Screenshot（截图）
     * 
     * @apiSuccessExample {json} 示例:
     *   //.摄像机组件、回调
     *   sdk.Screenshot((d)=>{
     *       if(d){
     *           console.log("图片保存成功：", d)
     *       }else{
     *           console.log("图片保存失败：", d)
     *       }
     *   })
     * 
     */
    Screenshot(callback){
        var self = this;
        //1.判断是否授权
        wx.getSetting({
            success(res){
                // console.log("授权状态", res.authSetting['scope.writePhotosAlbum'])
                if(res.authSetting['scope.writePhotosAlbum']){
                    self.capture(callback);
                }else{
                    // console.log("未授权", res)
                    wx.authorize({
                        scope: 'scope.writePhotosAlbum',
                        success(res2){
                            // console.log("success res2",res2)
                            self.Screenshot(callback);
                        },
                        fail(res2){
                            // console.log("重新授权")
                            wx.showModal({
                                title: '提示',
                                content: '请开启保存到相册功能',
                                showCancel: false,
                                success(){
                                    wx.openSetting({
                                        success(res3){
                                            // console.log("===重新授权===", res3)
                                            if(res3.authSetting['scope.writePhotosAlbum']){
                                                self.Screenshot(callback);
                                            }else{
                                                wx.showToast({ title: "授权失败" })
                                                callback(null)
                                            }
                                        }
                                    })
                                }
                            })
                        }
                    })
                }
            },
            fail(){
                callback(null)
            }
        })
    },
    capture (callback) {
        if(cc.ENGINE_VERSION < "2.0.0"){
            //1.9.3旧版本截图
            var canvas = cc.game.canvas;
            var width  = cc.winSize.width;
            var height  = cc.winSize.height;

            canvas.toTempFilePath({
                x: 0,
                y: 0,
                width: width,
                height: height,
                destWidth: width,
                destHeight: height,
                success (res) {
                    //.可以保存该截屏图片
                    // console.log(res)
                    //.保存到手机
                    wx.saveImageToPhotosAlbum({
                        filePath: res.tempFilePath,
                        success(res2){
                            console.log('sdk 旧版截图保存成功',res2)
                            callback(true)
                        },
                        fail(res2){
                            console.log('sdk 旧版截图保存失败',res2)
                            callback(null)
                        }
                    })
                }
            })
        }else{
            //2.0.1新版本截图
            var cameraNode = new cc.Node('camera');
            cameraNode.parent = cc.director.getScene().getChildByName('Canvas');
            var camera = cameraNode.addComponent(cc.Camera);


            //.要截取的范围（全屏）
            let texture = new cc.RenderTexture();
            // 如果截图内容中不包含 Mask 组件，可以不用传递第三个参数
            let gl = cc.game._renderContext;
            texture.initWithSize(cc.visibleRect.width, cc.visibleRect.height, gl.STENCIL_INDEX8);
            camera.targetTexture = texture;
            this.texture = texture;


            let width = this.texture.width;
            let height = this.texture.height;
            let canvas = document.createElement('canvas');
            let ctx = canvas.getContext('2d');
            canvas.width = width;
            canvas.height = height;
            camera.render();
            let data = this.texture.readPixels();
            let rowBytes = width * 4;
            for (let row = 0; row < height; row++) {
                let srow = height - 1 - row;
                let imageData = ctx.createImageData(width, 1);
                let start = srow*width*4;
                for (let i = 0; i < rowBytes; i++) {
                    imageData.data[i] = data[start+i];
                }
                ctx.putImageData(imageData, 0, row);
            }
            var dataURL = canvas.toDataURL("image/jpeg");
            var tempFilePath = canvas.toTempFilePathSync({
                x: 0,
                y: 0,
                width: width,
                height: height,
                destWidth: width,
                destHeight: height,
            });
            //.保存到手机
            wx.saveImageToPhotosAlbum({
                filePath: tempFilePath,
                success(res2){
                    console.log('sdk 新版截图保存成功',res2)
                    callback(true)
                },
                fail(res2){
                    console.log('sdk 新版截图保存失败',res2)
                    callback(null)
                }
            })
        }
        
    },
    //.一般性存储到服务器数据方法，并且做了本地缓存
    /**
     * @apiGroup C
     * @apiName setToServer
     * @api {setToServer} 数据存储 setToServer（存）
     * @apiParam {String} dataKey 键
     * @apiParam {String} dataType 数据类型,首字母大学的驼峰形式,例如：ShareGroup 或者 ShareLimit 
     * @apiParam {String} data 需要保存的数据
     * @apiParam {String} expireTime 过期时间 单位(秒),0：默认一天;-1:永不失效(10年);
     * 
     * 注意：dataKey和dataType共同确定一个数据的key值，也就是说 如果同样传递key111但是如果dataType不一样，sdk会认为是不同的两个数据key
     * 
     * var data = {'key3':'test'};
     * sdk.setToServer("testKeyttt3","TestData",data,3600);
     * 
     */
    setToServer: function(dataKey,dataType,data,expireTime){

        var self = this;

        
        var localExpireTime = 24*60*60;

        if(expireTime==-1)
        {
            localExpireTime=365*24*60*60;
        }else if(expireTime==0)
        {
            localExpireTime=24*60*60;
        }

        
        if(expireTime==-1)
        {
            expireTime=15*24*60*60;
        }else if(expireTime==0)
        {
            expireTime=24*60*60;
        }
        dataKey = sdk_conf.game+":"+dataType+":"+this.getUser().uid+":"+dataKey;


        self.setLocalCache(dataKey,JSON.stringify(data),localExpireTime);
        console.log("sdk setToServer "+dataKey + " ： "+JSON.stringify(data));
        this.Post(this.ip2 + this.set, { key: dataKey,data: JSON.stringify(data),data_type:dataType,expireTime:String(expireTime)}, function (d) {
            console.log("sdk setToServer 服务端返回",JSON.stringify(d));
             if(d.c==0)
             {
                console.error("sdk 设置失败,请联系服务端技术查看问题！");
                
             }
        });   
    },
    
    //.一般性获取服务器数据方法，并且做了本地缓存
    /**
     * @apiGroup C
     * @apiName getFromServer
     * @api {getFromServer} 数据存储 getFromServer（获取）
     * @apiParam {String} dataKey 键
     * @apiParam {String} dataType 数据类型 首字母大学的驼峰形式,例如：ShareGroup 或者 ShareLimit 
     * @apiParam {String} data 特殊情况下需要传递额外数据状况，一般不传递
     * @apiParam {String} callback 回调
     * 
     * sdk.getFromServer("testKey","TestData",null,(d)=>{
                console.log("获取返回",d.key3);
            });
     */
    getFromServer: function(dataKey,dataType,data,callbackFunction){
   
        var self = this;
        dataKey = sdk_conf.game+":"+dataType+":"+this.getUser().uid+":"+dataKey;
        
        var cacheData = this.getLocalCache(dataKey)
        console.log("sdk getFromServer "+dataKey+" ："+cacheData);

        if(cacheData==-1)
        {
            //去远程服务器拿数据
            this.Post(this.ip2 + this.get, { key: dataKey,data_type:dataType,data: JSON.stringify(data)}, function (d) {

                console.log("sdk getFromServer "+dataKey+" 本地不存在,去服务器获取值："+JSON.stringify(d.d));
                callbackFunction(d.d);
            });
        }else if(cacheData==0)
        {
            //本地缓存过期了直接返回
            //callbackFunction(null);

            //去远程服务器拿数据
            this.Post(this.ip2 + this.get, { key: dataKey,data_type:dataType,data: JSON.stringify(data)}, function (d) {

                console.log("sdk getFromServer "+dataKey+" 本地已经过期,去服务器获取值："+JSON.stringify(d.d));
                callbackFunction(d.d);
            });

        }else
        {
            //获取到数据
            console.log("cacheData->"+cacheData);
      
            try 
            {
                cacheData = JSON.parse(cacheData);
            } catch (e) {
               console.error("sdk json 转换异常");
            }

            callbackFunction(cacheData);
        }
        
    },

     /**
     * @apiGroup C
     * @apiName setLocalCache
     * @api {set} 数据存储 setLocalCache（存）
     * @apiParam {String} key 键
     * @apiParam {String} value 值
     * @apiParam {String} expireTime 过期时间单位(秒)
     * 
     * @apiSuccessExample {json} 示例:
     * sdk.setLocalCache("nick","hello")
     */
    setLocalCache(key, value,expireTime){

        var nowTime = new Date().getTime();
        console.log("sdk setLocalCache nowTime",nowTime);
        expireTime = nowTime+expireTime*1000;
        console.log("sdk setLocalCache expireTime",expireTime);
        var localData=  {'data': value,'expireTime':expireTime};
        cc.sys.localStorage.setItem(key, JSON.stringify(localData));
    },
  
    /**
     * @apiGroup C
     * @apiName getLocalCache
     * @api {数据存储} 数据存储 getLocalCache（取）
     * @apiParam {String} key 键
     * 
     * @apiSuccessExample {json} 示例:
     * var nick = sdk.getLocalCache("nick")
     */
    getLocalCache(key){

        var nowTime = new Date().getTime();
        console.log("sdk getLocalCache nowTime",nowTime);
        var localData =  cc.sys.localStorage.getItem(key);

        console.log("sdk getLocalCache "+key+" 本地获取值："+localData);


        if(localData)
        {
            var data = JSON.parse(localData);
            var expireTime = data.expireTime;
            return data.data;
            // if(nowTime>=expireTime)
            // {
            //     cc.sys.localStorage.removeItem(key);
            //     console.log("sdk getLocalCache dataKey : "+key+" is expire");
            //     return 0;
            // }else
            // {

            //     var data = data.data;
            //     console.log("sdk getLocalCache dataKey : "+key+" is "+data+" 离过期时间还有："+((expireTime-nowTime)/1000)+"S");

            //     return data;
            // }
        }else
        {
            //本地不存在数据,应该去远程服务器拿数据
            return -1;
        }
        
    },
    /**
     * @apiGroup C
     * @apiName getServerTime
     * @api {数据存储} 数据获取 getServerTime (取)
     * @apiSuccessExample {json} 示例:
     * sdk.getServerTime((d)=>{
                if(d.c==1){
                    console.log("获取返回",d.nowTime);
                }
            });
     */
    getServerTime(callbackFunction){


        this.Post(this.ip2 + this.time, { }, function (d) {
            callbackFunction(d);
        });
        
    },
    /**
     * @apiGroup C
     * @apiName formatTime
     * @api  数据获取 formatTime (取)
     * @apiParam {Date} time 时间 
     * @apiParam {String} type 类型 date or time
     * @apiParam {String} split 分隔符 / - : 空
     * @apiSuccessExample {json} 示例:
     * var time = this.formatTime(new Date(),"date",""); 20180920
     * var time = this.formatTime(new Date(),"time",""); 20180920122324
     */
    formatTime(time,type,split)
    {

        var mat={};
        mat.M=time.getMonth()+1;//月份记得加1
        mat.H=time.getHours();
        mat.s=time.getSeconds();
        mat.m=time.getMinutes();
        mat.Y=time.getFullYear();
        mat.D=time.getDate();
        mat.d=time.getDay();//星期几

        mat.d=this.formatZero(mat.d);
        mat.H=this.formatZero(mat.H);
        mat.M=this.formatZero(mat.M);
        mat.D=this.formatZero(mat.D);
        mat.s=this.formatZero(mat.s);
        mat.m=this.formatZero(mat.m);
     
        if(type=="date")
        {
            if(split.indexOf(":")>-1)
            {
        　　　　mat.Y=mat.Y.toString().substr(2,2);
        　　　　return mat.Y+"/"+mat.M+"/"+mat.D
            }else if(split.indexOf("/")>-1){
                return mat.Y+"/"+mat.M+"/"+mat.D
            }else if(split.indexOf("-")>-1){
                return mat.Y+"-"+mat.M+"-"+mat.D
            }else if(split.indexOf("-")>-1){
                return mat.Y+"-"+mat.M+"-"+mat.D
            }else
            {
                return mat.Y+mat.M+mat.D
            }
        }else
        {
            if(split.indexOf(":")>-1)
            {
                mat.Y=mat.Y.toString().substr(2,2);
                return mat.Y+"/"+mat.M+"/"+mat.D+" "+mat.H+":"+mat.m+":"+mat.s;
            }else if(split.indexOf("/")>-1){
                return mat.Y+"/"+mat.M+"/"+mat.D+" "+mat.H+"/"+mat.m+"/"+mat.s;
            }else if(split.indexOf("-")>-1){
                return mat.Y+"-"+mat.M+"-"+mat.D+" "+mat.H+"-"+mat.m+"-"+mat.s;
            }else if(split.indexOf("-")>-1){
                return mat.Y+"-"+mat.M+"-"+mat.D+" "+mat.H+"-"+mat.m+"-"+mat.s;
            }else
            {
                return mat.Y+mat.M+mat.D+mat.H+mat.m+mat.s;
            }
        }
    },
    formatZero(str){
        str=str.toString();
        if(str.length<2){
            str='0'+ str;
        }
        return str;
    },

    getUploadRowCount(){
        var res = sdk_conf.default_upload_row_count;
       try{
             res=  this.getConfig4().uploadRowCount;
             if(!res)
             {
                res = sdk_conf.default_upload_row_count;
             }
       }catch(e)
       {
            res = sdk_conf.default_upload_row_count;
       }
       return res;
    },

    getUploadInterval(){
        var res = sdk_conf.default_upload_interval;
       try{
            res =  this.getConfig4().uploadInterval;
            if(!res)
             {
                res = sdk_conf.default_upload_interval;
             }
       }catch(e)
       {
           res = sdk_conf.default_upload_interval;
       }
       return res;
    },


     /**
     * @apiGroup C
     * @apiName uploadSceneEvent
     * @api {数据存储} 数据存储 uploadSceneEvent(存) 将事件信息发送到乐玩服务器记录
     * @apiParam {JsonArray} eventJsonArray 要上传的json数组
     * sdk.uploadSceneEvent(null,'游戏结束',null)   //游戏上传场景数据
     * sdk.uploadSceneEvent(jsonArray,'',null)      //将要上传的数据传递过来
     */
    uploadSceneEvent(eventJsonArray,uploadEvent,callbackFunction){
        
        var lastUploadDataTime = this.getItem("lastUploadDataTime");

        var nowTime =  new Date().getTime()/1000;


        console.log("nowTime:"+nowTime+";lastUploadDataTime:"+lastUploadDataTime);
        if(lastUploadDataTime)
        {
            //存在更新时间 暂不做任何处理
        }else
        {
            //上次更新时间没有就等于当前时间
            lastUploadDataTime = nowTime;
            this.setItem("lastUploadDataTime",lastUploadDataTime);
        }

     
    
        if(eventJsonArray===null)
        {
             //如果没有传递要上传的数据
            var eventData = this.getItem("eventData");

            try 
            {
                eventJsonArray = JSON.parse(eventData);
                console.log(uploadEvent);
                this.uploadData(eventJsonArray,uploadEvent,callbackFunction);
            } catch (e) {
               console.error("埋点没有数据上传!");
            }

            
           
            
        }else if(eventJsonArray.data.length>=this.getUploadRowCount())
        {
            uploadEvent="数据累计("+this.getUploadRowCount()+"条)上传";
            console.log(uploadEvent);
            this.uploadData(eventJsonArray,uploadEvent,callbackFunction);
          

        }else if((nowTime-lastUploadDataTime)>=this.getUploadInterval())
        {

            uploadEvent="定时("+this.getUploadInterval()+"秒)上传";
            console.log(uploadEvent);
            this.uploadData(eventJsonArray,uploadEvent,callbackFunction);
        }
    },
    uploadData(eventJsonArray,uploadEvent,callbackFunction)
    {
       
        var nowTime =  new Date().getTime()/1000;
        eventJsonArray.upload_event=uploadEvent;

        //达到一定数量级
        console.log("当前上传数据",eventJsonArray);

        
        this.Post(this.ip3 + this.Logcommon, { log_type: "SceneEventLog", data: JSON.stringify(eventJsonArray) }, function (d) {
            if(callbackFunction)
            {
                callbackFunction(d);
            }
        });

        //上传完了之后删除数据
        this.removeItem("eventData");

        this.setItem("lastUploadDataTime",nowTime);
    },
    /**
     * @apiGroup C
     * @apiName setSceneEvent
     * @api {数据存储} 数据存储 setEvent(存) 将事件信息发送到乐玩服务器记录
     * @apiParam {String} sceneName 场景名称，比如：第1关,第2关，厨房，矿坑
     * @apiParam {String} eventName 事件名称，比如：点击、加载、触摸、移动
     * @apiParam {String} eventId 事件ID 通常谢按钮的英文或者中文名字，比如：首页-开始闯关
     * @apiParam {JSON} params 参数相关
     * @apiSuccessExample {json} 示例:
     * sdk.setSceneEvent("第一关","点击","首页-开始闯关",{'uid':'8975621'},null)
     */
    setSceneEvent(sceneName,eventName,eventId,params,callbackFunction){

        var eventData = this.getItem("eventData");

        var deviceModel = this.getItem('deviceModel');

        var eventJsonArray = {};


        var data = [];

        var insertData ={};
        if(eventData)
        {
           
            eventJsonArray = JSON.parse(eventData);
            data = eventJsonArray.data;

            //console.log("已经存在:"+data);
        }
        var uid = -1;
        try{
            uid = this.getUser().uid;
        }catch (e) {
           uid = -1;
         }
        insertData.uid=uid;
        insertData.scene_name= sceneName;
        insertData.event_id = eventId;
        insertData.event_name =eventName;
        insertData.params = JSON.stringify(params);
        insertData.device_model = deviceModel;
        insertData.event_time = this.formatTime(new Date(),"time","-")
        //console.log("添加数据",JSON.stringify(insertData));

        data.push(insertData);
        eventJsonArray.data = data;
        //console.log("添加后:"+JSON.stringify(eventJsonArray.data));

        this.setItem("eventData",JSON.stringify(eventJsonArray));


        this.uploadSceneEvent(eventJsonArray,'',callbackFunction);
        

        
    },


    /**
     * @apiGroup C
     * @apiName createOrder
     * @api {数据存储} 创建订单 createOrder(存) 
     * @apiParam {int} cash 订单金额，当前提现的订单金额
     * @apiSuccessExample {json} 示例:
     * sdk.createOrder(10,null)
     */
    createOrder(cash,callbackFunction){
     
        this.Post(this.ip2 + "/cash/createOrder", { uid: this.getUser().uid, cash:cash}, function (d) {
            if(callbackFunction)
            {
                callbackFunction(d);
            }
        });
        
    },
    /**
     * @apiGroup C
     * @apiName moneyAmount
     * @api {数据获取} 获取用户金额 moneyAmount(获取) 
     * @apiSuccessExample {json} 示例:
     * sdk.moneyAmount(null)
     */
    moneyAmount(callbackFunction){
    
        this.Post(this.ip2 + "/cash/amount", { uid: this.getUser().uid}, function (d) {
            if(callbackFunction)
            {
                callbackFunction(d);
            }
        });
        
    },

     /**
     * @apiGroup C
     * @apiName moneyAmount
     * @api {数据存储}  获得或者减少钱(分为单位)
     * @apiSuccessExample {json} 示例:
     * sdk.operateMoney({type:'add',way:'redPacket',cash:50},null)
     */
    operateMoney(data,callbackFunction){
    
        data.uid=this.getUser().uid;
        this.Post(this.ip2 + "/cash/operate",data, function (d) {
            if(callbackFunction)
            {
                callbackFunction(d);
            }
        });
        
    },



     /**
     * @apiGroup C
     * @apiName sceneStart
     * @api {数据存储} 数据存储 sceneStart(存) 玩家进场景界面开始调用
     * @apiParam {String} sceneName 场景名称，比如：第1关,第2关，厨房，矿坑,如果有调用setSceneEvent 两个传递场景名称必须要一样
     * @apiParam {JSON} extraData 额外数据,可以传递从哪里进入场景，比如：正常进入 或者 奖励进入
     * @apiSuccessExample {json} 示例:
     * sdk.sceneStart('第1关','正常进入',null)
     */
    setSceneStart(sceneName,params){

        if(sceneName==this.gameOnlineKey)
        {

            var cacheData = this.getItem(sceneName);
            var nowTime = new Date().getTime();
            var data = {};
            if(cacheData)
            {
                data = JSON.parse(cacheData);
                data.last_time = nowTime/1000;
                console.log(this.gameOnlineKey,JSON.stringify(data));
                this.setItem(sceneName,JSON.stringify(data));
            }else
            {
                
                var deviceModel = this.getItem('deviceModel');
                
                data.uid=this.getUser().uid;
                data.scene_name = sceneName;
                data.start_time = nowTime/1000;
                data.last_time = nowTime/1000;
                data.take_time = 0;
                data.end_time = nowTime/1000;
                data.params = JSON.stringify(params);
                data.device_model = deviceModel;
        
                console.log(this.gameOnlineKey,JSON.stringify(data));
                this.setItem(sceneName,JSON.stringify(data));
            }
           
        }else
        {
            var nowTime = new Date().getTime();
            var deviceModel = this.getItem('deviceModel');
            var data = {};
            data.uid=this.getUser().uid;
            data.scene_name = sceneName;
            data.start_time = nowTime/1000;
            data.last_time = nowTime/1000;
            data.take_time = 0;
            data.end_time = nowTime/1000;
            data.params = JSON.stringify(params);
            data.device_model = deviceModel;
    
            console.log("场景数据开始",JSON.stringify(data));
            this.setItem(sceneName,JSON.stringify(data));
        }
        

        
    },

     /**
     * @apiGroup C
     * @apiName sceneEnd
     * @api {数据存储} 数据存储 sceneEnd(存) 玩家结束游戏场景调用
     * @apiParam {String} sceneName 场景名称，比如：第1关,第2关，厨房，矿坑,如果有调用setSceneEvent 两个传递场景名称必须要一样
     * @apiParam {JSON} extraData 额外数据,如果是正常结束可以传递 从哪里退出的场景，比如：正常退出 或者 返回按钮退出
     * @apiSuccessExample {json} 示例:
     * sdk.sceneEnd('第1关','返回按钮退出',(d)=>{
     *               console.log("场景回调",d);
     *})
     */
    setSceneEnd(sceneName,params,callbackFunction){

        var data = this.getItem(sceneName);

        console.log("场景数据结束",data);

        var nowTime = new Date().getTime();

        if(data)
        {
            data = JSON.parse(data);
            data.end_time = nowTime/1000; 
            data.take_time =  data.take_time+((nowTime/1000)-data.last_time);
            
            if(sceneName==this.gameOnlineKey)
            {
                data.last_time=nowTime/1000;
                this.setItem(sceneName,JSON.stringify(data));
                console.log("setSceneEnd->场景数据结束",JSON.stringify(data));
            }
           

            this.Post(this.ip3 + this.Logcommon, { log_type: "SceneLog", data: JSON.stringify(data) }, function (d) {
                if(callbackFunction)
                {
                    callbackFunction(d);
                }
                
              });

        }
      
       
        
    },

     /**
     * @apiGroup C
     * @apiName gameStart
     * @api {数据存储} 数据存储 gameStart(存) 玩家进入游戏界面开始调用
     * @apiParam {JSON} params 额外数据
     * @apiSuccessExample {json} 示例:
     * sdk.gameStart({},null)
     */
    gameStart(params,callbackFunction){

        if(sdk_conf.game_online)
        {
            this.setSceneStart(this.getGameOnlineKey(),params);

            this.isGameStart = true;
        }else
        {
            console.error("您没有打开游戏在线时长统计");
        }
        // var nowTime = new Date().getTime();
        // var data = JSON.parse(this.getItem("游戏在线"));
        // data.last_time = nowTime/1000;
        // this.setItem("游戏在线",JSON.stringify(data));


    },



    getGameOnlineKey()
    {

        if(sdk_conf.game_online)
        {
            if(this.gameOnlineKey=='游戏在线')
            {
                //如果当前是默认游戏在线名称
                this.gameOnlineKey = this.gameOnlineKey+this.formatTime(new Date(),"date","");
                
            }else
            {
                //已经生成了游戏在线key
                var nowGameKey = '游戏在线'+this.formatTime(new Date(),"date","");
                if(this.gameOnlineKey==nowGameKey)
                {
                    //如果还在当天之内

                }else
                {
                    //如果已经过了一天了，做最后一次数据上传
                    this.setSceneEnd(this.gameOnlineKey,{});

                    //修改当前在线的key
                    this.gameOnlineKey = nowGameKey;

                    //并且开始新的游戏开始
                    this.setSceneStart(this.gameOnlineKey,{});

                }
            }
        

        
            return  this.gameOnlineKey;
        }else
        {
            console.error("您没有打开游戏在线时长统计");
        }
    },

    
    /**
     * @apiGroup C
     * @apiName getButtonConfig
     * @api {数据存储} 数据存储 getButtonConfig（取）
     * @apiParam {String} buttonKey 按钮的键值 比如 hz2 hz3
     * 
     * @apiSuccessExample {json} 示例:
     * var d = sdk.getButtonConfig("hz2");
     * 特别说明：对于视频分享切换的解析返回的json为：
     * {"type":"share","count":5,"left_count":3,"use_count":2,"next":"key_1"}
     * 技术获取之后根据d.type判断类型然后做响应处理就可以了;
     * 
     * 
     */
    getButtonConfig(buttonKey){


        return this.getButtonConfig2(buttonKey,1);
        
    },

    /**
     * @apiGroup C
     * @apiName getButtonConfig
     * @api {数据存储} 数据存储 getButtonConfig（取）
     * @apiParam {String} buttonKey 按钮的键值 比如 hz2 hz3
     * @apiParam {int} isCount 值为1或者0  1：表示本次调用使用次数加一;0：表示本次调用使用次数不发生变化
     * 
     * @apiSuccessExample {json} 示例:
     * var d = sdk.getButtonConfig2("xxx",1);
     * 特别说明：对于视频分享切换的解析返回的json为：
     * {"type":"share","count":5,"left_count":3,"use_count":2,"next":"key_1"}
     * 技术获取之后根据d.type判断类型然后做响应处理就可以了;
     * if(d.type=='share')
     * {
     *      //凋起分享
     *      sdk.shareAppMessage({type: 1,query: "",success:xxx,fail:xxx });
     * }else
     * {
     *      //凋起视频
     * 
     *      adSdk.videoSuccess = function(){
     *      //视频看完处理逻辑
     *      this.successFunction();
     *      };
     *      adSdk.videoFail = function(){
     *      //视频未看完处理逻辑
     *      this.failFunction();`
     *      };
     *      adSdk.videoError = function(){
     *          //视频凋起失败处理逻辑，要么就是广告id没有或者是调起视频广告太频繁微信限制调起，这里一般都会改成去调起分享
     *          this.errorFunction();
     *      };
     *      var videoAd = adSdk.createVideoAd(1,videoAdUnitId);
     *      videoAd.load().then(() => videoAd.show());
     *      
     * }
     * //如果多个视频广告id（videoAdUnitId）的情况，通过后台技术配置Config2获取对应的视频广告id，比如：sdk.getConfig2().videoAdUnitId1 或者sdk.getConfig2().videoAdUnitId2
     * 
     * 
     */
    getButtonConfig2(buttonKey,isCount)
    {
        var c3 = this.getConfig3();

        if(c3.length>0)
        {

            for(var i=0;i<c3.length;i++)
            {
                var c = c3[i];
                if(c.key===buttonKey)
                {
                    var dl =c.date_list;

                    for(var i=0;i<dl.length;i++)
                    {
                            var d = dl[i];

                            var nowTime =new Date().getTime();
                            var date = this.formatTime(new Date(),"date","");
                            if(nowTime >=d.s_time && nowTime <=d.e_time)
                            {
                                if(c.type==='mix')
                                {
                           
                                    var countKey = buttonKey+":"+date+":"+i+":count";
                                    var count = this.getItem(countKey);
                                    console.log(buttonKey+"->"+countKey,count);
                                    if(!count)
                                    {
                                            count = 1;
                                    }
                                    var startKey = buttonKey+":"+date+":"+i+":start:"+d.data.start.type+":"+count;
    
                                    
                                    var startVal = this.getItem(startKey);
                                      
                                    console.log(buttonKey+"->"+startKey,startVal);
                                    if(!startVal)
                                    {
                                                startVal = 0;
                                    }
        
                                    if(startVal>=d.data.start.count)
                                    {
            
                                                
                                        return this.nextConfig(buttonKey,date,d.data,d.data.start.next,i,count,isCount);
                                            
        
                                    }else
                                    {
                                        //当前记录的次数小于配置次数
        
                                        if(isCount==1)
                                        {
                                            startVal++;
                                            this.setItem(startKey,startVal);
                                      
                                            d.data.start.left_count = d.data.start.count-startVal;
                                            d.data.start.use_count = startVal;
                                        }
                                        
                                        return d.data.start;
                                    }
                     
                         
                                   

                                    
                                }else
                                {
                                    return d;
                                }
                                
                            }

                    }

                }
            }

            return null;


        }else{
            return null;
        }
    },

    nextConfig(buttonKey,date,data,nextKey,i,count,isCount)
    {

        if(nextKey=='end')
        {
            return null;
        }
        var nextCacheKey = buttonKey+":"+date+":"+i+":"+nextKey+":"+data[nextKey].type+":"+count;
        var nextCacheVal = this.getItem(nextCacheKey);
        console.log("nextConfig->"+nextCacheKey,nextCacheVal);                            
        if(!nextCacheVal)
        {
            nextCacheVal = 1;
        }else
        {
            nextCacheVal = nextCacheVal+1;
        }
            
        //计数的话
        if(isCount==1)
        {
            this.setItem(nextCacheKey,nextCacheVal);
        }
        
            
                                                   
            
        if(nextCacheVal>data[nextKey].count)
        {
            //当前缓存中的记录当前key的次数已经超过配置次数

            if(data[nextKey].next=='start')
            {
                var countKey = buttonKey+":"+date+":"+i+":count";
                count=count+1;
                this.setItem(countKey,count);
            }
           
            //往下递归
            return this.nextConfig(buttonKey,date,data,data[nextKey].next,i,count,isCount);                                
        }else
        {
            //计数的话
            if(isCount==1)
            {
                data[nextKey].left_count = data[nextKey].count-nextCacheVal;
                data[nextKey].use_count = nextCacheVal;
            }
            
            return data[nextKey];
        }
            
        
    },
     /**
     * @apiGroup C
     * @apiName navigateToMiniProgram
     * @api 跳转到小程序或者小游戏注意有时间限定 navigateToMiniProgram 
     * @apiParam {json} config json包含app_id,path,extraData,env_version
     * @apiParam {fucntion} success 成功返回
     * @apiParam {fucntion} fail 失败返回
     * @apiParam {fucntion} complete 完成返回
     * 
     * @apiSuccessExample {json} 示例:
     * var d = sdk.getButtonConfig('hz2');
     * sdk.navigateToMiniProgram(d);
     */

    navigateToMiniProgram(config,success,fail,complete)
    {
        //var nowTime =new Date().getTime();
        //if(nowTime >=config.s_time && nowTime <=config.e_time)
        //{
            wx.navigateToMiniProgram({
                appId: config.app_id,   // 要打开的小程序appId
                path: config.path,   //  打开的页面路径，如果为空则打开首页
                extraData: config.extra,  // 需要传递给目标小程序的数据
                envVersion:config.env_version, //特殊情况下需要跳转到对应小程序的开发版本
                success: success,
                fail: fail,
                complete: complete,
            });
        //}
    },


    

};
// module.exports = sdk;
window.sdk = sdk;

