import BehaviorBase from '../Framework/BehaviorBase';
import GameProcessManager from '../net/GameProcessManager';
import ConstMsgId from '../net/ConstMsgId';
import DataModelManager from '../framework/DataModelManager';
import Event from '../net/Event';
import Common from '../common/Common';
import Define from '../common/Define';
import MsgTransfer from '../net/MsgTransfer';
import LogicUnitManager from '../framework/LogicUnitManager';
import PlayerInfoItem from '../model/PlayerInfoItem';
import GameServerItem from '../model/GameServerItem';
import ViewManager from '../ui/ViewManager';
import NetConfig from '../net/NetConfig';

export default class BattleBehavior extends BehaviorBase
{
    constructor()
    {
        super();
        this._GameProcessManager = new GameProcessManager();
        this.dmm = DataModelManager;
        this.playerInfoModel = this.dmm.getModel('PlayerInfoModel'); 
        this.questionInfoModel = this.dmm.getModel('QuestionInfoModel'); 
        this.battleId = 0;
        this.questionId= 0;
        this.battleResult = null;

        this._roomList = new Array()

        this.wTableID	 	= Define.INVALID_TABLE
        this.wChairID	 	= Define.INVALID_CHAIR
        this.cbTableLock	= 0
        this.cbGameStatus 	= 0
        this.cbAllowLookon	= 0
        this.bChangeDesk = false
        this.bEnterAntiCheatRoom = false 		//--进入防作弊房间
        this.bSelfExitRoom = false
        this._tableUserList = new Array()
        this.TableList = []
        this._tableStatus = []
        this.bWaitQuit = false 		//-- 退出等待
        this._delayEnter = false
        this.m_bCallStateEnter = false
        this.m_bRoundOver = false
        this.m_bIsMyBanker = false

        //-- 游戏倒计时
        this.COUNTDOWN_READY = 30           // -- 准备倒计时
        this.COUNTDOWN_CALLSCORE = 20       // -- 叫分倒计时
        this.COUNTDOWN_OUTCARD = 20         // -- 出牌倒计时    
        this.COUNTDOWN_HANDOUTTIME = 30     // -- 首出倒计时
        this.callMaxScore = 0               //当前最大叫分

        this.counterInfos = [] //  倒计时
        this._counterInterVal = 1000
        this.readyCounterId = 1
        this.callScoreCounterStartId = 10
        this.outCardCounterStartId = 20
        this.m_bQuickStart = false
        this.needCheckConnectGame = false //杀掉进程的断线重连
        this.needCheckConnectGameing = false//没有杀掉进程的断线重连

        //this.Counter()
        this.roomIndex = 0
        this.handCards = {};
        
       
         var userInfoStr = cc.sys.localStorage.getItem(Define.UserInfo);
          var userInfo = JSON.parse(userInfoStr)

        this.selfUserID  = userInfo[Define.UserId]
        this.token =  userInfo[Define.Token]
        console.log('token:' + this.token)
        // this.selfUserID = 169
        // this.token = '5558AB18-9CA7-2B92-0077-6215CEB3543B'
        this.playerInfoModel.selfUserID = this.selfUserID
        this.selfPassword = userInfo[Define.Password]
        //this.selfPassword = '123456'
         cc.log(Define.UserInfo + ":" + userInfoStr)
         var currentGameId = cc.sys.localStorage.getItem('CurrentGameId')
         cc.log('currentGameId' + ":" + currentGameId)
         this.currentGameId = currentGameId
         this.currentGameId = 9
        this.wanFaInfo = null 
        this.currentRoomInfo = null
        var self = this
        
        this.currentWanFaId = -1

        // setTimeout(() => {
        //      self.requestWanFaInfo()
        // }, 1000);
        setTimeout(() => {
            self.requerMoregame()
        }, 1000);
       
    }

   

    requerMoregame()
    {
        var self = this
        var url = Define.GameWanFaMore + "?id=" + this.currentGameId
        Common.sendGetGameConfig(url,function(err,res)
        {
         
            if(err)
            {
                console.log('requerMoregame error:' + err + 'url:' +  url  )
                return
            }

            console.log('res:' + res)

            var info = JSON.parse(res)
            console.log('info.code:' + info['code'])

            if(info['code']!=200)
            {
                return
            }

            self.moregameInfo = info.data
            console.log('requerMoregame emit:' +  JSON.stringify( info.data))

            self.emit(Event.COM_MSG.MOREGAME_INFO,self.moregameInfo);
        }) 
    }

    requestWanFaInfo()
    {
        var self = this
        var url = Define.GameWanFaUrl + "?id=" + this.currentGameId
        Common.sendGetGameConfig(url,function(err,res)
        {
         
            if(err)
            {
                console.log('requestWanFaInfo error:' + err + 'url:' +  url  )
                return
            }

            console.log('res:' + res)

            var info = JSON.parse(res)
            console.log('info.code:' + info['code'])

            if(info['code']!=200)
            {
                return
            }

            self.wanFaInfo = info.data
            console.log('requestWanFaInfo emit:' +  JSON.stringify( info.data))

            self.emit(Event.COM_MSG.WANFA_INFO,self.wanFaInfo);
            self.checkRoomConnect()

            // self.requestRoomInfo(464)// test
        })

    }

    checkRoomConnect()
    {
        var serverinfoStr = cc.sys.localStorage.getItem(Define.ServerInfo);
        if(serverinfoStr!=null&&serverinfoStr!='')
        {

            var serverInfo = JSON.parse(serverinfoStr)

            if(serverInfo[Define.WanFaId]!=undefined&&serverInfo[Define.WanFaId]!=null&&serverInfo[Define.WanFaId]!='')
            {
                this.currentWanFaId = parseInt(serverInfo[Define.WanFaId])
                this.requestRoomInfo()
            }


        }
    }

    requestRoomInfo()
    {
        if(this.currentWanFaId <=0)
        {
            console.log('requestRoomInfo error wanFaId ' + this.currentWanFaId)
            return 
        }
        var self = this
        var url = Define.GameRoomUrl + "?id=" + this.currentWanFaId
        Common.sendGetGameConfig(url,function(err,res)
        {
         
            if(err)
            {
                console.log('requestRoomInfo error:' + err + 'url:' +  url  )
                return
            }
            var info = JSON.parse(res)

            console.log('res:' + res)
            if(info.code!=200)
            {
                return
            }

            for(var i=info.data.length-1;i>0;i--)
            {
                if( info.data[i].nullity!=0)
                {
                    info.data.splice(i,1)
                }
                
            }

            console.log('res.data:' + JSON.stringify(info.data))

            self.currentRoomInfo = info.data
            self.emit(Event.COM_MSG.ROOM_INFO,self.currentRoomInfo);
            self.checkServerConnnect()
        })

    }

    checkServerConnnect()
    {
        var serverinfoStr = cc.sys.localStorage.getItem(Define.ServerInfo);
        if(serverinfoStr!=null&&serverinfoStr!='')
        {
            var serverInfo = JSON.parse(serverinfoStr)
            for(var i = 0;i < this.currentRoomInfo.length;i++)
            {
                var roomInfo = this.currentRoomInfo[i]
                if(serverInfo[Define.ServerAddress] == roomInfo.gameserver_addr  && serverInfo[Define.ServerPort] == roomInfo.server_port)
                {
                    this.CreateGameStart(i)
                    this.needCheckConnectGame = true

                    // cc.sys.localStorage.setItem(Define.ServerInfo,'')
                    break
                }
            }
        }
    }

  

    requestUserInfo()
    {

        var self = this
        
        var url = Define.GameUserInfoUrl+'/' +  this.selfUserID + '?token=' + this.token
        console.log('requestUserInfo :' +  url )

        Common.sendGetGameConfig(url,function(err,res)
        {
         
            if(err)
            {
                console.log('requestUserInfo error:' + err + 'url:' +  url  )
                return
            }

            console.log('res:' + res)

            var info = JSON.parse(res)
            console.log('info.code:' + info['code'])

            if(info['code']!=200)
            {
                return
            }

            self.userInfo = info.data
            console.log('requestUserInfo emit:' +  JSON.stringify( info.data))

            self.emit(Event.COM_MSG.USER_INFO,self.userInfo);
            // self.requestRoomInfo(464)// test
        })


    }

    reSetData()
    {
        this.counterInfos = [] //  倒计时
        this.bWaitQuit = false 		//-- 退出等待
        this._delayEnter = false
        this.m_bCallStateEnter = false
        this.m_bRoundOver = false
        this.callMaxScore = 0               //当前最大叫分

    }

    createGameSocket(index, bBackToRoom)
    {
        if (bBackToRoom) {
            index = this.roomIndex;
        }
        this.roomIndex = index;
        var length = this._roomList[Define.GAMEID].length
        
        if(index < 0 || index >= length)
        {
            return
        }
        var gameServerItem = this._roomList[Define.GAMEID][index]
        var url =  gameServerItem.szServerAddr +":"+ gameServerItem.wServerPort
        console.log("createGameSocket:" + url)
        this._GameProcessManager.createSocket(url, null,Define.SOCKET_TYPE.GAME)

    }

    //测试游戏服务器
    createGameSocket1(index, bBackToRoom)
    {
        if (bBackToRoom) {
            index = this.roomIndex;
        }
        this.roomIndex = index;
        var length = this.currentRoomInfo.length
        if(index < 0 || index >= length)
        {
            return
        }
        var gameServerItem = this.currentRoomInfo[index]

        var url = 'ws://'+ gameServerItem.gameserver_addr +":"+ gameServerItem.server_port

        console.log("createGameSocket:" + url)
        this._GameProcessManager.createSocket(url, null,Define.SOCKET_TYPE.GAME)

    }

    quickStart()
    {
        if(this._GameProcessManager.getSocketState() == Common.SocketState.OK &&  this._GameProcessManager.socketType == Define.SOCKET_TYPE.GAME)
        {
            this.setQuickStart()
            // this.onSocketLogonFinish()           
        }
        else
        {
            this.closeSocket()
            console.log('this._roomList: ' + this._roomList)
            var length = this._roomList[Define.GAMEID].length
            
            if(this.roomIndex < 0 || this.roomIndex >= length)
            {
                return
            }
            var gameServerItem = this._roomList[Define.GAMEID][this.roomIndex]
            var url = gameServerItem.szServerAddr +":"+ gameServerItem.wServerPort
            console.log("quickStart createGameSocket:" + url)
            this._GameProcessManager.createSocket(url, this.setQuickStart.bind(this),Define.SOCKET_TYPE.GAME)

        }
    }

