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";
import Panel from "../MViews/MPanel";
import { NetManager } from "../../../libs/tw/manager/NetManager";
import PanelCtrl from "../MCtrls/MPanelCtrl";
import WinnigPanel from "./WinnigPanel";
import GameMgr from "../Mgr/GameMgr";

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

export default class RankListPanel extends Panel {
    get skinKey() { return "RankListPanel" }

    public nowBtn: eui.Image;
    public lastBtn: eui.Image;
    public nowBG: eui.Image;
    public lastBG: eui.Image;
    public nickname: eui.Label;
    public maxscore: eui.Label;
    public myrank: eui.Label;
    public prizedate: eui.Label;
    public closeBtn: eui.Button;
    public rankList: eui.Scroller;
    public rankGroup: eui.Group;
    public prizeList: eui.Scroller;
    public prizeGroup: eui.DataGroup;
    public noprizelab: eui.Label;
    public prizecode: eui.Label;
    public prizeBtn: MButton
    public getprize: eui.Group;
    public nickname2: MLabel;
    public labelNow: eui.Label;
    public labelLast: eui.Label;
    public groupWinning: eui.Group;
    public imgNotWinning: eui.Image;

    private mydata: any = "";
    private nowdata = "";
    private lastdata = "";
    private myid = "";


    onSkinComplete() {
        super.onSkinComplete();
        if (GameMgr.instance.activityEnd) {
            this.prizedate.visible = false;
        }


        this.nowBG.pixelHitTest = true;
        this.lastBG.pixelHitTest = true;
        this.noprizelab.text = "很遗憾，未中奖"
        this.getprize.visible = false;
        this.noprizelab.visible = false;
        // this.prizecode.type = egret.TextFieldType.INPUT;
        // Loading.instace.show();
        // this.btnClose.onTap(this, () => this.hidePanel());
        // this.btnViewReward.onTap(this, () => {
        //     //location.href = MConfigs.rewardRecordUrl;//领奖按钮点击事件（修改exml）
        // });

        // 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.nowBtn.onTap(this, () => { this.onTap_nowBtn() });
        this.lastBtn.onTap(this, () => { this.onTap_lastBtn() });
        this.closeBtn.onTap(this, () => {
            this.hidePanel()
        });
        this.prizeBtn.onTap(this, () => {
            // PanelCtrl.instance.show<WinnigPanel>(WinnigPanel).data = this.winningPanelData;
            window.location.href = this.winningPanelData.receiveUrl;
        });
        this.prizecode.onTap(this, () => { this.copyTXT(); ToastPanel.show("已复制") })
        this.getData();

        // this.netRequest();

        this.prizeGroup.itemRenderer = class extends MItem {
            public img: eui.Image;
            public label: eui.Label;
            data: {
                text: string,
                url: string
            }

            dataChanged() {
                this.img.source = this.data.url;
                this.label.text = this.data.text;
            }
        }
        this.prizeGroup.dataProvider = new eui.ArrayCollection(MConfigs.rankPrizes);

    }
    initEvents() {
        this.nowBtn.onTap(this, () => { this.onTap_nowBtn() });
        this.lastBtn.onTap(this, () => { this.onTap_lastBtn() });
        this.closeBtn.onTap(this, () => {
            this.hidePanel()
        });

        this.prizecode.onTap(this, () => { this.copyTXT(); ToastPanel.show("已复制") })
    }


    onTap_nowBtn() {
        this.nowBG.visible = true;
        this.lastBG.visible = false;
        this.showData(this.nowdata);
        this.showmyData(this.mydata, 1)
        this.labelLast.textColor = 0xffffff;
        this.labelNow.textColor = 0x1DB13E;
    }
    onTap_lastBtn() {
        this.lastBG.visible = true;
        this.nowBG.visible = false;
        this.showData(this.lastdata);
        this.showmyData(this.mydata, 2);
        this.labelLast.textColor = 0x1DB13E;
        this.labelNow.textColor = 0xffffff;
    }
    //显示奖品
    GetPrize() {
        return;

        // //MConfigs.rewardList分组获取数据
        let list: any = [];
        //暂定显示五个奖品
        for (let i = 0; i < MConfigs.rewardList.length; i++) {
            // list.push(MConfigs.rewardList[i]);
            let prefab: any = new eui.Component();
            prefab.skinName = "RankListPanelRewardItem";
            prefab.x = i * 125;
            prefab.y = 0;
            prefab['img'].source = MConfigs.rewardList[i].url;
            prefab['label'].text = "第" + MConfigs.rewardList[i].rank + "名";
            this.prizeGroup.addChild(prefab);
        }

    }

