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

cc.Class({
    extends: cc.Component,

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

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

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

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

        feiendtex: null,

        otherGamesIndex: 0,

        skinIndex: 0,

        showGuideValue: true
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad() {
        cc.audioEngine.playMusic(this.gamebgMusic, true);
		if(CC_QQPLAY && window.GameStatusInfo) {
			GameStatusInfo.startMs = ((new Date()).getTime()).toString()
		}
		
		// if (CC_QQPLAY) {
		// 	this.QQLogin();
		// 	this.initShare();
		// }
    },

    start() {
        this.feiendtex = 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')
    },

	QQLogin() {
		if(window.GameStatusInfo && window.GameStatusInfo.openId) {
			BK.Console.log('登录成功')
		}
	},

    // 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() {
	// 	// 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) {
        console.log('onrankbtn:', optData)
        // 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) {
                // window.indexBanner.hide();
                this.rankScene.status = 1;
                this.showRank();
            }
            if ("false" == optData) {
                // window.indexBanner.show();
                // wx.postMessage({
                //     method: 'hideRank',
                //     data: optData
                // });
                cc.find("Canvas/PHB").active = false;
            }
        } else {
            this.rankScene.status = 3;
            // window.accountBanner.show();
        }

    },

    showRank() {
		this.myRankNode.active = false;
		this.rankNode.active = true;
		// if (this.rankScene.status == 1) {
		// 	let openDataContext = wx.getOpenDataContext();
		// 	let sharedCanvas = openDataContext.canvas;
		// 	this.feiendtex.initWithElement(sharedCanvas);
		// 	this.feiendtex.handleLoadedTexture();
		// 	this.friendContentNode.getComponent(cc.Sprite).spriteFrame = new cc.SpriteFrame(this.feiendtex);
		// 	var scale = Math.min(750 / this.feiendtex.width, 1334 / this.feiendtex.height);
		// 	this.friendContentNode.setContentSize(this.feiendtex.width * scale, this.feiendtex.height * scale);
		// }
		this.PHB.active = true;
    },


    update: function () {
        
    },

    onGameStartBtn: function () {
        this.node.parent.getChildByName("SkinNode").active = false;
        // window.indexBanner.hide();
        if (this.showGuide()) {
            this.GuideNode.active = true;
        } else {
            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();
            }
        }
    },

    showGuide() {
        if (!this.showGuideValue) return false;
        console.log('show guide');
        
        var key = 'guideTime';
        var guideTime = cc.sys.localStorage.getItem(key);
        var now = new Date();
        var year = now.getFullYear();
        var month = now.getMonth() + 1;
        var date = now.getDate();
        var guideTimeValue = [year, month, date].join('/');

        if (!guideTime || guideTime != guideTimeValue) {
            cc.sys.localStorage.setItem(key, guideTimeValue);
            return false;
        } else {
            this.GuideNode && this.GuideNode.destroy();
            this.showGuideValue = false;
            return false;
        }
    },

    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();
            // window.indexBanner.hide();
        } else if (optData == "false") {
            this.node.parent.getChildByName("SkinNode").active = false;
            // window.indexBanner.show();
        }
    },

    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;
        }


        //})
    },

    onGuideBtn: function (event) {
        this.node.parent.getChildByName("Guide").active = false;
        // window.indexBanner.show();
    },

    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) {
            // objSdk.openGameCenter();
            // 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);
		}
		
		if (CC_QQPLAY) {
			var data = {
                titleData: UserInfo.shareDesc,
                imgurlData: UserInfo.shareUrl
			}
			QQCommon.ShareAppMessage(data, 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) {},
});
