package com.red.circle.game.fruit.application.command;

import com.red.circle.framework.dto.ResultResponse;
import com.red.circle.game.fruit.application.dto.GameTimelineManage;
import com.red.circle.game.fruit.application.dto.enums.ClaimStatusEnum;
import com.red.circle.game.fruit.application.dto.enums.RankingOriginEnum;
import com.red.circle.game.fruit.application.dto.enums.RankingTypeEnum;
import com.red.circle.game.fruit.core.domain.gateway.GameFruitUserBetGateway;
import com.red.circle.game.fruit.infrastructure.database.entity.GameFruitAwardRecord;
import com.red.circle.game.fruit.infrastructure.database.entity.GameFruitDaysRecord;
import com.red.circle.game.fruit.infrastructure.database.entity.GameFruitLotteryRecord;
import com.red.circle.game.fruit.infrastructure.database.entity.GameFruitPriorityWinners;
import com.red.circle.game.fruit.infrastructure.database.entity.GameFruitPrize;
import com.red.circle.game.fruit.infrastructure.database.entity.GameFruitPrizeBet;
import com.red.circle.game.fruit.infrastructure.database.entity.GameFruitRoundRecord;
import com.red.circle.game.fruit.infrastructure.database.entity.GameFruitRule;
import com.red.circle.game.fruit.infrastructure.database.entity.GameFruitUser;
import com.red.circle.game.fruit.infrastructure.database.entity.GameFruitUserBetRecord;
import com.red.circle.game.fruit.infrastructure.database.memory.service.GameFruitMemoryService;
import com.red.circle.game.fruit.infrastructure.database.repository.GameFruitAwardRecordService;
import com.red.circle.game.fruit.infrastructure.database.repository.GameFruitDaysRecordService;
import com.red.circle.game.fruit.infrastructure.database.repository.GameFruitLotteryRecordService;
import com.red.circle.game.fruit.infrastructure.database.repository.GameFruitPriorityWinnersService;
import com.red.circle.game.fruit.infrastructure.database.repository.GameFruitPrizeBetService;
import com.red.circle.game.fruit.infrastructure.database.repository.GameFruitPrizeService;
import com.red.circle.game.fruit.infrastructure.database.repository.GameFruitRoundRecordService;
import com.red.circle.game.fruit.infrastructure.database.repository.GameFruitRuleService;
import com.red.circle.game.fruit.infrastructure.database.repository.GameFruitUserService;
import com.red.circle.game.fruit.infrastructure.websocket.message.MessageSender;
import com.red.circle.game.fruit.infrastructure.websocket.message.TopicMessage;
import com.red.circle.game.fruit.props.GameProperties;
import com.red.circle.other.inner.asserts.GameErrorCode;
import com.red.circle.tool.core.collection.CollectionUtils;
import com.red.circle.tool.core.num.ArithmeticUtils;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @author lisizhe 2023/12/5  17:17
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class LotteryDrawExe {

  private final MessageSender messageSender;
  private final GameProperties gameProperties;
  private final GameFruitUserService gameFruitUserService;
  private final GameFruitRuleService gameFruitRuleService;
  private final GameFruitPrizeService gameFruitPrizeService;
  private final GameFruitMemoryService gameFruitMemoryService;
  private final GameFruitPrizeBetService gameFruitPrizeBetService;
  private final GameFruitDaysRecordService gameFruitDaysRecordService;
  private final GameFruitUserBetGateway gameFruitUserBetGateway;
  private final GameFruitRoundRecordService gameFruitRoundRecordService;
  private final GameFruitAwardRecordService gameFruitAwardRecordService;
  private final GameFruitLotteryRecordService gameFruitLotteryRecordService;
  private final GameFruitPriorityWinnersService gameFruitPriorityWinnersService;

  public Boolean execute() {

    // 是否有人押注
    GameFruitRoundRecord gameFruitRoundRecord = gameFruitRoundRecordService.getGameRound();

    if (Objects.isNull(gameFruitRoundRecord)) {
      return false;
    }

    String sysOrigin = gameProperties.getSysOrigin();

    // 判断该轮游戏是否超时
    /*ResponseAssert.isFalse(GameErrorCode.GAME_STATE_NOT_PROGRESS,
        (TimestampUtils.between(gameFruitRoundRecord.getCreateTime(), TimestampUtils.now()).getSeconds() > 40));*/

    // 判断是否已经开过奖

    Long gameId = gameFruitRoundRecord.getId();

    List<GameFruitLotteryRecord> gameFruitLotteryRecords = gameFruitLotteryRecordService.getRoundLotteryPrize(
        gameId);

    if (gameFruitMemoryService.getRoundSec() > GameTimelineManage.lotteryDrawSecond) {
      return Boolean.FALSE;
    }

    if (CollectionUtils.isNotEmpty(gameFruitLotteryRecords)) {
      return Boolean.FALSE;
    }
    // 获取后台配置规则
    GameFruitRule gameFruitRule = gameFruitRuleService.getRule(sysOrigin);
    if (Objects.isNull(gameFruitRule)) {
      messageSender.sendTopic(
          TopicMessage.of(
              "broadcast", ResultResponse.failure(
                  GameErrorCode.RULE_NOT_CONFIGURED)));
      return Boolean.FALSE;
    }
    // 获取押注情况
    BigDecimal userExpend = gameFruitRoundRecord.getUserExpend();

    // 获取大盘营收情况（试算开什么结果）
    GameFruitDaysRecord gameFruitDaysRecord = gameFruitDaysRecordService.getDaysRecord(sysOrigin);

    Map<Long, GameFruitPrize> gameFruitPrizeMap = gameFruitPrizeService.mapPrize(sysOrigin);
    if (ArithmeticUtils.eqZero(userExpend)) {
      // 走正常随机逻辑,无需试算，发放奖品
      sendPrize(Collections.singletonList(randomRule(gameFruitPrizeMap)), gameId);
      return Boolean.TRUE;
    }
    // 计算当日盈利金额
    BigDecimal earnings = gameFruitDaysRecord.getUserExpend()
        .subtract(gameFruitDaysRecord.getPlatformExpend());
    // 是否开出蔬菜
    if (gameFruitDaysRecord.getVegetableNum() < gameFruitRule.getVegetableNumber()
        && earnings.compareTo(gameFruitRule.getVegetableLotteryProfit()) >= 0) {
      if (drawVegetable(gameFruitDaysRecord, gameId,
          gameFruitRule, sysOrigin)) {
        gameFruitDaysRecordService.addLotteryDrawNum(1, sysOrigin);
        return Boolean.TRUE;
      }
    }
    // 是否开出披萨
    if (gameFruitDaysRecord.getPizzaNum() < gameFruitRule.getPizzaNumber()
        && earnings.compareTo(gameFruitRule.getPizzaLotteryProfit()) >= 0) {
      if (drawPizza(gameFruitDaysRecord, gameId,
          gameFruitRule, sysOrigin)) {
        gameFruitDaysRecordService.addLotteryDrawNum(2, sysOrigin);
        return Boolean.TRUE;
      }
    }
    // 走其他规则

    // 总榜补偿优先中奖名单
    if (overallRankingCompensatory(gameId, gameFruitDaysRecord, gameFruitPrizeMap, gameFruitRule, sysOrigin)) {
      return Boolean.TRUE;
    }

    // 月榜补偿优先中奖名单
    if (monthRankingCompensatory(gameId, gameFruitDaysRecord, gameFruitPrizeMap, gameFruitRule, sysOrigin)) {
      return Boolean.TRUE;
    }

    // 总榜优先中奖名单
    if (overallRanking(gameId, gameFruitDaysRecord, gameFruitPrizeMap, gameFruitRule, sysOrigin)) {
      return Boolean.TRUE;
    }

    // 月榜优先中奖名单
    if (monthRanking(gameId, gameFruitDaysRecord, gameFruitPrizeMap, gameFruitRule, sysOrigin)) {
      return Boolean.TRUE;
    }

    // 日榜优先中奖名单
    if (daysRanking(gameId, gameFruitDaysRecord, gameFruitPrizeMap, gameFruitRule, sysOrigin)) {
      return Boolean.TRUE;
    }

    GameFruitPrize gameFruitPrize = randomRule(gameFruitPrizeMap);
    if (Objects.isNull(gameFruitPrize)) {
      messageSender.sendTopic(
          TopicMessage.of(
              "broadcast", ResultResponse.failure(
                  GameErrorCode.INCOMPLETE_PRIZE)));
      return Boolean.FALSE;
    }
    // 走正常随机
    if (send(gameFruitDaysRecord, gameId, gameFruitRule,
        Map.of(gameFruitPrize.getId(), gameFruitPrize))) {
      return Boolean.TRUE;
    }
    // 取返奖率中间值
    BigDecimal median = gameFruitRule.getLossRatio().add(gameFruitRule.getProfitRatio())
        .divide(ArithmeticUtils.toBigDecimal(2), 4, RoundingMode.HALF_UP);

    // 如果以上都不满足开奖条件，则取最接近返奖率的奖品
    Map<Long, Double> moneyReturnRateMap = new HashMap<>();
    gameFruitPrizeMap.values().forEach(item -> {
      // 依次计算返奖率
      moneyReturnRateMap.put(item.getId(),
          computeLossRatio(gameId, gameFruitDaysRecord, Map.of(item.getId(), item)).doubleValue());
    });
    // 转换格式
    // List<Map.Entry<Long, Double>> set = new ArrayList<>(moneyReturnRateMap.entrySet());

    // 计算哪个奖品最接近返奖率
    /*Long prizeKey = Collections.min(set, Comparator.comparingInt(a -> Math.abs(a.getValue())))
        .getKey();*/

    // 计算哪个奖品最接近返奖率
    Long prizeKey = moneyReturnRateMap.entrySet().stream()
        .min(Comparator.comparingDouble(
            element -> Math.abs(element.getValue() - median.doubleValue())))
        .map(Map.Entry::getKey)
        .orElseThrow(); // 如果集合为空，则抛出异常

    // 发放奖品
    sendPrize(List.of(gameFruitPrizeMap.get(prizeKey)), gameId);
    log.warn("开奖接近返奖率，返奖率中间值：" + median + "所有奖品返奖率集合" + moneyReturnRateMap);
    return Boolean.TRUE;
  }
/*
  public static void main(String[] args) {
    Map<Integer, Double> moneyReturnRateMap = new HashMap<>();
    moneyReturnRateMap.put(1, 0.9);
    moneyReturnRateMap.put(2, -9.2);
    moneyReturnRateMap.put(3, -3.8);
    moneyReturnRateMap.put(4, -0.4);
    moneyReturnRateMap.put(5, 0.4);
    List<Integer> list = new ArrayList<>();  // 假设集合为整数类型
    list.add(-10);
    list.add(9);
    list.add(-30);
    list.add(-40);
    list.add(-50);

    Double target = 1.025;  // 目标数字

    List<Map.Entry<Integer, Double>> set = new ArrayList<>(moneyReturnRateMap.entrySet());

    // 计算哪个奖品最接近返奖率
    Integer prizeKey = Collections.min(set, Comparator.comparingDouble(a -> Math.abs(a.getValue())))
        .getKey();
    System.out.println(prizeKey);

    Double closest = moneyReturnRateMap.entrySet().stream()
        .min(Comparator.comparingDouble(element -> Math.abs(element.getValue() - target)))
        .map(Map.Entry::getValue)
        .orElseThrow(); // 如果集合为空，则抛出异常

    System.out.println(Math.abs(-0.2 - 1));
    System.out.println("最接近的元素是：" + closest);
  }*/


  private Map<String, List<GameFruitPriorityWinners>> mapPriorityWinners(String sysOrigin) {
    return gameFruitPriorityWinnersService.mapListGameFruitPriorityWinners(sysOrigin);
  }

  /**
   * 总榜补偿得奖
   */
  public boolean overallRankingCompensatory(Long gameId, GameFruitDaysRecord gameFruitDaysRecord,
      Map<Long, GameFruitPrize> gameFruitPrizeMap, GameFruitRule gameFruitRule,String sysOrigin) {

    // 榜单优先开奖
    return rankingLottery(RankingOriginEnum.OVERALL.joinType(RankingTypeEnum.COMPENSATORY_REWARD),
        gameId, gameFruitDaysRecord, sysOrigin, gameFruitRule,
        gameFruitPrizeMap);
  }

  /**
   * 月榜补偿得奖
   */
  private boolean monthRankingCompensatory(Long gameId, GameFruitDaysRecord gameFruitDaysRecord,
      Map<Long, GameFruitPrize> gameFruitPrizeMap, GameFruitRule gameFruitRule,String sysOrigin) {

    // 榜单优先开奖
    return rankingLottery(RankingOriginEnum.MONTH.joinType(RankingTypeEnum.COMPENSATORY_REWARD),
        gameId, gameFruitDaysRecord, sysOrigin, gameFruitRule,
        gameFruitPrizeMap);
  }

  /**
   * 日榜优先得奖
   */
  private boolean daysRanking(Long gameId, GameFruitDaysRecord gameFruitDaysRecord,
      Map<Long, GameFruitPrize> gameFruitPrizeMap, GameFruitRule gameFruitRule,String sysOrigin) {

    // 榜单优先开奖
    return rankingLottery(RankingOriginEnum.TODAY.joinType(RankingTypeEnum.PRIORITY_LOTTERY),
        gameId, gameFruitDaysRecord, sysOrigin, gameFruitRule,
        gameFruitPrizeMap);
  }


  /**
   * 总榜优先得奖
   */
  public boolean overallRanking(Long gameId, GameFruitDaysRecord gameFruitDaysRecord,
      Map<Long, GameFruitPrize> gameFruitPrizeMap, GameFruitRule gameFruitRule,String sysOrigin) {

    // 榜单优先开奖
    return rankingLottery(RankingOriginEnum.OVERALL.joinType(RankingTypeEnum.PRIORITY_LOTTERY),
        gameId, gameFruitDaysRecord, sysOrigin, gameFruitRule,
        gameFruitPrizeMap);
  }

  /**
   * 月榜优先得奖
   */
  private boolean monthRanking(Long gameId, GameFruitDaysRecord gameFruitDaysRecord,
      Map<Long, GameFruitPrize> gameFruitPrizeMap, GameFruitRule gameFruitRule,String sysOrigin) {

    // 榜单优先开奖
    return rankingLottery(RankingOriginEnum.MONTH.joinType(RankingTypeEnum.PRIORITY_LOTTERY),
        gameId, gameFruitDaysRecord, sysOrigin, gameFruitRule,
        gameFruitPrizeMap);
  }

  /**
   * 开奖蔬菜
   */
  private boolean drawVegetable(GameFruitDaysRecord gameFruitDaysRecord, Long gameId,
      GameFruitRule gameFruitRule, String sysOrigin) {
    // 在返奖率区间内则开
    Map<Long, GameFruitPrize> gameFruitPrizeMap = gameFruitPrizeService.mapByType(1, sysOrigin);
    if (CollectionUtils.isEmpty(gameFruitPrizeMap)) {
      messageSender.sendTopic(
          TopicMessage.of(
              "broadcast", ResultResponse.failure(
                  GameErrorCode.INCOMPLETE_PRIZE)));
      return Boolean.FALSE;
    }
    // 发放奖品 返回是否满足发放条件
    return send(gameFruitDaysRecord, gameId, gameFruitRule, gameFruitPrizeMap);
  }


  /**
   * 排行榜优先开奖
   */
  public boolean rankingLottery(String rankingKey, Long gameId,
      GameFruitDaysRecord gameFruitDaysRecord,String sysOrigin,
      GameFruitRule gameFruitRule, Map<Long, GameFruitPrize> gameFruitPrizeMap) {

    Map<String, List<GameFruitPriorityWinners>> priorityWinnersMaps = mapPriorityWinners(sysOrigin);

    if (CollectionUtils.isEmpty(priorityWinnersMaps)) {
      return Boolean.FALSE;
    }
    // 总榜优先获奖名单
    List<GameFruitPriorityWinners> overallRankings = priorityWinnersMaps.get(rankingKey);

    if (CollectionUtils.isEmpty(overallRankings)) {
      return Boolean.FALSE;
    }

    // 根据排名排序后的名单
    List<GameFruitPriorityWinners> sortOverallRankings = overallRankings.stream()
        .sorted(Comparator.comparing(GameFruitPriorityWinners::getRanking)).toList();
    // 获取下注的名单人
    List<GameFruitUserBetRecord> gameFruitUserBetRecords = gameFruitUserBetGateway.listLotteryUsers(
        gameId,
        overallRankings.stream().map(GameFruitPriorityWinners::getUserId)
            .collect(Collectors.toSet()));
    AtomicReference<Boolean> isSend = new AtomicReference<>(Boolean.FALSE);
    // 根据排名来决定开奖项
    sortOverallRankings.forEach(bets -> {
      if (isSend.get()) {
        return;
      }
      // 1、先把名单中用户的押注信息查询出 2、再把押注信息进行倍数排序（优先开倍数高的） 3、该奖品在返奖率区间则发送奖品
      gameFruitUserBetRecords.stream().filter(item -> item.getUserId().equals(bets.getUserId()))
          .sorted(Comparator.comparing(GameFruitUserBetRecord::getAward).reversed())
          .forEach(
              item -> {
                if (isSend.get()) {
                  return;
                }
                // 校验返奖率
                boolean isPass = checkLossRatio(gameFruitRule,
                    computeLossRatio(gameId, gameFruitDaysRecord,
                        Map.of(item.getPrizeId(), gameFruitPrizeMap.get(item.getPrizeId()))));
                // 通过校验则发奖
                if (isPass) {
                  isSend.set(Boolean.TRUE);
                  sendPrize(Collections.singletonList(gameFruitPrizeMap.get(item.getPrizeId())),
                      gameId);
                  // 机会改为已使用
                  gameFruitPriorityWinnersService.useChance(item.getUserId(), rankingKey);
                }
              }
          );
    });
    return isSend.get();
  }

  /**
   * 开奖披萨
   */
  private boolean drawPizza(GameFruitDaysRecord gameFruitDaysRecord, Long gameId,
      GameFruitRule gameFruitRule, String sysOrigin) {
    // 在返奖率区间内则开
    Map<Long, GameFruitPrize> gameFruitPrizeMap = gameFruitPrizeService.mapByType(2, sysOrigin);
    if (CollectionUtils.isEmpty(gameFruitPrizeMap)) {
      messageSender.sendTopic(
          TopicMessage.of(
              "broadcast", ResultResponse.failure(
                  GameErrorCode.INCOMPLETE_PRIZE)));
      return Boolean.FALSE;
    }
    // 发放奖品 返回是否满足发放条件
    return send(gameFruitDaysRecord, gameId, gameFruitRule, gameFruitPrizeMap);
  }

  private boolean send(GameFruitDaysRecord gameFruitDaysRecord, Long gameId,
      GameFruitRule gameFruitRule, Map<Long, GameFruitPrize> gameFruitPrizeMap) {
    // 校验返奖率
    boolean isPass = checkLossRatio(gameFruitRule,
        computeLossRatio(gameId, gameFruitDaysRecord, gameFruitPrizeMap));
    // 通过校验则发奖
    if (isPass) {
      sendPrize(gameFruitPrizeMap.values().stream().toList(), gameId);
      return Boolean.TRUE;
    }
    return Boolean.FALSE;
  }

  /**
   * 校验返奖率
   */
  private boolean checkLossRatio(GameFruitRule gameFruitRule, BigDecimal lossRatio) {
    BigDecimal loss = gameFruitRule.getLossRatio();
    BigDecimal profit = gameFruitRule.getProfitRatio();
    if (lossRatio.compareTo(loss) >= 0 && lossRatio.compareTo(profit) <= 0) {
      return Boolean.TRUE;
    }
    return Boolean.FALSE;
  }

  /**
   * 计算返奖率
   */
  private BigDecimal computeLossRatio(Long gameId, GameFruitDaysRecord gameFruitDaysRecord,
      Map<Long, GameFruitPrize> gameFruitPrizeMap) {

    // List<GameFruitPrize> gameFruitPrizeList = gameFruitPrizeMap.values().stream().toList();
    Set<Long> prizeIds = gameFruitPrizeMap.keySet();

    // 试算是否超出返奖率
    List<GameFruitPrizeBet> gameFruitWinPrizes;
    gameFruitWinPrizes = prizeIds.stream().map(item -> new GameFruitPrizeBet().setPrizeId(item)
            .setBetAmount(ArithmeticUtils.toBigDecimal(gameFruitMemoryService.getBetCache(item))))
        .toList();

    List<GameFruitPrizeBet> filterPrizes = gameFruitWinPrizes.stream()
        .filter(v -> !ArithmeticUtils.eqZero(v.getBetAmount())).toList();

    if (CollectionUtils.isEmpty(filterPrizes)) {
      filterPrizes = gameFruitPrizeBetService.listBetAmount(
          gameId, prizeIds);
    }

    // 校验是否所有奖品倍数相同

    // 本轮支出
    BigDecimal roundExpend = ArithmeticUtils.toBigDecimal(
        filterPrizes.stream().mapToDouble(item -> item.getBetAmount().multiply(
                ArithmeticUtils.toBigDecimal(gameFruitPrizeMap.get(item.getPrizeId()).getAward()))
            .doubleValue()).sum());
    // 试算是否超出返奖率
    List<GameFruitPrizeBet> gameFruitPrizeBets = gameFruitPrizeBetService.listBetAmount(
        gameId, null);

    // 平台总支出
    BigDecimal totalExpend = gameFruitDaysRecord.getPlatformExpend().add(roundExpend);

    // 本轮下注
    double roundBetAmount = gameFruitPrizeBets.stream()
        .mapToDouble(item -> item.getBetAmount().doubleValue()).sum();

    // 总下注
    BigDecimal totalBetAmount = gameFruitDaysRecord.getUserExpend()
        .add(ArithmeticUtils.toBigDecimal(roundBetAmount));

    if(ArithmeticUtils.eqZero(totalBetAmount)){
      return ArithmeticUtils.toBigDecimal(99999);
    }
    // 总支出 / 总下注 = 返奖率
    return totalExpend.divide(totalBetAmount, 4, RoundingMode.HALF_UP);
  }

  /**
   * 随机抽取奖品
   */
  private GameFruitPrize randomRule(Map<Long, GameFruitPrize> prizeMap) {
    // 走正常随机逻辑

    if (CollectionUtils.isNotEmpty(prizeMap.values()) && prizeMap.values().size() == 8) {
      Map<Long, Integer> probMap = prizeMap.values().stream()
          .collect(Collectors.toMap(GameFruitPrize::getId,
              (v) -> v.getProb().multiply(ArithmeticUtils.toBigDecimal(100)).intValue()));
      int totalProbability = probMap.values().stream().mapToInt(Integer::intValue).sum();

      double num = Math.random();
      double random = num * totalProbability;
      for (Long k : probMap.keySet()) {
        random -= probMap.get(k);
        if (random <= 0.0d) {
          return prizeMap.get(k);
        }
      }
    }
    return null;
  }

  /**
   * 发放奖品
   */
  private void sendPrize(List<GameFruitPrize> gameFruitPrizes, Long gameId) {

    List<GameFruitLotteryRecord> gameFruitLotteryRecords = gameFruitPrizes.stream()
        .map(gameFruitPrize -> new GameFruitLotteryRecord()
            .setPrizeId(gameFruitPrize.getId())
            .setPrizeType(gameFruitPrize.getType())
            .setProb(gameFruitPrize.getProb())
            .setPrizeImg(gameFruitPrize.getPrizeImg())
            .setAward(gameFruitPrize.getAward())
            .setPrizeName(gameFruitPrize.getPrizeName())
            .setGameId(gameId)).toList();
    // 保存开奖记录
    gameFruitLotteryRecordService.lotteryDraw(gameFruitLotteryRecords);

    Set<Long> prizeIds = gameFruitPrizes.stream().map(GameFruitPrize::getId)
        .collect(Collectors.toSet());

    List<GameFruitUserBetRecord> gameFruitUserBetRecords = gameFruitUserBetGateway.listLotteryInfo(
        gameId, prizeIds);
    // 为空证明无人中奖
    if (CollectionUtils.isEmpty(gameFruitUserBetRecords)) {
      return;
    }

    Set<Long> winnerUserIds = gameFruitUserBetRecords.stream()
        .map(GameFruitUserBetRecord::getUserId)
        .collect(Collectors.toSet());

    // 将状态改为已中奖
    gameFruitUserBetGateway.updateWinnerStatus(gameId, winnerUserIds, prizeIds);

    Map<Long, GameFruitUser> gameFruitUserMap = gameFruitUserService.mapGameFruitUser(winnerUserIds);

    List<GameFruitAwardRecord> gameFruitAwardRecords = gameFruitUserBetRecords.stream()
        .map(item -> new GameFruitAwardRecord()
            .setGameId(gameId)
            .setSysOrigin(gameFruitUserMap.get(item.getUserId()).getSysOrigin())
            .setClaimStatus(ClaimStatusEnum.WAITING.name())
            .setUserId(item.getUserId())).distinct().toList();

    gameFruitAwardRecordService.sendWaitingPrize(gameFruitAwardRecords);
  }



/*
  public static void main(String[] args) {

    String[] prizes = new String[]{"奖品1", "奖品2", "奖品3", "奖品4", "奖品5", "奖品6", "奖品7",
        "奖品8"};
    int[] probabilities = new int[]{17, 17, 17, 17, 14, 10, 5, 3};
    // Random random = new Random();

    int totalProbability = 0;
    for (int probability : probabilities) {
      totalProbability += probability;
    }

    int randomIndex = -1;
    double num = Math.random();
    double random = num * totalProbability;
    System.out.println("Math.random(): " + num + "，" + "random:" + random);
    for (int i = 0; i < probabilities.length; ++i) {
      random -= probabilities[i];
      if (random <= 0.0d) {
        randomIndex = i;
        break;
      }
    }

    System.out.println(prizes[randomIndex]);
  }*/
}
