
//奖品图片宽度
const itemWidth = 88;
//奖品图片高度
const itemHeight = 88;
//奖品图片上下间隔
const itemGap = 20;
//每列宽度
const colWidth = 116;
//摇奖机宽度
const maskWidth = 350;
//摇奖机高度
const maskHeight = 300;
/**
 * 摇奖机，暂时固定3列，宽高，其他背景啥的都自己搞
 */
export class LotteryScroll extends FYGE.Container {
    private ids: string[]
    private scrollItems: LotteryScrollItem[];
    constructor(datas: PrizeInt[] = data) {
        super();
        this.scrollItems = []
        for (var i = 0; i < 3; i++) {
            var s = this.addChild(new LotteryScrollItem(disturbArr(datas.slice())))
            s.position.set(colWidth * i, 0);
            this.scrollItems.push(s)
        }
        this.ids = [];
        datas.forEach((d) => { this.ids.push(d.id) });

        //遮罩
        var mask = this.addChild(new FYGE.Shape())
        mask.beginFill(0)
        mask.drawRect(0, -(maskHeight - itemHeight) / 2, maskWidth, maskHeight);//如果加了奖品背景图，这里y位置需要修改
        mask.endFill();
        this.mask = mask;
    }
    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) => {
                setTimeout(() => {
                    c.scrollTo(id, () => {
                        if (++count == countAll && callback) callback();
                    })
                }, 400 * i)

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



interface PrizeInt {
    image: string,
    name: string,
    id: string
}
class LotteryItem extends FYGE.Container {
    //显示的图片
    private showImage: FYGE.Sprite;
    //用来匹配中奖
    private id: string
    constructor(data: PrizeInt) {
        super();
        this.id = data.id;
        // this.addChild(FYGE.Sprite.fromUrl(""));//每项背景图片 TODO
        this.showImage = this.addChild(new FYGE.Sprite(FYGE.Texture.from(data.image)));
        this.showImage.width = itemWidth;
        this.showImage.height = itemHeight;
        this.showImage.position.set(0, 0);//如果有背景图片，自行调整位置适配，包括下面的遮罩
        //圆角遮罩，看需求加吧
        var mask = this.addChild(new FYGE.Shape())
        mask.beginFill(0);
        mask.drawRoundedRect(0, 0, itemWidth, itemHeight, 10);
        mask.endFill();
        this.showImage.mask = mask
    }
    reset(data: PrizeInt) {
        this.showImage.texture = FYGE.Texture.from(data.image);
        this.id = data.id;
    }
}

/**
 * 滚动条
 * 功能可以滚动到指定的图
 */
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++) {
            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() {
        //每项
        var h = itemHeight + itemGap;
        this.children.forEach((c: LotteryItem, j) => {
            c.y = ((this.cusP + j) % this.children.length) * h - h;
            //超过一定距离，移到上面
            if (c.y > h * 1.5) {
                c.y = c.y - this.children.length * h
            }
        })
    }

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


function disturbArr(arr) {
    return arr.sort(function () {
        return (0.5 - Math.random());
    });
}

function randomT(e, n?) {
    return e && "number" == typeof e.length && e.length ? e[Math.floor(Math.random() * e.length)] : ("number" != typeof n && (n = e || 1, e = 0), e + Math.random() * (n - e))
}

const data = [
    {
        "image": "https://img.alicdn.com/imgextra/i4/2275046294/O1CN01avEmL01wMhS5Wxd63_!!2275046294-2-miniprogram.png",
        "name": "实物11",
        "id": "5f213ff7738989c8b3f46f4d",
    },
    {
        "image": "https://source.unsplash.com/user/erondu/76x76",
        "name": "实物1实物1实物1实",
        "id": "5f213ff7738989c8b3f46f4b",
    },
    {
        "image": "https://img.alicdn.com/imgextra/i2/2275046294/O1CN01fcO2aS1wMhS2wKUZO_!!2275046294-0-miniprogram.jpg",
        "name": "优惠券1",
        "id": "5f213ff7738989c8b3f46f4c",
    },
    {
        "image": "http://wwc.alicdn.com/avatar/getAvatar.do?userIdStr=XFvSvGH0XmQGOFNWMCQyP08yX8cYPFgLXH*IXFMHvHcT&width=80&height=80&type=sns",
        "name": "实物测试名称过长的啦",
        "id": "5f22390fe5c0d7361f1e6b59",
    },
    {
        "image": "//yun.duiba.com.cn/images/201607/73htz55ih9.jpg",
        "name": "谢谢参与",
        "id": "5f22732b738989c8b3f6d7c2",
    }
]
