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

var Sdk = require('../Sdk/sdk')

cc.Class({
    extends: cc.Component,

    properties: {
        gamebgMusic: {
            default: null,
            url: cc.AudioClip
        },

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

        SignAtlas: {
            default: null,
            type: cc.SpriteAtlas,
        },

        ShareStrategyNode: { //游戏攻略图片节点
            default: null,
            type: cc.Node
        },

        feiendtex: null,

        otherGamesIndex: 0,

        skinIndex: 0
    },

    // LIFE-CYCLE CALLBACKS:

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


        if (CC_WECHATGAME) {
            this.WxLogin();
            this.initShare();
            // wx.setPreferredFramesPerSecond(30);
        }

        this.listenGame();

        //SDK接入
        if (CC_WECHATGAME) {
            var sdk = new Sdk('布丁弹一弹')
            sdk.showAdIcon(-300, -150, this.node);
            var launchOptions = wx.getLaunchOptionsSync();
            console.log(launchOptions.scene);
            sdk.initSdk(launchOptions.scene);
        }
    },

    start() {
        this.feiendtex = new cc.Texture2D();
    },

    WxLogin() {
        if (UserInfo.platform != 1) {
            return;
        }
        wx.login({
            success: function (res) {
                if (res.code) {
                    var js_code = res.code;
                } else {
                    console.log('登录失败！' + res.errMsg)
                }
            }
        });
    },

    initShare(data) {
        let datavalue = UserInfo.getString('allscore');
        let key = UserInfo.getCurWeekScoreValue();
        if (UserInfo.IsEmpty(datavalue)) {
            UserInfo.setString('allscore', key);
            return;
        }
        let datalist = datavalue.split('*');
        let removeIndex = -1;
        for (let index = 0; index < datalist.length; ++index) {
            if (key == datalist[index]) {
                // UserInfo.removeString(datalist[index]);
                removeIndex = index;
            }
        }

        if (removeIndex != -1) {
            datalist.splice(removeIndex, 1);
        }
        WxCommon.RemoveUserCloudStorage(datalist, this, this.RemoveScoreKey);
        // this.RemoveScoreKey(datalist, true);
    },

    listenGame() {
        if (CC_WECHATGAME) {
            // var date = UserInfo.GetNowFormatDate();
            this.OnUpdateGame();
            WxCommon.SetEnableDebug(false);
            WxCommon.OnShow(null, this, null);
            WxCommon.ShowShareMenu();
            WxCommon.OnShareAppMessage(null, this, this.shareCallback);
            WxCommon.GetSystemInfo(null, this, null);
        }
    },

    OnUpdateGame() {
        const updateManager = wx.getUpdateManager()

        updateManager.onCheckForUpdate(function (res) {
            // 请求完新版本信息的回调
            console.log(res.hasUpdate)
        })

        updateManager.onUpdateReady(function () {
            wx.showModal({
                title: '更新提示',
                content: '新版本已经准备好，是否重启应用？',
                success: function (res) {
                    if (res.confirm) {
                        // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                        updateManager.applyUpdate()
                    }
                }
            })

        })

        updateManager.onUpdateFailed(function () {
            // 新的版本下载失败
        })
    },

    onRankBtn: function (event, optData) {
        if (UserInfo.platform != 1 || !cc.vv.isRank) {
            return;
        }

        wx.postMessage({
            method: 'showFriendRank',
            data: optData
        });

        cc.find("Canvas/PHB").getChildByName("BtnPHBClose").active = (optData == "true");
        cc.find("Canvas/PHB").getChildByName("emptyBtn").active = (optData == "true");
        cc.find("Canvas/PHB").getChildByName("bg").active = (optData == "true");

        if (this.node.active) {
            if ("true" == optData) {
                this.showRank();
            }
            if ("false" == optData) {
                wx.postMessage({
                    method: 'hideRank',
                    data: optData
                });
                cc.find("Canvas/PHB").active = false;
            }
        }

    },

    showRank() {
        if (CC_WECHATGAME && cc.vv && cc.vv.isRank) {

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

            cc.find("Canvas/PHB").getChildByName("feiendrank").getComponent(cc.Sprite).spriteFrame = new cc.SpriteFrame(this.feiendtex);
            //cc.find("Canvas/PHB").getChildByName("feiendrank").setContentSize(720,1280);
            var scale = Math.min(750 / this.feiendtex.width, 1334 / this.feiendtex.height);
            cc.find("Canvas/PHB").getChildByName("feiendrank").setContentSize(this.feiendtex.width * scale, this.feiendtex.height * scale);

            cc.find("Canvas/PHB").active = true;
        }
    },


    update: function () {
        if (cc.find("Canvas/PHB").active) {
            this.showRank();
        }
    },

    onGameStartBtn: function () {
        this.node.parent.getChildByName("SkinNode").active = false;

        if (this.skinIndex != UserInfo.getSkinIndex()) {
            UserInfo.setSkinIndex(this.skinIndex);
        }

        if (this.node.active) {
            cc.audioEngine.stopMusic(this.gamebgMusic);
            this.node.parent.getComponent("SenceManager").enterSence("Home", "Game");
        } else {
            this.node.parent.getChildByName("Game").getComponent("GameSence").onRestartBtn();
        }
    },

    onSkinBtn: function (event, optData) {
        if (optData == "true") {
            this.node.parent.getChildByName("SkinNode").active = true;
            this.skinIndex = UserInfo.getSkinIndex();
            var sumScoreLabel = this.node.parent.getChildByName("SkinNode").getChildByName("SumScoreSp").getChildByName("SumScoreLabel");
            sumScoreLabel.getComponent("cc.Label").string = UserInfo.getTotalGold();

            this.updateSkinNode();
        } else if (optData == "false") {
            this.node.parent.getChildByName("SkinNode").active = false;
        }
    },

    updateSkinNode: function () {
        var skinNode = this.node.parent.getChildByName("SkinNode");
        if (this.skinIndex == 0) {
            skinNode.getChildByName("RightBtn").active = true;
            skinNode.getChildByName("LeftBtn").active = false;
        } else if (this.skinIndex == cfg.skinTypePath.length - 1) {
            skinNode.getChildByName("RightBtn").active = false;
            skinNode.getChildByName("LeftBtn").active = true;
        } else {
            skinNode.getChildByName("RightBtn").active = true;
            skinNode.getChildByName("LeftBtn").active = true;
        }

        var skSpine = skinNode.getChildByName("skSprite");
        skSpine.getComponent("sp.Skeleton").setSkin("p" + (this.skinIndex + 1));

        //var self = this;
        //cc.loader.loadRes(cfg.skinTypePath[self.skinIndex],cc.SpriteFrame,function(err,spriteFrame){
        //var skinsp = skinNode.getChildByName("SkinSp");
        //skinsp.getComponent("cc.Sprite").spriteFrame = spriteFrame;

        var condition1 = skinNode.getChildByName("Condition1");
        var condition2 = skinNode.getChildByName("Condition2");
        var lockerSp = skinNode.getChildByName("LockerSp");
        var playBtn = skinNode.getChildByName("PlayBtn");
        var unlockSp = skinNode.getChildByName("UnlockSp");
        if (this.skinIndex > 0) {
            if (cfg.skinCondition[this.skinIndex].scoreType == 0) {
                var historyScore = UserInfo.getHistoryScore();
                if (historyScore >= cfg.skinCondition[this.skinIndex].score) {
                    condition1.active = false;
                    condition2.active = false;
                    unlockSp.active = true;
                    lockerSp.active = false;
                    playBtn.active = true;
                } else {
                    condition1.active = true;
                    condition2.active = false;
                    unlockSp.active = false;
                    lockerSp.active = true;
                    playBtn.active = false;

                    condition1.getChildByName("ConditionLabel").getComponent("cc.Label").string = historyScore + "." + cfg.skinCondition[this.skinIndex].score;
                }

            } else if (cfg.skinCondition[this.skinIndex].scoreType == 1) {
                var sumScore = UserInfo.getTotalGold();
                if (sumScore >= cfg.skinCondition[this.skinIndex].score) {
                    condition1.active = false;
                    condition2.active = false;
                    unlockSp.active = true;
                    lockerSp.active = false;
                    playBtn.active = true;
                } else {
                    condition1.active = false;
                    condition2.active = true;
                    unlockSp.active = false;
                    lockerSp.active = true;
                    playBtn.active = false;

                    condition2.getChildByName("ConditionLabel").getComponent("cc.Label").string = cfg.skinCondition[this.skinIndex].score;
                }
            }
        } else {
            condition1.active = false;
            condition2.active = false;
            lockerSp.active = false;
            playBtn.active = true;
            unlockSp.active = true;
        }


        //})
    },

    onNextBtn: function (event, optData) {
        if (optData == "right") {
            this.skinIndex++;
        } else if (optData = "left") {
            this.skinIndex--;
        }

        this.updateSkinNode();
    },

    onHonourBtn: function () {

    },

    onMoreBtn: function (event, optData) {
        if(CC_WECHATGAME) {
            wx.navigateToMiniProgram({
                appId: "wx582548bc3a843fed",
                path: "pages/index",
                extraData: {
                    fromGame: "budinggame"
                }
            })
        } else {
            if (this.node.active) {
                this.node.getChildByName("GameStartBtn").getComponent("cc.Button").interactable = (optData == "false");
                this.node.getChildByName("SkinBtn").getComponent("cc.Button").interactable = (optData == "false");
                this.node.getChildByName("HonourBtn").getComponent("cc.Button").interactable = (optData == "false");
                this.node.getChildByName("RankBtn").getComponent("cc.Button").interactable = (optData == "false");
                this.node.getChildByName("MoreBtn").getComponent("cc.Button").interactable = (optData == "false");
            } else {
                this.node.parent.getChildByName("Game").getComponent("GameSence").onMoreGameBtn(optData);
            }
    
            this.ShareStrategyNode.active = (optData == "true");
    
            if (optData == "true") {
                this.createTimer();
            }
        }
    },

    //微信分享
    onShareBtn: function () {
        if(CC_WECHATGAME) {
            var data = {
                titleData: UserInfo.shareDesc,
                imgurlData: UserInfo.shareUrl
            }
            WxCommon.ShareAppMessage(data, this, null);
        }
    },

    createTimer: function () {
        var self = this;
        var updateOtherGames = function () {
            self.otherGamesIndex = (self.otherGamesIndex + 1 + WxCommon.otherGameCount) % WxCommon.otherGameCount;
            self.ShareStrategyNode.getChildByName("OtherGameBtn").getComponent(cc.Sprite).spriteFrame = self.SignAtlas.getSpriteFrame('games' + self.otherGamesIndex);
            self.createTimer();
        };

        if (this.ShareStrategyNode.active == true) {
            this.timerid = setTimeout(updateOtherGames, 2000);
        }
    },

    onShowOtherGame: function () {
        if (CC_WECHATGAME) {
            var path = WxCommon.otherGameMap.get(this.otherGamesIndex);
            WxCommon.PreviewImage(path, this, this.hideNode);
        }
    },

    killTimer: function () {
        if (this.timerid != null) {
            clearTimeout(this.timerid);
            this.timerid = null;
        }
    },

    hideNode: function () {
        if (this.ShareStrategyNode.active) {
            this.killTimer();
            this.ShareStrategyNode.active = false;

            if (this.node.active) {
                this.node.getChildByName("GameStartBtn").getComponent("cc.Button").interactable = true;
                this.node.getChildByName("SkinBtn").getComponent("cc.Button").interactable = true;
                this.node.getChildByName("HonourBtn").getComponent("cc.Button").interactable = true;
                this.node.getChildByName("RankBtn").getComponent("cc.Button").interactable = true;
                this.node.getChildByName("MoreBtn").getComponent("cc.Button").interactable = true;
            } else {
                this.node.parent.getChildByName("Game").getComponent("GameSence").onMoreGameBtn("false");
            }
        }
    },

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



    // update (dt) {},
});