//登陆逻辑
import BehaviorBase from '../framework/BehaviorBase';
import GameProcessManager from '../net/GameProcessManager';
import ConstMsgId from '../net/ConstMsgId';
import Event from '../net/Event';
import ConstDefine from '../model/ConstDefine';
import Common from '../common/Common';
import Define from '../common/Define';
import AudioControlManager from '../common/AudioControlManager';
import PlayerInfoItem from '../model/PlayerInfoItem';

import DataModelManager from '../framework/DataModelManager';

import MsgTransfer from '../net/MsgTransfer';

let loginBehavior = null

cc.WXNativeCallJS = function(method,code)
{
    console.log('cc.WXNativeCallJS:method' + method + 'code:' + code)
    loginBehavior.getAccessToken(code)
}

export default class LoginBehavior extends BehaviorBase
{
    constructor()
    {
        console.log("LoginBehavior constructor start")
        super();
        this._GameProcessManager = new GameProcessManager();
        this._AudioControlManager = new AudioControlManager();
        this.dmm = DataModelManager;
        this.playerInfoModel = this.dmm.getModel('PlayerInfoModel'); 
        this.configData = DataModelManager.getModel('ConfigData');
        this.hasLogin = false;
        this.needSendRandMatch = false;
        this.battleType = ConstDefine.BattleType.NONE;
        this.strength = 0;
        this.lastStrengthRestoreTime = 0;
        this.weekScore = 0;
        this.total_win = 0;
        this.honorEnable = false;
        this.bNeedCheckBoot = false;
        this.bNeedShowGroupRank = false;
        this.oldWeekScore = 0;
        this.oldRandomMath = 0;
        this.lefttime_day = 0;
        this.lefttime_hour = 0;
        this.lefttime_minute = 0;
        this.lefttime_second = 0; 
        this.shave_clearly_num = 0; //剃光头次数
        this.reversible_num = 0; // 逆转次数
        this.highest_score = 0;// 历史最高分
        this.currentweek_highest_score = 0;// 本周最高分
        this.highest_normalbattle_successive_win = 0;// 最高普通连胜次数
        this.highest_weekbattle_successive_win = 0;  // 最高周赛连胜次数  
        this.friendPKMatchId = 0;
        this.friendPKRoomId = '';
        this.needShowAuth = false;//luo 原来是true
        console.log("LoginBehavior constructor end")
        loginBehavior = this

    }


    CreateLoginStart(){
        var url =  Define.LOGIN_WS 
        console.log("CreateLoginStarta:" + url)
        this._GameProcessManager.createSocket(url, null,Define.SOCKET_TYPE.PLAZA)
    }

    wxCode2OpenId()
    {
        var self = this
        wx.login({
            timeout:9000,
            success:function(res){
                console.log("wx.login success")
                console.log(res)
                self.sendCode(res.code)
            },
            fail:function(res){
                console.log("wx.login fail")
                console.log(res)
            },
            complete:function(res){
                console.log("wx.login complete")
                console.log(res)
            },

        })
    }