    showData(data) {
        // this.prizecode.type = egret.TextFieldType.INPUT;
        let idlist: any = "";
        this.rankGroup.removeChildren();
        this.rankList.viewport.scrollV = 0;
        this.prizeList.viewport.scrollH = 0;
        if (data.length > 0) {
            for (let i = 0; i < data.length; i++) {
                idlist = idlist + data[i].userId + ",";
            }
            idlist = idlist.substring(0, idlist.length - 1);
            Net.sendGet(Net.uri.querynickname, { userIds: idlist }, (res) => {
                let uerdata = res.data;
                for (let i = 0; i < data.length; i++) {
                    let prefab: any = new eui.Component();
                    prefab.skinName = "RankListItem";
                    prefab.x = 0;
                    prefab.y = i * 53
                    if (data[i].index <= 3) {
                        prefab['imgBg'].visible = true;
                        prefab['labelTopRank'].text = data[i].index
                        prefab['labelOtherRank'].visible = false;
                    } else {
                        prefab['imgBg'].visible = false;
                        prefab['labelTopRank'].visible = false;
                        prefab['labelOtherRank'].text = data[i].index;
                    }
                    for (let n = 0; n < uerdata.length; n++) {
                        if (data[i].userId == uerdata[n].userId) {
                            if (uerdata[n].nickname != "") {
                                prefab['labelNickname'].text = "ID:" + uerdata[n].nickname;
                            } else {
                                prefab['labelNickname'].text = "ID:" + data[i].userId;
                            }

                            break
                        } else {
                            prefab['labelNickname'].text = "ID" + data[i].userId
                        }
                    }
                    if (this.myid == data[i].userId) {
                        prefab['myBG'].visible = true;
                    } else {
                        prefab['myBG'].visible = false;
                    }

                    prefab['labelScore'].text = data[i].score;
                    this.rankGroup.addChild(prefab);
                }
            })
        } else {
            let prefab: any = new eui.Label();
            prefab.x = 0;
            prefab.y = 10;
            prefab.text = "暂无数据"
            prefab.width = 499
            prefab.textAlign = "center"
            prefab.textColor = 0x1DB13E;
            this.rankGroup.addChild(prefab);
        }
    }