    getFitRoomIdx()
    {
       return 0
    }

    quickStart1()
    {
        var fixIdx = this.getFitRoomIdx()
        this.CreateGameStart(fixIdx)
    }

    CreateGameStart(idx)
    {
        cc.log("State==",this._GameProcessManager.getSocketState())
        cc.log("socketType==",this._GameProcessManager.socketType)
        if(idx == this.roomIndex &&this._GameProcessManager.getSocketState() == Common.SocketState.OK &&  this._GameProcessManager.socketType == Define.SOCKET_TYPE.GAME)
        {
            cc.log("have connnected ok ");
            this.setQuickStart()
            // this.onSocketLogonFinish()  
            this.onSocketLoginGameServer();         
        }
        else
        {
            cc.log("need select new server connect");
            this.closeSocket()
            this.roomIndex = idx
            var length = this.currentRoomInfo.length
            if(this.roomIndex < 0 || this.roomIndex >= length)
            {
                return
            }
            var gameServerItem = this.currentRoomInfo[this.roomIndex]
            var url = 'ws://'+ gameServerItem.gameserver_addr +":"+ gameServerItem.server_port
            console.log("quickStart createGameSocket:" + url)
            this._GameProcessManager.createSocket(url, this.setQuickStart.bind(this),Define.SOCKET_TYPE.GAME)

        }
    }


    closeSocket()
    {
        this._GameProcessManager.closeSocket()
    }

    setQuickStart()
    {
        this.m_bQuickStart = true

    }

    onSocketLoginGameServer(){
        var password = '07e85eed53036ba58628aeeb67818e0d'
        var msg = MsgTransfer.encodeLoginMsg(ConstMsgId.MDM_GP_LOGON,ConstMsgId.MDM_GP_LOGON, 238, this.selfUserID,this.selfPassword)
        //var msg = MsgTransfer.encodeLoginMsg(ConstMsgId.MDM_GP_LOGON,ConstMsgId.MDM_GP_LOGON, 238, this.selfUserID,password)

        this._GameProcessManager.sendMsg(msg);
    }


    sendLoginGameServer()
    {
        var msg = MsgTransfer.encodemsg(ConstMsgId.MDM_GR_LOGON,ConstMsgId.SUB_GR_LOGON_USERID,4 + 4 + 15 + (33 + 33 + 33 ) * 2 )
        this._GameProcessManager.sendMsg(msg);
    }
   


    sendSitDown(table,chair,password)
    {
    
        console.log("sendSitDown:"+ " table:"+table+"chair:"+chair)
        var msg = MsgTransfer.encodemsg(ConstMsgId.MDM_GR_USER,ConstMsgId.SUB_GR_USER_SITDOWN,4 + 4 + 70,table,chair,password)
        this._GameProcessManager.sendMsg(msg);
    }
  
    sendSelfSitUp(bForce)
    {
        var  MyTable = this.GetMeTableID()
        var  MyChair = this.GetMeChairID()
        this.sendSitUp(MyTable,MyChair,bForce)
    }

    sendSitUp(table,chair,bForce)
    {
 

        var msg = MsgTransfer.encodemsg(ConstMsgId.MDM_GR_USER,ConstMsgId.SUB_GR_USER_STANDUP,4 + 4 + 5,table,chair,bForce )
        this._GameProcessManager.sendMsg(msg); 
    }

    sendGameOption()
    {
        console.log('sendGameOption')
        var msg = MsgTransfer.encodemsg(ConstMsgId.MDM_GF_FRAME,ConstMsgId.SUB_GF_GAME_OPTION,4 + 4 + 9 )
        this._GameProcessManager.sendMsg(msg);       
    }

    sendReady()
    {
        var msg = MsgTransfer.encodemsg(ConstMsgId.MDM_GF_FRAME,ConstMsgId.SUB_GF_USER_READY,4 + 4 )
        this._GameProcessManager.sendMsg(msg);
    }

    sendCallScore(score)
    {
        console.log('sendCallScore score:'+ score)
        var msg = MsgTransfer.encodemsg(ConstMsgId.MDM_GF_GAME,ConstMsgId.SUB_C_CALL_SCORE,4 + 4 + 1,score )
        this._GameProcessManager.sendMsg(msg);
    }

    sendOutCard(cards, bPass)
    {
        var msg = null
        if (bPass )
        {
            msg = MsgTransfer.encodemsg(ConstMsgId.MDM_GF_GAME,ConstMsgId.SUB_C_PASS_CARD,4 + 4  )
            
        }
        else
        {
            var cardcount = cards.length
            msg = MsgTransfer.encodemsg(ConstMsgId.MDM_GF_GAME,ConstMsgId.SUB_C_OUT_CARD,4 + 4 + cardcount + 1,cards )
        }

        this._GameProcessManager.sendMsg(msg);


    }

    setData(wMainCmdID, wSubCmdID, data) {
        if (ConstMsgId.MDM_GR_LOGON === wMainCmdID) {
            if (ConstMsgId.SUB_GR_LOGON_FINISH === wSubCmdID) {
                console.log("SUB_GR_LOGON_FINISH");
                this.onSocketLogonFinish();
            } else if (ConstMsgId.SUB_GR_LOGON_SUCCESS === wSubCmdID) {
                console.log("登录成功");
            } else if (ConstMsgId.SUB_GR_LOGON_FAILURE === wSubCmdID) {
                this.readLoginFail(data);

                console.log("登录房间失败:");
            } else if (ConstMsgId.SUB_GR_UPDATE_NOTIFY === wSubCmdID) {
                console.log("升级提示");
            }
        } else  if (ConstMsgId.MDM_MB_SERVER_LIST === wMainCmdID) {
            if (ConstMsgId.SUB_MB_LIST_FINISH === wSubCmdID) {

            } else if (ConstMsgId.SUB_MB_LIST_SERVER === wSubCmdID) {
				this.readServerList(data);
            } else if (ConstMsgId.SUB_MB_AGENT_KIND === wSubCmdID) {

            }
        } else if (ConstMsgId.MDM_GR_CONFIG === wMainCmdID) {
            if (ConstMsgId.SUB_GR_CONFIG_SERVER === wSubCmdID) {
                this.readConfigServer(data);
            } else if (ConstMsgId.SUB_GR_CONFIG_FINISH === wSubCmdID) {
                console.log("房间配置完成");
               
            }
        } else if (ConstMsgId.MDM_GR_USER === wMainCmdID) {
            if (wSubCmdID === ConstMsgId.SUB_GR_USER_WAIT_DISTRIBUTE) {
                console.log("正在进行分组,请稍后...")
                this.emit(Event.COM_MSG.SEND_MSG,true,'正在进行分组,请稍后...')
            } else if (wSubCmdID === ConstMsgId.SUB_GR_USER_ENTER) {//--用户进入
                this.onSocketUserEnter(data);
            } else if (wSubCmdID === ConstMsgId.SUB_GR_USER_SCORE) {//--用户积分
               this.onSocketUserScore(data);
            } else if (wSubCmdID === ConstMsgId.SUB_GR_USER_STATUS) {//--用户状态
                this.onSocketUserStatus(data);
            } else if (wSubCmdID === ConstMsgId.SUB_GR_REQUEST_FAILURE) {//--请求失败
                this.onSocketReQuestFailure(data);
            }	
        } else if (ConstMsgId.MDM_GR_STATUS  === wMainCmdID) {
            if (ConstMsgId.SUB_GR_TABLE_INFO == wSubCmdID) {
               this.readTableInfo(data);
            } else if (wSubCmdID === ConstMsgId.SUB_GR_TABLE_STATUS) {//--桌子状态
               this.readTableStatus(data);
            }
        } else if (ConstMsgId.MDM_GF_FRAME === wMainCmdID) {//  游戏框架
            if (wSubCmdID == ConstMsgId.SUB_GF_GAME_STATUS ) {//--游戏状态
                this.readGameStatus(data);
            } else if ( wSubCmdID == ConstMsgId.SUB_GF_GAME_SCENE) {//--游戏场景
                this.readGameScene(data);
            } else if (wSubCmdID == ConstMsgId.SUB_GF_SYSTEM_MESSAGE) {//--系统消息
                this.onSocketSystemMessage(data);
            } else if (wSubCmdID == ConstMsgId.SUB_GF_ACTION_MESSAGE) {//--动作消息
                this.onSocketActionMessage(data);
            } else if (wSubCmdID == ConstMsgId.SUB_GF_USER_CHAT) {//--用户聊天
                //   local chat = ExternalFun.read_netdata(ConstMsgId.CMD_GF_S_UserChat, dataBuffer)
                // --获取玩家昵称
                // local useritem = self._UserList[chat.dwSendUserID]
                // if not  useritem then
                //     return
                // end
                // if self.wTableID == yl.INVALID_CHAIR or self.wTableID ~= useritem.wTableID then
                //     return
                // end
        
                // chat.szNick = useritem.szNickName
        
                // GameChatLayer.addChatRecordWith(chat)
        
                // if nil ~= self._viewFrame and nil ~= self._viewFrame.onUserChat then
                //     -- 播放声音
                //     local idx = GameChatLayer.compareWithText(chat.szChatString)
                //     if nil ~= idx then
                //         local sound_path = "sound/" .. useritem.cbGender .. "_" .. idx .. ".wav"
                //         if GlobalUserItem.bSoundAble then
                //             AudioEngine.playEffect(cc.FileUtils:getInstance():fullPathForFilename(sound_path),false)
                //         end
                //     end
                //     self._viewFrame:onUserChat(chat,useritem.wChairID)
                // end
            } else if (wSubCmdID == ConstMsgId.SUB_GF_USER_EXPRESSION) {//--用户表情
                //    local expression = ExternalFun.read_netdata(game_cmd.CMD_GF_S_UserExpression, dataBuffer)
                // --获取玩家昵称
                // local useritem = self._UserList[expression.dwSendUserID]
        
                // if not  useritem then
                //     return
                // end
                // if self.wTableID == yl.INVALID_CHAIR or self.wTableID ~= useritem.wTableID then
                //     return
                // end
                
                // expression.szNick = useritem.szNickName
        
                // GameChatLayer.addChatRecordWith(expression, true)
                // if nil ~= self._viewFrame and nil ~= self._viewFrame.onUserExpression then
                //     self._viewFrame:onUserExpression(expression,useritem.wChairID)
                // end
            } else if (wSubCmdID == ConstMsgId.SUB_GF_USER_VOICE) {//-- 用户语音
                //  AudioRecorder:getInstance():saveRecordFile(dataBuffer, function(uid, tid, spath)
                //     local msgTab = {}
                //     msgTab.uid = uid
                //     msgTab.tid = tid
                //     msgTab.spath = spath
                //     table.insert(self._tabVoiceMsgQueue, msgTab)
                    
                //     self:popVocieMsg()
                // end)
            }
        } else if (ConstMsgId.MDM_GF_GAME  === wMainCmdID) {// game
            if (ConstMsgId.SUB_S_GAME_START == wSubCmdID ) {//--游戏开始
                this.emit(Event.COM_MSG.SEND_MSG,false,'')

                this.cbGameStatus = Define.GAME_SCENE_CALL;
                this.onSubGameStart(data);
                //this.sendCallScore(3)
            } else if (ConstMsgId.SUB_S_CALL_SCORE == wSubCmdID) {//--用户叫分
                this.cbGameStatus = Define.GAME_SCENE_CALL;
                this.onSubCallScore(data);
            } else if (ConstMsgId.SUB_S_BANKER_INFO == wSubCmdID ) {//--庄家信息
                this.cbGameStatus = Define.GAME_SCENE_PLAY;
                this.onSubBankerInfo(data);
            } else if (ConstMsgId.SUB_S_OUT_CARD == wSubCmdID) {//--用户出牌    
                this.cbGameStatus = Define.GAME_SCENE_PLAY;
                this.onSubOutCard(data);
            } else if (ConstMsgId.SUB_S_PASS_CARD == wSubCmdID) {//--用户放弃
                this.cbGameStatus = Define.GAME_SCENE_PLAY;
                this.onSubPassCard(data);
            } else if (ConstMsgId.SUB_S_GAME_CONCLUDE == wSubCmdID) {// --游戏结束
                this.cbGameStatus = Define.GAME_SCENE_END;
                this.onSubGameConclude(data);
            }
        }
    }

