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 toggleCurrent: eui.RadioButton;
    public toggleLast: eui.RadioButton;
    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 dataGroupReward: eui.DataGroup;
    public btnViewReward: MButton;
    public currentBg: eui.Image;
    public lastBg: eui.Image;

    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();
        Loading.instace.show();
        this.btnClose.onTap(this, () => this.hidePanel());
        this.btnViewReward.onTap(this, () => {
            location.href = MConfigs.rewardRecordUrl;
        });

        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.dataGroupReward.itemRenderer = class extends MItem {
            data: {
                rank: string,
                url: string
            }
            public img: eui.Image;
            public label: eui.Label;
            dataChanged() {
                this.img.source = this.data.url;
                this.label.text = this.data.rank;
            }
        }

        this.dataGroupReward.dataProvider = new eui.ArrayCollection(MConfigs.rewardList);


        this.netRequest();
    }

    private callOld() {
        return new Promise((resolve) => {
            Net.sendGet(Net.Url.rankListOld, {
                rankId: "104",
                activityId: "3711231",
                needPreviousPeriod: true,
                pageNo: 0,
                pageSize: onceQueryNum
            }, (res) => {
                try {
                    let myData = res.data.previousRankList.currentUserRankInfo;
                    this.cache.last.me = {
                        index: parseInt(myData.rank),
                        nickname: myData.nickName,
                        score: myData.maxScore,
                        userId: null
                    }

                    const listData: any[] = res.data.previousRankList.userRankList;
                    let list: Record[] = [];
                    for (let i of listData) {
                        list.push({
                            nickname: i.nickName,
                            index: parseInt(i.rank),
                            score: i.maxScore,
                            userId: null
                        });
                    }
                    this.cache.last.list = list;
                } catch {
                    ToastPanel.show("读取上期排行榜数据失败");
                    this.setNullList(this.cache.last);
                }
                resolve();
            });
        });
    }

    private setNullList(list: {
        me: Record,
        list: Record[],
    }) {
        list.me = {
            userId: null,
            index: null,
            score: null
        };
        list.list = [];
    }

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

            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: 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];
                }
            }

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

            //查询上一期排行榜数据
            await new Promise(resolve => {
                Net.sendGet(Net.Url.queryRankListData, {
                    type: last.type,
                    topN: onceQueryNum
                }, (res3) => {
                    if (last.type == MConfigs.lastRankListType) {
                        //用旧接口
                        this.isFirstWeek = true;
                    } else {
                        this.cache.last.list = res3.data;
                    }
                    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];
                }
            }

            /* if (this.getRankListTypeTimestamp(last.type) > this.getRankListTypeTimestamp(MConfigs.lastRankListType)) {
               
            } else {
                //用旧接口
                await this.callOld();
            } */

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

    private getRankListTypeTimestamp(type: string) {
        let strDate = this.formatDate(type);
        return (new Date(`${strDate.year}-${strDate.month}-${strDate.day} 00:00:00:000`).valueOf());
    }

    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.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.refreshPage(
                this.cache.last.me,
                this.cache.last.list,
                this.rankResponse.data.prevPeriod  //第一周开奖日期
            );
        }
    }

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

        //我的记录
        let str = "小镇使者";
        if (typeof myRecord.nickname == "string" && myRecord.nickname != "null" && myRecord.nickname.length > 0) {
            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 = myRecord.score || "0";

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

        //开奖日期
        if (periodData) {
            const date = this.formatDate(periodData.openDate);
            this.labelLotteryDate.text = `排行榜奖励${date.month}月${date.day}日15: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;

    data: Record;

    dataChanged() {
        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 = this.data.score || "0";
        let str = "小镇使者";
        if (typeof this.data.nickname == "string" && this.data.nickname != "null" && this.data.nickname.length > 0) {
            str = this.data.nickname;
        }
        this.labelNickname.text = str;
    }
}