import Panel from "../MViews/MPanel";
import { Decorator } from "../Decorator/Decorator";
import MButton from "../MUI/MButton";
import Net from "../Global/Net";
import Loading from "../../loading/Loading";
import MItem from "../MComponents/MItem";
import MLabel from "../MUI/MLabel";
import { MConfigs } from "../Global/MConfigs";
import ToastPanel from "../MComponents/MToastPanel";

interface Record {
    userId: number,
    nickname?: string,
    index: number,
    score: string
}
// const onlineDate = new Date(MConfigs.onlineDate);
//一次查前100名
const onceQueryNum = 100;

@Decorator.ClassName("RankListPanel")
export default class RankListPanel extends Panel {

    public labelMyNickname: MLabel;
    public labelMyRank: MLabel;
    public labelTopScore: MLabel;

    public btnClose: MButton;
    public scrollerRank: eui.Scroller;
    public dataGroupRank: eui.List;

    public data: {
        defaultToggle: 1 | 2
    }
    private cache: {
        current: {
            me: Record,
            list: Record[],
        },
        last: {
            me: Record,
            list: Record[],
        }
    } = {
            current: {
                me: null,
                list: [],
            },
            last: {
                me: null,
                list: [],
            }
        };




    onSkinComplete() {
        super.onSkinComplete();
        Loading.instace.show();
        this.btnClose.onTap(this, () => this.hidePanel());

        this.dataGroupRank.itemRenderer = RankItem;

        this.netRequest();
    }



    private netRequest() {
        //查询排行榜接口
        Net.sendGet(Net.Url.rankInfo, undefined, async (res1) => {
            // const cur = res1.data.currentPeriod;
            //记录当前期我的数据
            this.cache.current.me = {
                userId: res1.data.userId,
                score: res1.data.maxScore,
                index: res1.data.index,
                nickname: res1.data.nickName,
            };
            //查询当前期排行榜数据
            await new Promise(resolve => {
                Net.sendGet(Net.Url.queryRankListData, {
                    type: res1.data.type,
                    topN: onceQueryNum
                }, (res2) => {
                    this.cache.current.list = res2.data;
                    resolve();
                }, () => Loading.instace.hide());
            });
            //查询我的用户昵称
            // let myId = this.cache.current.me.userId;
            // let obj = await this.queryNickname([myId]);
            // this.cache.current.me.nickname = obj[myId.toString()];
            //查询当前期用户昵称
            const curList = this.cache.current.list;
            if (curList.length > 0) {
                let curIds = [];
                for (let record of curList) {
                    curIds.push(record.userId);
                }
                let curNicknameObj = await this.queryNickname(curIds);
                for (let i in curList) {
                    curList[i].nickname = curNicknameObj[curList[i].userId];
                }
            }
            //刷新页面
            this.refreshPage(this.cache.current.me, this.cache.current.list);

            Loading.instace.hide(); //操作结束
        }, () => Loading.instace.hide());
    }

    private queryNickname(ids: number[]) {
        return new Promise<{ [key: string]: string }>((resolve) => {
            Net.sendGet(Net.Url.queryNickname, {
                userIds: ids.join(",")
            }, (res) => {
                //强制数据类型
                const datas: { userId: string, nickname: string }[] = res.data;
                let out: { [key: string]: string } = {};
                for (let i of datas) {
                    out[i.userId] = i.nickname;
                }
                resolve(out);
            }, true);
        });
    }

    private refreshPage(myRecord: Record, list: Record[]) {
        if (list.length <= 0) {
            ToastPanel.show("排行榜数据为空");
        }

        //我的记录
        let str = "我";
        if (myRecord.nickname && typeof myRecord.nickname == "string" && myRecord.nickname != "null") {
            str = myRecord.nickname;
        }
        this.labelMyNickname.text = str;

        //我的排名
        let rankText = "未上榜";
        if (myRecord.index && myRecord.index <= 10000) {
            rankText = myRecord.index + "";
        }
        this.labelMyRank.text = rankText;
        this.labelTopScore.text = myRecord.score || "0";

        //设置排行榜数据
        this.dataGroupRank.dataProvider = new eui.ArrayCollection(list);

    }
}

const colors = [
    0xf36455,
    0xff8745,
    0xf7c54e,
    0x7badff,
]

class RankItem extends MItem {
    public numIcon1: eui.Image;
    public numIcon2: eui.Image;
    public numIcon3: eui.Image;
    public groupOtherRank: eui.Group;
    public labelOtherRank: eui.Label;
    public labelNickname: MLabel;
    public labelScore: MLabel;

    data: Record;

    dataChanged() {
        this.numIcon1.visible = false;
        this.numIcon2.visible = false;
        this.numIcon3.visible = false;
        if (this.data.index <= 3 && this.data.index >= 1) {
            // this.labelOtherRank.text = this.data.index.toString() || "-";
            this.groupOtherRank.visible = false;
            this["numIcon" + this.data.index].visible = true;
            this.labelNickname.textColor = colors[this.data.index - 1];
        } else {
            this.labelOtherRank.text = this.data.index.toString() || "-";
            this.groupOtherRank.visible = true;
            this.labelNickname.textColor = colors[3];
        }

        this.labelScore.text = "分数：" + (this.data.score || "0");
        let str = "苏州农商行用户";
        if (this.data.nickname && typeof this.data.nickname == "string" && this.data.nickname != "null") {
            str = decodeURIComponent(this.data.nickname);
        }
        this.labelNickname.text = /*"ID：" +*/ str + "";
    }
}