    readLoginFail(data)
    {
        var len = data.byteLength;

        var readPos = 0;
        var dataview = new DataView(data);
        var code = dataview.getInt32(readPos, Common.littleEndian); //--code
        readPos += 4;
        
        var msg = Common.getString(data, readPos, len-4); 	//--msg
        readPos += (len-4);
        console.log(Common.GetDateString() + " code:" + code + "msg:" + msg)

    }

	readServerList(data)
	{
        console.log('readServerList')
        var len = data.byteLength;
        if ((len - Math.floor(len / Define.LEN_GAME_SERVER_ITEM) * Define.LEN_GAME_SERVER_ITEM) != 0) {
            Common.Print("roomlist_len_error" + len);
            return;
        }
        var itemcount = Math.floor(len / Define.LEN_GAME_SERVER_ITEM);
        //--读取房间信息
        var readPos = 0;
        var dataview = new DataView(data);
        this._roomList = new Array();
        for (var i = 0; i < itemcount; i++) {
            var item = new GameServerItem();
            item.wKindID = dataview.getUint16(readPos, Common.littleEndian); //--名称索引
            readPos += 2;
            item.wNodeID = dataview.getUint16(readPos, Common.littleEndian);				//--节点索引
            readPos += 2;
            item.wSortID = dataview.getUint16(readPos, Common.littleEndian);			//--排序索引
            readPos += 2;
            item.wServerID = dataview.getUint16(readPos, Common.littleEndian);			//--房间索引
            readPos += 2;
            item.wServerKind = dataview.getUint16(readPos, Common.littleEndian);			//--房间类型
            readPos += 2;
            item.wServerType = dataview.getUint16(readPos, Common.littleEndian);			//--房间类型
            readPos += 2;
            item.wServerLevel = dataview.getUint16(readPos, Common.littleEndian);			//--房间等级
            readPos += 2;
            item.wServerPort = dataview.getUint16(readPos, Common.littleEndian);		//--房间端口
            readPos += 2;
            item.lCellScore = Common.readint64(data, readPos);			//--单元积分
            readPos += 8;
            item.cbEnterMember = dataview.getUint8(readPos, Common.littleEndian);								//--进入会员
            readPos += 1;
            item.lEnterScore = Common.readint64(data, readPos);			//--进入积分
            readPos += 8;
            item.dwServerRule = dataview.getUint32(readPos, Common.littleEndian);			//--房间规则
            readPos += 4;
            item.dwOnLineCount = dataview.getUint32(readPos, Common.littleEndian);			//--在线人数
            readPos += 4;
            item.dwAndroidCount = dataview.getUint32(readPos, Common.littleEndian);		//--机器人数
            readPos += 4;
            item.dwFullCount = dataview.getUint32(readPos, Common.littleEndian);		//--满员人数
            readPos += 4;
            item.szServerAddr = Common.getString(data, readPos, 32 * 2); 	//--房间地址
            readPos += 32 * 2;
            item.szServerName = Common.getString(data, readPos, 32 * 2); 	//--房间名称
            readPos += 32 * 2;
            item.dwSurportType = dataview.getUint32(readPos, Common.littleEndian);	 		//--支持类型
            readPos += 4;
            item.wTableCount = dataview.getUint16(readPos, Common.littleEndian);			//--桌子数目
            readPos += 2;

            console.log(item.wKindID)
            console.log(item.wServerPort)
            console.log(item.szServerAddr)
            console.log(item.szServerName)
            console.log(item.dwSurportType)
            console.log(item.wTableCount)
            console.log(item)
            if(CC_JSB && cc.sys.OS_ANDROID === cc.sys.os)
            {
                item.szServerAddr = NetConfig.AndroidGameAdress

            }
            else
            {
                item.szServerAddr = NetConfig.gameAdress

            }
            if (item == null) {
                break;
            }
            if (null == this._roomList[item.wKindID] || undefined == this._roomList[item.wKindID]) {
                this._roomList[item.wKindID] = new Array();
            }
            if (item.wServerType == Define.GAME_GENRE_PERSONAL) {
                //if GlobalUserItem.bEnableRoomCard then
                //	if PriRoom then
                //		PriRoom:getInstance().m_tabPriModeGame[item.wKindID] = true
                //	end				
                //	table.insert(self._roomList[item.wKindID], item)
                //end
            } else {
                this._roomList[item.wKindID].push(item);
            }
        }
	}

    readConfigServer(data)
    {
        var readPos = 0
        var dataview = new DataView(data)
        this.wTableCount = dataview.getUint16(readPos,Common.littleEndian) //--名称索引
        readPos+=2
        this.wChairCount = dataview.getUint16(readPos,Common.littleEndian) //--名称索引
        readPos+=2
        this.wServerType = dataview.getUint16(readPos,Common.littleEndian) //--名称索引
        readPos+=2
        this.dwServerRule = dataview.getUint32(readPos,Common.littleEndian) //--名称索引
        readPos+=4

        
        console.log("房间配置[table:" + this.wTableCount + "][chair:" + this.wChairCount + "][type:" + this.wServerType + "][rule:" + this.dwServerRule + "]")

    }

    readTableInfo(data)
    {
        console.log("readTableInfo")
        var readPos = 0
        var dataview = new DataView(data)
        var  wTableCount = dataview.getUint16(readPos,Common.littleEndian) 

        readPos+=2
        this._tableStatus = []
        for (var i = 0 ; i < wTableCount;i++ )
        {   
            var tableStatus = {} 
            tableStatus.cbTableLock = dataview.getUint8(readPos,Common.littleEndian) 
            readPos+=1				
            tableStatus.cbPlayStatus = dataview.getUint8(readPos,Common.littleEndian) 
            readPos+=1				
            tableStatus.lCellScore = dataview.getInt32(readPos,Common.littleEndian) 
            readPos+=4	
            this._tableStatus.push(tableStatus)		
        }
        // console.log("tableStatus:"+ JSON.stringify( this._tableStatus))	

        this.onGetTableInfo()
        
    }

    readTableStatus(data)
    {

        var readPos = 0
        var dataview = new DataView(data)

        var wTableID = dataview.getUint16(readPos,Common.littleEndian) + 1	
        readPos+=2 	
        this._tableStatus[wTableID] = {}
        this._tableStatus[wTableID].cbTableLock = dataview.getUint8(readPos,Common.littleEndian) 
        readPos+=1								
        this._tableStatus[wTableID].cbPlayStatus = dataview.getUint8(readPos,Common.littleEndian) 
        readPos+=1				
        this._tableStatus[wTableID].lCellScore = dataview.getUint32(readPos,Common.littleEndian) 
        readPos+=4				

        console.log("SUB_GR_TABLE_STATUS ==> " + wTableID) //--[[ .. " ==> " .. this._tableStatus[wTableID].cbPlayStatus]])
      

        this.upDataTableStatus(wTableID)
    }







    //--用户进入

