var GameStates = require('GameStates');
// 游戏主逻辑，规则 时间计算 胜负条件
cc.Class({
    extends: cc.Component,

    properties: {
        Player:cc.Node,
        Champin:cc.Node,
        playerLife:cc.Node,
        toolPanel:cc.Node,
        gameoverPanel:cc.Node,
        gameResetPanel:cc.Node,
        speedAnimation:cc.Node,
        pauseBtn:cc.Node,
        runBtn:cc.Node,
        Toast:cc.Node,
        targetLabel:cc.Label,
        levelLabel:cc.Label,
        scoreLabel:cc.Label,
        timeLabel:cc.Label,

        playerAnimation:cc.Node,
        holeInAnimation:cc.Node,
        gameWinAnimation:cc.Node,
        toolPrefab:[cc.Prefab],
        boomPrefab:cc.Prefab,
        //音效
        sound:{        
            default:[],
            type: cc.AudioClip
        },
        bgsound:{
            default:[],
            type: cc.AudioClip
        },
    },

    // LIFE-CYCLE CALLBACKS

    start () {
        this.isAndroid = false;
        this.isiOS = false;
        console.log('平台信息=',navigator.userAgent);
        this.isAndroid = Boolean(navigator.userAgent.match(/android/ig));
        this.isIphone = Boolean(navigator.userAgent.match(/iphone|ipod/ig));
        this.isIpad = Boolean(navigator.userAgent.match(/ipad/ig));

        if(this.isIphone || this.isIpad)
        {
            this.isiOS = true;
        }
        
        if(this.isAndroid)
        {
            console.log('当前平台是：android')
        }
        else if(this.isiOS)
        {
            console.log('当前平台是：ios')
        }
        else
        {
            console.log('当前平台未检测到')
        }
        //开启碰撞检测
        cc.director.getCollisionManager().enabled = true;
        //初始化
        this.positionArr = [-250,-150,-50,50,150,250]
        this.playerPosition = 2
        this.dropTime = 2000-GameStates.levelNum*100 //下落时间间隔
        this.movetime = 0.1//左右移动速度
        this.targetNum = GameStates.levelNum*10
        this.speedRate = 1
        this.iceSpeedRate = 1
        this.myturnsNum = 0
        //条件
        this.missTool1 = 0
        this.missTool2 = 0
        this.missTool3 = 0
        this.getTool1 = 0
        this.getTool2Rule2 = 0
        this.getTool2Rule4 = 0
        this.getTool3 = 0
        this.getTool4 = 0
        //开始
        this.levelLabel.node.runAction(cc.scaleTo(1.5,0.5))
        setTimeout(function(){
            this.levelLabel.node.opacity = 140
        }.bind(this),1500)
        this.dropTimer = setInterval(function(){
            if(!this.ispause)
            this.dropFunc()
        }.bind(this),this.dropTime+Math.random()*1000-500)
        this.gameTimer = setInterval(function(){
            this.showTime()
        }.bind(this),1000)
        this.showScore()
        this.showTime()
        this.showLife()
        this.showTarget()
        this.levelLabel.string = 'Lv '+GameStates.levelNum
        this.onTurnsNumber(true)
        this.slowBgsound = cc.audioEngine.play(this.bgsound[0],true)
        cc.audioEngine.play(this.sound[5],false)
        //监听进入后台
        cc.game.on(cc.game.EVENT_HIDE,event=>{
            // console.log("------------>后台了");
            this.ispause = 1
        },this);
        cc.game.on(cc.game.EVENT_SHOW,event=>{
            // console.log("------------>前台了");
            this.ispause = 0
        },this);
    },
    dropFunc(){
        if(this.ispause)
        return
        var positionNumArr = [1,2,3,4,5]
        if(Math.random()>0.9){
            var maxNum = Math.floor(Math.random()*2)+3
        }
        else{
            var maxNum = 1
        }
        for(var i=0;i<maxNum;i++){
            var ranNum = Math.random()
            var toolIndex = 0
            if(ranNum<0.3){
                toolIndex = 0
            }
            else if(ranNum<0.5){
                toolIndex = 1
            }
            else if(ranNum<0.6){
                toolIndex = 2
            }
            else{
                toolIndex = 3
            }
            if(maxNum>1)
            toolIndex = 3
            else{
                var getRule = this.getRule()
                if(getRule>0 && !this.isUsingTool){
                    toolIndex = getRule
                    if(getRule==4)
                    this.getTool1 = 0
                    if(getRule==5)
                    this.getTool3 = 0
                    if(getRule==7)
                    this.getTool2Rule2 = 0
                    if(getRule==6)
                    this.getTool2Rule4 = 0
                }
            }
            var toolPrefab = cc.instantiate(this.toolPrefab[toolIndex])
            toolPrefab.index = toolIndex
            toolPrefab.y = 1000
            var num = Math.floor(Math.random()*positionNumArr.length)
            toolPrefab.x = this.positionArr[positionNumArr[num]]
            positionNumArr.splice(num,1)
            toolPrefab.parent = this.toolPanel
            toolPrefab.addComponent('ToolConfig')
        }  
        if(maxNum>1){
            var toolIndex = Math.floor(Math.random()*3)
            var toolPrefab = cc.instantiate(this.toolPrefab[toolIndex])
            toolPrefab.index = toolIndex
            toolPrefab.y = 1000
            var num = Math.floor(Math.random()*positionNumArr.length)
            toolPrefab.x = this.positionArr[positionNumArr[num]]
            positionNumArr.splice(num,1)
            toolPrefab.parent = this.toolPanel
            toolPrefab.addComponent('ToolConfig')
        }   
    },
    onTurnsNumber(f){
        window.bTurnsNumber = f;
        console.log('bShowTurnsNumberLog=',window.bTurnsNumber);
    },
    showToast(str){
        this.Toast.getChildByName('label').getComponent(cc.Label).string = str
        this.Toast.stopAllActions()
        this.Toast.opacity = 0
        this.Toast.position = cc.v2(0,0)
        this.Toast.runAction(cc.sequence(cc.fadeIn(0),cc.moveBy(2,0,200),cc.fadeOut(0)))
    },
    getRule(){  //查找出现道具条件
        //没有奖励A类到最底下方没取 + 没碰撞炸弹下连续取到 10个奖励A类   时钟 4
        //没有奖励B类到最底下方没取 + 没碰撞炸弹下连续取到 5个奖励B类  炸弹 7
        //没有奖励B到最底下方没取 + 没碰撞炸弹 + 获取3个UFO   彩虹鱼 5
        //没有奖励C类到最底下方没取，连续取到 5个奖励B类   牛奶 6
        if(this.missTool1==0 && this.getTool1>=10 && this.getTool4==0){
            return 4
        }
        if(this.missTool2==0 && this.getTool2Rule2>=5 && this.getTool4==0){
            return 7
        }
        if(this.getTool4==0 && this.missTool2==0 && this.getTool3>=3){
            return 5
        }
        if(this.missTool3==0 && this.getTool2Rule4>=5){
            return 6
        }
        return 0 
    },
    showTarget(){
        this.targetLabel.string = this.targetNum
    },
    showTime(){
        var newDate = new Date()
        var timeNum = Math.floor((newDate.getTime()-GameStates.gameTime.getTime())/1000)
        var mm = Math.floor(timeNum/60)
        if (mm<10)
        mm = '0'+mm
        var ss = timeNum - mm*60
        if (ss<10)
        ss = '0'+ss
        this.timeLabel.string = mm+':'+ss
    },
    showScore(){
        this.scoreLabel.string = GameStates.gameScore
    },
    showLife(){
        for(var i=0;i<3;i++){
            if(i<GameStates.lifeNum)
            this.playerLife.children[i].active = true
            else
            this.playerLife.children[i].active = false
        }  
    },
    addTarget(){
        if(this.isUsingDefence){
            cc.audioEngine.play(this.sound[6],false)
        }
        else{
            cc.audioEngine.play(this.sound[7],false)
        }
        this.targetNum--
        this.showTarget()
        if(this.targetNum==0){
            this.ispause = 1
            this.toolPanel.removeAllChildren()
            this.gameWinAnimation.active = true
            setTimeout(function(){
                this.gameWinAnimation.active = false
                if(GameStates.levelNum==10)
                this.gameOver(1)
                else
                this.gameWin()
            }.bind(this),1000)
        }
    },
    addScore(n){
        GameStates.gameScore+=n
        this.showScore()
    },
    loseLife(){
        cc.audioEngine.play(this.sound[2],false)
        if(this.delaytime)  //连续碰撞 短时间内无敌 只扣一次生命
        return
        this.delaytime = 1
        setTimeout(function(){
            this.delaytime = 0
        }.bind(this),500)
        GameStates.lifeNum--
        if(GameStates.lifeNum<=0){
            GameStates.lifeNum=0
            cc.audioEngine.play(this.sound[1],false)
            this.ispause = 1
            this.gameOver(null,'0')
        }
        this.showLife()
    },
    addLife(){
        cc.audioEngine.play(this.sound[3],false)
        GameStates.lifeNum++
        if(GameStates.lifeNum>3)
        GameStates.lifeNum = 3
        this.showLife()
    },
    showDefence(){
        cc.audioEngine.play(this.sound[4],false)
        this.isUsingTool = 1
        this.speedRate = 0.8
        this.isUsingDefence = 1
        this.speedAnimation.active = true
        this.Player.getChildByName('playerDefence').active = true
        this.movetime = 0.05
        cc.audioEngine.stop(this.slowBgsound)
        this.fastBgsound = cc.audioEngine.play(this.bgsound[1],true)
        clearInterval(this.dropTimer)
        this.dropTimer = setInterval(function(){
            this.dropFunc()
        }.bind(this),this.dropTime+Math.random()*1000-1300)
        setTimeout(function(){
            this.isUsingDefence = 0
            this.isUsingTool = 0
            this.speedRate = 1
            this.speedAnimation.active = false
            this.Player.getChildByName('playerDefence').active = false
            this.movetime = 0.1
            cc.audioEngine.stop(this.fastBgsound)
            this.slowBgsound = cc.audioEngine.play(this.bgsound[0],true)
            this.droptime+=500
            clearInterval(this.dropTimer)
            this.dropTimer = setInterval(function(){
                this.dropFunc()
            }.bind(this),this.dropTime+Math.random()*1000-500)
        }.bind(this),15000)
    },
    useIce(){
        cc.audioEngine.play(this.sound[4],false)
        this.isUsingTool = 1
        this.iceSpeedRate = 3
        setTimeout(function(){
            this.isUsingTool = 0
            this.iceSpeedRate = 1

        }.bind(this),8000)
    },
    useBoom(){
        cc.audioEngine.play(this.sound[4],false)
        for(var i=0;i<this.toolPanel.children.length;i++){
            var tool_Stone = this.toolPanel.children[i]
            if(tool_Stone.name == 'tool_Stone'){
                var boom = cc.instantiate(this.boomPrefab)
                boom.parent = tool_Stone
                tool_Stone.getComponent('ToolConfig').runDestroy()
            }
        }
    },
    gameOver(event,n){
        this.speedRate = 1
        this.speedAnimation.active = false
        clearInterval(this.dropTimer)
        clearInterval(this.gameTimer)
        for(var i=0;i<this.toolPanel.children.length;i++){
            this.toolPanel.children[i].destroy()
        }
        this.ispause = 1
        clearInterval(this.resetTimer)
        if(n=='0'){
            var newDate = new Date()
            this.durationTime = Math.floor((newDate-GameStates.gameTime)/1000)
            this.gameResetPanel.active = true
            this.gameResetPanel.getChildByName('scoreLabel').getComponent(cc.Label).string = GameStates.gameScore
            this.gameResetPanel.getChildByName('levelLabel').getComponent(cc.Label).string = 'Lv '+GameStates.levelNum
            this.gameResetPanel.getChildByName('timeLabel').getComponent(cc.Label).string = this.timeLabel.string
            this.gameResetPanel.getChildByName('kcalLabel').getComponent(cc.Label).string = Math.floor((window.calorie-GameStates.carlNum)/1000)
            this.gameResetPanel.getChildByName('circle').getComponent(cc.Sprite).fillRange = 1
            cc.log(this.gameResetPanel.getChildByName('circle').getComponent(cc.Sprite).fillRange)
            this.resetTime = 15
            this.gameResetPanel.getChildByName('overTime').getComponent(cc.Label).string = this.resetTime
            this.resetTimer = setInterval(function(){
                this.resetTime--
                this.gameResetPanel.getChildByName('overTime').getComponent(cc.Label).string = this.resetTime
                this.gameResetPanel.getChildByName('circle').getComponent(cc.Sprite).fillRange = this.resetTime/15
                if(this.resetTime<=0){
                    clearInterval(this.resetTimer)
                    this.gameOver(null,'1')
                }
            }.bind(this),1000)
        }
        else{
            this.onTurnsNumber(false)
            this.gameoverPanel.active = true
            this.gameResetPanel.active = false
            this.gameoverPanel.getChildByName('scoreLabel').getComponent(cc.Label).string = GameStates.gameScore
            this.gameoverPanel.getChildByName('levelLabel').getComponent(cc.Label).string = 'Lv '+GameStates.levelNum
            this.gameoverPanel.getChildByName('timeLabel').getComponent(cc.Label).string = this.timeLabel.string
            this.gameoverPanel.getChildByName('kcalLabel').getComponent(cc.Label).string = Math.floor((window.calorie-GameStates.carlNum)/1000)
            var self = this
            var gripName = this.isiOS ? 'IOS' : 'Android'
            var scoreJson = {
                startTime:parseInt(GameStates.gameTime.getTime()/1000),
                durationTime:self.durationTime,
                fromType:15,
                calories:window.calorie-GameStates.carlNum,
                gripName:gripName,
                ip:"ip",
                objectJson:{"courseId":1002,"circles":window.turnsNum-GameStates.turnsNum,"averspeed":((window.turnsNum-GameStates.turnsNum)/self.durationTime).toFixed(2),"score":GameStates.gameScore,"round":GameStates.levelNum},
            }
            var scoreStr = JSON.stringify(scoreJson)
            console.log(scoreStr)
            if(this.isAndroid)
            {
                console.log('submitGameScore:',scoreStr)
                window.eventJsBridge.submitGameScore(scoreStr);
            }
            else if(this.isiOS)
            {
                console.log('submitGameScore:',scoreStr)
                window.webkit.messageHandlers.submitGameScore.postMessage(scoreStr);
            }
            
            if(!((this.isAndroid && window.eventJsBridge.maxScore) || (this.isiOS && window.webkit.messageHandlers.maxScore))){
                this.Champin.active = false
            }
            else{
                if(this.isAndroid)
                {
                    console.log('isSendData')
                    window.eventJsBridge.maxScore()
                }
                else if(this.isiOS)
                {
                    console.log('isSendData')
                    window.webkit.messageHandlers.maxScore.postMessage(null);
                }
                window.maxScore = function(maxScore){
                    console.log('maxScore',maxScore)
                    if(self.isAndroid){
                        var mymaxScore = maxScore
                        self.gameoverPanel.getChildByName('MaxScore').getComponent(cc.Label).string = mymaxScore.maxScore
                    }
                    else if(self.isiOS){
                        var mymaxScore = JSON.parse(maxScore)
                        self.gameoverPanel.getChildByName('MaxScore').getComponent(cc.Label).string = mymaxScore.maxScore
                    }
                }
            }
            
        }
    },
    gameBack(){
        if(this.isAndroid)
        {
           window.eventJsBridge.goBack()
        }
        else if(this.isiOS)
        {
            window.webkit.messageHandlers.goBack.postMessage(null)
        }
    },
    gameWin(){
        GameStates.levelNum++
        cc.director.loadScene('GameScene')
    },
    gameReset(){
        this.ispause = 0
        cc.audioEngine.play(this.sound[0],false)
        var self = this
        if(this.isAndroid)
        {
           console.log('aliveGame')
           window.eventJsBridge.aliveGame()
        }
        else if(this.isiOS)
        {
            console.log('aliveGame')
            window.webkit.messageHandlers.aliveGame.postMessage(null);
        }
        window.aliveGameResponse= function(response){
            console.log('aliveGameResponse:',response)
            GameStates.lifeNum = 3
            cc.director.loadScene('GameScene')
        }
        var self = this
        window.aliveGameOnError= function(response){
            if(self.isAndroid)
            window.aliveCode = response.errCode
            else if(self.isiOS)
            window.aliveCode = JSON.parse(response).errCode
            console.log('aliveGameOnError:',response)
            if(window.aliveCode == 5031){
                self.showToast('余额不足，请至“我的钱包”充值')
            }
            else{
                GameStates.lifeNum = 3
                cc.director.loadScene('GameScene')
            }
        }
    },
    gameHome(event,n){
        cc.audioEngine.play(this.sound[0],false)
        if(n=='0'){
            cc.sys.localStorage.setItem('showRank',1)
        }
        else{
            cc.sys.localStorage.setItem('showRank',0)
        }
        cc.director.loadScene('BeginScene')
    },
    gameBegin(){
        //接口
        cc.audioEngine.play(this.sound[0],false)
        GameStates.levelNum = 1
        GameStates.lifeNum = 3
        GameStates.carlNum = window.calorie
        GameStates.turnsNum = window.turnsNum
        var date = new Date()
        GameStates.gameTime = date
        GameStates.gameScore = 0
        cc.director.loadScene('GameScene')
    },
    gamePause(){
        cc.audioEngine.play(this.sound[0],false)
        if(!this.ispause){
            this.ispause = 1
            this.runBtn.active = true
            this.pauseBtn.active = false
            for(var i=0;i<this.toolPanel.children.length;i++){
                this.toolPanel.children[i].pauseAllActions()
            }
        }
        else{
            this.ispause = 0
            this.runBtn.active = false
            this.pauseBtn.active = true
            for(var i=0;i<this.toolPanel.children.length;i++){
                this.toolPanel.children[i].resumeAllActions()
            }
        }
    },
    moveLeft(){
        if(this.cannotMove || this.ispause)
        return
        this.cannotMove = 1
        this.playerPosition--
        if(this.playerPosition<0){
            this.playerPosition = 5
            this.Player.runAction(cc.sequence(cc.moveBy(this.movetime,0,0),cc.moveBy(0,600,0),cc.moveBy(this.movetime,-100,0)))
            this.Player.runAction(cc.sequence(cc.scaleTo(this.movetime,0),cc.scaleTo(this.movetime,1)))
            this.Player.runAction(cc.sequence(cc.rotateBy(this.movetime,-30),cc.rotateBy(this.movetime,30)))
            this.holeInAnimation.getComponent(dragonBones.ArmatureDisplay).playAnimation('03',1)
            setTimeout(function(){
                this.holeInAnimation.getComponent(dragonBones.ArmatureDisplay).playAnimation('02',0)
            }.bind(this),this.movetime*2000)
            cc.audioEngine.play(this.sound[9],false)
            
        }
        else{
            this.Player.runAction(cc.moveBy(0.2,-100,0))
            this.Player.runAction(cc.sequence(cc.rotateBy(this.movetime,-30),cc.rotateBy(this.movetime,30)))
        }
        setTimeout(function(){
            this.cannotMove = 0
        }.bind(this),this.movetime*2000)
    },
    moveRight(){
        if(this.cannotMove || this.ispause)
        return
        this.cannotMove = 1
        this.playerPosition++
        if(this.playerPosition>5){
            this.playerPosition = 0
            this.Player.runAction(cc.sequence(cc.moveBy(this.movetime,100,0),cc.moveBy(0,-700,0),cc.moveBy(this.movetime,100,0)))
            this.Player.runAction(cc.sequence(cc.scaleTo(this.movetime,0),cc.scaleTo(this.movetime,1)))
            this.Player.runAction(cc.sequence(cc.rotateBy(this.movetime,30),cc.rotateBy(this.movetime,-30)))
            this.holeInAnimation.getComponent(dragonBones.ArmatureDisplay).playAnimation('03',1)
            setTimeout(function(){
                this.holeInAnimation.getComponent(dragonBones.ArmatureDisplay).playAnimation('02',0)
            }.bind(this),this.movetime*2000)
            cc.audioEngine.play(this.sound[9],false)
        }
        else{
            this.Player.runAction(cc.moveBy(0.2,100,0))
            this.Player.runAction(cc.sequence(cc.rotateBy(this.movetime,30),cc.rotateBy(this.movetime,-30)))
        }
        setTimeout(function(){
            this.cannotMove = 0
        }.bind(this),this.movetime*2000)
    },
    update(){        
        //转圈
        if(window.turnsNum>this.myturnsNum){
            this.myturnsNum = window.turnsNum
            if(window.direction==1){
                console.log('moveleft')
                this.moveLeft()
            }
            else{
                console.log('moveright')
                this.moveRight()
            }
        }
    },
    onDestroy(){
        cc.audioEngine.stopAllEffects()
        clearInterval(this.dropTimer)
        clearInterval(this.gameTimer)
        clearInterval(this.resetTimer)
    },
});
