const GameStatesStatic = require('GameStates');
cc.Class({
    extends: cc.Component,

    properties: {
        MyArrivedTime: [],
        RivalArrivedTime: [],
        fadeInAndOutTag: false,
        bHasAddScore: false,
        bHasOverPosition: false,
        isEndGame: false,//游戏是否已经结束


        isSeverJaveDis: 0,//服务器在这里记录标枪的数据，判断输赢
        isClientJaveDis: 0,


        _severValue: 0,//服务器的数据，判断输赢
        _clientValue: 0,
        _inputIndex: 0,//传入的数据次数

        isUploaded: false,

        finishDeltavalue: 50,//其他项目 平局delta差值
        bikeDeltaValue: 50,//骑车项目 平局delta差值

    },

    SyncJaveEndAddScore: function () {
        //服务器统一计算，谁的值大，给谁加分
        if (this.isSeverJaveDis - this.isClientJaveDis >= 0) {
            var Hero = cc.find('Hero');
            this.addScore(Hero, this.isSeverJaveDis, true);
        } else {
            var Rivel = cc.find('Rivel');
            this.addScore(Rivel, this.isClientJaveDis, true);
            var data = { FunctionName: 'addScore', PlayerName: 'Rival', value: this.isClientJaveDis };
            this.SynchronizationFun(data);
        }
    },
    SynchronizationFun: function (data) {
        var str = JSON.stringify(data);
        // cc.log("让我们不动33333",str);
        if (str.trim().length <= 0) {
            return
        }
        // cc.log("让我们不动4444",str);
        qqNetwork.send(qqNetwork.game2Room.gameData, JSON.stringify({ str: str }));
    },
    CheckPlayersDistance: function (bFromServer) {

        var GameStates = cc.find('Canvas').getComponent('GameStates');
        // cc.log('我是gamemode里面的check'+GameStates.EnterStartLinePlayersArray.length);

        if (GameStates.EnterStartLinePlayersArray.length > 1) return;
        // cc.log('GameStates.EnterStartLinePlayersArray.length=',GameStates.EnterStartLinePlayersArray.length)
        // var Hero = cc.find('Hero');
        // var Rivel = cc.find('Rivel');
        // cc.log("Hero.x - Rivel.x ====第1次打印====="+(Hero.position.x - Rivel.position.x));
        this.OverPosition();


    },
    OverPosition: function () {
        if (this.bHasOverPosition) {
            return;
        }
        this.bHasOverPosition = true;
        var GameMode = cc.find('Canvas').getComponent('GameMode');
        var GameStates = cc.find('Canvas').getComponent('GameStates');
        var Hero = cc.find('Hero');
        var Rivel = cc.find('Rivel');
        var HeroControl = Hero.getComponent('HeroControl');
        var RivelControl = Rivel.getComponent('HeroControl');
        var PlayerStateScript = Hero.getComponent("PlayerState");

        PlayerStateScript.TouchControlEnableTouch = false;

        // var data = {FunctionName: 'FadeInAndOut'};
        // GameMode.SynchronizationFun(data);
        // cc.log("FadeInAndOut!!!!!!!!!!!!atOverPositionInGameMode");
        this.schedule(function () {
            // cc.log("我是来自GameMode的OverPosition里面的schedule11111");
            GameStates.EnterStartLinePlayersArray = [];
        }.bind(this), 5, 0);
        // this.scheduleOnce(function () {
        //     // cc.log("我是来自GameMode的OverPosition里面的schedule22222");
        // }, 5);

        // cc.log('========='+cc.find("Shade").getComponent('Shade').FadeTag);
        // cc.log('我是对应的moves to'+GameStates.StartLinePositionX);
        cc.find("Shade").getComponent('Shade').FadeInAndOut(function () {
            var CurrentLevel = GameStates.strCureentLevel;
            if ('LongJump' == CurrentLevel || 'Javelin' == CurrentLevel) {
                HeroControl.resetHero();
                RivelControl.resetHero();
                var data = { FunctionName: 'resetHero' };
                this.SynchronizationFun(data);
            }
            cc.find('Canvas').getComponent('GameMode').bHasOverPosition = false;
            // cc.log(GameStates.strCureentLevel+"==========comeIn=======GameMode");
            // cc.log("拉人过去了 大于3000",cc.find('Canvas').getComponent('GameStates').StartLinePositionX);
            Hero.setPositionX(GameStates.StartLinePositionX - 30);
            // cc.log('hero moves to '+GameStates.StartLinePositionX+' and Rivel move to '+GameStates.StartLinePositionX);
            Rivel.setPositionX(GameStates.StartLinePositionX);

            // cc.log(cc.find('Hero').position.x+'========moves to========='+cc.find('Rivel').position.x);

            HeroControl.StopPlayerAllSchedule();
            // RivelControl.StopPlayerAllSchedule();
            var data = { FunctionName: 'StopPlayerAllSchedule' };
            this.SynchronizationFun(data);
            // cc.log("我向对方发送请求StopPlayerAllSchedule");
            // cc.log(GameStates.bServer+'是不是服务器');

            if (GameStates.bServer) {
                // cc.log("i am server and 第1次打印");

                this.schedule(function () {
                    // cc.log("i am server and i 第2次打印");
                    this.PlayersStartToRun();
                }.bind(this), 2, 0);

                // this.scheduleOnce(function () {
                //     // cc.log('i am server and 第3次打印')
                // }, 2);

            }
            // });
        }.bind(this, GameMode, Rivel, HeroControl, RivelControl, GameMode, GameStates));
    },
    Transport: function () {
        // cc.log('GameMode Transport');
        this.unschedule(this.UnScheduleFadeIn);
        var Hero = cc.find('Hero');
        var Rivel = cc.find('Rivel');
        var HeroControl = Hero.getComponent('HeroControl');
        var RivelControl = Rivel.getComponent('HeroControl');

        this.fadeInAndOutTag = false;
        var PlayerState = cc.find("Hero").getComponent("PlayerState");
        PlayerState.TouchControlEnableTouch = false;
        cc.find("Shade").getComponent('Shade').FadeInAndOut(function () {
            this.fadeInAndOutTag = true;
            
            Hero.setPositionX(cc.find('Canvas').getComponent('GameStates').StartLinePositionX - 30);
            Rivel.setPositionX(cc.find('Canvas').getComponent('GameStates').StartLinePositionX);
            HeroControl.node.stopAllActions();
            RivelControl.node.stopAllActions();
 
        }.
            bind(this), function () {
                this.schedule(function () {
                    cc.find('Canvas').getComponent('GameStates').EnterStartLinePlayersArray = [];

                }.bind(this), 5, 0);

                this.schedule(function () {
                    cc.find('Canvas').getComponent('GameStates').CurrentProgress = GameStatesStatic.GameProgress.LongJump;
                    HeroControl.javelinTag = false;
                    RivelControl.javelinTag = false;

                    HeroControl.CameraNode.parent = Hero;

                    if (cc.find('Canvas').getComponent('GameStates').bServer) {
                        this.schedule(function () {
                            this.PlayersStartToRun();
                        }.bind(this), 1, 0);
                    }
                }.bind(this), cc.find('Canvas').getComponent('GameStates').ReadyToRunDuration, 0);

            }.bind(this));
    },
    UnScheduleFadeIn: function () {
        var GameStates = cc.find('Canvas').getComponent('GameStates');
        var EnterStartLinePlayersArray = GameStates.EnterStartLinePlayersArray;

        if (EnterStartLinePlayersArray.length == 2) {
            // cc.log('GameMode Unschedule');
            this.unschedule(this.UnScheduleFadeIn);
            this.unschedule(this.Transport);

            var Hero = cc.find('Hero');
            var Rivel = cc.find('Rivel');
            var HeroControl = Hero.getComponent('HeroControl');
            var RivelControl = Rivel.getComponent('HeroControl');

            HeroControl.javelinTag = false;
            RivelControl.javelinTag = false;

            HeroControl.CameraNode.parent = Hero;
            // HeroControl.StopPlayerAllSchedule();
            // RivelControl.StopPlayerAllSchedule();
            // var data = {FunctionName: 'StopPlayerAllSchedule'};
            // this.SynchronizationFun(data);
            // cc.log("我向对方发送请求StopPlayerAllSchedule");

            Hero.setPositionX(GameStates.StartLinePositionX - 30);
            Rivel.setPositionX(GameStates.StartLinePositionX);

            this.schedule(function () {
                GameStates.EnterStartLinePlayersArray = [];
            }.bind(this), 5, 0);

            if (GameStates.bServer) {
                this.schedule(function () {
                    this.PlayersStartToRun();
                }.bind(this), 2, 0);
            }
            var data = { FunctionName: 'UnScheduleFadeIn' };
            this.SynchronizationFun(data);
        }
    },
    PlayersStartToRun: function () {
        if (this.isEndGame) {
            // console.log("PlayersStartToRun 游戏已经结束！");
            return;
        }
        // console.log("PlayersStartToRun.......From.......GameMode...");

        // cc.log("起跑");
        var Hero = cc.find('Hero');
        var Rivel = cc.find('Rivel');
        Hero.getComponent('HeroControl').playAudioByName('StartGun');//项目开始时哨声
        //项目开始时，UI比分淡出
        if (cc.find('UIPKScore')) {
            cc.find('UIControl').getComponent('GameUI').hideMiddlePKScore();
        }
        var PlayerStateScript = Hero.getComponent("PlayerState");
        PlayerStateScript.TouchControlEnableTouch = false;

        var HeroControl = Hero.getComponent('HeroControl');
        var RivelControl = Rivel.getComponent('HeroControl');
        HeroControl.HeroIsStop = false;
        RivelControl.HeroIsStop = false;
        // console.log(11);
        HeroControl.ResetSpeed_noType();
        RivelControl.ResetSpeed_noType();
        // cc.log("被拉过来的起点位置 开始跑",cc.find('Canvas').getComponent('GameStates').StartLinePositionX);
        var data = { FunctionName: 'PlayersStartToRun' };
        this.SynchronizationFun(data);
    },
    SyncPositionXRange: function (PlayerNode, CurrentPositionX) {
        return;
        if (Math.abs(CurrentPositionX - PlayerNode.position.x - 40) > cc.find('Canvas').getComponent('GameStates').bSyncPositionXRange) {
            PlayerNode.setPositionX(CurrentPositionX + 40);
        }
    },
    //slam todo

    //平局加分
    drawAddScrore(CurrentPlayerNode) {
        //判断两个人的分数 完美解决
        var Hero = cc.find('Hero');
        var Rivel = cc.find('Rivel');
        var PlayerStateHero = Hero.getComponent("PlayerState");
        var PlayerStateRivel = Rivel.getComponent("PlayerState");
        var GameStates = cc.find('Canvas').getComponent('GameStates');
        var CurrentLevel = GameStates.strCureentLevel;

        // var PlayerState = CurrentPlayerNode.getComponent("PlayerState");
        var UIControl = cc.find("UIControl").getComponent("UIControl");

        Hero.getComponent('HeroControl').playAudioByName("Cheers");
        PlayerStateHero.TerminalPoint += 1;
        PlayerStateRivel.TerminalPoint += 1;

        UIControl.GameUI.setTopMyScore(PlayerStateHero.TerminalPoint);
        UIControl.GameUI.setTopRivalScore(PlayerStateRivel.TerminalPoint);

        if (CurrentPlayerNode.name == 'Hero' && 'RideBike' == CurrentLevel) {
            Hero.getComponent('HeroControl').downBikeHero("Hero");
            var data = { FunctionName: 'downBikeHero', EndPositionX: Hero.x, isCollision: false, isStop: false };
            cc.find('Canvas').getComponent('GameMode').SynchronizationFun(data);
        }


        var Level = cc.find('Level');
        Level.getComponent('LevelControl').displayTimerMiddlePKScore(cc.find('Hero'));
        this.PlayWinAudio();
  
        //console.log('PlayerStateHero', PlayerStateHero.TerminalPoint, PlayerStateRivel.TerminalPoint);

        setTimeout(function () {
            if (('Javelin' == CurrentLevel) && (PlayerStateHero.TerminalPoint == PlayerStateRivel.TerminalPoint)) {
                //console.log('平局时候，CurrentLevel ==', CurrentLevel);
                Hero.getComponent('HeroControl').resets();
                var data = { FunctionName: 'resetHerojavelin' };
                cc.find('Canvas').getComponent('GameMode').SynchronizationFun(data);
            }
        }.bind(this), 1000);

        if (CurrentPlayerNode.name == 'Hero'&&'LongJump' == CurrentLevel) {
            Hero.getComponent('HeroControl').FromLongJumpToHurdle();
        }

    },

    oldAddScore(CurrentPlayerNode) {
       // console.log('当前是谁加分：', CurrentPlayerNode.name)
        if (this.bHasAddScore == false) {
            var PlayerState = CurrentPlayerNode.getComponent("PlayerState");
            var UIControl = cc.find("UIControl").getComponent("UIControl");
            if (CurrentPlayerNode.name == "Hero") {
                cc.find('Hero').getComponent('HeroControl').playAudioByName("Cheers");
                UIControl.GameUI.setTopMyScore(PlayerState.TerminalPoint += 1);
                this.PlayWinAudio();
            } else {
                UIControl.GameUI.setTopRivalScore(PlayerState.TerminalPoint += 1);
                this.PlayWinAudio();
            }
            this.scheduleOnce(function () {
                var Level = cc.find('Level');
                Level.getComponent('LevelControl').displayTimerMiddlePKScore(cc.find('Hero'));
            }, 0.1);
            this.bHasAddScore = true;

            // 判断两个人的分数 完美解决
            var Hero = cc.find('Hero');
            var Rivel = cc.find('Rivel');
            var PlayerStateHero = Hero.getComponent("PlayerState");
            var PlayerStateRivel = Rivel.getComponent("PlayerState");
            //从跳远项目跳转到跨栏项目
            var GameStates = cc.find('Canvas').getComponent('GameStates');
            var CurrentLevel = GameStates.strCureentLevel;
            // cc.log("两个分数",PlayerStateHero.TerminalPoint,PlayerStateRivel.TerminalPoint);
           // console.log('标枪重置CurrentLevel', CurrentLevel);
            if (('Javelin' == CurrentLevel)&& (PlayerStateHero.TerminalPoint == PlayerStateRivel.TerminalPoint)) {
                setTimeout(function () {
                    console.log('标枪重置');
                    cc.find('Hero').getComponent('HeroControl').resets();
                    var data = { FunctionName: 'resetHerojavelin' };
                    cc.find('Canvas').getComponent('GameMode').SynchronizationFun(data);
                }.bind(this), 1000);
            }

            if ('LongJump' == CurrentLevel) {
                cc.find('Hero').getComponent('HeroControl').FromLongJumpToHurdle();
            }

        }
    },

    addScore: function (CurrentPlayerNode, inputValue, isServer, deltaValue) {
        if (!deltaValue) {
            deltaValue = 0;
            // console.log('deltaValue 为空， 设为 =', deltaValue);
        }

        //记录谁传入的值
        if (isServer) {
            this._severValue = Number(inputValue);
        } else {
            this._clientValue = Number(inputValue);
        }


        var Hero = cc.find('Hero');
        var Rivel = cc.find('Rivel');
        let distance = Math.abs(Hero.position.x - Rivel.position.x);
        //console.log('CurrentPlayerNode.name', CurrentPlayerNode.name, 'inputValue==', inputValue, 'distance=', distance);
        //如果只传入一个值
        if (distance > 300) {//hero rivel相差 基础是40
            this.oldAddScore(CurrentPlayerNode);
            //console.log('CurrentPlayerNode ====', CurrentPlayerNode.name);
            if (CurrentPlayerNode.name == 'Hero') {
                var data = { FunctionName: 'callBackAddScore', value: 1 };
                this.SynchronizationFun(data);
            } else if (CurrentPlayerNode.name == 'Rivel') {
                var data = { FunctionName: 'callBackAddScore', value: -1 };
                this.SynchronizationFun(data);

            }
        } else {//如果加了两个
            if (this._inputIndex < 1) {
                this._inputIndex++;
            } else {
                this._inputIndex = 0;//重置为0
                //调用加分
                let judgementValue = this._severValue - this._clientValue;
                //console.log('severValue-clientValue = ', judgementValue);
                //如果值相差小于0.5（可变），平局
                if (judgementValue > deltaValue) {
                    //服务器胜利
                    var data = { FunctionName: 'callBackAddScore', value: 1 };
                    this.SynchronizationFun(data);
                    // console.log('服务器胜利');
                    this.oldAddScore(Hero);

                } else if (judgementValue < -deltaValue) {
                    //客户端的胜利
                    var data = { FunctionName: 'callBackAddScore', value: -1 };
                    this.SynchronizationFun(data);
                    // console.log('客户端的胜利');
                    this.oldAddScore(Rivel);
                } else if (judgementValue >= -deltaValue && judgementValue <= deltaValue) {
                    //平局
                    var data = { FunctionName: 'callBackAddScore', value: 0 };
                    this.SynchronizationFun(data);
                    // console.log('平局');
                    this.drawAddScrore(Hero);
                }
                //重置数据
                this._severValue = 0;
                this._clientValue = 0;
            }

        }
    },


    PlayWinAudio: function () {

        // this.scheduleOnce(function () {
        var NetworkSocket = cc.find('Hero').getComponent("NetworkSocket");
        var MyScore = cc.find('Hero').getComponent("PlayerState").TerminalPoint;
        var RivalScore = cc.find('Rivel').getComponent("PlayerState").TerminalPoint;
        //从跳远项目跳转到跨栏项目
        var GameStates = cc.find('Canvas').getComponent('GameStates');
        var CurrentLevel = GameStates.strCureentLevel;
        // console.log('判断胜利前的比分：', MyScore, RivalScore);
        if (MyScore >= 3 && MyScore > RivalScore) {
            cc.find('UIControl').getComponent('GameUI').playFireworks();
            var data = {
                isSelf: 2
            }
            NetworkSocket.endGame(1);
            NetworkSocket.quitGame(data);
        }
        else if (RivalScore >= 3 && MyScore < RivalScore) {
            cc.find('Hero').getComponent('HeroControl').playAudioByName("Boos");
            var data = {
                isSelf: 1
            }
            NetworkSocket.endGame(2);
            NetworkSocket.quitGame(data);
            var HeroPlayerState = cc.find('Hero').getComponent('PlayerState');
            HeroPlayerState.TouchControlEnableTouch = false;
            HeroPlayerState.enableTouch = false;
        }
        else if ('RideBike' == CurrentLevel && RivalScore == MyScore) {
           // console.log('上报平局数据。');
            var data = {
                isSelf: 0
            }
            NetworkSocket.endGame(0);
            NetworkSocket.quitGame(data);
            var HeroPlayerState = cc.find('Hero').getComponent('PlayerState');
            HeroPlayerState.TouchControlEnableTouch = false;
            HeroPlayerState.enableTouch = false;
        }

        // }, 0.1);
        // if (!this.inTag1) {
        //     this.inTag1 = true;
        // }
    },
    TestEndGame: function () {
        var NetworkSocket = cc.find('Hero').getComponent("NetworkSocket");
        NetworkSocket.endGame(1);
    }
});
