import GameData from "./GameData";
import List from "./ListView/List";
import HttpUtil from "./crypto/HttpUtil";
import { GameTool } from "./tool/GameTool";

const { ccclass, property } = cc._decorator;
//排行榜
@ccclass
export default class RankManager extends cc.Component {
    @property(cc.Node)          //用户上方头像
    Player: cc.Node = null;
    @property(cc.Node)          //用户最下方个人信息
    selfNode: cc.Node = null;
    @property(cc.Sprite)        //用户头像换图
    phone: cc.Sprite = null;
    private rankList: List;     //排行榜
    tween: cc.Tween<cc.Node>;   //最上方用户头像动画
    listData: any;              //总列表信息
    selfData: any;              //自己信息
    rankNumber: number;         //用户自己排名 有可能不在排行榜内99+
    rankTotal: number;          //获取排行榜用户数量 现在为100

    onLoad() {
        this.init();
    }
    //初始化数据
    init(){
        this.rankList = cc.find("ScrollView", this.node).getComponent(List);
        this.Player.getChildByName("rank").active = false;
        this.listData = [];
        this.selfData = null;
        this.rankNumber = 100;
        this.rankTotal= 100;
        this.selfNode.opacity = 0;
        this.fit();
    }

    fit(){
        var jg = GameTool.setFit();
        if(!jg){
            this.node.getChildByName("ScrollView").getChildByName("view").height = 840;
        }
    }

    start() {
        this.Player.active = false;
        this.getRank();
    }
    //调用获取排行榜接口
    getRank(){
        let postData = {
            "page":1,
            "pageSize":100
        }; 
        //回调进getRankData
        HttpUtil.rankData(2,this.getRankData.bind(this),postData);
    }
    //实际设置排行数据
    getRankData(data){
        if(data){
            // console.log(data);
            this.listData = data.data.list;
            this.selfData = data.data.info;
            let rankData = [];
            let self = false;
            for(let i=0;i<=this.listData.length-1;i++){
                rankData.push({rank:(i+1), name:this.listData[i].nickName, total:this.listData[i].score, pic:this.listData[i].pic});
                if(GameData._instance.GM_INFO.userId == this.listData[i].userId){
                    self = true;
                    this.rankNumber = i;
                    this.selfNode.getChildByName("rankLab").getComponent(cc.Label).string =(i+1) + ""; 
                }
                if(i == (this.listData.length-1) && self == false){
                    this.rankNumber = 101;
                    //如果列表大于99显示99+ 否则显示未排名
                    if(this.listData.length >= 99)this.selfNode.getChildByName("rankLab").getComponent(cc.Label).string = "99+"; 
                    else this.selfNode.getChildByName("rankLab").getComponent(cc.Label).string = "未排名" 
                }
            }
            //如果排行榜列表没有人
            if(this.listData.length == 0) this.selfNode.getChildByName("rankLab").getComponent(cc.Label).string = "未排名" 
            this.rankList.setData(rankData);
            if(this.selfData.nickName.length > 6){
                this.selfData.nickName= this.selfData.nickName.substring(0,6) + "..."
            }
            this.selfNode.getChildByName("nameLab").getComponent(cc.Label).string = this.selfData.nickName;
            //如果没有排行分数信息
            if(this.selfData.score){
                this.selfNode.getChildByName("totalLab").getComponent(cc.Label).string = this.selfData.score;
            }
            this.setPic(this.selfData.pic);
            if(this.selfNode.getChildByName("rankLab").getComponent(cc.Label).string == "1"){
                this.selfNode.getChildByName("rank").getChildByName("one").active = true;
            }
            else if(this.selfNode.getChildByName("rankLab").getComponent(cc.Label).string == "2"){
                this.selfNode.getChildByName("rank").getChildByName("two").active = true;
            }
            else if(this.selfNode.getChildByName("rankLab").getComponent(cc.Label).string == "3"){
                this.selfNode.getChildByName("rank").getChildByName("three").active = true;
            }
            else{
                // this.selfNode.getChildByName("four").active = true;
            }
            this.selfNode.opacity = 255;
            if(this.selfData.score == 0) this.selfNode.opacity = 0;
        }
    }
    //返回按钮
    backClick(){
        cc.director.loadScene("LoadScene");
    }
    //最上方用户动画
    playerAction(){
        //-254 377  210 453
        this.Player.getChildByName("rank").active = false;
        let time = 1;
        this.tween = cc.tween(this.Player)
        .to(2,{position:cc.v3(210,535,0)})
        .call(() =>{
            this.Player.getChildByName("rank").active = true;
            this.Player.getChildByName("rank").getChildByName("number")
            .getComponent(cc.Label).string =  parseInt(time*100 + "") + "%";
        })
        .start();

        if(this.listData.length > 0){
            if(this.listData.length >= 99){
                if(this.rankNumber >= 99){
                    time = this.getRankRandom();
                }
                else  time = (this.listData.length - this.rankNumber)/this.listData.length;
            }
            else{
                if(this.rankNumber > 99){
                    time = 0
                }
                else time = (this.listData.length - this.rankNumber)/this.listData.length;
            }
        }
        else{
            time = 0;
        }
        setTimeout(() => {
            if(this.tween)this.tween.stop();
            if(this.Player){
                this.Player.getChildByName("rank").active = true;
                this.Player.getChildByName("rank").getChildByName("number")
                .getComponent(cc.Label).string =  parseInt(time*100 + "") + "%";
            }
        }, time*2000);
    }

    getRankRandom(){
        let time = (Math.random()*49+1)/100
        var matchId = cc.sys.localStorage.getItem("matchNumber");
        if(matchId == null || matchId == undefined){
            time = 0;
        }
        return time;
    }

    //设置头像
    public setPic(pic){
        this.phone.node.parent.getChildByName("icon").active = false;
        this.phone.node.active = false;
        this.Player.active = true;
        this.Player.opacity = 0;
        this.Player.getChildByName("mask").getChildByName("icon").active = false;
        this.Player.getChildByName("mask").getChildByName("phone").active = false;
        fetch(pic)
        .then(response => {
            return response.headers.get('Content-Length');
        })
        .then(errNo => {
            if(errNo == "5093"){
                this.phone.node.parent.getChildByName("icon").active = true;
                this.Player.getChildByName("mask").getChildByName("icon").active = true;
            }
        })
        .catch(error => {
            // console.error('Error fetching X-Info:', error);
        });
        var self = this;
        cc.assetManager.loadRemote(pic, {ext:'.png'},(err, texture:cc.Texture2D) => {
            self.Player.opacity = 255;
            if(texture){
                self.phone.node.active = true;
                self.phone.spriteFrame = new cc.SpriteFrame(texture);
                self.Player.getChildByName("mask").getChildByName("icon").active = false;
                self.Player.getChildByName("mask").getChildByName("phone").active = true;
                self.Player.getChildByName("mask").getChildByName("phone").getComponent(cc.Sprite)
                .spriteFrame = new cc.SpriteFrame(texture);
                setTimeout(() => {
                    self.playerAction();
                }, 500);
            }
            else{
                self.Player.getChildByName("mask").getChildByName("icon").active = true;
                setTimeout(() => {
                    self.playerAction();
                }, 500);
            }
        })
    }
}
