const GameStatesStatic = require('GameStates');
// var PlayerStateStatic = require('PlayerState');
cc.Class({
    extends: cc.Component,
    properties: {
        NodeTouchScript: null,
        Rivel: null,
        javelin_prefab: {//标枪计距带起点
            default: null,
            type: cc.Prefab
        },

        isReported: false,//是否上报过分数？
        isRuning: false,
        isReadyGo: false,

        isGameStart: false,//如果没收到回调的gamestart

        TipToast: {//Toast 提示
            default: null,
            type: cc.Node
        },

        TipText: {//提示的文字
            default: null,
            type: cc.Label
        },

        _GameUI: null,
        _isChannelCreated: false,
    },
    onLoad: function () {
        qqNetwork.regMsgCallback(this.onMessage.bind(this));
        qqNetwork.enableDebug();
        this._isChannelCreated = false;

        this._GameUI = cc.find('UIControl').getComponent('GameUI');
        this.startGame();

    },

    startGame: function () {

        this.GameStates = cc.find("Canvas").getComponent("GameStates");
        this.GetGameMode = cc.find('Canvas').getComponent('GameMode');
        cc.game.setFrameRate(60);
        var TouchLayout = cc.find("TouchLayout");
        this.NodeTouchScript = TouchLayout.getComponent("NodeTouch");
        this.Rivel = cc.find("Rivel");

    },

    update() {
        if (qqNetwork.isHasChannelData && !this._isChannelCreated) {
            this._isChannelCreated = true;
            var msgData = qqNetwork.ChannelData;

            // console.log(msgData);
            // console.log("channelCreated ====", JSON.stringify(msgData.playerInfos[0]));
            // console.log("channelCreated ====", JSON.stringify(msgData.playerInfos[1]));
            this.onNetWorkChannel(msgData);

        }
    },

    onNetWorkChannel(msgData) {
        this.setNetWorkData(msgData);

        this.GameStates.bConnect = true;

        if (1 == msgData.playerInfos[0].seat) {
            this.GameStates.bServer = true;
            this.GameStates.isRobot = window.qqgame.isRobot;
            var randomSkin = cc.find("randomSkin");
            randomSkin.getComponent("upDateSkin").setRandomSkinss();

            if (!qqNetwork.debugFlag) {
                var data = { FunctionName: 'isrobot', status: "Server", isRobot: window.qqgame.isRobot };
                this.GetGameMode.SynchronizationFun(data);
            }
        }
        else {
            this.GameStates.bServer = false;
            cc.find('Rivel').getChildByName('Player').getChildByName('PlayerCollisionLine').destroy();
            this.GameStates.isRobot = window.qqgame.isRobot;

            if (!qqNetwork.debugFlag) {
                var data = { FunctionName: 'isrobot', status: "Client", isRobot: window.qqgame.isRobot };
                this.GetGameMode.SynchronizationFun(data);
            }
        }
        // GLog.addLog("是服务器吗=" + GameStates.bServer);

        if (this.GameStates.bServer) {
            var myDate = new Date();
            var name = myDate.getMilliseconds();
            this.GameStates.HostName = JSON.stringify('ID:' + name);
            cc.log('HostName:' + this.GameStates.HostName);
            var data = { FunctionName: 'HostName', OurName: this.GameStates.HostName };
        }

        this.scheduleOnce(function () {
            qqNetwork.send(qqNetwork.game2Room.gameReady, {});
        }, 0.5);


    },
    //开始游戏，播放开始动画
    onStartGame() {
        this.isGameStart = true;
        if (cc.find('Canvas').getComponent(cc.AudioSource) != null) {
            cc.find('Canvas').getComponent(cc.AudioSource).play();
        }

        // var GameStates = cc.find('Canvas').getComponent('GameStates');
        var ReadyGoPrefab = this._GameUI.CreateReadyGo();
        var readGo = ReadyGoPrefab.getComponent('readGo');
        readGo.active = true;
        var id = readGo.PlayAudio();
        cc.audioEngine.setFinishCallback(id, function () {
            this.startNetGame();
            var testDate = new Date();
            var mytime = testDate.getTime();
            this.GameStates.startTime = mytime;
            this.GameStates.bHasStartGame = true;
            cc.find('ReadyGoRoot').destroy();

        }.bind(this));
    },
    onMessage: function (msgName, msgData) {
        if (!msgData || !msgName) {
            return;
        }

        switch (msgName) {
            // case qqNetwork.room2Game.offline:
            //     break;
            // case qqNetwork.room2Game.channelCreated: // 匹配成功
            //     break;
            // case qqNetwork.room2Game.frameData:
            //     // this.frameDataControl(msgData);
            //     break;
            case qqNetwork.room2Game.gameStart:
                this.scheduleOnce(function () {
                    this.onStartGame();
                }, 1);

                break;
            case qqNetwork.room2Game.gameData: // 消息同步
                var myData;
                if (msgData == "gameStart") {
                    return;
                }
                myData = JSON.parse(msgData.str);

                var Hero = this.GameStates.getHero;// cc.find('Hero');
                var Rivel = this.GameStates.getRivel;//cc.find('Rivel');
                var HeroControl = this.GameStates.getHeroControl;// Hero.getComponent('HeroControl');
                var RivelControl = this.GameStates.getRivelControl;// Rivel.getComponent('HeroControl');

                var RivelPlayerState = Rivel.getComponent('PlayerState');
                var GameMode = this.GetGameMode // cc.find('Canvas').getComponent('GameMode');
                var GameStates = this.GameStates;// cc.find('Canvas').getComponent('GameStates');


                if ('HostName' == myData.FunctionName) {
                    GameStates.HostName = myData.OurName;
                    console.log('HostName:' + GameStates.HostName);
                }

                if ('ReadyToRun' == myData.FunctionName) {
                    if (!this.GameStates.bReadyToRun) {
                        this.GameStates.bReadyToRun = !this.GameStates.bReadyToRun;
                    }
                    else {
                        this.StartToRun();
                    }
                } else if ('StaggerAnimation' == myData.FunctionName) {
                    RivelPlayerState.SyschroAtionArray.push(myData);
                    GameMode.SyncPositionXRange(Rivel, myData.CurrentPositionX);
                }
                else if ('SynchroHeroPositionXAndSpeed' == myData.FunctionName) {

                    RivelPlayerState.HeroPositionX = myData.PositionX;
                    RivelPlayerState.HeroCurrentSpeed = myData.HeroCurrentSpeed;
                }
                else if ('myRandomSetSkins' === myData.FunctionName) {
                    // var RivelPlayer = Rivel.getChildByName("Player");
                    // RivelPlayer.active = true;
                    // var HeroPlayer = Hero.getChildByName("Player");
                    // HeroPlayer.active = true;
                    Rivel.getChildByName("Player").getComponent("Charactor").setSkins(myData.arr[1]);
                    Hero.getChildByName("Player").getComponent("Charactor").setSkins(myData.arr[0]);
                }
                else if ('SetCurrentSpeedAndAnimation' === myData.FunctionName) {
                    // RivelControl.SetCurrentSpeedAndAnimation(myData.Speed);
                    RivelPlayerState.SyschroAtionArray.push(myData);
                    GameMode.SyncPositionXRange(Rivel, myData.CurrentPositionX);
                }
                else if ('SetCurrentSpeedAndAnimationSpeedDown' === myData.FunctionName) {

                    if (RivelControl.PlayerStateScript.CurrentSpeed != 0) {
                        // cc.log("当前速度是 通知",RivelControl.PlayerStateScript.CurrentSpeed);
                        RivelControl.SetCurrentSpeedAndAnimation(myData.Speed);
                    }
                } else if ('reqAddScore' == myData.FunctionName) {
                    //console.log("请求计算分数");
                    GameMode.SyncJaveEndAddScore();
                }
                else if ('addScore' == myData.FunctionName) {
                    let deltaValue = 0;
                    if (myData.deltaValue) {
                        // console.log('myData.deltaValue ==', myData.deltaValue)
                        deltaValue = myData.deltaValue;
                    }
                    GameMode.addScore(Rivel, myData.value, false, deltaValue);
                } else if ('callBackAddScore' == myData.FunctionName) {
                    //服务器回调结果
                    if (myData.value == 0) {
                        GameMode.drawAddScrore(Hero);
                    } else if (myData.value == 1) {//服务器的对应的玩家胜利
                        GameMode.oldAddScore(Rivel);
                    } else if (myData.value == -1) {//客户端对应的玩家胜利
                        GameMode.oldAddScore(Hero);
                    }
                }

                else if ('SendMyArrivedTime' == myData.FunctionName) {
                    GameMode.RivalArrivedTime = myData.MyArrivedTime;//设置客户端的到达时间
                }
                else if ('PushPlayerToEnterFinishLinePlayersArray' == myData.FunctionName) {
                    GameStates.EnterFinishLinePlayersArray.push(Rivel);
                }
                else if ('CheckPlayersDistance' == myData.FunctionName) {
                    GameStates.EnterStartLinePlayersArray.push(Rivel);
                    GameStates.StartLinePositionX = myData.StartLinePositionX;

                    GameMode.CheckPlayersDistance(false);
                }
                else if ('SetStartLinePositionX' == myData.FunctionName) {
                    GameStates.StartLinePositionX = myData.StartLinePositionX;
                    //Code added by slam
                    RivelControl.SetSpeedToZeroAndIdle();
                    RivelControl.node.setPositionX(myData.StartLinePositionX);

                }
                else if ('ClearEnterFinishLinePlayersArray' == myData.FunctionName) {
                    GameStates.EnterStartLinePlayersArray = [];
                }
                else if ('ResetSpeed' == myData.FunctionName) {
                    RivelPlayerState.SyschroAtionArray.push(myData);
                    GameMode.SyncPositionXRange(Rivel, myData.CurrentPositionX);
                }
                else if ('SetRivelPosition' == myData.FunctionName) {
                    // console.log("跳远同步的位置！！", myData)
                    Rivel.setPositionX(myData.positionX + 40);
                }
                else if ('SetSpeedToZeroAndIdle' == myData.FunctionName) {
                    RivelPlayerState.SyschroAtionArray.push(myData);

                } else if ('FinishLineReduceSpeedPositionArray' == myData.FunctionName) {
                    RivelPlayerState.SyschroAtionArray.push(myData);
                }
                else if ('PushPlayerToEnterStartLinePlayersArrayAndSetStartLinePositionX' == myData.FunctionName) {
                    var EnterStartLinePlayersArray = GameStates.EnterStartLinePlayersArray;
                    GameStates.StartLinePositionX = myData.StartLinePositionX;
                    EnterStartLinePlayersArray.push(Rivel);
                }
                else if ('UnScheduleFadeIn' == myData.FunctionName) {
                    GameMode.unschedule(GameMode.Transport);
                    HeroControl.javelinTag = false;
                    RivelControl.javelinTag = false;
                    HeroControl.CameraNode.parent = Hero;
                    this.schedule(function () {
                        GameStates.EnterStartLinePlayersArray = [];
                    }.bind(this), 5, 0);
                }
                else if ("SetEndLinePositionXAndStop" == myData.FunctionName) {
                    var EndLinePositionX = myData.PositionX;
                    RivelControl.SetSpeedToZeroAndIdle();
                    GameStates.EndLinePositionX = EndLinePositionX;
                }
                else if ('Transport' == myData.FunctionName) {
                    GameMode.schedule(GameMode.Transport, 3, 0);
                }
                else if ("FadeInAndOut" == myData.FunctionName) {
                    cc.find("Shade").getComponent('Shade').FadeInAndOut(function () {
                        RivelControl.SetSpeedToZeroAndIdle();
                        Rivel.setPositionX(GameStates.StartLinePositionX);
                        HeroControl.SetSpeedToZeroAndIdle();
                        Hero.setPositionX(GameStates.StartLinePositionX);
                        HeroControl.javelinTag = false;
                        RivelControl.javelinTag = false;
                        HeroControl.CameraNode.parent = Hero;

                    }.bind(this))

                }
                else if ('StopPlayerAllSchedule' == myData.FunctionName) {
                    RivelPlayerState.SyschroAtionArray.push(myData);
                }
                else if ('PlayersStartToRun' == myData.FunctionName) {

                    RivelPlayerState.SyschroAtionArray.push(myData);
                }
                else if ("HeroLongJumpHeroAnimation" == myData.FunctionName) {
                    RivelPlayerState.SyschroAtionArray.push(myData);
                }
                else if ("HeroLongJumpRivelAnimation" == myData.FunctionName) {
                    RivelPlayerState.SyschroAtionArray.push(myData);
                }
                else
                    if ("SetCurrentSpeed_max_jumpLong" == myData.FunctionName) {
                        RivelPlayerState.SyschroAtionArray.push(myData);
                    }
                    else if ("HeroJumpHeroAnimation" == myData.FunctionName) {
                        RivelPlayerState.SyschroAtionArray.push(myData);
                    }
                    else if ("PerfectHurdleBandRailing" == myData.FunctionName) {
                        RivelPlayerState.SyschroAtionArray.push(myData);
                    }
                    else if ("PerfectHurdleBandBarrier" == myData.FunctionName) {
                        RivelPlayerState.SyschroAtionArray.push(myData);
                    }
                    else if ("ShakeBarrier" == myData.FunctionName) {
                        RivelPlayerState.SyschroAtionArray.push(myData);
                    }
                    else if ("upBike" == myData.FunctionName) {
                        // cc.log("上车 准备网络");
                        RivelPlayerState.SyschroAtionArray.push(myData);
                    }
                    else if ("downBikeHero" == myData.FunctionName) {
                        Rivel.x = myData.EndPositionX + 30;
                        RivelPlayerState.SyschroAtionArray.push(myData);
                        let distance = Math.abs(Hero.x - Rivel.x);

                        if (myData.isStop) {//另外一个玩家直接停止
                            RivelControl.stopBikeHero("Rivel");
                        } else {
                            RivelControl.downBikeHero("Rivel");

                        }
                        //第一个hero到达终点通知
                        if (myData.isCollision) {
                            //console.log('distance ====', distance);
                            if (distance < 70) {//距离大概一个车位
                                HeroControl.downBikeHero("Hero");
                                var data = { FunctionName: 'downBikeHero', EndPositionX: Hero.x, isCollision: false, isStop: false };
                                GameMode.SynchronizationFun(data);
                            } else {
                                HeroControl.stopBikeHero("Hero");
                                var data = { FunctionName: 'downBikeHero', EndPositionX: Hero.x, isCollision: false, isStop: true };
                                GameMode.SynchronizationFun(data);
                            }

                            if (!GameMode.isUploaded) {
                                //这里是传给服务器判断的值，比如当前玩家的奔跑时间
                                let testDate = new Date();
                                let dateTime = testDate.getTime();//获取当前时间(从1970.1.1开始的毫秒数)
                                cc.log(dateTime, 'stopBikeHero 当前毫秒数');

                                let inputValue = GameStates.uploadValue;

                                let deltaValue = GameMode.bikeDeltaValue;//毫秒
                                if (!GameStates.bServer) {
                                    var data = { FunctionName: 'addScore', PlayerName: 'Hero', value: inputValue, deltaValue: deltaValue };
                                    GameMode.SynchronizationFun(data);
                                }
                                else {
                                    GameMode.addScore(cc.find('Hero'), inputValue, true, deltaValue)
                                }

                                GameMode.isUploaded = true;
                            }

                        }

                    }
                    //通知存储值
                    else if ("callFinishLine" == myData.FunctionName) {
                        GameStates.uploadValue = Hero.x;
                    }

                    else if ("upJavelinHeroAnimation" == myData.FunctionName) {
                        RivelPlayerState.SyschroAtionArray.push(myData);
                    }
                    else if ("Restrictions" == myData.FunctionName) {
                        RivelPlayerState.SyschroAtionArray.push(myData);
                    }
                    else if ("upJavelinend" == myData.FunctionName) {
                        RivelPlayerState.SyschroAtionArray.push(myData);
                    }
                    //Code added by slam
                    else if ("JavelinData" == myData.FunctionName) {

                        Rivel.setPositionX(myData.HeroPosition + 40);

                        RivelPlayerState.SyschroAtionArray.push(myData);
                    }
                    else if ("SetCurrentSpeed_max" == myData.FunctionName) {
                        RivelPlayerState.SyschroAtionArray.push(myData);
                    }
                    else if ("SetCurrentSpeed_noRestrictions" == myData.FunctionName) {
                        RivelPlayerState.SyschroAtionArray.push(myData);
                    }
                    else if ("SetCurrentSpeed_noRestrictions800" == myData.FunctionName) {
                        RivelPlayerState.SyschroAtionArray.push(myData);
                    }
                    else if ("resetHero" == myData.FunctionName) {
                        RivelPlayerState.SyschroAtionArray.push(myData);
                    }
                    else if ("resetHerojavelin" == myData.FunctionName) {
                        RivelPlayerState.SyschroAtionArray.push(myData);
                    }
                    else if ("endGame" == myData.FunctionName) {
                        // console.log("让我们不动222",myData);
                        RivelPlayerState.SyschroAtionArray.push(myData);
                    }
                break;

            case qqNetwork.room2Game.leave:
                // GLog.addLog("on退出游戏=" + JSON.stringify(msgData));
                let netData1 = JSON.parse(JSON.stringify(msgData));

                //data.isSelf == 1表示自己离开，data.isSelf == 2表示对手离开。
                if (netData1.isSelf == 1) {
                    this.endGame(2);
                    var data = {
                        // isSelf: netData1.isSelf
                        isSelf: 3
                    }
                    this.quitGame(data);
                } else if (netData1.isSelf == 2) {
                    this.endGame(1);
                    var data = {
                        // isSelf: netData1.isSelf
                        isSelf: 4
                    }
                    this.quitGame(data);
                }



                break;
            case qqNetwork.room2Game.network:
                let netData2 = JSON.parse(JSON.stringify(msgData));
                if (this.isRuning && this.isReported)
                    return;
                // GLog.addLog("on网络变化 提交数据=" + JSON.stringify(msgData));

                if (netData2.status == 'online') {
                    if (netData2.isSelf == 1) {
                        this.endGame(2, '对手网络不稳定');

                    } else {
                        this.endGame(1);
                    }
                    var data = {
                        isSelf: netData2.isSelf
                    }
                    this.quitGame(data);
                }

                break;
            case qqNetwork.room2Game.playerEnter:
                if (this.isReadyGo && !this.isRuning) {
                    this.startNetGame();
                }
                let netDataEnter = JSON.parse(JSON.stringify(msgData));
                if (this.isRuning) {
                    // GLog.addLog(this.netWorkData.playerInfos[0].qqgameid + " ==" + JSON.stringify(msgData));
                    if (this.netWorkData.playerInfos[0].qqgameid == netDataEnter.qqgameid) {
                        //自己
                        //GLog.addLog("自己 qqgameid ==" + this.netWorkData.playerInfos[0].qqgameid);
                        this.endGame(2);
                        this.setToast('网络不稳定');
                        var data = {
                            isSelf: 1
                        }
                        this.quitGame(data);
                    }
                    //  else if (this.netWorkData.playerInfos[1].qqgameid == netDataEnter.qqgameid) {
                    //     //对手
                    //     GLog.addLog("对手 qqgameid ==" + this.netWorkData.playerInfos[1].qqgameid);
                    //     this.endGame(1);  
                    //     var data = {
                    //         isSelf: 2
                    //     }
                    //     this.quitGame(data);
                    // }
                }
                break;

            case qqNetwork.room2Game.gameReset:
                console.log("NetworkSocket 游戏重置", msgData);

                break;

            // 有一端退出游戏
            // case qqNetwork.room2Game.gameEnd:
            //     return;
            //     if (this.isReported)
            //         return;
            //     console.log("NetworkSocket gameEnd" + JSON.stringify(msgData));
            //     //提前退出游戏，不管是谁退出接收到消息的话就自己赢
            //     let tempData = {
            //         isSelf: 2
            //     }
            //     this.endGame(1);
            //     this.quitGame(tempData);
            //     break;

            //语音变化
            //"isSelf": 1, // 1：自己，2：对手
            //"isOpen": 0,  // 0：语音关闭，1：语音打开
            //"isTalking": 1  // 0：不在说话，1：正在说话
            case qqNetwork.room2Game.voice: // 麦克风
                // do something
                let netDataVoice = JSON.parse(JSON.stringify(msgData));
                this._GameUI.setPlayerVoice(netDataVoice.isSelf, netDataVoice.isOpen);
                break;
        }
    },

    //帧同步控制器
    frameDataControl: function (data) {
        console.log("帧同步", data);
    },


    quitGame: function (data) {
        // GLog.addLog("quit data ====" + JSON.stringify(data));
        if (this.isReported)
            return;
        this.isReported = true;

        console.log('quit data ====', data)
        /* qqgame.pvpResponse({
         eID: 'frameData',
         ePara: data
         }); */

        // return;

        // var Hero = cc.find("Hero");
        // var NetworkSocket = Hero.getComponent('NetworkSocket');
        var GameStates = cc.find('Canvas').getComponent('GameStates');

        // GameStates.playTime = Math.floor((GameStates.endTime - GameStates.startTime) / 1000);
        GameStates.dtTime = Math.round(GameStates.dtTime);

        var PlayerState = cc.find('Hero').getComponent("PlayerState");
        var RivelState = cc.find('Rivel').getComponent("PlayerState");
        cc.log(PlayerState.TerminalPoint + '=============' + RivelState.TerminalPoint);


        var myWin = 0;
        var myLose = 0;
        //自己退出了
        //游戏结束了 自己输了 就是1   自己赢了 就是2  ,0 就是平局
        if (data.isSelf == 1) {
            myWin = qqgame.RESULT_LOSE;
            myLose = qqgame.RESULT_WIN;
        } else if (data.isSelf == 0) {
            myWin = qqgame.RESULT_EQUAL;
            myLose = qqgame.RESULT_EQUAL;
        } else if (data.isSelf == 3) {
            myWin = qqgame.RESULT_ESCAPE;
            myLose = qqgame.RESULT_WIN;
        } else if (data.isSelf == 4) {
            myWin = qqgame.RESULT_WIN;
            myLose = qqgame.RESULT_ESCAPE;
        }
        else {
            //别人退出了
            myWin = qqgame.RESULT_WIN;
            myLose = qqgame.RESULT_LOSE;
        }

        var datas = {
            // "report":{"key":"value", ...},         ----大厅侧的上报账单中的字段及值
            // "reportKey":"xxx",                ----大厅侧上报后台为每个游戏分配的key"
            //
            // "result":{
            // "win":-1/0/1,    ---- 输(-1)/平(0)/胜(1)
            // "myScore":"",   ---- 有分数才填写
            // "competitorScore":""  ---- 有分数才填写

            // myScore : 22,
            // competitorScore : 33,
            resultDisplay: { // 用于客户端结算面板的显示
                result: myWin
            },
            resultData: [
                {
                    qqgameid: this.netWorkData.playerInfos[0].qqgameid,
                    record: {
                        result: myWin, // 默认字段，必须有
                        playTime: GameStates.dtTime,// readygo开始   游戏开始======游戏结束     然后双方上报的时间要同步
                        amount: PlayerState.TerminalPoint,
                        // score: PlayerState.TerminalPoint,
                        // score: 88
                    }
                }, {
                    qqgameid: this.netWorkData.playerInfos[1].qqgameid,
                    record: {
                        result: myLose,
                        playTime: GameStates.dtTime,// readygo开始   游戏开始======游戏结束     然后双方上报的时间要同步
                        amount: RivelState.TerminalPoint, // 字段有大厅提供，游戏根据文档上报,
                        // score: RivelState.TerminalPoint,
                        // score: 88
                    }
                }
            ]



        };

        setTimeout(() => {
            console.log("退出游戏 上报数据", datas);
            //锚点
            this.sendSyncDataGameOver(datas);
        }, 1000);
    },

    sendSyncData: function (str) {
        // if (str.trim().length <= 0) {
        //     return
        // }
        var data = { str: str };
        // this.addLog("发送数据" + JSON.stringify(data));
        qqNetwork.send(qqNetwork.game2Room.gameData, data);
    },
    sendSyncDataGameOver: function (str) {
        qqNetwork.send(qqNetwork.game2Room.gameResult, str);
        // GLog.addLog("gameResult ===="+JSON.stringify(str));
    },

    GetSyncObj: function (ParentName, ObjName, PositionX) {
        var Level = cc.find("Level");
        var aX = parseFloat(PositionX);

        var Obj = null;
        var LevelChildren = Level.children;
        // cc.log('Level'+length);
        for (var i = 0; i < LevelChildren.length; i++) {
            if (LevelChildren[i].name === ParentName) {
                var aObj = LevelChildren[i].getChildByName(ObjName);

                if (aObj && aX === aObj.convertToWorldSpaceAR(cc.Vec2.ZERO).x) {
                    Obj = aObj;
                }
            }
        }
        return Obj;
    },
    /**
     * 设置网络数据
     * @param netWorkData
     */
    setNetWorkData: function (netWorkData) {
        // playerInfos
        // console.log(netWorkData.playerInfos);
        // console.log("channelCreated ====", netWorkData.playerInfos[0].headurl);
        // console.log("channelCreated ====", netWorkData.playerInfos[1].headurl);
        var UIControl = cc.find("UIControl").getComponent("UIControl");
        UIControl.setImage_Player1(netWorkData.playerInfos[0].headurl);
        UIControl.setImage_Player2(netWorkData.playerInfos[1].headurl);
        UIControl.setName_Player1(netWorkData.playerInfos[0].nick);
        UIControl.setName_Player2(netWorkData.playerInfos[1].nick);
        UIControl.setName_Gender1(netWorkData.playerInfos[0].gender);
        UIControl.setName_Gender2(netWorkData.playerInfos[1].gender);

        this.netWorkData = netWorkData;
    },
    //游戏最终结束
    endGame: function (num, isShowText) {

        var Hero = this.GameStates.getHero;// cc.find('Hero');
        var Rivel = this.GameStates.getRivel;//cc.find('Rivel');
        var HeroHeroControl = this.GameStates.getHeroControl;// Hero.getComponent('HeroControl');
        var RivelHeroControl = this.GameStates.getRivelControl;// Rivel.getComponent('HeroControl');

        if (cc.find('Canvas').getComponent('GameStates').strCureentLevel != "RideBike") {

            // if (num == 2) {
            HeroHeroControl.SetSpeedToZeroAndIdle();
            // }
            RivelHeroControl.SetSpeedToZeroAndIdle();
        }



        HeroHeroControl.HeroIsStop = true;//玩家停止
        RivelHeroControl.HeroIsStop = true;//玩家停止
        HeroHeroControl.SetCurrentSpeed(0);
        RivelHeroControl.SetCurrentSpeed(0);

        HeroHeroControl.javelinTag = false;
        RivelHeroControl.javelinTag = false;
        // if (num == 2) {
        Hero.getChildByName('Player').stopAllActions();
        // }
        Rivel.getChildByName('Player').stopAllActions();
        Hero.getChildByName('Player').setPositionY(-132);
        Rivel.getChildByName('Player').setPositionY(-37);

        // var GameMode = cc.find('Canvas').getComponent('GameMode');
        this.GetGameMode.isEndGame = true;
        var data = { FunctionName: 'endGame', num: num, showText: isShowText ? isShowText : null };
        this.GetGameMode.SynchronizationFun(data);

        var GameState = cc.find('Canvas').getComponent('GameStates');
        GameState.bHasEndGame = true;


    },
    //游戏最终结束
    endGameAll: function (num) {
        var Hero = this.GameStates.getHero;// cc.find('Hero');
        var Rivel = this.GameStates.getRivel;//cc.find('Rivel');
        var HeroHeroControl = this.GameStates.getHeroControl;// Hero.getComponent('HeroControl');
        var RivelHeroControl = this.GameStates.getRivelControl;// Rivel.getComponent('HeroControl');

        if (cc.find('Canvas').getComponent('GameStates').strCureentLevel != "RideBike") {

            // if (num == 2) {
            HeroHeroControl.SetSpeedToZeroAndIdle();
            // }
            RivelHeroControl.SetSpeedToZeroAndIdle();
        }
        HeroHeroControl.HeroIsStop = true;//玩家停止
        RivelHeroControl.HeroIsStop = true;//玩家停止
        HeroHeroControl.SetCurrentSpeed(0);
        RivelHeroControl.SetCurrentSpeed(0);
        HeroHeroControl.javelinTag = false;
        RivelHeroControl.javelinTag = false;
        // if (num == 2) {
        Hero.getChildByName('Player').stopAllActions();
        // }
        Rivel.getChildByName('Player').stopAllActions();
        Hero.getChildByName('Player').setPositionY(-132);
        Rivel.getChildByName('Player').setPositionY(-37);

        this.GetGameMode.isEndGame = true;

    },





    startNetGame: function () {

        if (this.GameStates.bReadyToRun) {
            this.StartToRun();
        }
        else {
            this.GameStates.bReadyToRun = !this.GameStates.bReadyToRun;
        }

        var NetworkSocket = this.GameStates.getHero.getComponent('NetworkSocket');
        var data = { FunctionName: 'ReadyToRun' };

        NetworkSocket.sendSyncData(JSON.stringify(data));
        this._GameUI.hideTimerTipOfNormalAcceleration(8);//普通加速带点击提示

        this.isReadyGo = true;
    },

    StartToRun: function () {

        this.GameStates.getHero.getChildByName("Player").getComponent("Charactor").setOnTouchListener(event);
        this.GameStates.getRivel.getChildByName("Player").getComponent("Charactor").setOnTouchListener(event);

        this.GameStates.getHeroControl.EnableHeroMoving(true);
        this.GameStates.getRivelControl.EnableHeroMoving(true);

        this.schedule(function () {
            this.GameStates.getHeroControl.InitialPositionY = this.GameStates.getHeroControl.node.getPositionY();
            this.GameStates.getRivelControl.InitialPositionY = this.GameStates.getRivelControl.node.getPositionY();

        }, 0.01, 0);

        this.isRuning = true;


        let index = 0;
        cc.game.on(cc.game.EVENT_HIDE, event => {
            if (this.isRuning && !this.isReported) {
                if (1 === ++index) {
                    this.endGame(2, '对手网络不稳定');
                    var data = {
                        isSelf: 1
                    }
                    this.quitGame(data);

                }

            }
        });
    },

    readGoAudio: function (url, callBack) {
        cc.loader.loadRes(url, cc.AudioClip, function (err, clip) {
            var audioID = cc.audioEngine.play(clip, false, 1);
            if (callBack != null) {
                cc.audioEngine.setFinishCallback(audioID, callBack);
            }

        });
    },
    //设置游戏结束相应的提示
    setToast(showText) {
        this.TipToast.active = true;
        this.TipText.string = showText;
        setTimeout(function () {
            this.TipToast.active = false;
            this.TipText.string = '';
        }.bind(this), 1000)
    }
});
