HolidayWheelService.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. <?php
  2. namespace App\Services;
  3. use App\Utility\SetNXLock;
  4. use App\Util;
  5. use Illuminate\Support\Facades\DB;
  6. class HolidayWheelService
  7. {
  8. /**
  9. * 获取节假日大转盘配置 + 用户状态
  10. */
  11. public function getWheelInfo(int $userId): array
  12. {
  13. $activity = DB::connection('write')
  14. ->table('agent.dbo.holiday_wheel_activity')
  15. ->orderBy('id', 'desc')
  16. ->first();
  17. $now = now();
  18. $status = 0;
  19. $startTime = null;
  20. $endTime = null;
  21. $iconUrl = '';
  22. // 默认规则从活动配置 + 商城档位中计算(包含金额、次数和档位信息)
  23. $rechargeRules = $this->getDefaultRechargeRules();
  24. if ($activity) {
  25. $status = (int)($activity->status ?? 0);
  26. $startTime = $activity->start_time;
  27. $endTime = $activity->end_time;
  28. $iconUrl = $activity->icon_url ?? '';
  29. // 如果当前时间不在活动时间范围内,则前端状态强制视为关闭(0)
  30. if (!empty($startTime) && $now->lt($startTime)) {
  31. $status = 0;
  32. }
  33. if (!empty($endTime) && $now->gt($endTime)) {
  34. $status = 0;
  35. }
  36. }
  37. // 前端展示时只需要简单的奖励值数组,例如 [177, 1, 0.2, ...],隐藏 slot_index 和 weight
  38. $slots = DB::connection('write')
  39. ->table('agent.dbo.holiday_wheel_config')
  40. ->orderBy('sort_index', 'asc')
  41. ->orderBy('slot_index', 'asc')
  42. ->pluck('reward')
  43. ->map(function ($reward) {
  44. return (float)$reward;
  45. })
  46. ->values()
  47. ->toArray();
  48. $userTimes = DB::connection('write')
  49. ->table('agent.dbo.holiday_wheel_user')
  50. ->where('UserID', $userId)
  51. ->first();
  52. $leftTimes = $userTimes ? (int)$userTimes->left_times : 0;
  53. $totalTimes = $userTimes ? (int)$userTimes->total_times : 0;
  54. return [
  55. 'status' => $status,
  56. 'start_time' => $startTime,
  57. 'end_time' => $endTime,
  58. 'icon_url' => $iconUrl,
  59. 'slots' => $slots,
  60. 'user' => [
  61. 'left_times' => $leftTimes,
  62. 'total_times' => $totalTimes,
  63. ],
  64. 'recharge_rules' => $rechargeRules,
  65. 'now' => $now->toDateTimeString(),
  66. ];
  67. }
  68. /**
  69. * 充值赠送转盘次数(在充值成功后调用)
  70. * 有 gift_id(首充礼包301,破产礼包302)的充值不添加次数
  71. */
  72. public function grantTimesOnRecharge(int $userId, float $payAmt, int $giftId = 0): void
  73. {
  74. if (in_array($giftId, [301, 302], true)) {
  75. return;
  76. }
  77. $activity = DB::connection('write')
  78. ->table('agent.dbo.holiday_wheel_activity')
  79. ->orderBy('id', 'desc')
  80. ->first();
  81. if (!$activity || (int)$activity->status !== 1) {
  82. return;
  83. }
  84. $now = now();
  85. if (!empty($activity->start_time) && $now->lt($activity->start_time)) {
  86. return;
  87. }
  88. if (!empty($activity->end_time) && $now->gt($activity->end_time)) {
  89. return;
  90. }
  91. // 统一使用默认规则(已基于活动配置 + 商城档位计算),保持金额与 times 一致
  92. $rules = $this->getDefaultRechargeRules();
  93. $payStr = number_format($payAmt, 2, '.', '');
  94. $addTimes = 0;
  95. foreach ($rules as $rule) {
  96. $amount = isset($rule['amount']) ? number_format($rule['amount'], 2, '.', '') : null;
  97. $times = (int)($rule['times'] ?? 0);
  98. if ($amount !== null && $amount === $payStr && $times > 0) {
  99. $addTimes += $times;
  100. }
  101. }
  102. if ($addTimes <= 0) {
  103. return;
  104. }
  105. DB::connection('write')->transaction(function () use ($userId, $addTimes) {
  106. $row = DB::connection('write')
  107. ->table('agent.dbo.holiday_wheel_user')
  108. ->where('UserID', $userId)
  109. ->lockForUpdate()
  110. ->first();
  111. if ($row) {
  112. DB::connection('write')
  113. ->table('agent.dbo.holiday_wheel_user')
  114. ->where('UserID', $userId)
  115. ->update([
  116. 'left_times' => (int)$row->left_times + $addTimes,
  117. 'total_times' => (int)$row->total_times + $addTimes,
  118. 'updated_at' => now(),
  119. ]);
  120. } else {
  121. DB::connection('write')
  122. ->table('agent.dbo.holiday_wheel_user')
  123. ->insert([
  124. 'UserID' => $userId,
  125. 'left_times' => $addTimes,
  126. 'total_times' => $addTimes,
  127. 'created_at' => now(),
  128. 'updated_at' => now(),
  129. ]);
  130. }
  131. });
  132. }
  133. /**
  134. * 执行一次转盘抽奖
  135. */
  136. public function spin(int $userId): array
  137. {
  138. $redisKey = 'holiday_wheel_spin_' . $userId;
  139. $lock = SetNXLock::getExclusiveLock($redisKey, 5);
  140. if (!$lock) {
  141. throw new \RuntimeException('操作太频繁,请稍后再试');
  142. }
  143. try {
  144. $activity = DB::connection('write')
  145. ->table('agent.dbo.holiday_wheel_activity')
  146. ->orderBy('id', 'desc')
  147. ->first();
  148. if (!$activity || (int)$activity->status !== 1) {
  149. throw new \RuntimeException('活动未开启');
  150. }
  151. $now = now();
  152. if (!empty($activity->start_time) && $now->lt($activity->start_time)) {
  153. throw new \RuntimeException('活动未开始');
  154. }
  155. if (!empty($activity->end_time) && $now->gt($activity->end_time)) {
  156. throw new \RuntimeException('活动已结束');
  157. }
  158. $slots = DB::connection('write')
  159. ->table('agent.dbo.holiday_wheel_config')
  160. ->orderBy('sort_index', 'asc')
  161. ->orderBy('slot_index', 'asc')
  162. ->get();
  163. if ($slots->isEmpty()) {
  164. throw new \RuntimeException('转盘配置不存在');
  165. }
  166. DB::connection('write')->beginTransaction();
  167. $userRow = DB::connection('write')
  168. ->table('agent.dbo.holiday_wheel_user')
  169. ->where('UserID', $userId)
  170. ->lockForUpdate()
  171. ->first();
  172. if (!$userRow || (int)$userRow->left_times <= 0) {
  173. DB::connection('write')->rollBack();
  174. throw new \RuntimeException('没有可用的转盘次数');
  175. }
  176. $totalWeight = 0;
  177. $weights = [];
  178. foreach ($slots as $slot) {
  179. $w = (int)$slot->weight;
  180. if ($w < 0) {
  181. $w = 0;
  182. }
  183. $weights[] = $w;
  184. $totalWeight += $w;
  185. }
  186. if ($totalWeight <= 0) {
  187. DB::connection('write')->rollBack();
  188. throw new \RuntimeException('转盘权重配置错误');
  189. }
  190. $rand = mt_rand(1, $totalWeight);
  191. $cumulative = 0;
  192. $selectedIndex = 0;
  193. foreach ($slots as $idx => $slot) {
  194. $cumulative += $weights[$idx];
  195. if ($rand <= $cumulative) {
  196. $selectedIndex = $idx;
  197. break;
  198. }
  199. }
  200. $selectedSlot = $slots[$selectedIndex];
  201. $reward = (float)$selectedSlot->reward;
  202. $slotIndex = (int)$selectedSlot->slot_index;
  203. DB::connection('write')
  204. ->table('agent.dbo.holiday_wheel_user')
  205. ->where('UserID', $userId)
  206. ->update([
  207. 'left_times' => (int)$userRow->left_times - 1,
  208. 'updated_at' => now(),
  209. ]);
  210. DB::connection('write')
  211. ->table('agent.dbo.holiday_wheel_history')
  212. ->insert([
  213. 'UserID' => $userId,
  214. 'slot_index' => $slotIndex,
  215. 'reward' => $reward,
  216. 'created_at' => now(),
  217. ]);
  218. DB::connection('write')->commit();
  219. return [
  220. 'slot_index' => $slotIndex,
  221. 'reward' => $reward,
  222. 'left_times' => (int)$userRow->left_times - 1,
  223. ];
  224. } catch (\Throwable $e) {
  225. DB::connection('write')->rollBack();
  226. throw $e;
  227. } finally {
  228. SetNXLock::release($redisKey);
  229. }
  230. }
  231. /**
  232. * 默认充值规则:
  233. * - 基于固定金额和次数:[9.99=>1次, 19.99=>3次, 49.99=>6次]
  234. * - 额外从 recharge_gear 中取出相同金额的档位详情(类似商城列表的数据),
  235. * times 字段保持不变。
  236. */
  237. public function getDefaultRechargeRules(): array
  238. {
  239. // 固定的基础规则(金额+次数)
  240. // 1) 先从活动配置中读取 recharge_rules
  241. $rules = [];
  242. $activity = DB::connection('write')
  243. ->table('agent.dbo.holiday_wheel_activity')
  244. ->orderBy('id', 'desc')
  245. ->first();
  246. if ($activity && !empty($activity->recharge_rules)) {
  247. $decoded = json_decode($activity->recharge_rules, true);
  248. if (is_array($decoded)) {
  249. $rules = $decoded;
  250. }
  251. }
  252. // 2) 如果没有配置,则使用默认规则
  253. if (empty($rules)) {
  254. $rules = [
  255. ['amount' => 9.99, 'times' => 1],
  256. ['amount' => 19.99, 'times' => 3],
  257. ['amount' => 19.99, 'times' => 3],
  258. ['amount' => 49.99, 'times' => 6],
  259. ];
  260. }
  261. // 为每条规则附加与金额相同的 recharge_gear 配置(类似商城 gear 列表)
  262. foreach ($rules as &$rule) {
  263. $amount = $rule['amount'];
  264. $item = DB::connection('write')
  265. ->table('agent.dbo.recharge_gear')
  266. ->where('status', 1)
  267. // ->where('in_shop', 1)
  268. ->where('money', $amount)
  269. ->select('id', 'money', 'favorable_price', 'give', 'recommend', 'gear')
  270. ->orderBy('id', 'asc')
  271. ->first();
  272. if ($item) {
  273. // 过滤 gear 支付方式,跟商城接口一致
  274. if (!empty($item->gear)) {
  275. $item->gear = Util::filterGearByDevice($item->gear);
  276. }
  277. $rule['gear'] = [
  278. 'id' => $item->id,
  279. 'money' => (float)$item->money,
  280. 'favorable_price' => (float)$item->favorable_price,
  281. 'give' => (float)$item->give,
  282. 'recommend' => (int)($item->recommend ?? 0),
  283. 'gear' => $item->gear,
  284. ];
  285. } else {
  286. $rule['gear'] = null;
  287. }
  288. }
  289. unset($rule);
  290. return $rules;
  291. }
  292. }