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

    properties: {
        Player:cc.Node,
        submitlabel:cc.Label,
        errorlabel:cc.Label,
        Bg:[cc.Node],
        BgFrame:[cc.SpriteFrame],
        Camera:cc.Node,
        LeftButton:cc.Node,
        RightButton:cc.Node,
        Toast:cc.Node,
        Camera:cc.Node,
        AnimationPanle:cc.Node,
        EnemyNumLabel:cc.Label,
        EnergyBlue:cc.Node,
        EnergyGreen:cc.Node,
        BlackMask:cc.Node,
        SettlePanel:cc.Node,
        toolPanel0:cc.Node,
        energyMax:cc.Node,
        toolLock:cc.Node,
        toolTime:cc.Node,
        LevelNum:cc.Label,
        EndLevelNum:cc.Node,
        EndTimeHH:cc.Label,
        EndTimeMM:cc.Label,
        EndTimeSS:cc.Label,
        ScoreNum:cc.Label,
        defenceAnimation:cc.Prefab, //防护动画
        PlayerBullet:[cc.Prefab],   //子弹
        Animation:[cc.Prefab],      //动画
        EnemyBullet:cc.Prefab,      //敌人子弹
        Enemy:[cc.Prefab],          //敌人
        Tool:[cc.Prefab],           //道具
        ImageFrame:[cc.SpriteFrame],
        Title0Frame:[cc.SpriteFrame],
        Title1Frame:[cc.SpriteFrame],
        Title2Frame:[cc.SpriteFrame],
        Title3Frame:[cc.SpriteFrame],
        LevelNumber:[cc.Prefab],    //通关数字
        Ice:cc.Prefab,              //冰子弹
        EnemyNode:cc.Node,
        //音效
        sound:{        
            default:[],
            type: cc.AudioClip
        },
        bgsound:{
            default:[],
            type: cc.AudioClip
        },

    },

    // LIFE-CYCLE CALLBACKS:

    onLoad () {
        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.isPause = 0
        //开火时间间隔
        this.fireTimeNum = 30
        this.fireTime = this.fireTimeNum
        this.Player.zIndex = 100
        this.EnemyNode.zIndex = 100
        this.toolPanel0.zIndex = 110
        this.SettlePanel.zIndex = 200
        this.Toast.zIndex = 210
        this.enemyArr = []
        this.frameArr = []
        this.PlayerBulletIndex = 0
        //初始化
        GameStates.lifeNum = 3
        this.myturnsNum = 0
        this.showEnemyNum = GameStates.enemyNum
        if(GameStates.levelNum==17){
            this.EnemyNumLabel.node.getChildByName('max').active = true
            this.EnemyNumLabel.string = ''
        }
        if(GameStates.levelNum==16)
        this.EnemyNumLabel.string = 99
        this.LevelNum.string = GameStates.levelNum
        cc.log(GameStates.levelNum)
        // if(GameStates.levelNum>9)
        // this.LevelNum.node.x = 10
        if(GameStates.levelNum>16){
            this.LevelNum.node.parent.getChildByName('LevelMax').active = true
            this.LevelNum.node.active = false
        }
        this.EnemyNode.runAction(cc.repeatForever(cc.sequence(cc.moveBy(1.5,-50,0),cc.moveBy(3,100,0),cc.moveBy(1.5,-50,0))))
        //关卡背景
        this.Bg[0].getComponent(cc.Sprite).spriteFrame = this.BgFrame[Math.floor((GameStates.levelNum-1)/3)%5*2]
        this.Bg[1].getComponent(cc.Sprite).spriteFrame = this.BgFrame[Math.floor((GameStates.levelNum-1)/3)%5*2+1]
        this.Bg[2].getComponent(cc.Sprite).spriteFrame = this.BgFrame[Math.floor((GameStates.levelNum-1)/3)%5*2]
        this.Bg[3].getComponent(cc.Sprite).spriteFrame = this.BgFrame[Math.floor((GameStates.levelNum-1)/3)%5*2+1]
        if(GameStates.levelNum==16){
            this.Bg[0].getComponent(cc.Sprite).spriteFrame = this.BgFrame[10]
            this.Bg[1].getComponent(cc.Sprite).spriteFrame = this.BgFrame[11]
            this.Bg[2].getComponent(cc.Sprite).spriteFrame = this.BgFrame[10]
            this.Bg[3].getComponent(cc.Sprite).spriteFrame = this.BgFrame[11]
            this.Bg[0].position = cc.v2(0,0)
            this.Bg[0].height = cc.winSize.height
        }
        else{
            this.Bg[0].y = -1280
            this.Bg[1].y = this.Bg[0].y+this.Bg[0].height
            this.Bg[2].y = this.Bg[1].y+this.Bg[1].height
            this.Bg[3].y = this.Bg[2].y+this.Bg[2].height
        }
        //关卡音乐
        if(GameStates.levelNum!=16)
        cc.audioEngine.play(this.bgsound[GameStates.levelNum%2],true)
        else
        cc.audioEngine.play(this.bgsound[2],true)
        //按钮闪烁
        this.LeftButton.runAction(cc.sequence(cc.fadeOut(0),cc.delayTime(0.3),cc.fadeIn(0),cc.delayTime(0.3),
        cc.fadeOut(0),cc.delayTime(0.3),cc.fadeIn(0),cc.delayTime(0.3),
        cc.fadeOut(0),cc.delayTime(0.3),cc.fadeIn(0),cc.delayTime(0.3),
        cc.fadeOut(0),cc.delayTime(0.3),cc.fadeIn(0),cc.delayTime(0.3),cc.fadeOut(0)))
        this.RightButton.runAction(cc.sequence(cc.fadeOut(0),cc.delayTime(0.3),cc.fadeIn(0),cc.delayTime(0.3),
        cc.fadeOut(0),cc.delayTime(0.3),cc.fadeIn(0),cc.delayTime(0.3),
        cc.fadeOut(0),cc.delayTime(0.3),cc.fadeIn(0),cc.delayTime(0.3),
        cc.fadeOut(0),cc.delayTime(0.3),cc.fadeIn(0),cc.delayTime(0.3),cc.fadeOut(0)))
        //
        this.startDate = new Date()
        var self = this
        if(this.isAndroid)
        {
           console.log('getRankingList1')
           window.eventJsBridge.getRankingList(1)
        }
        else if(this.isiOS)
        {
            console.log('getRankingList1')
            window.webkit.messageHandlers.getRankingList.postMessage(1);
        }
        var self = this
        window.rankingResponse= function(response){
            console.log('rankin:',response)
            if(self.isAndroid)
            window.ranking = response
            else if(self.isiOS)
            window.ranking = JSON.parse(response)
            var myRank = window.ranking.myRanking
            self.node.getChildByName('UI').getChildByName('UI_NameStr').getComponent(cc.Label).string = self.strlen(myRank.nickName)>4?myRank.nickName.substring(0,self.substrlen(myRank.nickName))+'...' : myRank.nickName
            cc.loader.load({url: myRank.portraits, type: 'png'}, function (err, frame) {  
                self.node.getChildByName('UI').getChildByName('mask').getChildByName('UI_Head').getComponent(cc.Sprite).spriteFrame =  new cc.SpriteFrame(frame)
            })
        }
    },
    start () {
        this.showEnemy()
        //第四关开始出现道具
        this.toolTimer = 25
        if(GameStates.levelNum>9)
        this.toolTimer = 20
        this.showtoolTimer = setTimeout(function(){
            if(GameStates.levelNum>3 && GameStates.levelNum!=16)
            this.showTool()
        }.bind(this),this.toolTimer*1000)
        
        this.onTurnsNumber(true)
        if(GameStates.levelNum==16)
        return
        this.showEnemyTimer = setInterval(function(){
            if(this.isPause || this.isTool0)
            return
            this.enemyMovedown()
            if(this.isPause)
            return
            this.showEnemy()
        }.bind(this),8000-GameStates.levelNum*130)
    },
    strlen(str){
        var len = 0;
        for (var i=0; i<str.length; i++) { 
         var c = str.charCodeAt(i); 
        //单字节加1 
         if ((c >= 0x0001 && c <= 0x007e) || (0xff60<=c && c<=0xff9f))    { 
           len++; 
         } 
         else { 
          len+=2; 
         } 
        } 
        return len;
    },
    substrlen(str){
        var len = 0;
        var num = 0
        for (var i=0; i<str.length; i++) { 
            var c = str.charCodeAt(i); 
            //单字节加1 
            if ((c >= 0x0001 && c <= 0x007e) || (0xff60<=c && c<=0xff9f))    { 
                len++; 
                num++
            } 
            else { 
                len+=2;
                num++ 
            } 
            if(len>8){
                return num-1
            }
        } 
    },

    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)))
    },
    // showFrame(){
    //     for(var i=0;i<8;i++){
    //         var frameLineArr = []
    //         for(var j=0;j<8;j++){
    //             var framePrefab = cc.instantiate(this.Frame)
    //             framePrefab.parent = this.EnemyNode
    //             framePrefab.y = 80*i-160
    //             framePrefab.x = 80*j-240
    //             frameLineArr.push(framePrefab)
    //         }
    //         this.frameArr.push(frameLineArr)
    //     }
    // },
    showEnemy(){
        if(GameStates.levelNum!=16){
            for(var i=0;i<7;i++){
                var length = this.enemyArr.length
                var indexNum = GameStates.levelNum+1
                if(indexNum>=16)
                indexNum = 16
                var enemyIndex = Math.floor(Math.random()*indexNum)
                if(i==6 && enemyIndex>11 )
                enemyIndex =  Math.floor(Math.random()*12)
                if(i==5 && enemyIndex>13)
                enemyIndex =  Math.floor(Math.random()*12)
                if(this.enemyArr[length-6] && (this.enemyArr[length-6].enemyIndex>11) && enemyIndex>11)
                enemyIndex =  Math.floor(Math.random()*12)
                if(this.enemyArr[length-13] && (this.enemyArr[length-13].enemyIndex>13) && enemyIndex>11)
                enemyIndex =  Math.floor(Math.random()*12)
                if(this.enemyArr[length-12] && (this.enemyArr[length-12].enemyIndex>13) && enemyIndex>11)
                enemyIndex =  Math.floor(Math.random()*12)
                if(this.enemyArr[length-5] && (this.enemyArr[length-5].enemyIndex>11) && enemyIndex>13)
                enemyIndex =  Math.floor(Math.random()*12)
                if(this.enemyArr[length-6] && (this.enemyArr[length-6].enemyIndex>11) && enemyIndex>13)
                enemyIndex =  Math.floor(Math.random()*12)
                if(this.enemyArr[length-13] && (this.enemyArr[length-13].enemyIndex>13) && enemyIndex>13)
                enemyIndex =  Math.floor(Math.random()*12)
                if(this.enemyArr[length-12] && (this.enemyArr[length-12].enemyIndex>13) && enemyIndex>13)
                enemyIndex =  Math.floor(Math.random()*12)

                //适配大体积敌人
                var newEnemy = cc.instantiate(this.Enemy[enemyIndex])
                newEnemy.scale = 0.6
                if(enemyIndex>11)
                newEnemy.scale = 0.7
                if(enemyIndex>13)
                newEnemy.scale = 1
                // newEnemy.children[0].getComponent(dragonBones.ArmatureDisplay).playAnimation('idle',0)
                if(this.enemyArr[length-1] && (this.enemyArr[length-1].enemyIndex==12 ||this.enemyArr[length-1].enemyIndex==13))
                newEnemy = null
                if(this.enemyArr[length-7] && (this.enemyArr[length-7].enemyIndex==12 ||this.enemyArr[length-7].enemyIndex==13))
                newEnemy = null
                if(this.enemyArr[length-8] && (this.enemyArr[length-8].enemyIndex==12 ||this.enemyArr[length-8].enemyIndex==13))
                newEnemy = null
                if(this.enemyArr[length-1] && (this.enemyArr[length-1].enemyIndex==15 ||this.enemyArr[length-1].enemyIndex==14))
                newEnemy = null
                if(this.enemyArr[length-2] && (this.enemyArr[length-2].enemyIndex==15 ||this.enemyArr[length-2].enemyIndex==14))
                newEnemy = null
                if(this.enemyArr[length-7] && (this.enemyArr[length-7].enemyIndex==15 ||this.enemyArr[length-7].enemyIndex==14))
                newEnemy = null
                if(this.enemyArr[length-8] && (this.enemyArr[length-8].enemyIndex==15 ||this.enemyArr[length-8].enemyIndex==14))
                newEnemy = null
                if(this.enemyArr[length-9] && (this.enemyArr[length-9].enemyIndex==15 ||this.enemyArr[length-9].enemyIndex==14))
                newEnemy = null
                if(this.enemyArr[length-14] && (this.enemyArr[length-14].enemyIndex==15 ||this.enemyArr[length-14].enemyIndex==14))
                newEnemy = null
                if(this.enemyArr[length-15] && (this.enemyArr[length-15].enemyIndex==15 ||this.enemyArr[length-15].enemyIndex==14))
                newEnemy = null
                if(this.enemyArr[length-16] && (this.enemyArr[length-16].enemyIndex==15 ||this.enemyArr[length-16].enemyIndex==14))
                newEnemy = null
                if(newEnemy){
                    this.showEnemyNum--
                    if(this.showEnemyNum<0)
                    return
                    newEnemy.parent = this.EnemyNode
                    newEnemy.addComponent('EnemyConfig')
                    newEnemy.anchorX = 0
                    newEnemy.anchorY = 0
                    newEnemy.x = Math.random()*2400 - 1200
                    newEnemy.y = Math.sqrt(1300*1300 - newEnemy.x*newEnemy.x)
                    newEnemy.runAction(cc.moveTo(3,cc.v2(80*i-240,400)))
                    newEnemy.enemyIndex = enemyIndex
                    newEnemy.heightNum = 9
                }                
                this.enemyArr.push(newEnemy)
            }
        }            
        else{
            //Boss Stage
            var enemyIndex = 16
            var newEnemy = cc.instantiate(this.Enemy[enemyIndex])
            newEnemy.parent = this.EnemyNode
            newEnemy.addComponent('EnemyConfig')
            newEnemy.children[0].getComponent(dragonBones.ArmatureDisplay).playAnimation('idle',0)
            newEnemy.anchorX = 0.5
            newEnemy.anchorY = 0.5
            newEnemy.x = - 1200
            newEnemy.y =1000
            newEnemy.runAction(cc.moveTo(3,cc.v2(0,240)))
            newEnemy.enemyIndex = enemyIndex
            this.enemyArr.push(newEnemy)
        }
    },
    enemyMovedown(){
        if(GameStates.levelNum==16)
        return
        this.shakeEffect()
        cc.audioEngine.play(this.sound[4],false)
        for(var i=0;i<this.enemyArr.length;i++){
            if(this.enemyArr[i]){
                this.enemyArr[i].runAction(cc.moveBy(0.2,0,-80))
                this.enemyArr[i].heightNum--
            }
        }
        this.isOver()
    },
    showTool(){
        // 冰冻弹 整个屏幕结冰 敌人限时内任你攻击 （ 1 ）   0
        // 激光炮 发射一发就可以消灭一整列敌人 ( 1 )    1
        // 影分身 限时内左右各出现一个分身 帮你同时攻击 ( 1 )   2
        // 雷神之力 你的子弹击中一个敌人 敌人身边半径3格内的敌人都会被雷击消灭 ( 1 ）   3
        // 防护罩 获得一定时长免疫攻击的防护罩  4
        var ranNum = Math.random()
        var toolIndex = 0
        if(ranNum<0.3){ //分身
            toolIndex = 2
        }
        else if(ranNum<0.5){    //防护
            toolIndex = 4
        }
        else if(ranNum<0.7){    //冰冻
            toolIndex = 0
        }
        else if(ranNum<0.9){    //雷电
            toolIndex = 3
        }
        else    //激光
        toolIndex = 1
        var toolPrefab = cc.instantiate(this.Tool[toolIndex])
        toolPrefab.scale = 0.5
        toolPrefab.x = Math.random()*600-300
        toolPrefab.y = Math.random()*600-300
        toolPrefab.toolIndex = toolIndex
        toolPrefab.addComponent('ToolConfig')
        toolPrefab.parent = this.node
        setTimeout(function(){
            if(this.isPause)
            return
            this.showTool()
        }.bind(this),this.toolTimer*1000)
    },
    isOver(){
        var heightNum = 1
        cc.log(this.enemyArr)
        for(var i=0;i<this.enemyArr.length;i++){
            if(this.enemyArr[i] && this.enemyArr[i].name && this.enemyArr[i].heightNum==0){
                heightNum = 0
            }
        }
        if(heightNum==0){
            this.node.getChildByName('UI').getChildByName('UI_Life').runAction(cc.sequence(cc.fadeIn(0.1),cc.fadeOut(0.1),cc.fadeIn(0.1),cc.fadeOut(0.1),cc.fadeIn(0.1),cc.fadeOut(0.1),cc.fadeIn(0.1),cc.fadeOut(0.1),cc.fadeIn(0.1)))
            setTimeout(function(){
                this.GameOver(0)
            }.bind(this),1000)  
        }
    },
    loseLife(){
        GameStates.lifeNum--
        var lifeArr = this.node.getChildByName('UI').getChildByName('UI_Life').children
        for(var i=0;i<3;i++){
            if(lifeArr[i].active){
                lifeArr[i].active = false
                break
            }
        }
        if(GameStates.lifeNum==0){
            this.Player.getComponent(dragonBones.ArmatureDisplay).playAnimation('die',-1)
            this.shakeEffect()
            this.isPause = 1
            this.node.getChildByName('UI').getChildByName('UI_Life').runAction(cc.sequence(cc.fadeIn(0.1),cc.fadeOut(0.1),cc.fadeIn(0.1),cc.fadeOut(0.1),cc.fadeIn(0.1),cc.fadeOut(0.1),cc.fadeIn(0.1),cc.fadeOut(0.1),cc.fadeIn(0.1)))
            setTimeout(function(){
                this.GameOver(0)
            }.bind(this),1000)  
        }
    },
    addScore(node,n){
        GameStates.gameScore+=n
        this.ScoreNum.string = GameStates.gameScore
    },
    addTool(toolIndex){//增加道具
        cc.audioEngine.play(this.sound[10],false)
        this.toolLock.active = false
        this.toolTime.active = true
        this.toolTime.runAction(cc.repeatForever(cc.sequence(cc.fadeOut(0.1),cc.delayTime(0.1),cc.fadeIn(0.1),cc.delayTime(0.1))))
        this.EnergyBlue.width=239
        this.isUsingTool = 1
        this.energyMax.active = true
        this.isTool = 1
        this.toolIndex = toolIndex
        setTimeout(function(){
            if(this.isTool){
                this.toolTime.stopAllActions()
                this.toolLock.active = true
                this.toolTime.active = false
                this.isUsingTool = 0
                this.isTool = 0
                this.energyMax.active = false
                this.EnergyGreen.width = 0
            }
        }.bind(this),6000)
    },
    useTool(){//使用道具
        // 冰冻弹 整个屏幕结冰 敌人限时内任你攻击 （ 1 ）   0
        // 激光炮 发射一发就可以消灭一整列敌人 ( 1 )    1
        // 影分身 限时内左右各出现一个分身 帮你同时攻击 ( 1 )   2
        // 雷神之力 你的子弹击中一个敌人 敌人身边半径3格内的敌人都会被雷击消灭 ( 1 ）   3
        // 防护罩 获得一定时长免疫攻击的防护罩  4
        switch (this.toolIndex) {
            case 0:
                cc.audioEngine.play(this.sound[0],false)
                this.toolPanel0.active = true
                this.PlayerBulletIndex = 1
                this.isTool0 = 1
                this.EnemyNode.position = cc.v2(0,0)
                this.EnemyNode.stopAllActions()
                setTimeout(function(){
                    this.energyMax.active = false
                    this.toolPanel0.active = false
                    this.toolLock.active = true
                    this.toolTime.active = false
                    this.PlayerBulletIndex = 0
                    this.isTool0 = 0
                    this.isUsingTool = 0
                    this.EnemyNode.runAction(cc.repeatForever(cc.sequence(cc.moveBy(1.5,-50,0),cc.moveBy(3,100,0),cc.moveBy(1.5,-50,0))))
                }.bind(this),10000)
                break;
            case 1:
                cc.audioEngine.play(this.sound[7],false)
                this.PlayerBulletIndex = 2
                setTimeout(function(){
                    this.energyMax.active = false
                    this.toolLock.active = true
                    this.toolTime.active = false
                    this.PlayerBulletIndex = 0
                    this.isUsingTool = 0
                    this.EnergyGreen.stopAllActions()
                    this.EnergyGreen.width = 0
                }.bind(this),2000)
                
                break;
            case 2:
                cc.audioEngine.play(this.sound[1],false)
                this.playerLeft = cc.instantiate(this.Player)
                this.playerLeft.parent = this.node
                this.playerLeft.x = this.Player.x-140
                this.playerLeft.y = this.Player.y
                this.playerLeft.removeComponent('PlayerConfig')
                this.playerRight = cc.instantiate(this.Player)
                this.playerRight.parent = this.node
                this.playerRight.x = this.Player.x+140
                this.playerRight.y = this.Player.y
                this.playerRight.removeComponent('PlayerConfig')
                //动画
                var skillAnimation = cc.instantiate(this.PlayerBullet[3])
                skillAnimation.parent = this.node
                skillAnimation.position = this.Player.position
                setTimeout(function(){
                    this.energyMax.active = false
                    this.toolLock.active = true
                    this.toolTime.active = false
                    this.playerLeft.destroy()
                    this.playerLeft = null
                    this.playerRight.destroy()
                    this.playerRight = null
                    this.isUsingTool = 0
                    this.EnergyGreen.stopAllActions()
                    this.EnergyGreen.width = 0
                }.bind(this),10000)
                
                break;
            case 3:
                cc.audioEngine.play(this.sound[12],false)
                this.PlayerBulletIndex = 4
                this.fireTimeNum = 60
                setTimeout(function(){
                    this.energyMax.active = false
                    this.toolLock.active = true
                    this.toolTime.active = false
                    this.PlayerBulletIndex = 0
                    this.isUsingTool = 0
                    this.fireTimeNum = 30
                    // this.isPause = 0
                    this.EnergyGreen.stopAllActions()
                    this.EnergyGreen.width = 0
                }.bind(this),1000)
                break;
            case 4:
                cc.audioEngine.play(this.sound[13],false)
                var skill4 = cc.instantiate(this.PlayerBullet[5])
                skill4.parent = this.Player
                skill4.position = cc.v2(0,0)
                setTimeout(function(){
                    this.energyMax.active = false
                    this.toolLock.active = true
                    this.toolTime.active = false
                    this.PlayerBulletIndex = 0
                    this.isUsingTool = 0
                    this.EnergyGreen.stopAllActions()
                    this.EnergyGreen.width = 0
                    skill4.destroy()
                }.bind(this),10000)
                break;
        
            default:
                break;
        }

    }, 
    GameStop(){  
        this.node.getChildByName('UI').getChildByName('UI_Life').runAction(cc.sequence(cc.fadeIn(0.1),cc.fadeOut(0.1),cc.fadeIn(0.1),cc.fadeOut(0.1),cc.fadeIn(0.1),cc.fadeOut(0.1),cc.fadeIn(0.1),cc.fadeOut(0.1),cc.fadeIn(0.1)))
        setTimeout(function(){
            this.GameOver(0)
        }.bind(this),1000)       
    },
    GameOver(isWin){
        for(var i=0;i<this.enemyArr.length;i++){
            if(this.enemyArr[i])
            this.enemyArr[i].destroy()
        }
        this.onTurnsNumber(false)
        this.isPause = this.SettlePanel.active = true
        GameStates.keyNum+=GameStates.levelNum
        GameStates.carlNum+=GameStates.levelNum
        this.SettlePanel.getChildByName('StageNum').getComponent(cc.Label).string = GameStates.levelNum
        this.SettlePanel.getChildByName('ScoreNum').getComponent(cc.Label).string = GameStates.gameScore
        this.SettlePanel.getChildByName('CarlNum').getComponent(cc.Label).string = Math.floor((window.calorie-GameStates.carlNum)/1000)
        this.SettlePanel.getChildByName('KeyNum').getComponent(cc.Label).string = GameStates.levelNum
        var newDate = new Date()
        var timeNum = Math.floor((newDate-GameStates.gameTime)/1000)
        var h = Math.floor(timeNum/3600)
        var hh = h<10 ? '0'+h : h
        var m = Math.floor((timeNum-h*3600)/60)
        var mm = m<10? '0'+m : m
        var s = timeNum-h*3600-m*60
        var ss = s<10? '0'+s : s
        this.SettlePanel.getChildByName('TimeNumHH').getComponent(cc.Label).string = hh+':'+mm+':'+ ss
        this.EndLevelNum.removeAllChildren()
        var numPrefab = cc.instantiate(this.LevelNumber[11])
        numPrefab.parent = this.EndLevelNum
        if(GameStates.levelNum<10){
            var numPrefab = cc.instantiate(this.LevelNumber[GameStates.levelNum])
            numPrefab.parent = this.EndLevelNum
        }
        else if(GameStates.levelNum==10){
            var numPrefab1 = cc.instantiate(this.LevelNumber[10])
            numPrefab1.parent = this.EndLevelNum
        }
        else if(GameStates.levelNum<17){
            var numPrefab1 = cc.instantiate(this.LevelNumber[10])
            numPrefab1.parent = this.EndLevelNum
            var numPrefab2 = cc.instantiate(this.LevelNumber[GameStates.levelNum%10])
            numPrefab2.parent = this.EndLevelNum
        }
        else{
            var numPrefab1 = cc.instantiate(this.LevelNumber[12])
            numPrefab1.parent = this.EndLevelNum
        }
        var numPrefab3 = cc.instantiate(this.LevelNumber[0])
        numPrefab3.parent = this.EndLevelNum
        if(isWin){ //胜利
            cc.audioEngine.play(this.sound[8],false)
            GameStates.enemyNum = GameStates.levelNum*10+30 >99 ? 99 : GameStates.levelNum*10+30
            if(GameStates.levelNum==15)
            GameStates.enemyNum = 1
            if(GameStates.levelNum==16)
            GameStates.enemyNum = 1000000000000
            if(GameStates.levelNum<=16)
            GameStates.levelNum++
            this.SettlePanel.getChildByName('SettleLight').active = true
            this.SettlePanel.getChildByName('TitleWin').active = true
            this.SettlePanel.getChildByName('TitleLose').active = false
            this.SettlePanel.getChildByName('Button').active = true
            this.SettlePanel.getChildByName('Button0').active = false
            this.SettlePanel.getChildByName('ResetNum').active = false
        }
        else{   //失败
            cc.audioEngine.play(this.sound[2],false)
            this.SettlePanel.getChildByName('SettleLight').active = false
            this.SettlePanel.getChildByName('TitleWin').active = false
            this.SettlePanel.getChildByName('TitleLose').active = true
            this.SettlePanel.getChildByName('Button0').active = true
            this.SettlePanel.getChildByName('Button').active = false
            this.SettlePanel.getChildByName('ResetNum').active = true
            this.SettlePanel.getChildByName('KeyNum').getComponent(cc.Label).string = 0
        }
        var self = this
        var newDate = new Date()
        this.durationTime = Math.floor((newDate-GameStates.gameTime)/1000)
        var gripName = this.isiOS ? 'IOS' : 'Android'
        var scoreJson = {
            startTime:parseInt(self.startDate.getTime()/1000),
            durationTime:self.durationTime,
            fromType:15,
            calories:window.calorie-GameStates.carlNum,
            gripName:gripName,
            ip:"ip",
            objectJson:{"courseId":1001,"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)
        if(this.isAndroid && !isWin)
        {
            console.log('submitGameScore:',scoreStr)
            window.eventJsBridge.submitGameScore(scoreStr);
        }
        else if(this.isiOS && !isWin)
        {
            console.log('submitGameScore:',scoreStr)
            window.webkit.messageHandlers.submitGameScore.postMessage(scoreStr);
        }
    },
    GameRefresh(){
        cc.audioEngine.play(this.sound[5],false)
        GameStates.levelNum = 1
        GameStates.lifeNum = 3
        GameStates.gameScore = 0
        GameStates.keyNum = 0
        GameStates.gameTime = new Date()
        GameStates.enemyNum = 30
        GameStates.carlNum = window.calorie
        GameStates.turnsNum = window.turnsNum
        cc.director.loadScene('GameScene')
    },
    GameReset(){
        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)
            cc.audioEngine.play(self.sound[5],false)
            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('You don’t have enough Mcoin, please deposit more Mcoin')
            }
            else{
                cc.audioEngine.play(self.sound[5],false)
                GameStates.lifeNum = 3
                cc.director.loadScene('GameScene')
            }
        }        
    },
    GameHome(){
        cc.audioEngine.play(this.sound[5],false)
        GameStates.levelNum = 1
        GameStates.lifeNum = 3
        GameStates.gameScore = 0
        GameStates.keyNum = 0
        GameStates.enemyNum = 30
        GameStates.carlNum = window.calorie
        GameStates.turnsNum = window.turnsNum
        cc.director.loadScene('BeginScene')
    },
    GameNext(){
        this.SettlePanel.active = false
        this.Player.active = false
        cc.audioEngine.play(this.sound[5],false)
        if(((GameStates.levelNum-1)%3==0 && GameStates.levelNum<16) || GameStates.levelNum==16){
            this.AnimationPanle.active = true
            this.AnimationPanle.getChildByName('Bottom').getChildByName('Image').getComponent(cc.Sprite).spriteFrame = this.ImageFrame[Math.floor(GameStates.levelNum/3)-1]
            this.AnimationPanle.getChildByName('Bottom').getChildByName('Title0').getComponent(cc.Sprite).spriteFrame = this.Title0Frame[Math.floor(GameStates.levelNum/3)]
            this.AnimationPanle.getChildByName('Bottom').getChildByName('Title1').getComponent(cc.Sprite).spriteFrame = this.Title1Frame[Math.floor(GameStates.levelNum/3)]
            this.AnimationPanle.getChildByName('Bottom').getChildByName('Title2').getComponent(cc.Sprite).spriteFrame = this.Title2Frame[Math.floor(GameStates.levelNum/3)]
            this.AnimationPanle.getChildByName('Bottom').getChildByName('Title3').getComponent(cc.Sprite).spriteFrame = this.Title3Frame[Math.floor(GameStates.levelNum/3)]
            if(GameStates.levelNum==16){
                this.AnimationPanle.active = true
                this.AnimationPanle.getChildByName('Bottom').getChildByName('Image').getComponent(cc.Sprite).spriteFrame = this.ImageFrame[5]
                this.AnimationPanle.getChildByName('Bottom').getChildByName('Title0').getComponent(cc.Sprite).spriteFrame = this.Title0Frame[5]
                this.AnimationPanle.getChildByName('Bottom').getChildByName('Title1').getComponent(cc.Sprite).spriteFrame = this.Title1Frame[5]
                this.AnimationPanle.getChildByName('Bottom').getChildByName('Title2').getComponent(cc.Sprite).spriteFrame = this.Title2Frame[5]
                this.AnimationPanle.getChildByName('Bottom').getChildByName('Title3').getComponent(cc.Sprite).spriteFrame = this.Title3Frame[5]
            }
            this.AnimationPanle.getChildByName('Dot0').runAction(cc.repeatForever(cc.sequence(cc.delayTime(0),cc.fadeIn(0),cc.delayTime(1.5),cc.fadeOut(0),cc.delayTime(0.5))))
            this.AnimationPanle.getChildByName('Dot1').runAction(cc.repeatForever(cc.sequence(cc.delayTime(0.5),cc.fadeIn(0),cc.delayTime(1),cc.fadeOut(0),cc.delayTime(0.5))))
            this.AnimationPanle.getChildByName('Dot2').runAction(cc.repeatForever(cc.sequence(cc.delayTime(1),cc.fadeIn(0),cc.delayTime(0.5),cc.fadeOut(0),cc.delayTime(0.5))))
            this.AnimationPanle.getChildByName('bar').runAction(cc.scaleTo(3,1))
            setTimeout(function(){
                cc.director.loadScene('GameScene')
            }.bind(this),3000)
        }        
        else{
            cc.director.loadScene('GameScene')
        }        
    },
    shakeEffect: function (duration) {
        // this.camera.x=10
        var act = cc.repeatForever(
                    cc.sequence(
                        cc.moveTo(0.02, 2, 3),
                        cc.moveTo(0.02, -3, 3.5),
                        cc.moveTo(0.02, -6, 1.4),
                        cc.moveTo(0.02, 1.5, -3),
                        cc.moveTo(0.02, -2.5, 2.5),
                        cc.moveTo(0.02, 1, -4),
                        cc.moveTo(0.02, -4, -3),
                        cc.moveTo(0.02, 1.5, 4),
                        cc.moveTo(0.02, 0, 0)
                    )
                )
        this.Camera.runAction(act)                  
        setTimeout(function(){
            this.Camera.stopAllActions();
            this.Camera.setPosition(0,0);
        }.bind(this), 300);
    },
    onDestroy(){
        cc.audioEngine.stopAllEffects()
        clearInterval(this.showEnemyTimer)
        clearTimeout(this.showtoolTimer)
    },
    jump(){
        GameStates.levelNum = 17
        GameStates.enemyNum = 1000000000000
        cc.director.loadScene('GameScene')
    },
    update (dt) {
        if(this.isPause)
        return
        //地图滚动
        var rollSpeed = 1+4
        if(GameStates.levelNum!=16){
            for(var i=0;i<4;i++){
                if(this.Bg[i].y-rollSpeed<=-1480){
                    var n = i-1<0?3:i-1
                    this.Bg[i].y = this.Bg[n].y+this.Bg[0].height
                }
                this.Bg[i].y-=rollSpeed
            }
        }
       
        //增加能量
        if(window.turnsNum>this.myturnsNum){
            if(this.isTool){
                this.EnergyGreen.width+=40*(window.turnsNum-this.myturnsNum)
                if(this.EnergyGreen.width>=239){
                    this.EnergyGreen.width = 239
                    this.isTool = 0
                    this.useTool()
                }
            }
            else{
                this.EnergyBlue.width+=20*(window.turnsNum-this.myturnsNum)
                if(this.EnergyBlue.width>239)
                this.EnergyBlue.width = 239
            }            
            this.myturnsNum = window.turnsNum
        }
        //开火
        this.fireTime--
        if(this.fireTime<=0){
            this.fireTime = this.fireTimeNum
            var PlayerBullet = cc.instantiate(this.PlayerBullet[this.PlayerBulletIndex])
            PlayerBullet.parent = this.node
            PlayerBullet.addComponent('PlayerBullet')
            PlayerBullet.zIndex = this.Player.zIndex - 1
            PlayerBullet.position = this.Player.position
            if(this.PlayerBulletIndex==2)
            {
                this.BlackMask.runAction(cc.sequence(cc.fadeIn(0),cc.delayTime(2),cc.fadeOut(0)))
                this.fireTime = 100000000000
                PlayerBullet.parent = this.Player
                PlayerBullet.position = cc.v2(0,0)
                setTimeout(function(){
                    PlayerBullet.getComponent(dragonBones.ArmatureDisplay).playAnimation('EF_jiguang_2')
                }.bind(this),300)
                setTimeout(function(){
                    PlayerBullet.getComponent(dragonBones.ArmatureDisplay).playAnimation('EF_jiguang_3')
                    this.fireTime = this.fireTimeNum
                }.bind(this),2000-300)
            }
            else if(this.PlayerBulletIndex==4){
                this.BlackMask.runAction(cc.sequence(cc.fadeIn(0),cc.delayTime(1),cc.fadeOut(0)))
                PlayerBullet.zIndex = this.Player.zIndex + 1
                PlayerBullet.runAction(cc.sequence(cc.scaleTo(0,0.5),cc.delayTime(1),cc.moveBy(2,0,2000)))
                // this.isPause = 1
                PlayerBullet.parent = this.Player
                PlayerBullet.position = cc.v2(0,0)
            }            
            else
            PlayerBullet.runAction(cc.moveBy(2,0,2000))
            if(this.playerRight){
                var PlayerBullet = cc.instantiate(this.PlayerBullet[0])
                PlayerBullet.parent = this.node
                PlayerBullet.addComponent('PlayerBullet')
                PlayerBullet.zIndex = this.Player.zIndex - 1
                PlayerBullet.position = this.playerRight.position
                PlayerBullet.runAction(cc.moveBy(2,0,2000))
                var PlayerBullet = cc.instantiate(this.PlayerBullet[0])
                PlayerBullet.parent = this.node
                PlayerBullet.addComponent('PlayerBullet')
                PlayerBullet.zIndex = this.Player.zIndex - 1
                PlayerBullet.position = this.playerLeft.position
                PlayerBullet.runAction(cc.moveBy(2,0,2000))
            }
        }
    },
});
