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";
import { MConfigs } from "../Global/MConfigs";

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

const onceQueryNum = 100;

@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;
    public labelSpTIP: eui.Label;
    public btnView: MButton;

    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.btnView.onTap(this, () => {
            window.location.href = MConfigs.rewardRecordUrl;
        });
        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 queryNickname(ids: number[]) {
        return new Promise<{ [key: string]: string }>(async (resolve) => {
            let out: { [key: string]: string } = {};
            while (ids.length > 0) {
                const queryIds = ids.splice(0, onceQueryNum);
                await this.onceQueryNickname(queryIds, out);
            }
            resolve(out);
        });
    }

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

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

            //记录当前期我的数据
            if (res1.data.prevLastFlag == false) {
                const cur = res1.data.currentPeriod;
                this.cache.current.me = {
                    userId: cur.myUserId,
                    score: cur.myScore,
                    index: cur.myIndex
                };
                //查询当前期排行榜数据
                await new Promise(resolve => {
                    Net.sendGet(Net.Url.queryRankListData, {
                        type: cur.type,
                        topN: 200
                    }, (res2) => {
                        this.cache.current.list = res2.data;
                        resolve();
                    }, true);
                });
                //查询当前期用户昵称
                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];
                    }
                }
            }

            //记录上一期期我的数据
            if (res1.data.currentFirstFlag == false) {
                const last = res1.data.prevPeriod;
                this.cache.last.me = {
                    userId: last.myUserId,
                    score: last.myScore,
                    index: last.myIndex
                };
                //查询上一期期排行榜数据
                await new Promise(resolve => {
                    Net.sendGet(Net.Url.queryRankListData, {
                        type: last.type,
                        topN: 200
                    }, (res3) => {
                        this.cache.last.list = res3.data;
                        resolve();
                    }, true);
                });
                const lastList = this.cache.last.list;
                if (lastList.length > 0) {
                    let lastIds = [];
                    for (let record of lastList) {
                        lastIds.push(record.userId);
                    }
                    let lastNicknameObj = await this.queryNickname(lastIds);
                    for (let i in lastList) {
                        lastList[i].nickname = lastNicknameObj[lastList[i].userId];
                    }
                }
            }

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

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

    }

    onToggle(toggle: eui.RadioButton) {
        this.labelSpTIP.visible = false;
        this.dataGroupRank.visible = true;
        this.dataGroupReward.visible = true;
        this.labelLotteryDate.visible = true;

        if (toggle === this.toggleCurrent) {
            if (this.rankResponse.data.prevLastFlag) {
                this.labelSpTIP.visible = true;
                this.labelSpTIP.text = "活动已结束，无本期榜单数据哦";
                this.dataGroupReward.visible = false;
                this.labelLotteryDate.visible = false;
                this.setNullRank();
                this.btnView.visible = false;
                this.labelWinning.visible = false;
            } else {
                this.refreshPage(this.cache.current.me, this.cache.current.list, this.rankResponse.data.currentPeriod);
            }

        } else if (toggle === this.toggleLast) {
            if (this.rankResponse.data.currentFirstFlag) {
                this.labelSpTIP.visible = true;
                this.labelSpTIP.text = "本活动为第一期，无上期榜单信息哦~";
                this.dataGroupReward.visible = false;
                this.labelLotteryDate.visible = false;
                this.setNullRank();
                this.btnView.visible = false;
                this.labelWinning.visible = false;
            } else {
                this.refreshPage(this.cache.last.me, this.cache.last.list, this.rankResponse.data.prevPeriod);
            }
        }
    }

    private setNullRank() {
        this.labelMyNickname.text = "";
        this.labelMyRank.text = "";
        this.labelTopScore.text = "";
        this.dataGroupRank.visible = false;
    }

    private refreshPage(myRecord: Record, list: Record[], periodData: {
        openDate: string,
        openFlag: boolean,
        prizeId: string
    }) {
        //开奖
        const date = this.formatDate(periodData.openDate);
        this.labelLotteryDate.text = `排行榜奖励${date.month}月${date.day}日11:00开奖`;

        if (!list || list.length <= 0) {
            this.labelSpTIP.visible = true;
            this.labelSpTIP.text = "暂无榜单数据";
            this.setNullRank();
            return;
        }

        //我的记录
        this.labelMyNickname.text = "我";
        this.labelMyRank.text = typeof myRecord.index == "number" && myRecord.index <= 1000 ? `第${myRecord.index}名` : "未上榜";
        this.labelTopScore.text = "得分:" + (myRecord.score || "0");

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

        //奖励
        if (periodData.openFlag == true) {
            if (periodData.prizeId) {
                if (periodData.prizeId == "thanks") {
                    this.btnView.visible = false;
                    this.labelWinning.visible = true;
                    this.labelWinning.text = "抱歉，您已中过该奖励";
                } else {
                    this.btnView.visible = true;
                    this.labelWinning.visible = true;
                    this.labelWinning.text = "恭喜你中奖啦\n可在我的奖品中查看";
                }
            }
            else {
                this.btnView.visible = false;
                this.labelWinning.visible = true;
                this.labelWinning.text = "很遗憾未中奖\n再接再厉哦～"
            }
        } else {
            this.btnView.visible = false;
            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;
        } else {
            this.labelRank.visible = true;
            this.imgRankBg.source = "rank_other_rank_bg_png";
        }
    }
}