import Panel from "../views/Panel";
import { Decorator } from "../Decorator/Decorator";
import MButton from "../MUI/MButton";
import Net from "../Global/Net";
import Loading from "../Loading/Loading";
import MItem from "../components/MItem";

interface Record {
    userId: number,
    nickname?: string,
    index: string,
    score: string
}

@Decorator.ClassName("RankListPanel")
export default class RankListPanel extends Panel {
    public toggleCurrent: eui.RadioButton;
    public toggleLast: eui.RadioButton;
    public labelMyNickname: eui.Label;
    public labelMyRank: eui.Label;
    public labelTopScore: eui.Label;
    public labelLotteryDate: eui.Label;
    public labelWinning: eui.Label;
    public btnClose: MButton;
    public scrollerRank: eui.Scroller;
    public dataGroupRank: eui.List;
    public dataGroupReward: eui.DataGroup;

    private rankResponse: any = null;
    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());

        let toggleGroup = new eui.RadioButtonGroup();
        this.toggleCurrent.group = toggleGroup;
        this.toggleLast.group = toggleGroup;
        toggleGroup.addEventListener(eui.UIEvent.CHANGE, (evt: eui.UIEvent) => {
            this.onToggle((evt.target as eui.RadioButtonGroup).selection);
        }, this);

        this.dataGroupRank.itemRenderer = RankItem;

        this.dataGroupReward.itemRenderer = class extends MItem {
            public img: eui.Image;
            public label: eui.Label;
            dataChanged() {
                this.img.source = this.data.icon;
                this.label.text = `第${this.data.startRank}-${this.data.endRank}名`;
            }
        }

        this.netRequest();
    }

    private netRequest() {
        //查询排行榜接口
        Net.sendGet(Net.Url.rankList, undefined, async (res1) => {
            this.dataGroupReward.dataProvider = new eui.ArrayCollection(res1.data.prizeList);

            //记录当前期我的数据
            const cur = res1.data.currentPeriod;
            this.cache.current.me = {
                userId: cur.myUserId,
                score: cur.myScore,
                index: cur.myIndex
            };
            //记录上一期期我的数据
            const last = res1.data.prevPeriod;
            this.cache.last.me = {
                userId: last.myUserId,
                score: last.myScore,
                index: last.myIndex
            };
            this.rankResponse = res1;

            const onceQueryNum = 200;

            //查询当前期排行榜数据
            await new Promise(resolve => {
                Net.sendGet(Net.Url.queryRankListData, {
                    type: cur.type,
                    topN: onceQueryNum
                }, (res2) => {
                    this.cache.current.list = res2.data;
                    resolve();
                }, () => Loading.instace.hide());
            });

            //查询上一期期排行榜数据
            await new Promise(resolve => {
                Net.sendGet(Net.Url.queryRankListData, {
                    type: last.type,
                    topN: onceQueryNum
                }, (res3) => {
                    this.cache.last.list = res3.data;
                    resolve();
                }, () => Loading.instace.hide());
            });

            //查询所有的用户昵称
            //我的
            let userIds = [this.cache.current.me.userId];
            //当前期
            for (let record of this.cache.current.list) {
                userIds.push(record.userId);
            }
            //上一期
            const lastIdsBeginIndex = userIds.length;
            for (let record of this.cache.last.list) {
                userIds.push(record.userId);
            }

            //查询昵称接口
            Net.sendGet(Net.Url.queryNickname, {
                userIds: userIds.join(",")
            }, (res4) => {
                //强制数据类型
                const datas: { userId: string, nickname: string }[] = res4.data;

                try {
                    //获取我的昵称
                    this.setNickname(this.cache.current.me, datas[0]);
                    this.cache.last.me.nickname = this.cache.current.me.nickname;

                    //映射当前期用户的昵称
                    for (let i = 1; i <= lastIdsBeginIndex - 1; i++) {
                        this.setNickname(this.cache.current.list[i - 1], datas[i]);
                    }
                    //映射上一期用户的昵称
                    for (let i = lastIdsBeginIndex; i <= datas.length - 1; i++) {
                        this.setNickname(this.cache.last.list[i - lastIdsBeginIndex], datas[i]);
                    }

                } catch (e) {
                    console.error(e);
                    Loading.instace.hide();
                    return;
                }

                this.setDefaultPage((this.data && this.data.defaultToggle) || 1);
                Loading.instace.hide();
            }, () => Loading.instace.hide());
        }, () => Loading.instace.hide());
    }

    private setDefaultPage(toggle: 1 | 2 | eui.RadioButton) {
        let target: eui.RadioButton = null;
        if (toggle === 1) {
            target = this.toggleCurrent;
        } else if (toggle === 2) {
            target = this.toggleLast;
        } else if (toggle instanceof eui.RadioButton) {
            target = toggle;
        }
        target.selected = true;
        this.onToggle(target);

    }

    private setNickname(record: Record, resData: { userId: string, nickname: string }) {
        if (typeof record.userId == "number" && resData.userId == record.userId.toString()) {
            record.nickname = resData.nickname;
        } else {
            throw "nickname map error";
        }
    }

    onToggle(toggle: eui.RadioButton) {
        if (toggle === this.toggleCurrent) {
            this.refreshPage(this.cache.current.me, this.cache.current.list, this.rankResponse.data.currentPeriod);
        } else if (toggle === this.toggleLast) {
            this.refreshPage(this.cache.last.me, this.cache.last.list, this.rankResponse.data.prevPeriod);
        }
    }

    private refreshPage(myRecord: Record, list: Record[], periodData: {
        openDate: string,
        openFlag: boolean,
        prizeId: string
    }) {
        //我的记录
        this.labelMyNickname.text = "我";
        this.labelMyRank.text = `第${myRecord.index || "未上榜"}名`;
        this.labelTopScore.text = "得分:" + (myRecord.score || "0");

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

        //开奖
        const date = this.formatDate(periodData.openDate);
        this.labelLotteryDate.text = `排行榜奖励${date.month}月${date.day}日开奖`;

        //奖励
        if (periodData.openFlag == true) {
            if (periodData.prizeId)
                this.labelWinning.text = "恭喜你中奖啦\n奖励已发放至您的账户，请注意查收～";
            else
                this.labelWinning.text = "很遗憾未中奖\n再接再厉哦~"
        } else {
            this.labelWinning.text = "";
        }
    }

    private formatDate(date: string): { month: string, day: string } {
        const out = { month: "", day: "" }
        if (date[4] != "0") {
            out.month += date[4];
        }
        out.month += date[5];
        if (date[6] != "0") {
            out.day += date[6];
        }
        out.day += date[7];
        return out;
    }
}

class RankItem extends MItem {
    public imgRankBg: eui.Image;
    public labelRank: eui.Label;
    public labelNickname: eui.Label;
    public labelScore: eui.Label;
    data: Record;

    dataChanged() {
        this.labelRank.text = this.data.index || "";
        this.labelScore.text = "得分:" + this.data.score || "0";
        this.labelNickname.text = this.data.nickname || "-";

        const rankNum = parseInt(this.data.index);
        if (rankNum <= 3 && rankNum >= 1) {
            this.imgRankBg.source = RES.getRes(`rank${rankNum}_png`);
            this.labelRank.visible = false;
        }
    }
}