    showmyData(data, type) {
        this.imgNotWinning.visible = false;
        this.groupWinning.visible = false;

        if (type == 1) {
            if (data.currentPeriod && data.currentPeriod.myUserId) {

                if (data.currentPeriod.myScore != null) {
                    this.maxscore.text = data.currentPeriod.myScore;
                } else {
                    this.maxscore.text = "暂无数据";
                }

                if (data.currentPeriod.myIndex && data.currentPeriod.myIndex <= 1000) {
                    this.myrank.text = data.currentPeriod.myIndex;
                } else {
                    this.myrank.text = "未上榜";
                }
                this.prizedate.text = "排行榜奖励" + data.currentPeriod.openDate.substring(4, 6) + "月" + data.currentPeriod.openDate.substring(6) + "日10：00开奖";
            } else {
                this.nickname.text = "我";
                this.maxscore.text = "暂无数据";
                this.myrank.text = "未上榜";
                this.prizedate.text = "暂无数据";
            }
            if (data.currentPeriod) {
                if (data.currentPeriod.openFlag) {
                    if (data.currentPeriod.userRecordId) {
                        this.groupWinning.visible = true;
                        this.setWinningPanelData(data.currentPeriod);
                    } else {
                        this.imgNotWinning.visible = true;
                    }
                }
                /* if (data.currentPeriod.openFlag) {
                    if (data.currentPeriod.userRecordId) {

                        //获取领奖码 点击跳转
                        Net.sendGet(Net.uri.getCoupon, { projectOrderNo: data.currentPeriod.userRecordId }, (res) => {
                            this.prizecode.text = "领奖码：" + res.data.coupon_code;
                            document.getElementById('copy-txt').innerHTML = res.data.coupon_code;
                            this.prizeBtn.onTap(this, () => {
                                window.location.href = "https://a.app.qq.com/o/simple.jsp?pkgname=com.android.bankabc&ios_scheme=bankabc%3a%2f%2f%257b%2522param%2522%253a%2522%2522%252c%2522method%2522%253a%2522jumpToSharedProduct%2522%257d&android_scheme=bankabc%3a%2f%2f%257b%2522param%2522%253a%2522%2522%252c%2522method%2522%253a%2522jumpToSharedProduct%2522%257d";
                            })
                            this.getprize.visible = true;
                            this.noprizelab.visible = false;
                        }, () => {
                            this.getprize.visible = false;
                            this.noprizelab.visible = true;
                            this.noprizelab.text = "奖品异常，请联系客服处理"
                        })
                    } else {
                        this.getprize.visible = false;
                        this.noprizelab.visible = true;
                    }
                } else {
                    this.getprize.visible = false;
                    this.noprizelab.visible = false;
                } */
            }

        } else {
            if (data.prevPeriod && data.prevPeriod.myUserId) {
                // Net.sendGet(Net.uri.querynickname,{userIds:data.prevPeriod.myUserId},(res)=>{
                //     let nicknameshow = "";
                //     if(res.data[0].nickname !=""){
                //         nicknameshow = res.data[0].nickname;
                //     }else{
                //         nicknameshow = data.currentPeriod.myUserId;
                //     }

                //     this.nickname2.text = nicknameshow;
                //     this.nickname.text = "ID:" +  nicknameshow;
                // },(res)=>{
                //     this.nickname.text = "ID:" + data.prevPeriod.myUserId;
                // })
                if (data.prevPeriod.myScore != null) {
                    this.maxscore.text = data.prevPeriod.myScore;
                } else {
                    this.maxscore.text = "暂无数据";
                }
                if (data.prevPeriod.myIndex && data.prevPeriod.myIndex <= 100) {
                    this.myrank.text = data.prevPeriod.myIndex;
                } else {
                    this.myrank.text = "未上榜";
                }
                this.prizedate.text = "排行榜奖励" + data.prevPeriod.openDate.substring(4, 6) + "月" + data.prevPeriod.openDate.substring(6) + "日15：00开奖";
            } else {
                this.nickname.text = "我";
                this.maxscore.text = "暂无数据";
                this.myrank.text = "未上榜";
                this.prizedate.text = "暂无数据";
            }
            if (data.prevPeriod) {
                if (data.prevPeriod.openFlag) {
                    if (data.prevPeriod.userRecordId) {
                        this.groupWinning.visible = true;
                        this.setWinningPanelData(data.prevPeriod);
                    } else {
                        this.imgNotWinning.visible = true;
                    }
                }
                /* if (data.prevPeriod.openFlag) {
                    if (data.prevPeriod.userRecordId) {

                        //获取领奖码 点击跳转
                        Net.sendGet(Net.uri.getCoupon, { projectOrderNo: data.prevPeriod.userRecordId }, (res) => {
                            this.prizecode.text = "领奖码：" + res.data.coupon_code;
                            document.getElementById('copy-txt').innerHTML = res.data.coupon_code;
                            this.getprize.visible = true;
                            this.noprizelab.visible = false;
                            this.prizeBtn.onTap(this, () => {
                                window.location.href = "https://a.app.qq.com/o/simple.jsp?pkgname=com.android.bankabc&ios_scheme=bankabc%3a%2f%2f%257b%2522param%2522%253a%2522%2522%252c%2522method%2522%253a%2522jumpToSharedProduct%2522%257d&android_scheme=bankabc%3a%2f%2f%257b%2522param%2522%253a%2522%2522%252c%2522method%2522%253a%2522jumpToSharedProduct%2522%257d";
                            })
                        }, () => {
                            this.getprize.visible = false;
                            this.noprizelab.visible = true;
                            this.noprizelab.text = "奖品异常，请联系客服处理"
                        })
                    } else {
                        this.getprize.visible = false;
                        this.noprizelab.visible = true;
                    }
                } else {
                    this.getprize.visible = false;
                    this.noprizelab.visible = false;
                } */
            }
        }


    }


    private winningPanelData: {
        // imgUrl: string,
        // name: string,
        receiveUrl: string
    } = null;

    private setWinningPanelData(resData: any) {
        this.winningPanelData = {
            // imgUrl: resData.prizeIcon,
            // name: res.data[0].name,
            receiveUrl: "http://activity.m.duiba.com.cn/aaw/projectx/takePrize?projectOrderNo=" + resData.userRecordId
        }
        /*  Net.sendGet(Net.Url.queryPrize, {
             ids: resData.userRecordId
         }, (res) => {
             
         }) */
    }

