var cfg = require("Configure")
var QQCommon = require("../QQCommon")

cc.Class({
    extends: cc.Component,

    properties: {
        buDing: {
            default: null,
            type: cc.Sprite
        },
        // shield: {
        //     default: null,
        //     type: cc.Node
        // },

        obstacleNode: {
            default: null,
            type: cc.Node
        },

        scoreNode: {
            default: null,
            type: cc.Node
        },

        funcNode: {
            default: null,
            type: cc.Node
        },

        sumScore: 0,
        layerNum: 0,
        obstacleNum: 0,
        starNum: 0,

        gamebgMusic: {
            default: null,
            type: cc.AudioClip
        },

        changeColorAudio: {
            default: null,
            type: cc.AudioClip
        },

        eatGoldAudio: {
            default: null,
            type: cc.AudioClip
        },

        newRecordAudio: {
            default: null,
            type: cc.AudioClip
        },

        buttonAudio: {
            default: null,
            type: cc.AudioClip
        },

        passNode: { //超越提示节点
            default: null,
            type: cc.Node
        },

        bShare: false,
        bDead: false,
        bPause: false,

        feiendtex: null,
        childCanvas: null
    },

    onLoad: function () {
        if (cc.vv == undefined) {
            cc.vv = {};
        }

        var manager = cc.director.getCollisionManager();
        manager.enabled = true;

        this.registerTouchEventHandle();

        if (cc.winSize.height > 1334) {
            this.node.getChildByName("ScoreNode").setPosition(0, (cc.winSize.height - 1334) / 2);
            this.node.getChildByName("FuncNode").setPosition(0, -(cc.winSize.height - 1334) / 2);
        }

        this.showVd = false;
        this.debugErrorTips = false;

        this.shieldBtn = this.funcNode.getChildByName('ShieldBtn');
        this.nodePools = {};
        cfg.obstacleTypePath.forEach(type => {
            this.nodePools[type] = [];
        });
    },

    start: function () {
        this.feiendtex = new cc.Texture2D();
        this.childCanvas = new cc.Texture2D();
        this.PHB = cc.find("Canvas/PHB")
        this.rankScene = this.PHB.getComponent("RankScene");
        this.rankNode = this.PHB.getChildByName("Rank")
        this.myRankNode = this.PHB.getChildByName('MyRank')
        this.worldContentNode = this.rankNode.getChildByName('WorldContent')
        this.friendContentNode = this.rankNode.getChildByName('FriendContent')
    },

    startGame: function () {
        //通知子域重新填充rankList
        if (UserInfo.platform == 1 && cc.vv.isRank) {
            wx.postMessage({
                method: 'fillRankList'
            });
        }

        cc.audioEngine.playMusic(this.gamebgMusic, true);

        this.sumScore = 0;
        this.layerNum = 0;
        this.starNum = 0;
        this.obstacleNum = 0;
        this.bShare = true;
        this.bDead = false;
        this.bVideo = true;
        this.scoreNode.active = true;
        this.funcNode.active = true;
        this.shieldBtn.active = true;

        this.obstacleNode.removeAllChildren();

        this.node.getChildByName("Camera").setPosition(cc.p(0, 0));

        var sumScoreLabel = this.scoreNode.getChildByName("ScoreLabel");
        sumScoreLabel.getComponent("cc.Label").string = this.sumScore;

        //var layerNumLabel = this.scoreNode.getChildByName("LayerLabel");
        //layerNumLabel.getComponent("cc.Label").string = this.layerNum;

        this.node.getChildByName("Camera").getComponent("CameraControl").resetData();

        this.buDing.getComponent("BuDingSprite").initBuding();
        //cc.director.getPhysicsManager().enabled = true;

        this.createObstacle();
        this.node.runAction(cc.sequence(cc.delayTime(1), cc.callFunc(this.createObstacle, this), cc.delayTime(1), cc.callFunc(this.createObstacle, this)));

        let stmp = new Date().getTime();
        cc.loader.load({
            url: "https://pub.dwstatic.com/wxgame/budingGame/share.json?" + (stmp / 100000).toFixed(0),
            type: "json"
        }, (err, res) => {
            if (res) {
                this.showVd = res.showVd
                this.bShare = res.bShare
                this.debugErrorTips = res.debugErrorTips
            }
        })
    },

    finishGame: function () {
        this.bDead = true;
        this.buDing.node.active = false;
        this.buDing.node.getComponent("BuDingSprite").setSkSpriteVisible(false);
        this.scoreNode.active = false;
        this.funcNode.active = false;

        var gameOverNode = this.node.getChildByName("GameOver");
        gameOverNode.active = true;
        // window.deadBanner.show();

        var endLayerNumLabel = gameOverNode.getChildByName("EndLayerNumLabel");
        endLayerNumLabel.getComponent("cc.Label").string = this.sumScore;

        if (this.bShare) {
            // var endScoreLabel = gameOverNode.getChildByName("ShareNode").getChildByName("EndScoreLabel");
            // endScoreLabel.getComponent("cc.Label").string = this.sumScore;
            var shareNode = gameOverNode.getChildByName("ShareNode");
            shareNode.active = true;
            gameOverNode.getChildByName("EndNode").active = false;
            if (this.showVd) {
                //显示观看视频广告按钮
                shareNode.getChildByName("ShareBtn").active = false;
                shareNode.getChildByName("VideoBtn").active = true;
            } else {
                //显示邀请好友按钮
                shareNode.getChildByName("ShareBtn").active = true;
                shareNode.getChildByName("VideoBtn").active = false;
            }
            this.startFinishCount();
        } else {
            gameOverNode.getChildByName("EndNode").active = true;
            gameOverNode.getChildByName("ShareNode").active = false;

            this.gameOver();

            var data = [{
                key: UserInfo.getCurWeekScoreValue(),
                value: UserInfo.getScore().toString()
            }, {
                key: "driLevel",
                value: '0'
            }
            ];

            if (CC_WECHATGAME && cc.vv.isRank) {
                this.node.parent.getChildByName("PHB").getChildByName("bg").active = false;
                this.rankScene.status = 3;
                this.showRank();
                this.updateXYXScore('showMyRank', data);
            }
        }
    },

    //结束界面开始倒计时
    startFinishCount: function (countDown) {
        var countDown = 10;
        var gameOverNode = this.node.getChildByName("GameOver");
        var countDownLabel = gameOverNode.getChildByName("ShareNode").getChildByName("EndCountDownLabel");
        countDownLabel.getComponent("cc.Label").string = countDown;

        var callback = function () {
            if (countDown <= 0) {
                gameOverNode.getChildByName("ShareNode").active = false;
                gameOverNode.getChildByName("EndNode").active = true;

                this.gameOver();

                var data = [{
                    key: UserInfo.getCurWeekScoreValue(),
                    value: UserInfo.getScore().toString()
                }, {
                    key: "driLevel",
                    value: '0'
                }
                ];

                if (CC_WECHATGAME && cc.vv.isRank) {
                    this.rankScene.status = 3;
                    this.showRank();
                    this.updateXYXScore('showMyRank', data);
                }
            } else {
                countDown--;
                countDownLabel.getComponent("cc.Label").string = countDown;
                countDownLabel.runAction(cc.sequence(cc.delayTime(1), cc.callFunc(callback, this)));
            }
        }
        countDownLabel.runAction(cc.sequence(cc.delayTime(1), cc.callFunc(callback, this)));
    },

    gameOver: function () {
        var gameOverNode = this.node.getChildByName("GameOver");
        var historyScoreLabel = gameOverNode.getChildByName("EndNode").getChildByName("HistoryScoreLabel");
        var newRecordSp = gameOverNode.getChildByName("EndNode").getChildByName("NewRecordSp");
        if (this.sumScore > UserInfo.getHistoryScore()) {
            newRecordSp.active = true;
            UserInfo.setString("historyScore", this.sumScore);
            cc.audioEngine.playEffect(this.newRecordAudio);
            newRecordSp.runAction(cc.repeatForever(cc.sequence(cc.scaleTo(0.5, 1.5), cc.scaleTo(0.5, 1))));
        } else {
            newRecordSp.active = false;
        }

        if (this.sumScore > UserInfo.getScore()) {
            UserInfo.setScore(this.sumScore);
        }

        historyScoreLabel.getComponent("cc.Label").string = "历史最高分:" + UserInfo.getHistoryScore();

        UserInfo.addGold(this.sumScore);

        // window.deadBanner.hide();
        // window.accountBanner.show();
    },


    continueGame: function () {
        // window.deadBanner.hide();
        // window.accountBanner.hide();
        this.bShare = false;
        this.bDead = false;
        this.layerNum = 0;
        this.starNum = 0;
        this.obstacleNum = 0;
        this.scoreNode.active = true;
        this.funcNode.active = true;

        this.node.getChildByName("GameOver").active = false;
        this.obstacleNode.removeAllChildren();

        this.node.getChildByName("Camera").getComponent("CameraControl").resetData();

        this.node.getChildByName("Camera").setPosition(cc.p(0, 0));
        this.buDing.getComponent("BuDingSprite").initBuding();

        //cc.director.getPhysicsManager().enabled = true;

        this.createObstacle();
        this.node.runAction(cc.sequence(cc.delayTime(1), cc.callFunc(this.createObstacle, this), cc.delayTime(1), cc.callFunc(this.createObstacle, this)));
    },

    createObstacle: function () {
        var obstacleType = this.randomObstacleType();
        //根据当前分数控制障碍物之间的高度
        var disObstacleY;
        if (this.sumScore > 40) {
            disObstacleY = 0;
        } else if (this.sumScore > 30 && this.sumScore <= 40) {
            disObstacleY = 50;
        } else if (this.sumScore > 15 && this.sumScore <= 30) {
            disObstacleY = 100;
        } else {
            disObstacleY = 150;
        }

        var self = this;
        cc.loader.loadRes(cfg.obstacleTypePath[obstacleType], function (err, prefab) {
            var obstacle = null;
            if (self.nodePools[cfg.obstacleTypePath[obstacleType]].length) {
                obstacle = self.nodePools[cfg.obstacleTypePath[obstacleType]].pop();
                obstacle.active = true;
                obstacle.getChildByName('ScoreSkSpine').active = false;
                obstacle.getChildByName('ScoreSprite').active = true;
                obstacle.getChildByName('BuDingTypeSprite').active = true;
                console.log('回收利用:', obstacle)
            } else {
                obstacle = cc.instantiate(prefab);
                obstacle.type = cfg.obstacleTypePath[obstacleType]
            }
            // obstacle = cc.instantiate(prefab);
            // obstacle.type = cfg.obstacleTypePath[obstacleType];
            if (self.obstacleNode.getChildByName("obstacle1") == null) {
                var obstacle1 = obstacle
                obstacle1.setName("obstacle1");
                self.obstacleNode.addChild(obstacle1);
                if (self.obstacleNode.getChildByName("obstacle3") != null) {
                    var type = self.obstacleNode.getChildByName("obstacle3").getComponent("Obstacle").getType();

                    var specialOffsetY = 0
                    if (type == cfg.obstacleType.circle3) {
                        if (obstacleType == cfg.obstacleType.square || obstacleType == cfg.obstacleType.circle2) {
                            specialOffsetY = 100;
                        }
                    } else if (type == cfg.obstacleType.circle2) {
                        if (obstacleType == cfg.obstacleType.square) {
                            specialOffsetY = 100;
                        }
                    }
                    obstacle1.setPosition(0, self.obstacleNode.getChildByName("obstacle3").y + (cc.winSize.height + cfg.obstacleProperty[type].addY + specialOffsetY) * (1334 / cc.winSize.height) + disObstacleY);
                } else {
                    obstacle1.setPosition(0, 500 * (1334 / cc.winSize.height) + 100);
                }

                obstacle1.getComponent("Obstacle").initObstacle(obstacleType, self.obstacleNum, self.sumScore);
            } else if (self.obstacleNode.getChildByName("obstacle2") == null) {
                var obstacle2 = obstacle
                obstacle2.setName("obstacle2");
                self.obstacleNode.addChild(obstacle2);
                if (self.obstacleNode.getChildByName("obstacle1") != null) {
                    var type = self.obstacleNode.getChildByName("obstacle1").getComponent("Obstacle").getType();
                    var specialOffsetY = 0
                    if (type == cfg.obstacleType.circle3) {
                        if (obstacleType == cfg.obstacleType.square || obstacleType == cfg.obstacleType.circle2) {
                            specialOffsetY = 100;
                        }
                    } else if (type == cfg.obstacleType.circle2) {
                        if (obstacleType == cfg.obstacleType.square) {
                            specialOffsetY = 100;
                        }
                    }

                    obstacle2.setPosition(0, self.obstacleNode.getChildByName("obstacle1").y + (cc.winSize.height + cfg.obstacleProperty[type].addY + specialOffsetY) * (1334 / cc.winSize.height) + disObstacleY);
                } else {
                    obstacle2.setPosition(0, 500 * (1334 / cc.winSize.height) + 100);
                }

                obstacle2.getComponent("Obstacle").initObstacle(obstacleType, self.obstacleNum, self.sumScore);
            } else if (self.obstacleNode.getChildByName("obstacle3") == null) {
                var obstacle3 = obstacle
                obstacle3.setName("obstacle3");
                self.obstacleNode.addChild(obstacle3);
                if (self.obstacleNode.getChildByName("obstacle2") != null) {
                    var type = self.obstacleNode.getChildByName("obstacle2").getComponent("Obstacle").getType();
                    var specialOffsetY = 0
                    if (type == cfg.obstacleType.circle3) {
                        if (obstacleType == cfg.obstacleType.square || obstacleType == cfg.obstacleType.circle2) {
                            specialOffsetY = 100;
                        }
                    } else if (type == cfg.obstacleType.circle2) {
                        if (obstacleType == cfg.obstacleType.square) {
                            specialOffsetY = 100;
                        }
                    }

                    obstacle3.setPosition(0, self.obstacleNode.getChildByName("obstacle2").y + (cc.winSize.height + cfg.obstacleProperty[type].addY + specialOffsetY) * (1334 / cc.winSize.height) + disObstacleY);
                } else {
                    obstacle3.setPosition(0, 500 * (1334 / cc.winSize.height) + 100);
                }

                obstacle3.getComponent("Obstacle").initObstacle(obstacleType, self.obstacleNum, self.sumScore);
            }

        })
    },

    randomObstacleType: function () {
        var obstacleType = 0;
        this.obstacleNum++;
        var randNum = Math.floor(Math.random() * 100) + 1;
        if (this.obstacleNum == 1) {
            obstacleType = 0;
        } else if (this.obstacleNum > 1 && this.obstacleNum <= 5) {
            if (randNum > 0 && randNum <= 35) {
                obstacleType = 0;
            } else if (randNum > 35 && randNum <= 70) {
                obstacleType = 1;
            } else if (randNum > 70 && randNum <= 85) {
                obstacleType = 2;
            } else if (randNum > 85 && randNum <= 100) {
                obstacleType = 3;
            }
        } else if (this.obstacleNum > 15 && this.obstacleNum <= 45) {
            if (randNum > 0 && randNum <= 20) {
                obstacleType = 0;
            } else if (randNum > 20 && randNum <= 40) {
                obstacleType = 1;
            } else if (randNum > 40 && randNum <= 60) {
                obstacleType = 2;
            } else if (randNum > 60 && randNum <= 80) {
                obstacleType = 3;
            } else if (randNum > 80 && randNum <= 90) {
                obstacleType = 4;
            } else if (randNum > 90 && randNum <= 100) {
                obstacleType = 5;
            }
        } else if (this.obstacleNum > 45) {
            var randNum = Math.floor(Math.random() * 100) + 1;

            if (randNum > 0 && randNum <= 10) {
                obstacleType = 0;
            } else if (randNum > 10 && randNum <= 20) {
                obstacleType = 1;
            } else if (randNum > 20 && randNum <= 35) {
                obstacleType = 2;
            } else if (randNum > 35 && randNum <= 50) {
                obstacleType = 3;
            } else if (randNum > 50 && randNum <= 75) {
                obstacleType = 4;
            } else if (randNum > 75 && randNum <= 100) {
                obstacleType = 5;
            }
        }
        return obstacleType;
    },

    destroyObstacle: function () {
        let obstacle1 = this.obstacleNode.getChildByName("obstacle1"),
            obstacle2 = this.obstacleNode.getChildByName("obstacle2"),
            obstacle3 = this.obstacleNode.getChildByName("obstacle3");

        if (!obstacle1.active) {
            obstacle1.getComponent("Obstacle").stopObstacleAction();

            this.obstacleNode.removeChild(obstacle1);
            this.nodePools[obstacle1.type].push(obstacle1);
        }

        if (!obstacle2.active) {
            obstacle2.getComponent("Obstacle").stopObstacleAction();

            this.obstacleNode.removeChild(obstacle2);
            this.nodePools[obstacle2.type].push(obstacle2);
        }

        if (!obstacle3.active) {
            obstacle3.getComponent("Obstacle").stopObstacleAction();

            this.obstacleNode.removeChild(obstacle3);
            this.nodePools[obstacle3.type].push(obstacle3);
        }
        this.createObstacle();
    },

    registerTouchEventHandle: function () {
        this.node.on(cc.Node.EventType.TOUCH_START, function (event) {
            if (!this.bDead && !this.bPause) {
                this.buDing.getComponent("BuDingSprite").jump();
            }
        }, this)

        this.node.on(cc.Node.EventType.TOUCH_END, function (event) {

        }, this)
    },

    addScore: function () {
        cc.audioEngine.playEffect(this.eatGoldAudio);

        var addScoreLabel = this.node.getChildByName("AddScoreLabel");
        addScoreLabel.getComponent("cc.Label").string = "/" + 1;
        addScoreLabel.active = true;
        addScoreLabel.opacity = 255;
        addScoreLabel.runAction(cc.fadeTo(1, 0));

        this.sumScore += 1;
        this.starNum++;
        var sumScoreLabel = this.scoreNode.getChildByName("ScoreLabel");
        sumScoreLabel.getComponent("cc.Label").string = this.sumScore;
        sumScoreLabel.runAction(cc.sequence(cc.scaleTo(0.5, 1.2), cc.scaleTo(0.5, 1)));


        //超越
        // if (UserInfo.platform == 1 && cc.vv.isRank) {
        //     this.node.getChildByName("Pass").active = true;
        //     wx.postMessage({
        //         method: 'checkPass',
        //         data: this.sumScore
        //     });
        // }


        // if (this.starNum >= 2) 
        // {
        //     var isVisible = (this.starNum%2!=0);
        //     this.obstacleNode.getChildByName("obstacle1").active = isVisible;
        //     this.obstacleNode.getChildByName("obstacle2").active = !isVisible;
        //     this.destroyObstacle();
        // }
    },

    showPass: function () {
        if (UserInfo.platform == 1 && cc.vv.isRank) {

            let openDataContext = wx.getOpenDataContext();
            let sharedCanvas = openDataContext.canvas;

            this.childCanvas.initWithElement(sharedCanvas);
            this.childCanvas.handleLoadedTexture();

            this.passNode.getComponent(cc.Sprite).spriteFrame = new cc.SpriteFrame(this.childCanvas);

            //var scale = Math.min(750 / this.feiendtex.width, 1334 / this.feiendtex.height);
            //this.passNode.setContentSize(this.feiendtex.width * scale, this.feiendtex.height * scale);
        }
    },

    addLayerNum: function () {
        cc.audioEngine.playEffect(this.changeColorAudio);

        //var layerNumLabel = this.scoreNode.getChildByName("LayerLabel");
        this.layerNum++;
        //layerNumLabel.getComponent("cc.Label").string = this.layerNum;
        //layerNumLabel.runAction(cc.sequence(cc.scaleTo(0.5,1.2),cc.scaleTo(0.5,1)));

        //this.buDing.getComponent("BuDingSprite").changeColor(colorType);

        if (this.layerNum >= 2) {
            if (this.layerNum % 3 == 0) {
                this.obstacleNode.getChildByName("obstacle1").active = true;
                this.obstacleNode.getChildByName("obstacle2").active = false;
                this.obstacleNode.getChildByName("obstacle3").active = true;
            } else if (this.layerNum % 3 == 1) {
                this.obstacleNode.getChildByName("obstacle1").active = true;
                this.obstacleNode.getChildByName("obstacle2").active = true;
                this.obstacleNode.getChildByName("obstacle3").active = false;
            } else if (this.layerNum % 3 == 2) {
                this.obstacleNode.getChildByName("obstacle1").active = false;
                this.obstacleNode.getChildByName("obstacle2").active = true;
                this.obstacleNode.getChildByName("obstacle3").active = true;
            }
            this.scheduleOnce(this.destroyObstacle, 1);
        }
    },

    onShieldBtn: function () {

        if (CC_WECHATGAME && window.wx.createRewardedVideoAd) {
            this.onPauseBtn();

            var gameOverNode = this.node.getChildByName("GameOver");
            var countDownLabel = gameOverNode.getChildByName("ShareNode").getChildByName("EndCountDownLabel");

            countDownLabel.stopAllActions();

            let videoAd = wx.createRewardedVideoAd({
                adUnitId: 'adunit-563ed529855c1195'
            })

            videoAd.onClose(res => {
                // 用户点击了【关闭广告】按钮
                // 小于 2.1.0 的基础库版本，res 是一个 undefined
                if (res && res.isEnded || res === undefined) {
                    // 正常播放结束，可以下发游戏奖励
                    this.getShield();
                    this.onPlayBtn();
                    cc.audioEngine.playMusic(this.gamebgMusic, true);
                } else {
                    // 播放中途退出，不下发游戏奖励
                    this.onPlayBtn();
                }
            })

            videoAd.onError(res => {
                this.onPlayBtn()
            })

            videoAd.load()
                .then(() => videoAd.show())
                .catch(err => {
                    videoAd.load()
                        .then(() => videoAd.show())
                })
        } else {
            this.getShield()
        }
    },

    getShield() {
        this.node.getChildByName('Shield').active = true
        this.shieldBtn.active = false;
    },

    onPauseBtn: function () {
        this.bPause = true;
        this.buDing.getComponent("BuDingSprite").stopBuding();

        this.node.getChildByName("Mask").active = true;
        this.funcNode.getChildByName("PauseBtn").active = false;
        this.funcNode.getChildByName("PlayBtn").active = true;

        var obstacle1 = this.obstacleNode.getChildByName("obstacle1");
        var obstacle2 = this.obstacleNode.getChildByName("obstacle2");
        var obstacle3 = this.obstacleNode.getChildByName("obstacle3");

        if (obstacle1 != null) {
            obstacle1.getComponent("Obstacle").pauseObstacleAction();
        }

        if (obstacle2 != null) {
            obstacle2.getComponent("Obstacle").pauseObstacleAction();
        }

        if (obstacle3 != null) {
            obstacle3.getComponent("Obstacle").pauseObstacleAction();
        }
    },

    onPlayBtn: function () {
        var playBtn = this.funcNode.getChildByName("PlayBtn");
        playBtn.getComponent("cc.Button").interactable = false;

        playBtn.getChildByName("PlaySprite").active = false;

        var countDownLabel = this.funcNode.getChildByName("CountDownLabel");
        countDownLabel.active = true;
        var countDown = 3;
        countDownLabel.getComponent("cc.Label").string = countDown;

        var mask = this.node.getChildByName("Mask");
        var pauseBtn = this.funcNode.getChildByName("PauseBtn");
        var obstacle1 = this.obstacleNode.getChildByName("obstacle1");
        var obstacle2 = this.obstacleNode.getChildByName("obstacle2");
        var obstacle3 = this.obstacleNode.getChildByName("obstacle3");


        var self = this;
        var callback = function () {
            if (countDown <= 1) {

                playBtn.active = false;
                playBtn.getComponent("cc.Button").interactable = true;
                playBtn.getChildByName("PlaySprite").active = true;
                countDownLabel.active = false;

                var callback1 = function () {
                    mask.active = false;
                    pauseBtn.active = true;
                    self.bPause = false;
                    self.buDing.getComponent("BuDingSprite").resumeBuding();
                    if (obstacle1 != null) {
                        obstacle1.getComponent("Obstacle").resumeObstacleAction();
                    }

                    if (obstacle2 != null) {
                        obstacle2.getComponent("Obstacle").resumeObstacleAction();
                    }

                    if (obstacle3 != null) {
                        obstacle3.getComponent("Obstacle").resumeObstacleAction();
                    }
                }

                self.funcNode.runAction(cc.sequence(cc.delayTime(0.5), cc.callFunc(callback1, this)));
            } else {
                countDown--;
                countDownLabel.getComponent("cc.Label").string = countDown;
                countDownLabel.runAction(cc.sequence(cc.delayTime(1), cc.callFunc(callback, this)));
            }

        }
        countDownLabel.runAction(cc.sequence(cc.delayTime(1), cc.callFunc(callback, this)));
    },

    onChallengeBtn: function () {
        var sharedesc = "";
        sharedesc = '我的布丁穿过了' + this.sumScore + '个障碍物，快来挑战我吧！';
        var data = {
            titleData: sharedesc,
            imgurlData: UserInfo.shareUrl,
            queryData: 'pp=pp'
        }
        QQCommon.ShareAppMessage(data, null);
    },

    onShareBtn: function () {
        //接分享
        if (CC_WECHATGAME && cc.vv.isRank) {
            var data = {
                titleData: UserInfo.shareDesc,
                imgurlData: UserInfo.shareUrl,
                queryData: 'pp=pp'
            }
            
            QQCommon.ShareAppMessage(data, () => {
				var gameOverNode = this.node.getChildByName("GameOver");
				var countDownLabel = gameOverNode.getChildByName("ShareNode").getChildByName("EndCountDownLabel");
				countDownLabel.stopAllActions();
				this.continueGame();

				cc.audioEngine.playMusic(this.gamebgMusic, true);
			});
        } else {
            var gameOverNode = this.node.getChildByName("GameOver");
            var countDownLabel = gameOverNode.getChildByName("ShareNode").getChildByName("EndCountDownLabel");
            countDownLabel.stopAllActions();
            this.continueGame();

            cc.audioEngine.playMusic(this.gamebgMusic, true);
        }

    },

    onWatchVideoBtn: function () {
        var gameOverNode = this.node.getChildByName("GameOver");
        var countDownLabel = gameOverNode.getChildByName("ShareNode").getChildByName("EndCountDownLabel");


        if (CC_WECHATGAME && window.wx.createRewardedVideoAd) {
            this.bShare = false;
            countDownLabel.stopAllActions();

            if (this.debugErrorTips) {
                this.showWatchVdError();
                return;
            }

            let videoAd = wx.createRewardedVideoAd({
                adUnitId: 'adunit-563ed529855c1195'
            })

            videoAd.onClose(res => {
                // 用户点击了【关闭广告】按钮
                // 小于 2.1.0 的基础库版本，res 是一个 undefined
                if (res && res.isEnded || res === undefined) {
                    // 正常播放结束，可以下发游戏奖励
                    this.continueGame();
                    cc.audioEngine.playMusic(this.gamebgMusic, true);
                } else {
                    // 播放中途退出，不下发游戏奖励
                    this.startFinishCount();
                }
            })

            videoAd.onError(res => {
                wx.showToast({
                    title: "拉取视频广告失败",
                    icon: "none"
                })


            })

            videoAd.load()
                .then(() => videoAd.show())
                .catch(err => {
                    videoAd.load()
                        .then(() => videoAd.show())
                })
        } else {

        }
    },

    showWatchVdError: function () {
        if (CC_WECHATGAME) {
            wx.showModal({
                title: "提示",
                content: "拉取视频广告失败，邀请好友一起通关可获得一次复活机会",
                showCancel: false,
                cancelText: "取消",
                confirmText: "确定",
                success: () => {
                    var gameOverNode = this.node.getChildByName("GameOver");
                    var shareNode = gameOverNode.getChildByName("ShareNode");
                    //显示邀请好友按钮
                    shareNode.getChildByName("ShareBtn").active = true;
                    shareNode.getChildByName("VideoBtn").active = false;
                    this.startFinishCount();
                }
            })
        }
    },

    //分享到群复活
    comeBack: function (shareTickets) {
        //console.log("我又回来啦");
        if (!UserInfo.IsEmpty(shareTickets)) {
            let currentShareCount = parseInt(UserInfo.getString("shareWXCount"));
            if (currentShareCount > 0) {
                currentShareCount--;
                UserInfo.setString("shareWXCount", currentShareCount);

                var gameOverNode = this.node.getChildByName("GameOver");
                var countDownLabel = gameOverNode.getChildByName("ShareNode").getChildByName("EndCountDownLabel");
                countDownLabel.stopAllActions();
                this.continueGame();

                cc.audioEngine.playMusic(this.gamebgMusic, true);

                if (UserInfo.platform == 1 && cc.vv.isRank) {
                    wx.postMessage({
                        method: 'hideRank',
                        data: "false"
                    });
                    this.PHB.active = false;
                }

            } else {
                UserInfo.setString("shareWXCount", 0);
            }
        }
    },

    onPassBtn: function () {
        var gameOverNode = this.node.getChildByName("GameOver");
        var countDownLabel = gameOverNode.getChildByName("ShareNode").getChildByName("EndCountDownLabel");
        countDownLabel.stopAllActions();

        gameOverNode.getChildByName("ShareNode").active = false;
        gameOverNode.getChildByName("EndNode").active = true;

        this.gameOver();

        var data = [{
            key: UserInfo.getCurWeekScoreValue(),
            value: UserInfo.getScore().toString()
        },
        {
            key: "driLevel",
            value: '0'
        }
        ];

        if (CC_WECHATGAME && cc.vv.isRank) {
            // window.deadBanner.hide();
            this.rankScene.status = 3;
            this.showRank();
            this.updateXYXScore('showMyRank', data);
        }
    },

    onRestartBtn: function () {
        this.node.getChildByName("GameOver").active = false;
        this.node.parent.getChildByName("PHB").active = false;
        // window.accountBanner.hide();
        this.startGame();
    },

    onShopBtn: function () {

    },

    onRankBtn: function (event, optData) {
        if (CC_WECHATGAME && cc.vv.isRank) {
            wx.postMessage({
                method: 'showFriendRank',
                data: optData
            });

            this.node.parent.getChildByName("PHB").getChildByName("BtnPHBClose").active = (optData == "true");
            this.node.parent.getChildByName("PHB").getChildByName("emptyBtn").active = (optData == "true");
            this.node.parent.getChildByName("PHB").getChildByName("bg").active = (optData == "true");

            if ("true" == optData) {
                this.rankScene.status = 1;
                // window.accountBanner.hide();
                this.showRank();
            }
            if ("false" == optData) {
                wx.postMessage({
                    method: 'hideRank',
                    data: optData
                });
                this.PHB.active = false;
                // window.accountBanner.show();
            }
        }
    },

    updateXYXScore(strFun, data) {
        data.push({
            key: "starrank",
            value: JSON.stringify({
                "wxgame": {
                    "score": UserInfo.getScore().toString(),
                    "update_time": Date.now()
                }
            })

            // value: UserInfo.getScore().toString()
        })
        wx.setUserCloudStorage({
            KVDataList: data,
            success: function (res) {
                wx.postMessage({
                    method: strFun
                });
            },
            fail: function (res) {
                console.error(res);
            },
            complete: function (res) { }
        })
    },

    showRank() {
        console.log('this.rankScene.status:', this.rankScene.status)
        if (UserInfo.platform == 1 && cc.vv.isRank) {
            var slotNode;
            switch (this.rankScene.status) {
                case 2:
                    this.rankNode.active = true;
                    this.myRankNode.active = false;
                    break;
                case 1:
                    this.rankNode.active = true;
                    this.myRankNode.active = false;

                    slotNode = this.friendContentNode;
                    renderSharedCanvas.call(this);
                    break;
                case 3:
                    this.rankNode.active = false;
                    this.myRankNode.active = true;
                    slotNode = this.myRankNode;
                    renderSharedCanvas.call(this);
                    break;
            }

            this.PHB.active = true;
            this.node.getChildByName("Pass").active = false;

            function renderSharedCanvas() {
                let openDataContext = wx.getOpenDataContext();
                let sharedCanvas = openDataContext.canvas;
                this.feiendtex.initWithElement(sharedCanvas);
                this.feiendtex.handleLoadedTexture();

                slotNode.getComponent(cc.Sprite).spriteFrame = new cc.SpriteFrame(this.feiendtex);
                var scale = Math.min(750 / this.feiendtex.width, 1334 / this.feiendtex.height);
                slotNode.setContentSize(this.feiendtex.width * scale, this.feiendtex.height * scale);
            }
        }
    },

    onHonourBtn: function () {

    },

    onMoreGameBtn: function (optData) {
        var endNode = this.node.getChildByName("GameOver").getChildByName("EndNode");
        endNode.getChildByName("ChallengeBtn").getComponent("cc.Button").interactable = (optData == "false");
        endNode.getChildByName("RestartBtn").getComponent("cc.Button").interactable = (optData == "false");
        endNode.getChildByName("SkinBtn").getComponent("cc.Button").interactable = (optData == "false");
        endNode.getChildByName("RankBtn").getComponent("cc.Button").interactable = (optData == "false");
        endNode.getChildByName("MoreGameBtn").getComponent("cc.Button").interactable = (optData == "false");
        endNode.getChildByName("HonourBtn").getComponent("cc.Button").interactable = (optData == "false");
    },

    onBackHomeBtn: function () {
        // window.accountBanner.hide();
        this.node.getChildByName("GameOver").active = false;
        this.node.parent.getChildByName("PHB").active = false;
        this.node.parent.getComponent("SenceManager").enterSence("Game", "Home");
        // window.indexBanner.show();
    },

    onBtnAudio: function () {
        cc.audioEngine.playEffect(this.buttonAudio);
    },

    update: function (dt) {
        if (this.PHB.active) {
            this.showRank();
            // console.log("显示排行榜");
        }

        // if (this.node.getChildByName("Pass").active) 
        // {
        //     this.showPass();
        // }

    },
});