    onSocketUserEnter(data)
    {
        var readPos = 0
        var dataview = new DataView(data)


        var userItem = new PlayerInfoItem("","",-1,0,0)

        userItem.dwUserID		= dataview.getUint32(readPos,Common.littleEndian)
        readPos+=4
        var  selfUserID = this.selfUserID
        var bMySelfInfo = false
        console.log("onSocketUserEnter userItem.dwUserID:" + userItem.dwUserID)    
        var selfPlayer = this.playerInfoModel.getSelfTablePlayer()
        //--自己判断
        if(selfPlayer)
        {
            bMySelfInfo = (userItem.dwUserID == selfUserID)
        }
        console.log("bMySelfInfo:" + bMySelfInfo)    
        //--读取信息
        userItem.wFaceID 		= 1
        userItem.cbGender		= dataview.getUint8(readPos,Common.littleEndian) 
        readPos+=1
        userItem.wTableID		= dataview.getUint16(readPos,Common.littleEndian) 
        readPos+=2
        userItem.wChairID		= dataview.getUint16(readPos,Common.littleEndian) 
        readPos+=2
        userItem.cbUserStatus 	= dataview.getUint8(readPos,Common.littleEndian) 
        readPos+=1
        userItem.lScore			= Common.readint64(data,readPos)
        readPos+=8
        userItem.lIngot			=  Common.readint64(data,readPos)
        readPos+=8
        userItem.dwWinCount		= dataview.getUint32(readPos,Common.littleEndian) 
        readPos+=4
        userItem.dwLostCount	= dataview.getUint32(readPos,Common.littleEndian) 
        readPos+=4
        userItem.dwDrawCount	= dataview.getUint32(readPos,Common.littleEndian) 
        readPos+=4
        userItem.dwFleeCount	= dataview.getUint32(readPos,Common.littleEndian) 
        readPos+=4
        userItem.dwExperience	= dataview.getUint32(readPos,Common.littleEndian) 
        readPos+=4
        userItem.lIntegralCount = Common.readint64(data,readPos)
        readPos+=8       
        userItem.dwClientAddr		= dataview.getUint32(readPos,Common.littleEndian) 
        readPos+=4

        userItem.nickNameLen		= dataview.getUint16(readPos,Common.littleEndian) 
        readPos+=2
        userItem.nickNameDes		= dataview.getUint16(readPos,Common.littleEndian) 
        readPos+=2
        //变长不X2 而是X1
        userItem.szNickName  = Common.getString(data, readPos,userItem.nickNameLen * 1);
        readPos += userItem.nickNameLen * 1;

        userItem.szHeadLen		= dataview.getUint16(readPos,Common.littleEndian) 
        readPos+=2
        userItem.szHeadDes		= dataview.getUint16(readPos,Common.littleEndian) 
        readPos+=2
        //变长不X2 而是X1
        userItem.szHead  = Common.getString(data, readPos,userItem.szHeadLen * 1);
        readPos += userItem.szHeadLen * 1;
        

        //--添加/更新到缓存
        var  bAdded = false
        var  item = this.playerInfoModel.getTablePlayerInfoByUserID(userItem.dwUserID) 
        if (item != null )
         {  
            item.lScore			= userItem.lScore	
            item.lIngot			= userItem.lIngot	
            item.wFaceID 		= userItem.wFaceID
            item.cbGender		= userItem.cbGender
            item.wTableID		= userItem.wTableID
            item.wChairID		= userItem.wChairID
            item.cbUserStatus 	= userItem.cbUserStatus
            item.dwWinCount 	= userItem.dwWinCount
            item.dwLostCount 	= userItem.dwLostCount
            item.dwDrawCount 	= userItem.dwDrawCount
            item.dwFleeCount 	= userItem.dwFleeCount
            item.dwExperience 	= userItem.dwExperience
            item.lIntegralCount     = userItem.lIntegralCount
            item.dwClientAddr     = userItem.dwClientAddr
            item.szNickName     = userItem.szNickName
            item.szHead     = userItem.szHead

            bAdded = true

        }
    
        // if( bAdded == false )
        // {  
            this.playerInfoModel.setTablePlayerInfo( userItem )
        //}

        console.log(Common.GetDateString() + ' onSocketUserEnter userItem:' +  JSON.stringify(userItem) )

        //--记录自己桌椅号
        if ( userItem.dwUserID ==  selfUserID )
        {  
            console.log('this.wTableID:' + userItem.wTableID)
            this.wTableID = userItem.wTableID
            this.wChairID = userItem.wChairID
        }

      
        if(userItem.cbUserStatus <= Define.US_FREE && userItem.dwUserID == selfUserID)
        {
            this.onExitTable()
            return
        }

        // if(bMySelfInfo)
        // {
        //     return
        // }

       
    
        if ((userItem.wTableID != Define.INVALID_TABLE)  && (userItem.cbUserStatus != Define.US_LOOKON ))
        {    
            this.onUpDataTableUser(userItem.wTableID,userItem.wChairID,userItem)
            this.onEventUserEnter(userItem.wTableID,userItem.wChairID,userItem)
            
        }
    
        if (( bMySelfInfo == true) && (this._delayEnter == true ))
        {   
            this._delayEnter = false
            this.onSocketLogonFinish()
        }



    }

    //--登录完成
    onSocketLogonFinish()
    {
        console.log("onSocketLogonFinish: this._delayEnter:" + this._delayEnter)

     


        
        // var myUserItem   =  this.GetMeUserItem()
        // if (! myUserItem ) 
        // {    console.log("获取自己信息失败！")
        //     return
        // }
     
        

        if (this.wTableID == Define.INVALID_TABLE )
        {
            // this.onEnterTable()
            // console.log("找到游戏桌子，正在获取场景中...")
            // this.sendGameOption()

            if(this.needCheckConnectGame == true)
            {
                cc.sys.localStorage.setItem(Define.ServerInfo,'')
                this.needCheckConnectGame = false
                console.log('Game Has Over')
                return
            }
            if(this.needCheckConnectGameing == true)
            {
                cc.sys.localStorage.setItem(Define.ServerInfo,'')
                this.needCheckConnectGameing = false
                console.log('Game Has Over')
                return
            }
          

            if(this.m_bQuickStart == true)
            {
                this.m_bQuickStart = false
                this.sendSitDown(0,0,'')
            }
        }
        else
        {   
            if(this.needCheckConnectGame == true)
            {
                this.needCheckConnectGame = false
                console.log('Gameing reconnect')

                cc.sys.localStorage.setItem(Define.ServerInfo,'')
            }
            if(this.needCheckConnectGameing == true)
            {
                this.needCheckConnectGameing = false
                console.log('Gameing reconnect')
            }

            this.onEnterTable()
            this.sendGameOption();
        }   

        this.m_bQuickStart = false



    }


    //--用户积分
    onSocketUserScore(data)
    {
        console.log("onSocketUserScore")
        var readPos = 0
        var dataview = new DataView(data)
        // var dwUserID = Common.readint64(data,readPos)
        // readPos+=8       
        var dwUserID		= dataview.getUint32(readPos,Common.littleEndian) 
        readPos += 4
        var  item = this.playerInfoModel.getTablePlayerInfoByUserID(dwUserID) 
        if(item != null )
        {   // --更新数据
            item.lScore =  Common.readint64(data,readPos)
            readPos+=8     
            item.dBeans =  dataview.getFloat64(readPos,Common.littleEndian) 
            readPos+=8     
            item.dwWinCount = dataview.getUint32(readPos,Common.littleEndian) 
            readPos += 4
            item.dwLostCount = dataview.getUint32(readPos,Common.littleEndian) 
            readPos += 4
            item.dwDrawCount = dataview.getUint32(readPos,Common.littleEndian) 
            readPos += 4
            item.dwFleeCount = dataview.getUint32(readPos,Common.littleEndian) 
            readPos += 4
    
            item.dwExperience = dataview.getUint32(readPos,Common.littleEndian) 
            readPos += 4
    
            console.log("更新用户[" + dwUserID+ "][" + item.szNickName+ "][" + item.lScore + "]")
            
            //--自己信息
            var  selfPlayer = this.playerInfoModel.getSelfTablePlayer() 

            if (item.dwUserID == selfPlayer.dwUserID && this.IsAllowPlazzScoreChange() )
            {    console.log("更新金币")
                selfPlayer.lUserScore = item.lScore
                selfPlayer.dUserBeans = item.dBeans
            }
    
            //--通知更新界面
            if (this.wTableID != Define.INVALID_TABLE) 
            { 
                this.onEventUserScore(item)
            } 
        }     
    }
            
