package com.xxfc.platform.activity.util;

import com.xxfc.platform.activity.entity.ActivityPrize;

import java.util.List;

/**
 * @author libin
 * @version 1.0
 * @description
 * @data 2019/12/3 20:01
 */
public class LotteryUtils {

    public static int getrandomIndex(List<ActivityPrize> prizes) {
        int random = -1;
        try {
            //计算总权重
            double sumWeight = 0;
            for (ActivityPrize p : prizes) {
                sumWeight += p.getProbability();
            }
            //产生随机数
            double randomNumber;
            randomNumber = Math.random();
            //根据随机数在所有奖品分布的区域并确定所抽奖品
            double d1 = 0;
            double d2 = 0;
            for (int i = 0; i < prizes.size(); i++) {
                d2 += Double.parseDouble(String.valueOf(prizes.get(i).getProbability())) / sumWeight;
                if (i == 0) {
                    d1 = 0;
                } else {
                    d1 += Double.parseDouble(String.valueOf(prizes.get(i - 1).getProbability())) / sumWeight;
                }
                if (randomNumber >= d1 && randomNumber <= d2) {
                    random = i;
                    break;
                }
            }
        } catch (Exception e) {
            System.out.println("生成抽奖随机数出错，出错原因：" + e.getMessage());
        }
        return random;
    }
}
