namespace Fengling.Activity.Domain.Strategies.Actions; using Fengling.Activity.Domain.ValueObjects; public class LotteryAction : IActionStrategy { public string StrategyType => "Lottery"; public Task ExecuteAsync(CampaignContext context, ActionConfig config, CancellationToken cancellationToken = default) { var lotteryPoolId = config.GetParameter("LotteryPoolId"); var random = new Random(); var prizes = context.AdditionalData.TryGetValue("LotteryPrizes", out var prizesObj) ? prizesObj is List> list ? list : null : null; Dictionary? selectedPrize = null; if (prizes != null && prizes.Count > 0) { var totalWeight = prizes.Sum(p => p.TryGetValue("Weight", out var w) && w is int weight ? weight : 1); var randomValue = random.Next(totalWeight); var currentWeight = 0; foreach (var prize in prizes) { var weight = prize.TryGetValue("Weight", out var w) && w is int i ? i : 1; currentWeight += weight; if (randomValue < currentWeight) { selectedPrize = prize; break; } } } var rewards = new Dictionary { { "LotteryPoolId", lotteryPoolId ?? "" }, { "CampaignId", context.CampaignId.ToString() }, { "GrantedAt", DateTime.UtcNow } }; if (selectedPrize != null) { rewards["Prize"] = selectedPrize; var name = selectedPrize.TryGetValue("Name", out var n) ? n?.ToString() : null; rewards["Message"] = $"Congratulations! You won: {name ?? "a prize"}"; } else { rewards["Message"] = "Better luck next time!"; } return Task.FromResult(ActionResult.Success(rewards)); } }