import { RES } from "../../module/RES";
import { hideWaiting, showToast, showWaiting, wait } from "../../module/ctrls";
import { sendTbNet, TbNetName } from "../TaoBaoNet";
import { GTool } from "../../module/tools/GTool";
// import { MapScene } from "./map/MapScene";
import { Panel } from "../../module/views/Panel";
import { Tools } from "../Tools";

/**
 * 摇奖机弹框
 */
export class LotteryPanel extends Panel {
    get groupNames() { return ["lotteryScene"] }

    lotScroll: LotteryScroll;
    lotBtn: FYGE.Button;
    useBtn: FYGE.Button;
    thanksBtn: FYGE.Button;
    // data: {
    //     level: number,
    // }
    initUi() {
        //适配
        // this.y = -layers.stageOffsetY;
        //背景
        this.addChild(new FYGE.Sprite(RES.getRes("lotteryMachineBg.png")))

        //抽奖按钮
        this.lotBtn = this.addChild(new FYGE.Button(RES.getRes("lotteryBtn.png")))
            .addEventListener(FYGE.MouseEvent.CLICK, this.lottery, this)
        this.lotBtn.position.set((750 - RES.getRes("lotteryBtn.png").width) / 2, 1170);
        //领取奖励按钮
        this.useBtn = this.addChild(new FYGE.Button(RES.getRes("老虎机领取奖励.png")))
            .addEventListener(FYGE.MouseEvent.CLICK, this.getPrize, this);

        this.useBtn.position.set((750 - RES.getRes("老虎机领取奖励.png").width) / 2, 1170);
        this.useBtn.visible = false;
        //谢谢参与关闭按钮
        this.thanksBtn = this.addChild(new FYGE.Button(RES.getRes("老虎机好的.png")))
            .addEventListener(FYGE.MouseEvent.CLICK, this.hidePanel, this)
        this.thanksBtn.position.set((750 - RES.getRes("老虎机好的.png").width) / 2, 1170);
        this.thanksBtn.visible = false;
        //返回按钮，回到地图页
        this.addChild(new FYGE.Sprite(RES.getRes("lotteryReturnBtn.png")))
            .addEventListener(FYGE.MouseEvent.CLICK, () => {
                this.hidePanel();
            }, this)
            .position.set(0, 250)
        //刷新奖品列表和摇奖列表
        this.updatePrizes();
    }

    prizeData;

    getPrize(e) {
        this.btnDelay(e.target);
        const { type, _id } = this.prizeData;
        switch (type) {
            case 1: // 权益
                sendTbNet(TbNetName.receiveEnamePrize, { _id: _id, id:_id },
                    (success, res) => {
                        if (!success || !res) {
                            showToast('奖品发放失败\n请前往我的奖品处进行处理');
                            this.hidePanel();
                            return;
                        }
                        if (res.data && res.data.drawStatus == 3) {
                            showToast('奖品发放成功\n请前往我的奖品处查看');
                        } else {
                            showToast('奖品发放失败\n请前往我的奖品处进行处理');
                        }
                        this.data.callFun && this.data.callFun();
                        this.hidePanel();
                    }, true
                );
                break;
            case 3: // 实物
                sendTbNet(TbNetName.getUserAddress, { prizeId: _id },
                    (success, res) => {
                        if (!success) {
                            // showToast('奖品发放失败\n请前往我的奖品处进行处理');
                            return;
                        }
                        showToast('奖品发放成功\n请前往我的奖品处查看');
                        this.hidePanel();
                    }, true
                );
                break;

            case 2: // 积分
            case 5: // 谢谢参与
                this.hidePanel();
                break;
        }
    }

    hidePanel() {
        this.data.callFun && this.data.callFun();
        super.hidePanel();
    }

    async updatePrizes() {
        showWaiting();
        const { data: prizeList } = await sendTbNet(TbNetName.getTopLevelPrizes/*, { level: this.data.level }*/);
        //去掉type为5的谢谢参与
        var list = prizeList.slice().filter((e) => {
            return e.type != 5
        });
        //滚动列表
        // var scroll = this.addChild(new FYGE.ScrollList(PrizeItem, 122, 140, 345, 152, false))
        // scroll.position.set(195, 1013);
        // scroll.updateData(list || [])
        //摇奖部分
        var p = [91, 731]
        list.push({
            activityId: "602f33eb086e65bb22759048",
            image: "https://yun.duiba.com.cn/aurora/assets/20a5c02da9d2eb507af7f5dda581083798e8aa84.png",
            name: "谢谢参与",
            type: 5,
            _id: "thanks",
        });
        this.lotScroll = this.addChild(new LotteryScroll(list))
        this.lotScroll.position.set(p[0], p[1]);
        console.log(this.lotScroll.position)
    }
    lottery() {
        showWaiting()
        sendTbNet(TbNetName.drawTopLevelPrize/*, { level: this.data.level }*/)
            .then((res) => {
                hideWaiting();
                //如果是失败
                if (!res.success) return;
                Tools.gameData.isDrawTopLevelPrize = true;
                let id;//待考虑，谢谢参与要进哪？是否进列表，下面id不存在时当作无奖励，（如果谢谢参与不进列表）
                if (res.data && res.data.type == 5) {
                    id = 'thanks';
                } else if (res.data && res.data.prizeId) {
                    id = res.data.prizeId;
                }
                this.enableMouseEvt(false);
                console.log(id)
                this.prizeData = res.data;
                this.lotScroll.lot(id, () => {
                    this.enableMouseEvt(true)
                    //
                    this.lotBtn.visible = false;
                    //无奖
                    if (!id || res.data.type == 5) {
                        // showPanel(NoPrizePanel);
                        this.thanksBtn.visible = true;
                    } else {
                        // showPanel(PrizePanel, res.data)
                        this.useBtn.visible = true
                    }
                    // showPanel(id ? PrizePanel : NoPrizePanel, id ? res.data : null)
                })
            })

    }
}
interface PrizeInt {
    image: string,
    name: string,
    _id: string
}
class LotteryItem extends FYGE.Container {
    private showImage: FYGE.Sprite;
    id: string
    constructor(data: PrizeInt) {
        super();
        this.id = data._id;
        // this.addChild(new FYGE.Sprite(RES.getRes("lotteryItemBg.png")));
        this.showImage = this.addChild(new FYGE.Sprite(FYGE.Texture.from(data.image)));
        this.showImage.width = this.showImage.height = 160;//88
        // this.showImage.position.set((103 - 88) / 2, 6);
        var mask = this.addChild(new FYGE.Shape())
        mask.beginFill(0);
        // mask.drawRoundedRect((103 - 88) / 2, 6, 88, 88, 10);
        mask.drawRoundedRect(0, 0, 160, 160, 10);
        mask.endFill();
        this.showImage.mask = mask
    }
    reset(data: PrizeInt) {
        this.showImage.texture = FYGE.Texture.from(data.image);
        this.id = data._id;
    }
}
const HEIGHT = 200//123;
/**
 * 滚动条
 * 功能可以滚动到指定的图
 */
