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: number,
    isMe?: boolean
}
// const onlineDate = new Date(MConfigs.onlineDate);
//一次查前100名
const onceQueryNum = 100;

@Decorator.ClassName("RankListPanel")
export default class RankListPanel extends Panel {
    public toggleLast: eui.RadioButton;
    public toggleCurrent: eui.RadioButton;
    public currentBg: eui.Image;
    public lastBg: eui.Image;
    public labelMyNickname: MLabel;
    public labelMyRank: MLabel;
    public labelTopScore: MLabel;
    public labelLotteryDate: eui.Label;
    public btnClose: MButton;
    public scrollerRank: eui.Scroller;
    public dataGroupRank: eui.List;
    public labelCur: eui.Label;
    public labelLast: eui.Label;
    public labelTip: eui.Label;


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

        // this.labelLotteryDate.visible = false;

        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) => {
            let selection = (evt.target as eui.RadioButtonGroup).selection;
            this.onToggle(selection);
        }, this);

        this.dataGroupRank.itemRenderer = RankItem;
        this.netRequest();
    }

    private netRequest() {
        //查询排行榜接口
        Net.sendGet(Net.Url.rankList, undefined, async (res1) => {
            this.rankResponse = res1;

            const cur = res1.data.currentPeriod;
            if (res1.data.prevLastFlag == false && cur != null) {
                //记录当前期我的数据
                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: onceQueryNum
                    }, (res2) => {
                        for (let i in res2.data) {
                            this.cache.current.list[i] = res2.data[i];
                            this.cache.current.list[i].isMe =
                                cur.myIndex == res2.data[i].index;
                        }

                        resolve();
                    }, () => Loading.instace.hide());
                });
                //查询我的用户昵称
                let myId = this.cache.current.me.userId;
                this.cache.current.me.nickname = await this.queryMyNickname(myId);
                //查询当前期用户昵称
                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];
                    }
                }
            } else {
                this.cache.current.list = null;
                this.cache.current.me = null;
            }


            if (res1.data.currentFirstFlag == false && res1.data.prevPeriod != null) {
                const last = res1.data.prevPeriod;
                //记录上一期期我的数据
                let myNickname = "-";
                if (this.cache.current.me) {
                    myNickname = this.cache.current.me.nickname;
                } else {
                    myNickname = await this.queryMyNickname(res1.data.prevPeriod.myUserId);
                }
                this.cache.last.me = {
                    userId: last.myUserId,
                    score: last.myScore,
                    index: last.myIndex,
                    nickname: myNickname
                };

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

                //查询上一期用户昵称
                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];
                    }
                }
            } else {
                this.cache.last.list = null;
                this.cache.last.me = null;
            }

            //设置默认显示页面
            this.setDefaultPage((this.data && this.data.defaultToggle) || 1);
            Loading.instace.hide(); //操作结束
        }, () => Loading.instace.hide());
    }


    private async queryMyNickname(id: number) {
        let obj = await this.queryNickname([id]);
        return obj[id.toString()];
    }
    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 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) {
        if (toggle === this.toggleCurrent) {
            this.currentBg.visible = true;
            this.lastBg.visible = false;
            this.labelCur.textColor = 0x2298FE;
            this.labelLast.textColor = 0xffffff;
            this.refreshPage(this.cache.current.me, this.cache.current.list, this.rankResponse.data.currentPeriod);
        } else if (toggle === this.toggleLast) {
            this.currentBg.visible = false;
            this.lastBg.visible = true;
            this.labelCur.textColor = 0xffffff;
            this.labelLast.textColor = 0x2298FE;
            this.refreshPage(
                this.cache.last.me,
                this.cache.last.list,
                this.rankResponse.data.prevPeriod  //第一周开奖日期
            );
        }
    }

    private refreshPage(myRecord: Record, list: Record[], periodData: { openDate: string }) {
        if (list == null) {
            this.labelTip.visible = true;
            let myRecord = this.cache.current.me || this.cache.last.me;
            let str = "-";
            if (!myRecord.nickname || myRecord.nickname == "null") {
                str = myRecord.userId.toString();
            } else {
                str = myRecord.nickname;
            }

            this.labelMyNickname.text = str;
            this.labelMyRank.text = "-";
            this.labelMyRank.text = "-";
            this.labelTopScore.text = "-";
            this.dataGroupRank.dataProvider = new eui.ArrayCollection([]);
            this.labelLotteryDate.text = "";
            return;
        } else {
            this.labelTip.visible = false;
        }

        //我的记录
        let str = "-";
        if (!myRecord.nickname || myRecord.nickname == "null") {
            str = myRecord.userId.toString();
        } else {
            str = myRecord.nickname;
        }

        this.labelMyNickname.text = str;

        //我的排名
        let rankText = "";
        if (typeof myRecord.index == "number") {
            if (myRecord.index > 1000 || isNaN(myRecord.index)) {
                rankText = "1000+";
            } else {
                rankText = myRecord.index.toString();
            }
        } else {
            rankText = "1000+";
        }
        this.labelMyRank.text = rankText;

        this.labelTopScore.text = typeof myRecord.score == "number" ? myRecord.score.toString() : "-";

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

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

    private formatDate(date: string): { year: string, month: string, day: string } {
        const out = { year: "", month: "", day: "" }
        out.year = date.substr(0, 4);
        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 groupTopRank: eui.Group;
    public imgBg: eui.Image;
    public labelOtherRank: eui.Label;
    public labelNickname: eui.Label;
    public labelScore: eui.Label;
    public labelTopRank: eui.Label;
    public myBg: eui.Image;

    data: Record;

    dataChanged() {
        this.myBg.visible = this.data.isMe;


        if (this.data.index <= 3 && this.data.index >= 1) {
            this.labelTopRank.text = this.data.index.toString() || "-";
            this.groupTopRank.visible = true;
            this.labelOtherRank.visible = false;
        } else {
            this.labelOtherRank.text = this.data.index.toString() || "-";
            this.labelOtherRank.visible = true;
            this.groupTopRank.visible = false;
        }

        this.labelScore.text = typeof this.data.score == "number" ? this.data.score.toString() : "-";
        let str = "-";
        if (!this.data.nickname || this.data.nickname == "null") {
            str = this.data.userId.toString();
        } else {
            str = this.data.nickname;
        }

        this.labelNickname.text = str;
    }
}