    getData() {

        Net.sendGet(Net.uri.myrankList, undefined, (ret) => {
            this.mydata = ret.data;
            if (this.mydata.currentPeriod && this.mydata.currentPeriod.myUserId) {
                this.myid = this.mydata.currentPeriod.myUserId;
            } else {
                this.myid = this.mydata.prevPeriod.myUserId;
            }

            if (this.mydata.currentPeriod && this.mydata.currentPeriod.type) {
                Net.sendGet(Net.uri.ranklist, { type: this.mydata.currentPeriod.type, topN: 100 }, (res) => {
                    this.nowdata = res.data;
                    if (this.mydata.prevPeriod && this.mydata.prevPeriod.type) {
                        Net.sendGet(Net.uri.ranklist, { type: this.mydata.prevPeriod.type, topN: 100 }, (res) => {
                            this.lastdata = res.data;
                            Net.sendGet(Net.uri.querynickname, { userIds: this.mydata.currentPeriod.myUserId }, (res) => {
                                let nicknameshow = "";
                                if (res.data.length > 0 && res.data[0].nickname != "") {
                                    nicknameshow = res.data[0].nickname;
                                } else {
                                    nicknameshow = this.mydata.currentPeriod.myUserId;
                                }

                                this.nickname2.text = "ID:" + nicknameshow;
                                // this.nickname.text = "ID:" +  nicknameshow;
                            }, (res) => {
                                this.nickname2.text = "ID:" + this.mydata.currentPeriod.myUserId;
                            })
                            this.showmyData(this.mydata, 1);
                            this.showData(this.nowdata);
                            this.GetPrize();
                        }, (res) => {
                            // ToastPanel.show('网络连接失败,请重试');
                        })
                    }
                }, (res) => {
                    // ToastPanel.show('网络连接失败,请重试');
                })
            }


        }, (res) => {
            // ToastPanel.show('网络连接失败,请重试');
        })

    }

    copyTXT() {
        var copyDOM = document.querySelector('#copy-txt'); //指定的DOM元素
        var range = document.createRange(); // 创建容器
        range.selectNode(copyDOM); // 选中需要复制的节点
        window.getSelection().addRange(range); // 执行选中元素
        var successful = document.execCommand('copy');// 执行 copy 操作
        try {
            var msg = successful ? 'successful' : 'unsuccessful';
            console.log('Copy was ' + msg);
        } catch (err) {
            console.log('unable to copy');
        }
        window.getSelection().removeAllRanges(); // 移除选中的元素
    }



}



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


//                 /* const firstWeekStartTimestamp = onlineDate.getTime();
//                 const firstWeekEndTimestamp = firstWeekStartTimestamp + 7 * 24 * 60 * 60 * 1000;
//                 // const curTimestamp = res.timestamp;
//                 const curTimestamp = NetUtils.getTimestamp();;

//                 if (curTimestamp >= firstWeekStartTimestamp && curTimestamp < firstWeekEndTimestamp) {
//                     this.isFirstWeek = true;
//                 } */
//             });
//         });
//     }

//     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;
//             if (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) => {
//                         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];
//                     }
//                 }
//             } else {
//                 this.setNullList(this.cache.current);
//             }

//             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 (res3.data.length <= 0) { //是第一期
//                         console.log("new rank list is null");
//                         if (last.type == MConfigs.lastRankListType) {
//                             //用旧接口
//                             this.isFirstWeek = true;
//                         } else {
//                             console.warn("rank list type is wrong");
//                         }
//                     } else {
//                         this.cache.last.list = res3.data;

//                     }
//                     resolve();
//                 }, () => Loading.instace.hide());
//             });

//             //查询上一期用户昵称
//             if (!this.isFirstWeek) {
//                 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 {
//                 await this.callOld();
//             }
//             //设置默认显示页面
//             this.setDefaultPage((this.data && this.data.defaultToggle) || 1);
//             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 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("排行榜数据为空");
//         }

//         //我的记录
//         this.labelMyNickname.text = myRecord.nickname || "欢趣使者";

//         //我的排名
//         let rankText = "";
//         if (typeof myRecord.index == "number") {
//             if (myRecord.index > 1000) {
//                 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): { 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 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";
//         this.labelNickname.text = this.data.nickname || "欢趣使者";
//     }
