// Learn TypeScript:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/life-cycle-callbacks.html

import Utils from "./module/Pay/Utils";
import NumberToImage from "./NumberToImage";
import { MiniGameSdk } from "./Sdk/MiniGameSdk";

const { ccclass, property } = cc._decorator;

@ccclass
export default class ranking extends cc.Component {
    @property(cc.SpriteAtlas)
    ui: cc.SpriteAtlas = null;
    @property(cc.Node)
    subContextView: cc.Node = null;
    @property(cc.Node)
    closeButton: cc.Node = null;
    @property(cc.Node)
    btnRanks: cc.Node = null;
    @property(cc.Node)
    selfNode: cc.Node = null;
    @property(cc.SpriteFrame)
    defaultsprite: cc.SpriteFrame = null;
    private isShow: boolean = true;
    wordRank: any[];
    selfInfo: any;
    rankNumber: number = 0;
    _touchCancle: boolean = false;
    // LIFE-CYCLE CALLBACKS:
    onLoad() {
        this.wordRank = [];
        this.selfInfo = null;
        this.rankNumber = 0;
        this._touchCancle = false;
    }
    start() {
    }

    init() {
        this.openLoad();
        this.btnRanks.active = true;
        let user_Info = cc.fx.StorageMessage.getStorage("user_Info");
        if (user_Info != null && user_Info != undefined && user_Info != "") {
            cc.fx.GameConfig.GM_INFO.username = user_Info.username;
            cc.fx.GameConfig.GM_INFO.useravatar = user_Info.useravatar;
            setTimeout(() => {
                if (!this.node.getChildByName("friend").active) {
                    this.onRanksBtnClicked();
                    this.node.getChildByName("friend").active = false;
                    this.node.getChildByName("word").active = true;
                    this.node.getChildByName("word_rank").active = true;
                    this.closeFriend();
                }
                else {

                    this._touchCancle = true;
                    this.openFriend();
                    this.closeWord();
                }
            }, 0);
        }
        else {
            this.onRanksBtnClicked();
        }
        // this.openWord();
    }

    showRanks() {
        if (typeof wx === 'undefined') {
            return;
        }
        this.closeLoad();
        // 设置容器可见
        this.node.getChildByName("rank").active = true;
        this.subContextView.active = true;
        console.log("展示排行榜");
        // 设置随机数(把这个当做玩家每局结算时的分数)

        this.subContextView.getComponent(cc.SubContextView).updateSubContextViewport();
        setTimeout(() => {
            console.log('显示排行榜');
            //@ts-ignore
            wx.getOpenDataContext().postMessage({
                message: cc.fx.GameConfig.GM_INFO.openid
            });
            //@ts-ignore
            wx.getOpenDataContext().postMessage({
                message: parseInt(cc.fx.GameConfig.GM_INFO.level)
            });
            this.subContextView.getComponent(cc.SubContextView).updateSubContextViewport();
        }, 200);
    };

    requestFriendInfo() {

    }


    onRanksBtnClicked() {
        if (typeof wx === 'undefined') {
            this.showRanks(); // 非微信环境直接显示
            return;
        }
        cc.fx.GameTool.getUserAvatar(() => {
            this.showWord(true); // ✅ 授权成功，显示排行榜
            this.isShow = false;
        })

    }
    protected update(dt: number): void {
        // if (this.isShow) {
        //     this.onRanksBtnClicked();
        // }
    }

    closeRanks() {
        // console.log('关闭排行榜');
        this.subContextView.getComponent(cc.SubContextView).updateSubContextViewport();
        this.closeButton.active = false;
        // 设置容器不可见，即关闭排行榜，并让开放域清空排名信息
        this.node.getChildByName("rank").active = false;
        this.subContextView.active = false;
        //@ts-ignore
        wx.getOpenDataContext().postMessage({
            message: 'close'
        });
    }