    login()
    {
        var self = this;
        if(CC_WECHATGAME)
        {
            wx.getSetting({
                success:function(res){
                    console.log("getSetting success")
                    console.log(res)
                    if (res.authSetting['scope.userInfo']) {

                    wx.getUserInfo({
                        lang:'zh_CN',
                        fail:function(res){
                            console.log("getUserInfo fail res")
                            console.log(res)

                        },
                        success: function(res) {
                            console.log("getUserInfo success res")
                            console.log(res)
                            var userInfo = res.userInfo
                            self.playerInfoModel.setSelfWXPlayerInfo(userInfo)
                            self.wxCode2OpenId()
                            self.needShowAuth = false
                        }
                    })
                }
                else
                {
                    self.needShowAuth = true
                    let button = wx.createUserInfoButton({
                        type: 'text',
                        text: '登录',
                        lang:'zh_CN',
                        style: {
                            left: 10,
                            top: 76,
                            width: 200,
                            height: 40,
                            lineHeight: 40,
                            backgroundColor: '#ff0000',
                            color: '#ffffff',
                            textAlign: 'center',
                            fontSize: 16,
                            borderRadius: 4,
        
                        }
        
                    })
                    button.onTap((res) => {
                        console.log("userinfo")
                        console.log(res)
                        var userInfo = res.userInfo
                        if(userInfo!=null&&userInfo!=undefined)
                        {
                            self.playerInfoModel.setSelfWXPlayerInfo(userInfo)
                            self.wxCode2OpenId()
                            self.needShowAuth = false
                            button.destroy()
                        }
                        else
                        {
                            
                        }


                    })
                }


                },
                fail:function(res){
                    console.log("getSetting fail")
                    console.log(res)
                    let button = wx.createUserInfoButton({
                        type: 'text',
                        text: '登录',
                        lang:'zh_CN',
                        style: {
                            left: 10,
                            top: 76,
                            width: 200,
                            height: 40,
                            lineHeight: 40,
                            backgroundColor: '#ff0000',
                            color: '#ffffff',
                            textAlign: 'center',
                            fontSize: 16,
                            borderRadius: 4,
        
                        }
        
                    })
                    button.onTap((res) => {
                        console.log("userinfo")
                        console.log(res)
                        var userInfo = res.userInfo
                        if(userInfo!=null&&userInfo!=undefined)
                        {
                            self.playerInfoModel.setSelfWXPlayerInfo(userInfo)
                            self.wxCode2OpenId()
                            self.needShowAuth = false
                            button.destroy()
                        }
                        else
                        {
                            
                        }

                    })

                },
                complete:function(res){
                    console.log("getSetting complete")
                    console.log(res)
                },

            })
        }
        else if(CC_JSB && cc.sys.OS_ANDROID === cc.sys.os)
        {
            console.log('com/xixi/cyqp/wxapi/WXEntryActivity getTokenRequest')
            jsb.reflection.callStaticMethod("com/xixi/cyqp/wxapi/WXEntryActivity", "getTokenRequest", "()V");//调用java代码进行微信登录

        }
         else {
            setTimeout(function() {
                self.needShowAuth = false;
                self.sendLoginWX();
            }, 1000);
        }
    }