    //--用户状态
    onSocketUserStatus(data)
    {
        console.log("onSocketUserStatus")
        //--读取信息
        var readPos = 0;
        var dataview = new DataView(data);
        //var selfPlayer = this.playerInfoModel.getSelfTablePlayer();
        var  selfUserID = this.selfUserID
        var dwUserID = dataview.getUint32(readPos, Common.littleEndian);
        readPos += 4;
        var newstatus = {};
        newstatus.wTableID = dataview.getUint16(readPos, Common.littleEndian);
        readPos += 2;
        newstatus.wChairID = dataview.getUint16(readPos, Common.littleEndian);
        readPos += 2;
        newstatus.cbUserStatus = dataview.getUint8(readPos, Common.littleEndian);
        readPos += 1;
        cc.log("onSocketUserStatus dwUserID:"+ dwUserID + "  Status:" + newstatus.cbUserStatus);
        if (newstatus.cbUserStatus == Define.US_LOOKON) {//--过滤观看
            console.log("dwUserID:"+ dwUserID + "观战");
            return;
        }
    
        var bMySelfInfo = (dwUserID == selfUserID);//--自己判断
        var useritem =  this.playerInfoModel.getTablePlayerInfoByUserID(dwUserID);
        if( bMySelfInfo && Define.US_PLAYING == newstatus.cbUserStatus)
        {
            console.log("游戏状态");
            this.onEnterTable();

        }  
        //--找不到用户
        if (useritem == null ) {//--当前桌子用户
            if (newstatus.wTableID != Define.INVALID_TABLE) {//--虚拟信息
                var newitem = new PlayerInfoItem("", "", -1, 0, 0);
                newitem.szNickName = "游戏玩家";
                newitem.dwUserID = dwUserID;
                newitem.cbUserStatus = newstatus.cbUserStatus;
                newitem.wTableID = newstatus.wTableID;
                newitem.wChairID = newstatus.wChairID;
                this.playerInfoModel.setTablePlayerInfo(newitem);
                this.onUpDataTableUser(newitem.wTableID, newitem.wChairID, newitem);
                //--发送查询
                this.QueryUserInfo(newstatus.wTableID, newstatus.wChairID);
            }
            return;
        }


        //--记录旧状态
        var oldstatus = {};
        oldstatus.wTableID = useritem.wTableID;
        oldstatus.wChairID = useritem.wChairID;
        oldstatus.cbUserStatus = useritem.cbUserStatus;
        //--更新信息
        useritem.wTableID = newstatus.wTableID;
        useritem.wChairID = newstatus.wChairID;
        useritem.cbUserStatus = newstatus.cbUserStatus;

        this.playerInfoModel.setTablePlayerInfo(useritem);

        console.log("newstatus:" + JSON.stringify(newstatus));
        console.log("oldstatus:" + JSON.stringify(oldstatus));
        //--清除旧桌子椅子记录
        if (oldstatus.wTableID != Define.INVALID_TABLE) {
            if ((oldstatus.wTableID != newstatus.wTableID) || (oldstatus.wChairID != newstatus.wChairID)) {//--新旧桌子不同
                this.onUpDataTableUser(oldstatus.wTableID, oldstatus.wChairID, null);
            }
        }
        //--新桌子记录
        if (newstatus.wTableID != Define.INVALID_TABLE) { 
            this.onUpDataTableUser(newstatus.wTableID, newstatus.wChairID, useritem);
        }
        // --自己状态
        if (bMySelfInfo == true) {
            this.wTableID = newstatus.wTableID;
            this.wChairID = newstatus.wChairID;
            if (newstatus.cbUserStatus == Define.US_NULL) {//--离开
                console.log("自己离开")
                if (this.bWaitQuit  == false) {
                    this.onExitRoom();
                }

                this.onEventUserStatus(useritem,newstatus,oldstatus);

            } else if ((newstatus.cbUserStatus == Define.US_FREE) && (oldstatus.cbUserStatus > Define.US_FREE)) {//--起立
                console.log("自己起立")
                // if(this.bSelfExitRoom)
                // {
                    this.onExitTable();
                    this.onUpDataTableUser(oldstatus.wTableID, oldstatus.wChairID, null);
                    cc.log('Zhong remove myself tabel info!!!!!')
                    this.emit(Event.CPT_MSG.SELF_ON_STAND_UP);
                    this.bSelfExitRoom = false
               //}
                this.onEventUserStatus(useritem,newstatus,oldstatus);

            } else if ((newstatus.cbUserStatus == Define.US_SIT)) {//--坐下
                console.log("自己坐下")
                this.bChangeDesk = false;
                this.onEnterTable();
                this.sendGameOption();
                this.onEventUserStatus(useritem,newstatus,oldstatus);
            } else if ((newstatus.wTableID != Define.INVALID_TABLE) && (this.bChangeDesk == true)) {
                console.log("换位");
                this.onEnterTable();
                this.sendGameOption();
                this.onEventUserStatus(useritem,newstatus,oldstatus);
            }
            else if( Define.US_READY == newstatus.cbUserStatus)
            {
                console.log("准备");
                this.bChangeDesk = false;
                this.onEnterTable();
                this.sendGameOption();

                this.onEventUserStatus(useritem, newstatus, oldstatus);

            }
            else if( Define.US_MATCH == newstatus.cbUserStatus)
            {
                console.log("匹配状态");
                this.onEnterTable();

                this.onEventUserStatus(useritem, newstatus, oldstatus);

            }
            else if( Define.US_PLAYING == newstatus.cbUserStatus)
            {
                console.log("游戏状态");
                this.onEnterTable();

                this.onEventUserStatus(useritem, newstatus, oldstatus);

            }              
            else {

                console.log("自己新状态:" + newstatus.cbUserStatus);
                this.onEventUserStatus(useritem, newstatus, oldstatus);
            } 
        } else {//--他人状态
            //--更新用户
            this.onEventUserStatus(useritem, newstatus, oldstatus);
            if (newstatus.cbUserStatus == Define.US_NULL) {//--删除用户
                this.onRemoveUser(dwUserID);
            }
        }
        cc.log('****************Zhong tabel players:' + JSON.stringify(this._tableUserList));
    }

    //请求失败
    onSocketReQuestFailure(data)
    {
        //     game_cmd.CMD_GR_RequestFailure =
        // {
        //     {k = "lErrorCode", t = "int"},											--错误代码
        //     {k = "szDescribeString", t = "string"}									--描述信息
        // }

        var readPos = 0
        var fail = {}
        var dataview = new DataView(data)
        fail.lErrorCode = dataview.getInt32(readPos,Common.littleEndian) 
        readPos+=4   
        fail.szDescribeString = Common.getString(data,readPos,31*2) 
        readPos+=31*2   

        console.log('****************onSocketReQuestFailure:' + JSON.stringify(fail));
        this.emit(Event.CPT_MSG.REQUEST_FAILURE_MSG,fail);
        
    }

    readGameStatus(data)
    {
        var readPos = 0
        var dataview = new DataView(data)
        this.cbGameStatus = dataview.getUint8(readPos,Common.littleEndian) 
        readPos+=1   
        this.cbAllowLookon = dataview.getUint8(readPos,Common.littleEndian) 
        readPos+=1   

    }

    readGameScene(data)
    {
        this.onEventGameScene(this.cbGameStatus,data)
    }

    onSocketSystemMessage(data)
    {

    }

    onSocketActionMessage(data)
    {

    }

    onSubGameStart(data) //游戏开始
    {
        this.saveServerInfo()

        // {k = "wStartUser", t = "word"},                             --开始玩家
        // {k = "wCurrentUser", t = "word"},                           --当前玩家
        // {k = "cbValidCardData", t = "byte"},                        --明牌扑克
        // {k = "cbValidCardIndex", t = "byte"},                       --明牌位置
        // {k = "cbCardData", t = "byte", l = {cmd.NORMAL_COUNT}},     --扑克列表
        var cards = {}
        var readPos = 0
        var dataview = new DataView(data)
        cards.wStartUser   	= dataview.getUint16(readPos,Common.littleEndian) 
        readPos+=2   
        cards.wCurrentUser   	= dataview.getUint16(readPos,Common.littleEndian) 
        readPos+=2   
        cards.cbValidCardData   	= dataview.getUint8(readPos,Common.littleEndian) 
        readPos+=1   
        cards.cbValidCardIndex   	= dataview.getUint8(readPos,Common.littleEndian) 
        readPos+=1   
        cards.cbCardData = []

        
        for (var i = 0 ;i < Define.NORMAL_COUNT; i++)
        {
            var card   	= dataview.getUint8(readPos,Common.littleEndian) 
            readPos+=1  
            cards.cbCardData.push(card)
        }  

        this.reSetData()

        console.log("onSubGameStart:cards"+ JSON.stringify(cards))

        this.m_bRoundOver = false

        this.handCards = cards;
        this.m_bCallStateEnter= false
        this.emit(Event.CPT_MSG.GAME_START,cards,false);
    }


    saveServerInfo()
    {
        var gameServerItem = this.currentRoomInfo[this.roomIndex]
        var gameserver_addr = gameServerItem.gameserver_addr 
        var server_port = gameServerItem.server_port
        
        var serverInfo = {}
        serverInfo[Define.ServerAddress] = gameserver_addr
        serverInfo[Define.ServerPort] = server_port
        serverInfo[Define.WanFaId] = this.currentWanFaId
        cc.sys.localStorage.setItem(Define.ServerInfo,JSON.stringify(serverInfo));
    }


    onSubCallScore(data)     //    --用户叫分
    {
        var callScore = {}

        // {k = "wCurrentUser", t = "word"},                           --当前玩家
        // {k = "wCallScoreUser", t = "word"},                         --叫分玩家
        // {k = "cbCurrentScore", t = "byte"},                         --当前叫分
        // {k = "cbUserCallScore", t = "byte"},                        --上次叫分
        var readPos = 0
        var dataview = new DataView(data)
        callScore.wCurrentUser   	= dataview.getUint16(readPos,Common.littleEndian) 
        readPos+=2   
        callScore.wCallScoreUser   	= dataview.getUint16(readPos,Common.littleEndian) 
        readPos+=2   
        callScore.cbCurrentScore   	= dataview.getUint8(readPos,Common.littleEndian) 
        readPos+=1   
        callScore.cbUserCallScore   	= dataview.getUint8(readPos,Common.littleEndian) 
        console.log("onSubCallScore:"+JSON.stringify( callScore))

        if(callScore.cbCurrentScore > this.callMaxScore)
        {
            this.callMaxScore = callScore.cbCurrentScore
        }
        
        this.emit(Event.CPT_MSG.CALL_SCORE,callScore.wCurrentUser,callScore.wCallScoreUser,callScore.cbCurrentScore,callScore.cbUserCallScore)
    }

    onSubBankerInfo(data)   //--庄家信息
    {
        // {k = "wBankerUser", t = "word"},                            --庄家玩家
        // {k = "wCurrentUser", t = "word"},                           --当前玩家
        // {k = "cbBankerScore", t = "byte"},                          --庄家叫分
        // {k = "cbBankerCard", t = "byte", l = {3}},                  --庄家扑克
        var bankerInfo = {}
        var readPos = 0
        var dataview = new DataView(data)
        bankerInfo.wBankerUser   	= dataview.getUint16(readPos,Common.littleEndian) 
        readPos+=2   
        bankerInfo.wCurrentUser   	= dataview.getUint16(readPos,Common.littleEndian) 
        readPos+=2   
        bankerInfo.cbBankerScore   	= dataview.getUint8(readPos,Common.littleEndian) 
        readPos+=1   
        bankerInfo.cbBankerCard = []
        for (var i=0;i<3;i++)
        {
          var card  = dataview.getUint8(readPos,Common.littleEndian) 
          readPos+=1   
          bankerInfo.cbBankerCard.push(card)
        }
           
        console.log("onSubBankerInfo:"+JSON.stringify( bankerInfo))   
        this.emit(Event.CPT_MSG.BANKER_INFO,bankerInfo);

    }
  
    onSubOutCard(data)  //--用户出牌
    {
        // --用户出牌
        // cmd.CMD_S_OutCard = 
        // {
        //     {k = "cbCardCount", t = "byte"},                            --出牌数目
        //     {k = "wCurrentUser", t = "word"},                           --当前玩家
        //     {k = "wOutCardUser", t = "word"},                           --出牌玩家
        //     {k = "cbCardData", t = "byte", l = {cmd.MAX_COUNT}},      --扑克列表
        // }

        var cards = {}
        var readPos = 0
        var dataview = new DataView(data)
        cards.cbCardCount   	= dataview.getUint8(readPos,Common.littleEndian) 
        readPos+=1   
        cards.wCurrentUser   	= dataview.getUint16(readPos,Common.littleEndian) 
        readPos+=2   
        cards.wOutCardUser   	= dataview.getUint16(readPos,Common.littleEndian) 
        readPos+=2   
   
        cards.cbCardData = []

        for (var i = 0 ;i < Define.MAX_COUNT; i++)
        {
            
            if(i >= cards.cbCardCount)
            {
                break
            }
            var card   	= dataview.getUint8(readPos,Common.littleEndian) 
            readPos+=1  
            cards.cbCardData.push(card)
        }  
        console.log("onSubOutCard:"+JSON.stringify( cards))   
        this.emit(Event.CPT_MSG.OUT_CARD,cards);

    }