    closeFriend() {
        // console.log('关闭好有排行榜');
        this.subContextView.getComponent(cc.SubContextView).updateSubContextViewport();
        //@ts-ignore
        wx.getOpenDataContext().postMessage({
            message: 'close'
        });
        // 设置容器不可见，即关闭排行榜，并让开放域清空排名信息
        this.node.getChildByName("rank").active = false;
        this.subContextView.active = false;

    }

    closeWord() {
        // console.log('关闭世界排行榜');
        this.node.getChildByName("word_rank").active = false;
    }

    openFriend() {
        if (!this._touchCancle) {
            return;
        }
        console.log("进入好友排行榜");
        if (cc.fx.GameConfig.GM_INFO.wxFriend == true) {
            console.log("已经授权过好友信息");
            this.showRanks();
        }
        else {
            console.log("未授权过好友信息");
            MiniGameSdk.API.getWechatFriend((data) => {
                console.log("获取好友信息成功?", data);
                if (data == true)
                    this.showRanks();
            })
        }
        this.node.getChildByName("friend").active = true;
        this.node.getChildByName("word").active = false;
        this.closeWord();
    }

    openWord() {
        if (!this._touchCancle) {
            return;
        }
        this.node.getChildByName("friend").active = false;
        this.node.getChildByName("word").active = true;
        this.node.getChildByName("word_rank").active = true;
        this.closeFriend();
        this.showWord(false);
    }

    showWord(type) {
        // console.log("__________进入世界排行榜了");
        if (type) {
            this.wordRank = [];

            Utils.getRank((data) => {
                this.closeLoad();
                if (data.code == 1) {
                    // console.log("获取排行榜数据", data.data.rank);
                    this.wordRank = data.data.rank;
                    this.rankNumber = data.data.index;
                    for (let i = 0; i < this.wordRank.length; i++) {
                        this.wordRank[i].rank = i + 1;
                    }
                    this.node.getChildByName("word_rank").active = true;
                    this.setSelfInfo();
                    this.node.getChildByName("word_rank").getComponent("RankManager").init(this.wordRank);
                }
                else {
                    MiniGameSdk.API.showToast('网络异常，获取排行榜数据失败');
                    this.btnRanks.active = false;
                }
            })
        }
        else {
            // console.log("_______________", this.wordRank.length);
        }

    }

    openLoad() {
        this.node.parent.getChildByName("Loading").active = true;
        this.node.parent.getChildByName("Loading").getChildByName("load").stopAllActions();
        this.node.parent.getChildByName("Loading").getChildByName("load").runAction(cc.rotateTo(2, 1080).repeatForever());
    }

    closeLoad() {
        this.node.parent.getChildByName("Loading").active = false;
        this._touchCancle = true;
    }

