package com.cyksj.service.distribute.impl;

import com.cyksj.mapper.manage.distribute.DistributeExtraRebateConfigMapper;
import com.cyksj.model.entity.DistributeExtraRebateConfig;
import com.cyksj.service.distribute.DistributeExtraRebateService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

/**
 * 项目名: yhlxj
 * 文件名: DistributeExtraRebateServiceImpl
 * 创建者: JavaZou
 * 创建时间:2024/5/29 15:24
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class DistributeExtraRebateServiceImpl implements DistributeExtraRebateService {
	private final DistributeExtraRebateConfigMapper distributeExtraRebateConfigMapper;

	private static BigDecimal sums =  new BigDecimal(0);

	private static List<DistributeExtraRebateConfig> distributeExtraRebateConfigs = null;

	@PostConstruct
	public void initConfig() {
		distributeExtraRebateConfigs = distributeExtraRebateConfigMapper.selectList(null);

		distributeExtraRebateConfigs.forEach(e->{
			sums = sums.add(e.getRate());
		});
	}

	@Override
	public DistributeExtraRebateConfig getRandomExtraRebate() {
		if (distributeExtraRebateConfigs == null) {
			return null;
		}
		int i = randomProbabilityIndex(distributeExtraRebateConfigs);
		if (i == -1) {
			log.info("普通分销 推广奖励倍数异常..");
			return null;
		}
		return distributeExtraRebateConfigs.get(i);
	}

	public int randomProbabilityIndex(List<DistributeExtraRebateConfig> list) {
		int random = -1;
		//总权重
		Double totalProbability = sums.doubleValue();
		//产生随机数
		Double randomNumber = ThreadLocalRandom.current().nextDouble();
		//根据随机数在所有奖品分布的区域并确定所抽奖品
		Double d1 = 0d;
		Double d2 = 0d;
		for (int i = 0; i < list.size(); i++) {
			d2 += Double.parseDouble(String.valueOf(list.get(i).getRate())) / totalProbability;
			if (i == 0) {
				d1 = 0d;
			} else {
				d1 += Double.parseDouble(String.valueOf(list.get(i - 1).getRate())) / totalProbability;
			}
			if (randomNumber >= d1 && randomNumber < d2) {
				random = i;
				break;
			}
		}
		return random;
	}
}