    onSubPassCard(data)  // --用户放弃
    {
        // --放弃出牌
        // cmd.CMD_S_PassCard = 
        // {
        //     {k = "cbTurnOver", t = "byte"},                             --一轮结束
        //     {k = "wCurrentUser", t = "word"},                           --当前玩家
        //     {k = "wPassCardUser", t = "word"},                          --放弃玩家
        // }
        var passCard = {}
        var readPos = 0
        var dataview = new DataView(data)        
        passCard.cbTurnOver   	= dataview.getUint8(readPos,Common.littleEndian) 
        readPos+=1   
        passCard.wCurrentUser   	= dataview.getUint16(readPos,Common.littleEndian) 
        readPos+=2   
        passCard.wPassCardUser   	= dataview.getUint16(readPos,Common.littleEndian) 
        readPos+=2   
        console.log("onSubPassCard:"+JSON.stringify( passCard))   

        this.emit(Event.CPT_MSG.PASS_CARD,passCard);

    }
    onSubGameConclude(data) // --游戏结束
    {
        // --游戏结束
        // cmd.CMD_S_GameConclude = 
        // {
        //     --积分变量
        //     {k = "lCellScore", t = "int"},                              --单元积分
        //     {k = "lGameScore", t = "score", l = {3}},                   --游戏积分
        
        //     --春天标识
        //     {k = "bChunTian", t = "byte"},                              --春天
        //     {k = "bFanChunTian", t = "byte"},                           --反春天
        
        //     --炸弹信息
        //     {k = "cbBombCount", t = "byte"},                            --炸弹个数
        //     {k = "cbEachBombCount", t = "byte", l = {cmd.PLAYER_COUNT}},--炸弹个数
        
        //     --游戏信息
        //     {k = "cbBankerScore", t = "byte"},                          --叫分数目
        //     {k = "cbCardCount", t = "byte", l = {cmd.PLAYER_COUNT}},    --扑克数目
        //     {k = "cbHandCardData", t = "byte", l = {cmd.FULL_COUNT}},   --扑克列表
        // }

        cc.sys.localStorage.setItem(Define.ServerInfo,'');


        var readPos = 0
        var gameConclude = {}
        var dataview = new DataView(data)        
        gameConclude.lCellScore   	= dataview.getInt32(readPos,Common.littleEndian) 
        readPos+=4   
        gameConclude.lGameScore = []
        for (var i=0;i<3;i++)
        {
            var score  = Common.readint64(data,readPos)
            readPos+=8  
            gameConclude.lGameScore.push(score)     
        }
    
        gameConclude.bChunTian   	= dataview.getUint8(readPos,Common.littleEndian) 
        readPos+=1   
        gameConclude.bFanChunTian   	= dataview.getUint8(readPos,Common.littleEndian) 
        readPos+=1
        gameConclude.cbBombCount   	= dataview.getUint8(readPos,Common.littleEndian) 
        readPos+=1    
        gameConclude.cbEachBombCount = []
        for (var i=0;i<Define.PLAYER_COUNT;i++)
        {
            var bommb	= dataview.getUint8(readPos,Common.littleEndian) 
            gameConclude.cbEachBombCount.push(bommb)     
            readPos+=1           
        }  
        gameConclude.cbBankerScore   	= dataview.getUint8(readPos,Common.littleEndian) 
        readPos+=1    
        gameConclude.cbCardCount = []
        for (var i=0;i<Define.PLAYER_COUNT;i++)
        {
            var card	= dataview.getUint8(readPos,Common.littleEndian) 
            gameConclude.cbCardCount.push(card)     
            readPos+=1           
        }  
        gameConclude.cbHandCardData = []
        for (var i=0;i<Define.FULL_COUNT;i++)
        {
            var card	= dataview.getUint8(readPos,Common.littleEndian) 
            gameConclude.cbHandCardData.push(card)     
            readPos+=1           
        }  


        console.log("onSubGameConclude:"+JSON.stringify( gameConclude))   

        this.emit(Event.CPT_MSG.GAME_CONCLUDE,gameConclude);
        //this.emit(Event.COM_MSG.UPDATE_BTN_READY,true)


    }
        
    onEnterRoom()
    {
        //todo enter room ui
       
    }

    onGetTableInfo()
    {
        this.emit(Event.COM_MSG.ENTER_ROOM)
    }

    upDataTableStatus(wTableID)
    {
        //update table info
    }

    //--更新桌椅用户
    onUpDataTableUser(wTableID, wChairID, userItem) {
        var id = wTableID;
        var idex = wChairID;
        if (!this._tableUserList[id]) {
            this._tableUserList[id] = new Array(this.wChairCount);
        }
        if (userItem) {
            this._tableUserList[id][idex] = userItem.dwUserID;
        } else {
            this._tableUserList[id][idex] = null;
        }
    }

    onRemoveUser(dwUserID)
    {
        this.playerInfoModel.removeTablePlayerInfoByUserID(dwUserID)
    }

  
    //--获取桌子用户
    getTableUserItem(tableid,chairid)
    {

    
        var id = tableid 
        var idex = chairid 
        if (this._tableUserList[id]  )
        {
            var userid = this._tableUserList[id][idex] 
            if (userid) 
            {
               return this.playerInfoModel.getTablePlayerInfoByUserID(userid)
            } 
        } 

        return null    

    }
    
    getTableInfo(index)
    {
        if (index >= 0 && index < this._tableStatus.length)
        {
            return this._tableStatus[index]
        } 

        return null    
    }


    //--用户状态
    onEventUserStatus(useritem,newstatus,oldstatus)
    {
        var  MyTable = this.GetMeTableID()
        var  MyChair = this.GetMeChairID()
        if (( MyTable == null) || (MyTable == Define.INVALID_TABLE)) { 
            return
        }
        //--旧的清除
        if (oldstatus.wTableID == MyTable) {
            var viewid = this.SwitchViewChairID(oldstatus.wChairID)
            if (viewid && viewid != Define.INVALID_CHAIR) {
                this.OnUpdateUser(oldstatus.wChairID, null, useritem.cbUserStatus == Define.US_FREE)
            }
        }
        //--更新新状态
        if (newstatus.wTableID == MyTable) {
            var viewid = this.SwitchViewChairID(newstatus.wChairID)
            if (viewid && viewid != Define.INVALID_CHAIR) {
                this.OnUpdateUser(newstatus.wChairID, useritem, false)
            }
        }
    }
    
    //--用户积分
    onEventUserScore(useritem)
    {
        var  MyTable = this.GetMeTableID()
        if (MyTable == null || MyTable == Define.INVALID_TABLE) {    
            return
        } 
        if (MyTable == useritem.wTableID) {
            var viewid = this.SwitchViewChairID(useritem.wChairID)
            if ((viewid != null) && (viewid != Define.INVALID_CHAIR)) {    
                this.OnUpdateUser(useritem.wChairID, useritem, false)
            }
        } 
    }
    
    //--查询用户
    QueryUserInfo(table ,chair)
    {
        console.log("QueryUserInfo")
        var msg = MsgTransfer.encodemsg(ConstMsgId.MDM_GR_USER,ConstMsgId.SUB_GR_USER_CHAIR_INFO_REQ,4 + 4 + 4,table,chair)
        this._GameProcessManager.sendMsg(msg);

    }
    
    //--换位请求
    QueryChangeDesk()
    {
        this.bChangeDesk = true
        var msg = MsgTransfer.encodemsg(ConstMsgId.MDM_GR_USER,ConstMsgId.SUB_GR_USER_CHAIR_REQ,4 + 4 )
        this._GameProcessManager.sendMsg(msg);
    }


    //-- 场景信息
    onEventGameScene(cbGameStatus,data)
    {
        console.log("场景数据:" + cbGameStatus)
        this.cbGameStatus = cbGameStatus
        //--初始化已有玩家
        for (var i = 0; i < Define.PLAYER_COUNT; i++) {
            var userItem = this.getTableUserItem(this.GetMeTableID(), i)
            if (null != userItem) {
                var  wViewChairId = this.SwitchViewChairID(i)
                this.OnUpdateUser(i, userItem,false)
            }
        }
        if (cbGameStatus == Define.GAME_SCENE_FREE) {    
            this.m_bCallStateEnter = false
            //  --空闲状态
             this.onEventGameSceneFree(data)
        }
        else if (cbGameStatus == Define.GAME_SCENE_CALL )                          //   --叫分状态
        {   
            this.m_bCallStateEnter = true
            this.saveServerInfo()
            this.onEventGameSceneCall(data)   
        }     
        else if (cbGameStatus == Define.GAME_SCENE_PLAY )                           //  --游戏状态
        {    
           
            this.m_bCallStateEnter = false
            this.saveServerInfo()

            this.onEventGameScenePlay(data)
        }
    }