    setSelfInfo() {
        this.selfNode.opacity = 0;
        this.selfInfo = null;
        for (let i = 0; i < this.wordRank.length; i++) {
            if (this.wordRank[i]._id == cc.fx.GameConfig.GM_INFO.uid) {
                this.selfInfo = JSON.parse(JSON.stringify(this.wordRank[i]));
                if (this.selfInfo.useravatar == "0" || this.selfInfo.useravatar == "1" || this.selfInfo.useravatar == "2"
                    || this.selfInfo.useravatar == "3") {
                    this.selfInfo.useravatar = "icon_" + this.selfInfo.useravatar;
                }
                this.selfInfo.useravatarIcon = "kuang_" + (parseInt(this.selfInfo.useravatarIcon) + 1);
                console.log("我自己的信息", this.selfInfo);

            }
        }
        if (this.selfInfo == null) {
            if (this.rankNumber == -1 || this.rankNumber == 0) {
                this.rankNumber = 9999;
            }
            this.selfInfo = {
                useravatarIcon: cc.fx.GameConfig.GM_INFO.useravaterkuang,
                useravatar: cc.fx.GameConfig.GM_INFO.useravatarIcon,
                username: cc.fx.GameConfig.GM_INFO.username,
                levelAmount: cc.fx.GameConfig.GM_INFO.level,
                rank: this.rankNumber
            }
            this.selfInfo.useravatar = cc.fx.GameConfig.GM_INFO.useravatarIcon;
            this.selfInfo.useravatarIcon = cc.fx.GameConfig.GM_INFO.useravaterkuang;
        }

        let useravatarIcon = this.selfInfo.useravatarIcon;
        console.log("自己的头像框", useravatarIcon);
        this.selfNode.getChildByName("icon").getComponent(cc.Sprite).spriteFrame =
            this.ui.getSpriteFrame(useravatarIcon);
        this.selfInfo.username = cc.fx.GameTool.subName(this.selfInfo.username, 7);
        let name = this.selfInfo.username;
        if (name == "user") name = "匿名玩家";
        this.selfNode.getChildByName("nameLab").getComponent(cc.Label).string = name + "";

        NumberToImage.numberToImageNodes3((this.selfInfo.rank), 43, 15, "rank_", this.selfNode.getChildByName("rankLab"), true);
        NumberToImage.numberToImageNodes3(this.selfInfo.levelAmount, 43, 15, "level_", this.selfNode.getChildByName("totalLab"), true);
        if (this.selfInfo.rank == 9999) {
            this.selfNode.getChildByName("rankLab").scaleX = 0.75;
            this.selfNode.getChildByName("rankLab").scaleY = 0.75;
            this.selfNode.getChildByName("add").active = true;
        }
        else this.selfNode.getChildByName("add").active = false;
        // this.node.getChildByName("timeLab").getComponent(cc.Label).string = timeTemp + "";
        this.selfNode.getChildByName("rank").getChildByName("one").active = false;
        this.selfNode.getChildByName("rank").getChildByName("two").active = false;
        this.selfNode.getChildByName("rank").getChildByName("three").active = false;
        if (this.selfInfo.rank == 1) {
            this.selfNode.getChildByName("rank").getChildByName("one").active = true;
            this.selfNode.getChildByName("rankLab").active = false;
        }
        else if (this.selfInfo.rank == 2) {
            this.selfNode.getChildByName("rank").getChildByName("two").active = true;
            this.selfNode.getChildByName("rankLab").active = false;
        }
        else if (this.selfInfo.rank == 3) {
            this.selfNode.getChildByName("rank").getChildByName("three").active = true;
            this.selfNode.getChildByName("rankLab").active = false;
        } else {
            this.selfNode.getChildByName("rankLab").active = true;
        }
        console.log("自己的他头像:", this.selfInfo.useravatar);
        if (this.selfInfo.useravatar == "" || this.selfInfo.useravatar == null || this.selfInfo.useravatar == undefined
        ) {
            this.selfNode.getChildByName("pic").getComponent(cc.Sprite).spriteFrame = this.defaultsprite;
        }
        else if (this.selfInfo.useravatar == "icon_0" || this.selfInfo.useravatar == "icon_1" || this.selfInfo.useravatar == "icon_2"
            || this.selfInfo.useravatar == "icon_3") {
            let useravatar = this.selfInfo.useravatar;
            this.selfNode.getChildByName("pic").getComponent(cc.Sprite).spriteFrame = this.ui.getSpriteFrame(useravatar);
        }
        else this.setPic();
        this.selfNode.opacity = 255;
    }

    public setPic() {
        // console.log("设置头像:", this.selfInfo.useravatar);
        // this.node.getChildByName("pic").getChildByName("icon").active = false;
        this.selfNode.getChildByName("pic").active = false;
        var self = this;
        let url = this.selfInfo.useravatar;

        cc.assetManager.loadRemote(url, { ext: '.png' }, (err, texture: cc.Texture2D) => {
            if (texture) {
                this.selfNode.getChildByName("pic").active = true;
                var sprite = this.selfNode.getChildByName("pic").getComponent(cc.Sprite);
                sprite.spriteFrame = new cc.SpriteFrame(texture);
                // console.log(this.data.rank,"设置头像成功",err);
            }
            else {
                // console.log("设置头像失败",url);
                // console.log(err, texture)
            }
        })
    }

    // update (dt) {}
}
