ChristmasWheelService.php 15 KB

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