class LotteryScrollItem extends FYGE.Container {
    /**
     * 当前childre的中位索引
     */
    get currentIndex(): number {
        var a = 1 - this.cusP;
        var l = this.children.length
        return a < 0 ? a % l + l : a % l
    };

    private cusP: number
    constructor(datas: PrizeInt[]) {
        super();
        datas.forEach((d) => {
            this.addChild(new LotteryItem(d))
        })
        this.cusP = 0;
        this.updatePosition();
        //修改位置
        this.addEventListener(FYGE.Event.ENTER_FRAME, this.updatePosition, this)
    }


    scrollTo(id: string, callback: () => void) {
        //找出目标图
        let child, curIndex;
        for (var i = 0; i < this.children.length; i++) {
            // @ts-ignore
            if (this.children[i].id == id) {
                child = this.children[i];
                curIndex = i;
                break
            }
        }
        var delta = this.currentIndex - curIndex;
        if (delta < 0) delta += this.children.length;
        //目标图的位置必须是，多加几圈
        var cusP = this.cusP + delta + 10 * this.children.length;
        FYGE.Tween.get(this)
            .to({ cusP }, 5000, FYGE.Ease.quadInOut)
            .call(() => {
                callback && callback();
            })
    }
    reset() {

    }

    updatePosition() {
        this.children.forEach((c: LotteryItem, j) => {
            c.y = ((this.cusP + j) % this.children.length) * HEIGHT - HEIGHT;
            //超过一定距离，移到上面
            if (c.y > HEIGHT * 1.5) {
                c.y = c.y - this.children.length * HEIGHT
            }
        })
    }

    // 0   0-  10 21  1
    // 1   00  11 2-  0
    // 2   01  1- 20  2
    // 3   0-  10 21  1
    destroy() {
        FYGE.Tween.removeTweens(this);
        super.destroy()
    }
}
/**
 * 暂时固定3列，宽高
 */
class LotteryScroll extends FYGE.Container {
    ids: string[]
    scrollItems: LotteryScrollItem[];
    constructor(datas: PrizeInt[]) {
        super();
        this.scrollItems = []
        for (var i = 0; i < 3; i++) {
            var s = this.addChild(new LotteryScrollItem(GTool.disturbArr(datas.slice())))
            s.position.set(208 * i, 0);
            this.scrollItems.push(s)
        }
        this.ids = [];
        datas.forEach((d) => { this.ids.push(d._id) });

        var h = -130
        //遮罩
        var mask = this.addChild(new FYGE.Shape())
        mask.beginFill(0)
        // mask.drawRect(0, h + 3, 350, 195 - 5)
        mask.drawRect(0, h + 3, 590, 422)
        mask.endFill();
        this.mask = mask;
        //蒙层
        // this.addChild(new FYGE.Sprite(RES.getRes("shadowMask.png")))
        //     .position.set(0, h)
    }
    lot(id?: string, callback?: () => void) {
        //有id且在中奖列表里
        if (id && this.ids.indexOf(id) != -1) {
            //确保得是ids里的id。否则无效
            // if (this.ids.indexOf(id) == -1) {
            //     console.error("中奖id不存在")
            //     return;
            // }
            let count = 0;
            let countAll = this.scrollItems.length;
            this.scrollItems.forEach((c: LotteryScrollItem, i) => {
                wait(() => {
                    c.scrollTo(id, () => {
                        if (++count == countAll && callback) callback();
                    })
                }, 400 * i)

            })
        } else {
            //保证几个id不能一致
            var ids = [
                GTool.randomT(this.ids),
                GTool.randomT(this.ids),
            ];
            //如果都相同
            // if(!ids.some(function (value, index) { return value !== ids[0];})){
            //     ids.push()
            // }
            //才两个，直接判断
            ids[0] === ids[1] ? ids.push(
                GTool.randomT((() => {
                    var arr = this.ids.slice();
                    arr.splice(this.ids.indexOf(ids[0]), 1)
                    return arr
                })())
            ) : ids.push(GTool.randomT(this.ids));
            // console.log(ids)
            let count = 0;
            let countAll = this.scrollItems.length;
            this.scrollItems.forEach((c: LotteryScrollItem, i) => {
                wait(() => {
                    c.scrollTo(ids[i], () => {
                        if (++count == countAll && callback) callback();
                    })
                }, 400 * i)
            })
        }
    }
}