    onEventGameSceneFree( data )
    {

//  --空闲状态
// cmd.CMD_S_StatusFree = 
// {
//     --游戏属性
//     {k = "lCellScore", t = "int"},                              --基础积分

//     --时间信息
//     {k = "cbTimeOutCard", t = "byte"},                          --出牌时间
//     {k = "cbTimeCallScore", t = "byte"},                        --叫分时间
//     {k = "cbTimeStartGame", t = "byte"},                        --开始时间
//     {k = "cbTimeHeadOutCard", t = "byte"},                      --首出时间

//     --历史积分
//     {k = "lTurnScore", t = "score", l = {cmd.PLAYER_COUNT}},    --积分信息
//     {k = "lCollectScore", t = "score", l = {cmd.PLAYER_COUNT}}, --积分信息
// }
        var readPos = 0
        var  cmd_table = {}
        var dataview = new DataView(data)        
        cmd_table.lCellScore   	= dataview.getInt32(readPos,Common.littleEndian) 
        readPos+=4   
        cmd_table.cbTimeOutCard  = dataview.getUint8(readPos,Common.littleEndian) 
        readPos+=1 
        cmd_table.cbTimeCallScore  = dataview.getUint8(readPos,Common.littleEndian) 
        readPos+=1 
        cmd_table.cbTimeStartGame  = dataview.getUint8(readPos,Common.littleEndian) 
        readPos+=1 
        cmd_table.cbTimeHeadOutCard  = dataview.getUint8(readPos,Common.littleEndian) 
        readPos+=1
        cmd_table.lTurnScore = []
        for(var i=0;i<Define.PLAYER_COUNT;i++)
        {
            var score  = Common.readint64(data,readPos)
            readPos+=8 
            cmd_table.lTurnScore.push(score)
        }
        cmd_table.lCollectScore = []
        for(var i=0;i<Define.PLAYER_COUNT;i++)
        {
            var score  = Common.readint64(data,readPos)
            readPos+=8 
            cmd_table.lCollectScore.push(score)
        }


        this.COUNTDOWN_READY = cmd_table.cbTimeStartGame
        this.COUNTDOWN_CALLSCORE = cmd_table.cbTimeCallScore
        this.COUNTDOWN_OUTCARD = cmd_table.cbTimeOutCard
        this.COUNTDOWN_HANDOUTTIME = cmd_table.cbTimeHeadOutCard
        //-- 更新底分
        this.emit(Event.COM_MSG.UPDATE_CELL_SCORE,cmd_table.lCellScore)
        console.log("emit Event.COM_MSG.UPDATE_CELL_SCORE" + cmd_table.lCellScore)
        //self._gameView:onGetCellScore(cmd_table.lCellScore)

        //-- 空闲消息
       // self._gameView:onGetGameFree()
       this.emit(Event.COM_MSG.UPDATE_BTN_READY,true)

        //this.KillGameClock()
        //-- 私人房无倒计时
       // if not GlobalUserItem.bPrivateRoom then
            //-- 设置倒计时
        //this.SetGameClock(this.GetMeChairID(), Define.TAG_COUNTDOWN_READY, this.COUNTDOWN_READY)
        //end    
    }

    onEventGameSceneCall( data )
    {

        // --时间信息
        // {k = "cbTimeOutCard", t = "byte"},                          --出牌时间
        // {k = "cbTimeCallScore", t = "byte"},                        --叫分时间
        // {k = "cbTimeStartGame", t = "byte"},                        --开始时间
        // {k = "cbTimeHeadOutCard", t = "byte"},                      --首出时间
    
        // --游戏信息
        // {k = "lCellScore", t = "int"},                              --单元积分
        // {k = "wCurrentUser", t = "word"},                           --当前玩家
        // {k = "cbBankerScore", t = "byte"},                          --庄家叫分
        // {k = "cbScoreInfo", t = "byte", l = {cmd.PLAYER_COUNT}},    --叫分信息
        // {k = "cbHandCardData", t = "byte", l = {cmd.NORMAL_COUNT}}, --手上扑克
    
        // --历史积分
        // {k = "lTurnScore", t = "score", l = {cmd.PLAYER_COUNT}},    --积分信息
        // {k = "lCollectScore", t = "score", l = {cmd.PLAYER_COUNT}}, --积分信息

        var readPos = 0
        var cmd_table = {}
        var dataview = new DataView(data)        
        cmd_table.cbTimeOutCard   	= dataview.getUint8(readPos,Common.littleEndian) 
        readPos+=1   
        cmd_table.cbTimeCallScore  = dataview.getUint8(readPos,Common.littleEndian) 
        readPos+=1 
        cmd_table.cbTimeStartGame  = dataview.getUint8(readPos,Common.littleEndian) 
        readPos+=1 
        cmd_table.cbTimeHeadOutCard  = dataview.getUint8(readPos,Common.littleEndian) 
        readPos+=1 

    


        cmd_table.lCellScore  = dataview.getInt32(readPos,Common.littleEndian) 
        readPos+=4
        cmd_table.wCurrentUser  = dataview.getUint16(readPos,Common.littleEndian) 
        readPos+=2
        cmd_table.cbBankerScore  = dataview.getUint8(readPos,Common.littleEndian) 
        readPos+=1 

        cmd_table.cbScoreInfo = []
        for(var i=0;i<Define.PLAYER_COUNT;i++)
        {
            var score = dataview.getUint8(readPos,Common.littleEndian) 
            readPos+=1 
            cmd_table.cbScoreInfo.push(score)
        }

        cmd_table.cbHandCardData = []
        for(var i=0;i<Define.NORMAL_COUNT;i++)
        {
            var card  = dataview.getUint8(readPos,Common.littleEndian) 
            readPos+=1 
            cmd_table.cbHandCardData.push(card)
        }

        cmd_table.lTurnScore = []
        for(var i=0;i<Define.PLAYER_COUNT;i++)
        {
            var score  = Common.readint64(data,readPos)
            readPos+=8 
            cmd_table.lTurnScore.push(score)
        }
        cmd_table.lCollectScore = []

        for(var i = 0;i < Define.PLAYER_COUNT; i++)
        {
            var score  = Common.readint64(data,readPos)
            readPos+=8 
            cmd_table.lCollectScore.push(score)
        }

 


        console.log('onEventGameSceneCall' + JSON.stringify( cmd_table) )

        this.COUNTDOWN_READY = cmd_table.cbTimeStartGame
        this.COUNTDOWN_CALLSCORE = cmd_table.cbTimeCallScore
        this.COUNTDOWN_OUTCARD = cmd_table.cbTimeOutCard
        this.COUNTDOWN_HANDOUTTIME = cmd_table.cbTimeHeadOutCard    

        this.m_bRoundOver = false

        var cards = {}
        cards.cbCardData = []       
        for (var i = 0 ;i < cmd_table.cbHandCardData.length; i++)
        {
            cards.cbCardData.push(cmd_table.cbHandCardData[i])
        }  

        this.reSetData()
        console.log("onEventGameSceneCall:cards"+ JSON.stringify(cards))
        this.handCards = cards;

        this.emit(Event.CPT_MSG.GAME_START,cards,true);

        this.emit(Event.CPT_MSG.GAME_SCENE_CALL,cmd_table)//里面叫分

    }
  

    onEventGameScenePlay( data )
    {

        // --时间信息
        // {k = "cbTimeOutCard", t = "byte"},                          --出牌时间
        // {k = "cbTimeCallScore", t = "byte"},                        --叫分时间
        // {k = "cbTimeStartGame", t = "byte"},                        --开始时间
        // {k = "cbTimeHeadOutCard", t = "byte"},                      --首出时间

        // --游戏变量
        // {k = "lCellScore", t = "int"},                              --单元积分
        // {k = "cbBombCount", t = "byte"},                            --炸弹次数
        // {k = "wBankerUser", t = "word"},                            --庄家用户
        // {k = "wCurrentUser", t = "word"},                           --当前庄家
        // {k = "cbBankerScore", t = "byte"},                          --庄家叫分

        // --出牌信息
        // {k = "wTurnWiner", t = "word"},                             --胜利玩家
        // {k = "cbTurnCardCount", t = "byte"},                        --出牌数目
        // {k = "cbTurnCardData", t = "byte", l = {cmd.MAX_COUNT}},    --出牌数据

        // --扑克信息
        // {k = "cbBankerCard", t = "byte", l = {3}},                  --游戏底牌
        // {k = "cbHandCardData", t = "byte", l = {cmd.MAX_COUNT}},    --手上扑克
        // {k = "cbHandCardCount", t = "byte", l = {cmd.PLAYER_COUNT}},--扑克数目

        // --历史积分
        // {k = "lTurnScore", t = "score", l = {cmd.PLAYER_COUNT}},    --积分信息
        // {k = "lCollectScore", t = "score", l = {cmd.PLAYER_COUNT}}, --积分信息

        this.reSetData()

        var readPos = 0
        var cmd_table = {}
        var dataview = new DataView(data)    

        // --时间信息
        cmd_table.cbTimeOutCard   	= dataview.getUint8(readPos,Common.littleEndian) 
        readPos+=1   
        cmd_table.cbTimeCallScore  = dataview.getUint8(readPos,Common.littleEndian) 
        readPos+=1 
        cmd_table.cbTimeStartGame  = dataview.getUint8(readPos,Common.littleEndian) 
        readPos+=1 
        cmd_table.cbTimeHeadOutCard  = dataview.getUint8(readPos,Common.littleEndian) 
        readPos+=1 



         // --游戏变量
        cmd_table.lCellScore  = dataview.getInt32(readPos,Common.littleEndian) 
        readPos+=4
        cmd_table.cbBombCount  = dataview.getUint8(readPos,Common.littleEndian) 
        readPos+=1
        cmd_table.wBankerUser  = dataview.getUint16(readPos,Common.littleEndian) 
        readPos+=2 
        cmd_table.wCurrentUser  = dataview.getUint16(readPos,Common.littleEndian) 
        readPos+=2 
        cmd_table.cbBankerScore  = dataview.getUint8(readPos,Common.littleEndian) 
        readPos+=1         

        //--出牌信息
        cmd_table.wTurnWiner  = dataview.getUint16(readPos,Common.littleEndian) 
        readPos+=2   
        cmd_table.cbTurnCardCount  = dataview.getUint8(readPos,Common.littleEndian) 
        readPos+=1   
        cmd_table.cbTurnCardData = []
        for(var i=0; i < Define.MAX_COUNT ;i++)
        {
            var card = dataview.getUint8(readPos,Common.littleEndian) 
            readPos+=1 
            cmd_table.cbTurnCardData.push(card)
        }    

        // --扑克信息

        cmd_table.cbBankerCard = []
        for(var i=0;i< 3;i++)
        {
            var card = dataview.getUint8(readPos,Common.littleEndian) 
            readPos+=1 
            cmd_table.cbBankerCard.push(card)
        }

        cmd_table.cbHandCardData = []
        for(var i=0;i<Define.MAX_COUNT;i++)
        {
            var card  = dataview.getUint8(readPos,Common.littleEndian) 
            readPos+=1 
            if(card > 0) //0 补位的，不是牌
            {
                cmd_table.cbHandCardData.push(card)
            }
        }

        cmd_table.cbHandCardCount = []
        for(var i=0;i<Define.PLAYER_COUNT;i++)
        {
            var count  = dataview.getUint8(readPos,Common.littleEndian)
            readPos+=1 
            cmd_table.cbHandCardCount.push(count)
        }

       cmd_table.lTurnScore = []
        for(var i=0;i<Define.PLAYER_COUNT;i++)
        {
            var score  = Common.readint64(data,readPos)
            readPos+=8 
            cmd_table.lTurnScore.push(score)
        }
        cmd_table.lCollectScore = []

        for(var i = 0;i < Define.PLAYER_COUNT; i++)
        {
            var score  = Common.readint64(data,readPos)
            readPos+=8 
            cmd_table.lCollectScore.push(score)
        }

        console.log('onEventGameScenePlay' + JSON.stringify( cmd_table) )

        this.COUNTDOWN_READY = cmd_table.cbTimeStartGame
        this.COUNTDOWN_CALLSCORE = cmd_table.cbTimeCallScore
        this.COUNTDOWN_OUTCARD = cmd_table.cbTimeOutCard
        this.COUNTDOWN_HANDOUTTIME = cmd_table.cbTimeHeadOutCard
        this.m_bRoundOver = false


        var cards = {}
        cards.cbCardData = []       
        for (var i = 0 ;i < cmd_table.cbHandCardData.length; i++)
        {
            cards.cbCardData.push(cmd_table.cbHandCardData[i])
        }  


        console.log("onEventGameScenePlay:cards"+ JSON.stringify(cards))
        this.handCards = cards;
        this.emit(Event.CPT_MSG.GAME_START,cards,true);


        var bankerInfo = {}
        var readPos = 0
        bankerInfo.wBankerUser = cmd_table.wBankerUser
        bankerInfo.wCurrentUser   	= cmd_table.wCurrentUser
        bankerInfo.cbBankerScore   	= cmd_table.cbBankerScore

        bankerInfo.cbBankerCard = []

        for(var i=0;i< cmd_table.cbBankerCard.length;i++)
        {
            bankerInfo.cbBankerCard.push(cmd_table.cbBankerCard[i])
        }
        //-- 自己是否庄家
        var bankerView = this.SwitchViewChairID(bankerInfo.wBankerUser)
        
        this.m_bIsMyBanker = (bankerView === Define.MY_VIEWID)
           
        console.log("onEventGameScenePlay bankerInfo:"+JSON.stringify( bankerInfo))   
        this.emit(Event.CPT_MSG.BANKER_INFO,bankerInfo,true);

        var outCards = {}
        outCards.cbCardCount   	=  cmd_table.cbTurnCardCount
        outCards.wCurrentUser   = cmd_table.wCurrentUser 
        outCards.wOutCardUser   = cmd_table.wTurnWiner
   
        outCards.cbCardData = []

        for (var i = 0 ;i < cmd_table.cbTurnCardData.length; i++)
        {
            
            if(i >= outCards.cbCardCount)
            {
                break
            }
            outCards.cbCardData.push(cmd_table.cbTurnCardData[i])
        }  
        console.log("onEventGameScenePlay OutCard:"+JSON.stringify( outCards))   
        this.emit(Event.CPT_MSG.OUT_CARD,outCards);



        this.emit(Event.CPT_MSG.GAME_SCENE_PLAY,cmd_table)

    }