    getAccessToken(code){        //获取accessToken

        if(code==null|| code.length<=0)
        {
            console.log('getAccessToken code==null|| code.length<=0 ')
            return
        }

        var url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + Common.androidappid + "&secret="+ Common.androidappsecret + "&code=" + code + "&grant_type=authorization_code";
        var self = this;
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function(){
            if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 400)) {
                var response = xhr.responseText;
                console.log("response===>>>",response);
                var msg = JSON.parse(response);
                var access_token = msg.access_token;
                var refresh_token = msg.refresh_token;
                var openid = msg.openid;
                //如果超时进行重新刷新accessToken
                if(msg.expires_in >= 7200){
                    //刷新accesstoken
                    self.freshAccessToken(refresh_token).then(function(data){
                       console.log("刷新accessToken 是",data);
                       access_token = data;
                       self.getUserInfo(access_token,openid);
                       //cc.director.loadScene("helloworld");
                    });
                    console.log("这个accessToken是刷新出来的token",access_token);
                }else{
                    self.getUserInfo(access_token,openid);
                    //cc.director.loadScene("helloworld");
                }
                
            }
        };
        xhr.open("GET",url,true);
        xhr.send();
    }
    getUserInfo (access_token,openid){       //获取用户信息
        console.log("accessToken is " + access_token);
        console.log("openid is " + openid);
        var url = "https://api.weixin.qq.com/sns/userinfo?access_token="+access_token + "&openid="+openid+"&lang=zh_CN";
        var self = this;
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function(){
            if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 400)) {
                var response = xhr.responseText;
                console.log("response===>>>",response);
                var msg = JSON.parse(response);
                console.log("msg is " , msg);
                console.log("nickName is " + msg.nickname);
                console.log("city is " + msg.city);
                console.log("country " + msg.country);
                console.log("sex is  " + msg.sex);
                msg.openId = msg.openid
                msg.openid = ""
                msg.nickName = msg.nickname
                msg.nickname = ""
                msg.avatarUrl = msg.headimgurl 
                msg.headimgurl = ""
                msg.unionId = msg.unionid 
                msg.unionid = ""
                self.needShowAuth = false
                self.playerInfoModel.setSelfWXPlayerInfo(msg)
                var selfuserinfo = self.playerInfoModel.getSelfWXPlayerInfo()
                console.log("selfuserinfo===>>>",JSON.stringify(selfuserinfo));

                self.playerInfoModel.setSelfOpenId(openid)
                
                self.sendLoginWX() //立即登录


            }
        };
        xhr.open("GET",url,true);
        xhr.send();
 
    }

    freshAccessToken (refresh_token){
        var url = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=" + Common.androidappid + "&grant_type=refresh_token&refresh_token="+refresh_token;
        var self = this;
        var xhr = new XMLHttpRequest();
        var ac;
        return new Promise(function(resolve,reject){
            xhr.onreadystatechange = function(){
                if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 400)) {
                    var response = xhr.responseText;
                    console.log("response===>>>",response);
                    var msg = JSON.parse(response);
                    ac = msg.access_token;
                    console.log("ac is " + ac);
                    resolve(ac);
                }
            };
            xhr.open("GET",url,true);
            xhr.send();
        });
        
    }







    saveStrengthInfo(pb)
    {
        this.strength = pb.strength;
        this.lastStrengthRestoreTime = parseInt(pb.last_strength_resotre_time);
    }

    showUserInfo()
    {

    }

    setData(wMainCmdID,wSubCmdID,data)
    {
        if (ConstMsgId.MDM_MB_LOGON === wMainCmdID) {
            if (ConstMsgId.SUB_MB_LOGON_WX === wSubCmdID) {
                var wxLoginData = JSON.parse(data)
                console.log(wxLoginData);
                if (wxLoginData.hasOwnProperty('openid')) {
                    this.playerInfoModel.setSelfOpenId(wxLoginData.openid)
                }
                if (wxLoginData.hasOwnProperty('session_key')) {
                    this.playerInfoModel.setSelfSessionKey(wxLoginData.session_key)
                }
                console.log("this.playerInfoModel.getSelfOpenId():"+this.playerInfoModel.getSelfOpenId())
                console.log("this.playerInfoModel.getSelfSessionKey():"+this.playerInfoModel.getSelfSessionKey())


                this.sendLoginWX() //立即登录

            } else if ( ConstMsgId.SUB_MB_LOGON_SUCCESS === wSubCmdID) {//登录成功读取用户信息
                cc.log("登录成功提示")
                this.readPlayerInfo(data);
                this.sendLevelInfo();
            } else if (ConstMsgId.SUB_MB_LOGON_FAILURE === wSubCmdID) {//登录失败
                this.readLoginFailureResion(data);
            }
        } else if ( ConstMsgId.MDM_GP_LOGON === wMainCmdID) {
            cc.log("广场登录")
            if ( ConstMsgId.SUB_MB_LOGON_SUCCESS === wSubCmdID) {
                cc.log("登录成功提示")
                this.readPlayerInfo(data);
                this.sendLevelInfo();
            }
        } else if (ConstMsgId.MDM_GP_USER_SERVICE === wMainCmdID) {
            if (ConstMsgId.SUB_GP_GROWLEVEL_PARAMETER === wSubCmdID) {
                this.onSubLevelParameter(data);
            }
        }
    }

    readPlayerInfo(data)
    {
        var openid = this.playerInfoModel.getSelfOpenId()
        var wxinfo = this.playerInfoModel.getSelfWXPlayerInfo()
        
        var player = new PlayerInfoItem(openid,wxinfo,2,0,0)
        var dataview = new DataView(data)
        var readPos = 0
        player.wFaceID = dataview.getUint16(readPos,Common.littleEndian)
        readPos += 2
        player.cbGender = dataview.getUint8(readPos,Common.littleEndian)
        readPos += 1
        player.dwCustomID = dataview.getUint32(readPos,Common.littleEndian)
        readPos += 4
        player.dwUserID = dataview.getUint32(readPos,Common.littleEndian)
        readPos += 4
        player.dwGameID = dataview.getUint32(readPos,Common.littleEndian)
        readPos += 4
        player.dwExperience = dataview.getUint32(readPos,Common.littleEndian)
        readPos += 4    
        player.dwLoveLiness = Common.readint64(data,readPos)
        readPos += 8        
        var szAccountbuffer = data.slice(readPos, readPos+32*2);
        player.szAccount = Common.ab2str(szAccountbuffer)
        readPos += 32*2  
        var szNickNamebuffer = data.slice(readPos, readPos+32*2);
        player.szNickName = Common.ab2str(szNickNamebuffer)
        readPos += 32*2 
        var szDynamicPassbuffer = data.slice(readPos, readPos+33*2);
        player.szDynamicPass = Common.ab2str(szDynamicPassbuffer)
        readPos += 33*2 
        player.lUserScore = Common.readint64(data,readPos)
        readPos += 8  
        player.lUserIngot = Common.readint64(data,readPos)
        readPos += 8  
        player.lUserInsure = Common.readint64(data,readPos)
        readPos += 8  
        player.dUserBeans = Common.readint64(data,readPos)
        readPos += 8  
        player.cbInsureEnabled = dataview.getUint8(readPos,Common.littleEndian)
        readPos += 1
        var  bAngent =  dataview.getUint8(readPos,Common.littleEndian)
        player.bIsAngentAccount = (bAngent === 1)
        readPos += 1
        player.cbLockMachine = dataview.getUint8(readPos,Common.littleEndian)
        readPos += 1
        player.lRoomCard = Common.readint64(data,readPos)
        readPos += 8 
        player.dwLockServerID = dataview.getUint32(readPos,Common.littleEndian)
        readPos += 4        
        player.dwLockKindID = dataview.getUint32(readPos,Common.littleEndian)
        readPos += 4                             
        Common.Print("lock server " + player.dwLockServerID)
        Common.Print("lock kind " + player.dwLockKindID)
        Common.Print("szNickName " + player.szNickName)
        Common.Print("szAccount " + player.szAccount)
        Common.Print("szDynamicPass " + player.szDynamicPass)
        Common.Print("dwCustomID " + player.dwCustomID)
        Common.Print("dwUserID " + player.dwUserID)
        Common.Print("dwGameID " + player.dwGameID)
        Common.Print("lUserScore " + player.lUserScore)
        Common.Print("lUserIngot " + player.lUserIngot)
        Common.Print("lUserInsure " + player.lUserInsure)
    
        var  curlen = readPos
        var datalen = data.byteLength
    
        Common.Print("*** curlen-"+ curlen)
        Common.Print("*** datalen-"+ datalen)
    
        var tmpSize 
        var tmpCmd
        while(curlen<datalen){
            tmpSize = dataview.getUint16(readPos,Common.littleEndian)
            readPos += 2    
            tmpCmd = dataview.getUint16(readPos,Common.littleEndian)
            readPos += 2    
      
            if (!tmpSize || ! tmpCmd )
            {   
                break
            }
    
            Common.Print("*** tmpSize-" + tmpSize)
            Common.Print("*** tmpCmd-" + tmpCmd)
            if (tmpCmd == ConstMsgId.DTP_GP_UI_UNDER_WRITE) 
            {
                player.szSign = Common.getString(data,readPos,  tmpSize)
                readPos += tmpSize

                if (! player.szSign )
                {
                   player.szSign = "此人很懒，没有签名"
                }
            }    
            else if (tmpCmd == ConstMsgId.DTP_GP_MEMBER_INFO) 
            {   player.cbMemberOrder = dataview.getUint8(readPos,Common.littleEndian)
                readPos+=1
                for(var i = 1;i < 8;i ++ ) 
                {
                    var  systemtime = dataview.getUint16(readPos,Common.littleEndian)
                    readPos += 2
                    Common.Print("systemtime-"+ systemtime)
                } 
            }

            else if (tmpCmd == ConstMsgId.login.DTP_GP_UI_QQ) 
            {
                player.szQQNumber = Common.getString(data,readPos, tmpSize)
                readPos += tmpSize
                Common.Print("qq " + player.szQQNumber)
            }
            else if (tmpCmd == ConstMsgId.login.DTP_GP_UI_EMAIL)
            {   player.szEmailAddress = Common.getString(data,readPos,tmpSize) 
                readPos += tmpSize
                Common.Print("email " + player.szEmailAddress)
            }     
            else if (tmpCmd == ConstMsgId.login.DTP_GP_UI_SEAT_PHONE )
            {
                player.szSeatPhone = Common.getString(data,readPos,tmpSize) 
                Common.Print("szSeatPhone " + player.szSeatPhone)
            }    
            else if (tmpCmd == ConstMsgId.login.DTP_GP_UI_MOBILE_PHONE )
            {   player.szMobilePhone = Common.getString(data,readPos,tmpSize) 
                readPos += tmpSize
                Common.Print("szMobilePhone " + player.szMobilePhone)
            }    
            else if (tmpCmd == ConstMsgId.login.DTP_GP_UI_COMPELLATION )
            {   player.szTrueName = Common.getString(data,readPos,tmpSize) 
                readPos += tmpSize
                Common.Print("szTrueName " + player.szTrueName)
            }    
            else if (tmpCmd == ConstMsgId.login.DTP_GP_UI_DWELLING_PLACE )
            {   player.szAddress = Common.getString(data,readPos,tmpSize) 
                readPos += tmpSize
                Common.Print("szAddress " + player.szAddress)
            }    
            else if (tmpCmd == ConstMsgId.login.DTP_GP_UI_PASSPORTID )
            {   player.szPassportID = Common.getString(data,readPos,tmpSize) 
                readPos += tmpSize
                Common.Print("szPassportID " + player.szPassportID)
            }    
            else if (tmpCmd == ConstMsgId.login.DTP_GP_UI_SPREADER )
            {   player.szSpreaderAccount = Common.getString(data,readPos,tmpSize) 
                readPos += tmpSize
                Common.Print("szSpreaderAccount" + player.szSpreaderAccount)
            }     
            else if (tmpCmd == 0) 
                break
            else
            {    
                for( i = 1;i < tmpSize; i++ )
                { 
                    var bt = dataview.getUint8(readPos,Common.littleEndian)
                    readPos+=1
                     if (!bt) 
                    { 
                        break
                    } 
                }
            }
            curlen = readPos
        }
        var playerStr = JSON.stringify(player)  
        this.playerInfoModel.setSelfPlayerInfo(player)  
        Common.Print("player"+playerStr)
        Common.Print("player.szAccount " + player.szAccount)
        Common.Print("player.szDynamicPass " + player.szDynamicPass)
        Common.Print("player.dwCustomID " + player.dwCustomID)

    }

    readLoginFailureResion(data) {
        var callBackData = {};
        var dataview = new DataView(data);
        var readPos = 0;
        callBackData.lResultCode = dataview.getUint32(readPos, Common.littleEndian);
        readPos += 4;
        callBackData.szDescribeString = Common.getString(data, readPos, 56);
    }

    readVIPInfo(data)
    {
        var dataview = new DataView(data)
        var readPos = 0
        var count = dataview.getUint16(readPos,Common.littleEndian)
        readPos+=2

        var wxinfo = this.playerInfoModel.getSelfWXPlayerInfo()

        
        for (var i=1;i<count;i++ )
        {
            var item = {}
            item._order = dataview.getUint8(readPos,Common.littleEndian)
            readPos+=1
            item._name  = Common.getString(data,readPos,16*2) 
            readPos+=16*2
            item._right = dataview.getUint32(readPos,Common.littleEndian)
            readPos+=4
            item._task  = dataview.getUint32(readPos,Common.littleEndian)
            readPos+=4
            item._shop  = dataview.getUint32(readPos,Common.littleEndian)
            readPos+=4
            item._insure= dataview.getUint32(readPos,Common.littleEndian)
            readPos+=4
            item._present=dataview.getUint32(readPos,Common.littleEndian)
            readPos+=4
            item._gift  = dataview.getUint32(readPos,Common.littleEndian)
            readPos+=4
            this.playerInfoModel.setVipInfo(item._order , item)
            console.log("item:" + item._order + "item._gift: "+ item._gift)

        }
        
    }

    checkBoot()
    {
        var bootOptionData  = DataModelManager.getModel('BootOptionData').getBootOptionData();
        //DataModelManager.getModel('BootOptionData').setBootOptionData({});
        if(bootOptionData.hasOwnProperty('query'))
        {
            var queryData = bootOptionData['query'];
            if(queryData.hasOwnProperty('method'))
            {
                if(ConstDefine.ShareFriendPKMessage.shareType == queryData['method'] && queryData.hasOwnProperty('roomId') && queryData.hasOwnProperty('matchId'))
                {
                    var matchId = Number(queryData['matchId']);
                    this.friendPKMatchId = matchId;
                    this.friendPKRoomId = queryData['roomId'];
                    this.enterFriendPKRoom();
                }
                else if(ConstDefine.ShareDoublePKMessage.shareType == queryData['method'] && queryData.hasOwnProperty('teamId') && queryData.hasOwnProperty('matchId'))
                {
                    var matchId = Number(queryData['matchId']);
                    this.joinTeamRequest(matchId, queryData['teamId']);                    
                }
            }   

        }
    }

    checkGroupRank()
    {
        if (!CC_WECHATGAME)
        {
            return;
        }
        var bootOptionData  = DataModelManager.getModel('BootOptionData').getBootOptionData();
        //DataModelManager.getModel('BootOptionData').setBootOptionData({});
        if(bootOptionData.hasOwnProperty('query'))
        {
            var queryData = bootOptionData['query'];
            var shareTicket = bootOptionData['shareTicket'];
            this.shareTicket = shareTicket;
            let self = this;
            if(queryData.hasOwnProperty('method'))
            {
                if (ConstDefine.ShareGroupRankMessage.shareType == queryData['method'])
                {
                    if (CC_WECHATGAME)
                    {
                        DataModelManager.getModel('BootOptionData').setBootOptionData({});
                        this.emit(Event.COM_MSG.REFRESH_GROUP_RANK_VIEW, true);

                        wx.getShareInfo
                        ({
                            shareTicket : shareTicket,

                            complete : function(res)
                            {
                                console.log('================')
                                console.log('get share info ' + JSON.stringify(res));
                                self.test(res);
                                console.log('================')
                            }
                        })
                    }
                }
            }
        }
        
    }

    guestAuth()
    {
        var account = cc.sys.localStorage.getItem("account");

        if(account == null){
            account = "yk_"+ Date.now();
            cc.sys.localStorage.setItem("account",account);
        }
        
        cc.vv.http.sendRequest("/guest",{account:account},this.onAuth);
    }


    sendCode(code)
    {
        var msg = MsgTransfer.encodeLoginMsg(ConstMsgId.MDM_MB_LOGON,ConstMsgId.SUB_MB_LOGON_WX,4 + 4 + code.length*2 + 2,code)
        this._GameProcessManager.sendMsg(msg);
    }

    sendLoginWX()
    {
        if (CC_WECHATGAME) {
            var msg = MsgTransfer.encodeLoginMsg(ConstMsgId.MDM_MB_LOGON,ConstMsgId.SUB_MB_LOGON_OTHERPLATFORM,4 + 4 + 9 + (126+512)*2)
            this._GameProcessManager.sendMsg(msg);
        } else if(CC_JSB && cc.sys.OS_ANDROID === cc.sys.os)
        {
            var msg = MsgTransfer.encodeLoginMsg(ConstMsgId.MDM_MB_LOGON,ConstMsgId.SUB_MB_LOGON_OTHERPLATFORM,4 + 4 + 9 + (126+512)*2)
            this._GameProcessManager.sendMsg(msg);
        }
         else {
             cc.log("账号登录走起");
            // var msg = MsgTransfer.encodeLoginMsg(ConstMsgId.MDM_GP_LOGON,ConstMsgId.SUB_GR_LOGON_USERID, 235,"156","284589f4de6ad3c86230fdcbe7d6f969")
            // this._GameProcessManager.sendMsg(msg);
        }
    }



    pullData(token)
    {
        var requestUrl = this.configData.getApiAddress() == '' ? 'http://192.168.3.178:8080/utils/wx_login' : this.configData.getApiAddress()+'/utils/wx_login';
         
        //var requestUrl = 'http://192.168.3.182:7654/utils/wx_login';
        var xhr = cc.loader.getXMLHttpRequest();
        xhr.open("POST", requestUrl, true);
        let self = this;
        xhr.onreadystatechange = function()
        {
            if (xhr.readyState === 4 && (xhr.status >= 200 && xhr.status < 300))
            {
                console.log('http res(' + xhr.responseText.length + '):' + xhr.responseText);
                try
                {
                    var ret = JSON.parse(xhr.responseText);
                    self.onGetDataSuccess(ret);
                }
                catch(e)
                {
                    console.log('err:' + e);
                }
            }
        };
        var body = {"token" :  token};
        xhr.send(JSON.stringify(body));

    }

    onGetDataSuccess(ret)
    {
        var wxResp = JSON.parse(ret.wxResp);
        this.session_key = wxResp.session_key;
        console.log('sessionKey : ' + wxResp.session_key);
    }

    test(res)
    {
        var Buffer = require('buffer').Buffer;
        var crypto = require('crypto');
        var appId = 'wx76718bdb7dcc8a35'
        var sessionKey = this.session_key;
        // var encryptedData = 
        //     'CiyLU1Aw2KjvrjMdj8YKliAjtP4gsMZM'+
        //     'QmRzooG2xrDcvSnxIMXFufNstNGTyaGS'+
        //     '9uT5geRa0W4oTOb1WT7fJlAC+oNPdbB+'+
        //     '3hVbJSRgv+4lGOETKUQz6OYStslQ142d'+
        //     'NCuabNPGBzlooOmB231qMM85d2/fV6Ch'+
        //     'evvXvQP8Hkue1poOFtnEtpyxVLW1zAo6'+
        //     '/1Xx1COxFvrc2d7UL/lmHInNlxuacJXw'+
        //     'u0fjpXfz/YqYzBIBzD6WUfTIF9GRHpOn'+
        //     '/Hz7saL8xz+W//FRAUid1OksQaQx4CMs'+
        //     '8LOddcQhULW4ucetDf96JcR3g0gfRK4P'+
        //     'C7E/r7Z6xNrXd2UIeorGj5Ef7b1pJAYB'+
        //     '6Y5anaHqZ9J6nKEBvB4DnNLIVWSgARns'+
        //     '/8wR2SiRS7MNACwTyrGvt9ts8p12PKFd'+
        //     'lqYTopNHR1Vf7XjfhQlVsAJdNiKdYmYV'+
        //     'oKlaRv85IfVunYzO0IKXsyl7JCUjCpoG'+
        //     '20f0a04COwfneQAGGwd5oa+T8yO5hzuy'+
        //     'Db/XcxxmK01EpqOyuxINew=='
        // var iv = 'r7BXXKkLb8qrSNn05n0qiA=='
        var iv = res.iv;
        var encryptedData = res.encryptedData;
        sessionKey = new Buffer(sessionKey, 'base64');
        encryptedData = new Buffer(encryptedData, 'base64');
        iv = new Buffer(iv, 'base64');

        try
        {
            var decipher = crypto.createDecipheriv('aes-128-cbc', sessionKey, iv);
            decipher.setAutoPadding(true);
            var decoded = decipher.update(encryptedData, 'binary', 'utf8');
            decoded += decipher.final('utf8');
            decoded = JSON.parse(decoded);
        }
        catch(err)
        {
            throw new Error('Illegal Buffer');
        }

        if (decoded.watermark.appid !== appId)
        {
            throw new Error('Illegal appId');
        }

        console.log('解密后 : ' + JSON.stringify(decoded));
    }

 
    savePlayerInfo(pb)
    {
        if (pb.success == true )
            {
                Common.H5SDKReport('SceneFlow',200001,2,1,108,{});

                this.playerInfoModel.selfRoleId = pb.role_id;
                this.hasLogin  = true;
                this.lefttime_day = pb.lefttime_day;
                this.lefttime_hour = pb.lefttime_hour;
                this.lefttime_minute = pb.lefttime_minute;
                this.lefttime_second = pb.lefttime_second;

                this.emit(Event.CPT_MSG.LOGIN_SHOW_USERINFO);
                var scene =  cc.director.getScene();

               console.log("currentscene: " + scene.name);

                if(CC_WECHATGAME&&scene.name=='game')
                {     
                    this.checkBoot();
                }

                // if (cc.sys.os != cc.sys.OS_WINDOWS)
                // { 
                //     console.log("getUserInfo");
                    
                //     // wx.postMessage({
                //     //     message: 'getUserInfo',
                //     //     data: {data:{selfPlayerOpenId:pb.open_id}},
                //     // });     
                //     var self = this;
                //     wx.getUserInfo({
                //         openIdList: ['selfOpenId'],
                //         lang: 'zh_CN',
                //         success: (res) => {
                //             console.log('success', res)
                //             self.playerInfoModel.setWXPlayerInfo(res.userInfo);
                //             self.emit(Event.CPT_MSG.LOGIN_SHOW_USERINFO,res);     
                //             self.checkBoot();
                //         },
                //         fail: (res) => {
                //             reject(res)
                            
                //         }
                //     })

                // }
            }
    }

    randomMatch()
    {
        this.exitFriendPKRoom();

        var info = this.playerInfoModel.getSelfWXPlayerInfo();

        this.battleType = ConstDefine.BattleType.NormalBattle;
        
        var _pb = {weixin_user_info: JSON.stringify( info), type: this.battleType};
        cc.log('++++++++++++client request random match++++++++++++');
        Common.H5SDKReport('SceneFlow',200003,1,1,100,{I0:0});
        this._GameProcessManager.send(ConstMsgId.CS.MatchRequest, _pb);
    }

    saveOldData()
    {
        this.oldWeekScore = this.weekScore;
        this.oldRandomMath = this.total_win;
    }
    
    unMatch()
    {
        var _pb = {};
        this._GameProcessManager.send(ConstMsgId.CS.UnMatchRequest, _pb);
    }

    weeklyMatch()
    {
        this.exitFriendPKRoom();
        
        var info = this.playerInfoModel.getSelfWXPlayerInfo();
        this.battleType = ConstDefine.BattleType.WeeklyBattle;
        Common.H5SDKReport('SceneFlow',200003,1,1,100,{I0:1});

        var _pb = {weixin_user_info: JSON.stringify( info), type: this.battleType};
        cc.log('++++++++++++client request weekly match++++++++++++');
        this._GameProcessManager.send(ConstMsgId.CS.MatchRequest, _pb);
    }

    requestStrength()
    {
        var _pb = {};
        this._GameProcessManager.send(ConstMsgId.CS.PullStrengthInfoRequest, _pb);
    }

    friendMatch()
    {
        var info = this.playerInfoModel.getSelfWXPlayerInfo();
        var _pb = {weixin_user_info: JSON.stringify( info)};
        this._GameProcessManager.send(ConstMsgId.CS.CreateFriendPkRoomRequest, _pb);       
    }

    exitFriendPKRoom()
    {
        var _pb = {};
        this._GameProcessManager.send(ConstMsgId.CS.ExitFriendPkRoomRequest, _pb);       
    }


    enterFriendPKRoom()
    {
        this.playerInfoModel.setMatchType(Common.MatchType.FriendPK);

        var info = this.playerInfoModel.getSelfWXPlayerInfo();
        var _pb = {'match_id':this.friendPKMatchId,'room_id': this.friendPKRoomId,'weixin_user_info':JSON.stringify( info)};
        this._GameProcessManager.send(ConstMsgId.CS.EnterFriendPkRoomRequest, _pb);       
    }
    
    playMusic(state)
    {
        this._AudioControlManager.playMusic(state);
    }

    playEffect(name)
    {
        this._AudioControlManager.playEffect(name);
    }

    setMusicOpen(val)
    {
        this._AudioControlManager.setMusicOpen(val);
    }


    createTeamRequest()
    {
        var info = this.playerInfoModel.getSelfWXPlayerInfo();
        var _pb = {'weixin_user_info':JSON.stringify( info)};
        this._GameProcessManager.send(ConstMsgId.CS.CreateTeamRequest, _pb);             
    }

    joinTeamRequest(match_id,team_id)
    {
        var info = this.playerInfoModel.getSelfWXPlayerInfo();
        var _pb = {'match_id':match_id,'team_id':team_id,'weixin_user_info':JSON.stringify( info)};
        this._GameProcessManager.send(ConstMsgId.CS.JoinTeamRequest, _pb);    
    }

    leaveTeamRequest()
    {
        var info = this.playerInfoModel.getSelfWXPlayerInfo();
        var _pb = {'weixin_user_info':JSON.stringify( info)};
        this._GameProcessManager.send(ConstMsgId.CS.LeaveTeamRequest, _pb);             
    }


    sendLevelInfo() {
        var msg = MsgTransfer.encodeLoginMsg(ConstMsgId.MDM_GP_USER_SERVICE, ConstMsgId.SUB_GP_GROWLEVEL_QUERY, 144);
        this._GameProcessManager.sendMsg(msg);
    }

    onSubLevelParameter(data) {
        var selfLevelInfo = {};
        var readPos = 0;
        var dataview = new DataView(data);
        selfLevelInfo.wCurrLevelID = dataview.getUint16(readPos,Common.littleEndian);
        readPos += 2;
        selfLevelInfo.dwExperience = dataview.getUint32(readPos,Common.littleEndian);
        readPos += 4;
        selfLevelInfo.dwUpgradeExperience = dataview.getUint32(readPos,Common.littleEndian);
        readPos += 4;
        selfLevelInfo.lUpgradeRewardGold = Common.readint64(data, readPos);
        readPos += 8;
        selfLevelInfo.lUpgradeRewardIngot = Common.readint64(data, readPos);
        readPos += 8;
        window.selfLevelInfo = selfLevelInfo;
        this.emit(Event.CPT_MSG.LEVEL_INFO, selfLevelInfo);
    }
}