    //-- 关闭计时器
    KillGameClock(id)
    {
        for (var i=0;i<this.counterInfos.length;i++)
        {
            var info = this.counterInfos[i]

            if(info.id == id)
            {
                this.counterInfos[i].viewId  = 0
                this.counterInfos[i].time   =  0
                this.counterInfos[i].call   =  null
                return
            }
        }
    }



    //-- 设置计时器
    SetGameClock(id,chair,time,intvalCall)
    {
        var counterInfo = {}
        counterInfo.id = id
        counterInfo.viewId =  this.SwitchViewChairID(chair) - 1
        counterInfo.time = time
        counterInfo.call = intvalCall
        for (var i = 0; i < this.counterInfos.length; i++) {
            var info = this.counterInfos[i]
            if (info.id == id) {
                this.counterInfos[i].viewId  = this.SwitchViewChairID(chair) - 1
                this.counterInfos[i].time   =  time
                this.counterInfos[i].call   =  intvalCall
                return
            }
        }
        this.counterInfos.push(counterInfo)
    }

    //--用户进入
    onEventUserEnter(tableid,chairid,useritem)
    {
        console.log('onEventUserEnter tableid: ' + tableid + 'chairid:' + 'useritem:' + JSON.stringify(useritem) )
        this.emit(Event.COM_MSG.USER_ENTER,tableid,chairid,useritem)
    }

    setEnterAntiCheatRoom( bEnter )
    {
        this.bEnterAntiCheatRoom = bEnter
    }
	
    GetTableCount()
    {
	    return this.wTableCount
    }
    

    GetChairCount()
    {
        return this.wChairCount
    }
        
    

    GetServerType()
    {
        return this.wServerType
    }
        
    

    GetServerRule()
    {
        return this.dwServerRule
    }
        
    //-- 退出桌子
    onExitTable()
    {
        console.log('BattleBehavior onExitTable')

        this.emit(Event.COM_MSG.EXIT_TABLE)
        this.emit(Event.COM_MSG.SEND_MSG,false,'')

    }
    
     onExitRoom()
     {
        // self._gameFrame:onCloseSocket()
        // self:stopAllActions()
        // self:KillGameClock()
        // self:dismissPopWait()
        // self._scene:onChangeShowMode(yl.SCENE_ROOMLIST)
    }
    
    onEnterTable()
    {
        console.log("ClientScene onEnterTable")

        // if PriRoom and GlobalUserItem.bPrivateRoom then
        //     -- 动作记录
        //     PriRoom:getInstance().m_nLoginAction = PriRoom.L_ACTION.ACT_ENTERTABLE
        // end
        // local tag = self._sceneRecord[#self._sceneRecord]
        // if tag == yl.SCENE_GAME then
        //     self._gameFrame:setViewFrame(self._sceneLayer:getChildByTag(yl.SCENE_GAME))
        // else
        //     self:onChangeShowMode(yl.SCENE_GAME)
        // end
        ViewManager.replaceView('game')

    }


    //--重置框架
    OnResetGameEngine()
    { 
        // self:KillGameClock()
    }

    //-- 返回键处理
    // onKeyBack()
    //     self:onQueryExitGame()
    //     return true
    // end
    
    //-- 获取自己椅子
    GetMeChairID()
    {
      return  this.wChairID
    }
   
    //-- 获取自己桌子
    GetMeTableID()
    {
       return this.wTableID
    }
    
    //-- 获取自己
    GetMeUserItem()
    {
       return this.playerInfoModel.getSelfTablePlayer()
    }
    
    
    //-- 椅子号转视图位置,注意椅子号从0~nChairCount-1,返回的视图位置从1~nChairCount
    SwitchViewChairID(chair)
    {
        var  viewid = Define.INVALID_CHAIR
        var  nChairCount = this.GetChairCount()
        var  nChairID = this.GetMeChairID()
        if ((chair != Define.INVALID_CHAIR) && (chair < nChairCount))
        {
            viewid = ((chair + Math.floor(nChairCount * 3/2) - nChairID) % nChairCount) + 1
        } 

        return viewid
    }
    
    IsValidChairID(chair)
    {
        var nChairCount = this.GetChairCount();
        return (chair != Define.INVALID_CHAIR) && (chair >= 0 && chair < nChairCount);
    }

    //-- 是否合法视图id
    IsValidViewID( viewId )
    {
        var  nChairCount = this.GetChairCount()
        return (viewId > 0) && (viewId <= nChairCount)
    }   


    OnUpdateUser(viewId, userItem, bLeave)
    {
        this.emit(Event.COM_MSG.UPDATE_USER,viewId,userItem,bLeave)
    }

    //--房间取款准许
    OnRoomAllowBankTake()
    { 
        return ((this.dwServerRule & 0x00010000) != 0)
    } 

    //--房间存款准许
    OnRoomAllowBankSave()
    {
        return ((this.dwServerRule & 0x00040000) != 0)
    }

    //--游戏取款准许
    OnGameAllowBankTake()
    {
        return ((this.dwServerRule & 0x00020000) != 0)
    }

    //--游戏存款准许
    OnGameAllowBankSave()
    {
        return ((this.dwServerRule & 0x00080000) != 0)
    }
        
    

    IsAllowAvertCheatMode( )
    {
        return false
       // return ((this.dwServerRule & Define.SR_ALLOW_AVERT_CHEAT_MODE) != 0)
    }
        
    //--是否更新大厅金币
    IsAllowPlazzScoreChange()
    {
        return (this.wServerType != Define.GAME_GENRE_SCORE) && (this.wServerType != Define.GAME_GENRE_EDUCATE)
    }
        
    //--游戏赠送准许
    OnGameAllowBankTransfer()
    {
        return false
    }
     
    loadImage(url,texture)
    {
        cc.loader.load(url, function (err, tex) {
            cc.log('Should load a texture from external url: ' + (tex instanceof cc.Texture2D));
            texture = tex;
        });
    }

    loadData(completeCallback)
    {
        var questions = this.questionInfoModel.getQuestionInfo();

        var resouces = [];

        for (var i = 0; i < questions.length; ++i)
        {
            var question = questions[i];
            var res_url = question.res_name;
            var res_type = question.type;
            
            if( (res_type==1||res_type==2) && res_url != null && res_url != "")
            {
                resouces.push(res_url);
            } 
 
        }

        cc.loader.load(resouces, function (errors, results) 
        {
            if (errors) 
            {
                for (var i = 0; i < errors.length; i++)
                {
                    cc.log('Error url [' + errors[i] + ']: ' + results.getError(errors[i]));
                }
            }

            for (var i = 0; i < questions.length; ++i)
            {
                var question = questions[i];
                var res_type = question.type;
                var res_url = question.res_name;
                var texture = null;//纹理数据
                this.audioClip = null;//二进制数据
                if(res_type == 1)//图片 下载
                {
                    console.log("res_url:"+res_url)
                    var texture = results.getContent(res_url);
                    question.texture = texture;
                } 
                else if(res_type == 2)
                {
                    console.log("res_url:"+res_url)
                    
                    var audioClip = results.getContent(res_url);
                    question.audioClip = audioClip;
                }
            }
        
            if(completeCallback)
            {
                completeCallback.call();
            }

        });
    }
  

    onDataLoaded()
    {
        console.log("onDataLoaded complete");
    }


    getGenderByChair(chair) {
        var item = this.playerInfoModel.getTablePlayerInfoByUserID(chair);
        if (item != null ) {  
            return item.cbGender;
        } else {
            return 0;
        }
    }
}