2
0

PayRechargeController.php 67 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609
  1. <?php
  2. namespace App\Http\Controllers\Game;
  3. use App\Facade\TableName;
  4. use App\Game\GlobalUserInfo;
  5. use App\Game\Services\OuroGameService;
  6. use App\Http\Controllers\Controller;
  7. use App\Http\helper\NumConfig;
  8. use App\Models\Order;
  9. use App\Services\OrderServices;
  10. use App\Utility\SetNXLock;
  11. use App\Util;
  12. use Illuminate\Http\Request;
  13. use Illuminate\Support\Facades\App;
  14. use Illuminate\Support\Facades\DB;
  15. use Illuminate\Support\Facades\Redis;
  16. class PayRechargeController extends Controller
  17. {
  18. /**
  19. * 设置用户语言环境
  20. */
  21. private function setUserLocale($request)
  22. {
  23. $user = $request->user();
  24. if ($user) {
  25. $locale = GlobalUserInfo::getLocaleByUserID($user->UserID, 'en');
  26. App::setLocale($locale);
  27. }
  28. }
  29. // 充值记录
  30. public function orderList(Request $request)
  31. {
  32. $user_id = (int)$request->globalUser->UserID;//$request->get('user_id', 1);
  33. $page = $request->get('page', 1);
  34. $pageSize = $request->get('pageSize', 7);
  35. $redisKey = 'PayRecharge_orderList_'.$user_id;
  36. if (!SetNXLock::getExclusiveLock($redisKey)) {
  37. return apiReturnFail(['web.withdraw.try_again_later','Tente novamente mais tarde']);
  38. }
  39. $where[] = ['user_id', $user_id];
  40. $where[] = ['pay_status', 1];
  41. $cacheTime = 60 * rand(1, 2);
  42. // $list = cache()->remember($user_id . '_order_list', $cacheTime, function () use ($where, $pageSize) {
  43. //
  44. // return Order::where($where)
  45. // ->orderBy('finished_at', 'desc')
  46. // ->selectRaw('amount,payment_code,order_sn as payment_sn,finished_at,created_at,pay_status')
  47. // ->paginate(15,['*'],'page',1);
  48. // });
  49. $list = Order::query()->where($where)
  50. ->orderBy('finished_at', 'desc')
  51. ->selectRaw('amount,payment_code,order_sn as payment_sn,finished_at,created_at,pay_status,type')
  52. ->paginate($pageSize);
  53. // ->paginate(15,['*'],'page',1);
  54. foreach ($list as &$val) {
  55. $val->amount = number_format($val->amount, 2, '.', '');
  56. }
  57. SetNXLock::release($redisKey);
  58. return apiReturnSuc($list);
  59. }
  60. // 首充
  61. public function firstPay(Request $request)
  62. {
  63. $user = $request->user();
  64. $user_recharge = DB::table(TableName::QPAccountsDB() . 'YN_VIPAccount')
  65. ->where('UserID', $user->UserID)
  66. ->value('Recharge') ?: 0;
  67. if($user_recharge)return apiReturnSuc();
  68. $firstPayGift = DB::table('agent.dbo.recharge_gift')
  69. ->where('gift_id', 301)->first();
  70. if(!$firstPayGift) return apiReturnFail();
  71. $names = DB::table('agent.dbo.admin_configs')
  72. ->where([
  73. 'type' => 'pay_method',
  74. 'status' => 1,
  75. ])
  76. ->selectRaw('id, name, status, new_pay_type as type')
  77. ->orderByDesc('sort')->get()->toArray();
  78. $list = DB::table('agent.dbo.recharge_gear')
  79. ->select('id','money','favorable_price','give')
  80. ->orderBy('money', 'asc')->where('status', 1)->get();
  81. $gear = Util::filterGearByDevice(\GuzzleHttp\json_encode($names));
  82. foreach ($list as &$val) {
  83. $val->favorable_price = $val->favorable_price + $val->give;
  84. $val->gear = $gear;
  85. $val->recommend = 0;
  86. if($val->money == $firstPayGift->recommend){
  87. $val->recommend = 1;
  88. }
  89. }
  90. return apiReturnSuc(compact('list', 'firstPayGift'));
  91. }
  92. // 首充礼包(带倒计时逻辑)
  93. public function firstPayGift(Request $request)
  94. {
  95. $user = $request->user();
  96. $this->setUserLocale($request);
  97. // 获取礼包配置
  98. $giftConfig = DB::table('agent.dbo.recharge_gift')
  99. ->where('gift_id', 301)
  100. ->first();
  101. if (!$giftConfig) {
  102. return apiReturnFail(['web.gift.config_not_exists', __('web.gift.config_not_exists')]);
  103. }
  104. // 检查用户是否购买了首充礼包
  105. $giftRecord = DB::table('agent.dbo.first_pay_gift_records')
  106. ->where('user_id', $user->UserID)
  107. ->first();
  108. // ========== 未购买礼包:返回充值列表 + 礼包配置 + 倒计时 ==========
  109. if (!$giftRecord) {
  110. // 获取充值档位列表
  111. $list = DB::table('agent.dbo.recharge_gear')
  112. ->select('money', 'favorable_price', 'give', 'gear')
  113. ->orderBy('money', 'asc')
  114. ->where('status', 1)
  115. ->where('in_shop', 1)
  116. ->get();
  117. foreach ($list as &$val) {
  118. $val->favorable_price = $val->favorable_price + $val->give;
  119. $val->recommend = 0;
  120. if ($val->money == $giftConfig->recommend) {
  121. $val->recommend = 1;
  122. }
  123. if (!empty($val->gear)) {
  124. $val->gear = Util::filterGearByDevice($val->gear);
  125. }
  126. }
  127. // ========== 处理倒计时逻辑(仅未购买时) ==========
  128. $redisKey = "first_pay_gift_timer_{$user->UserID}";
  129. $currentTime = time();
  130. $timeLeft = 0;
  131. $timerData = Redis::get($redisKey);
  132. if ($timerData) {
  133. $timerData = json_decode($timerData, true);
  134. $firstRequestTime = $timerData['first_request_time'];
  135. $phase = $timerData['phase'];
  136. // 阶段1:valid_h倒计时
  137. if ($phase === 'first') {
  138. $expireTime = $firstRequestTime + ($giftConfig->valid_h * 3600);
  139. if ($currentTime >= $expireTime) {
  140. $expireDate = date('Y-m-d', $expireTime);
  141. $currentDate = date('Y-m-d', $currentTime);
  142. if ($expireDate !== $currentDate) {
  143. // 进入阶段2
  144. $nextDayStart = time();
  145. $newExpireTime = $nextDayStart + ($giftConfig->valid_h_2 * 3600);
  146. $newTimerData = [
  147. 'first_request_time' => $firstRequestTime,
  148. 'phase' => 'daily',
  149. 'current_cycle_start' => $nextDayStart,
  150. 'last_expire_time' => $newExpireTime
  151. ];
  152. Redis::set($redisKey, json_encode($newTimerData));
  153. $timeLeft = max(0, $newExpireTime - $currentTime);
  154. }
  155. } else {
  156. $timeLeft = $expireTime - $currentTime;
  157. }
  158. }
  159. // 阶段2:每日循环
  160. elseif ($phase === 'daily') {
  161. $currentCycleStart = $timerData['current_cycle_start'];
  162. $expireTime = $currentCycleStart + ($giftConfig->valid_h_2 * 3600);
  163. if ($currentTime >= $expireTime) {
  164. $expireDate = date('Y-m-d', $expireTime);
  165. $currentDate = date('Y-m-d', $currentTime);
  166. if ($expireDate !== $currentDate) {
  167. $todayStart = time();
  168. $newExpireTime = $todayStart + ($giftConfig->valid_h_2 * 3600);
  169. $newTimerData = [
  170. 'first_request_time' => $firstRequestTime,
  171. 'phase' => 'daily',
  172. 'current_cycle_start' => $todayStart,
  173. 'last_expire_time' => $newExpireTime
  174. ];
  175. Redis::set($redisKey, json_encode($newTimerData));
  176. $timeLeft = max(0, $newExpireTime - $currentTime);
  177. }
  178. } else {
  179. $timeLeft = $expireTime - $currentTime;
  180. }
  181. }
  182. } else {
  183. // 首次请求,初始化倒计时
  184. $expireTime = $currentTime + ($giftConfig->valid_h * 3600);
  185. $timerData = [
  186. 'first_request_time' => $currentTime,
  187. 'phase' => 'first',
  188. 'last_expire_time' => $expireTime
  189. ];
  190. Redis::set($redisKey, json_encode($timerData));
  191. $timeLeft = $giftConfig->valid_h * 3600;
  192. }
  193. return apiReturnSuc([
  194. 'has_purchased' => false, // 未购买标记
  195. 'list' => $list, // 充值档位列表
  196. 'gift_info' => [
  197. 'gift_id' => $giftConfig->gift_id,
  198. 'gift_name' => $giftConfig->gift_name,
  199. 'total_bonus' => $giftConfig->total_bonus,
  200. 'bonus_instantly' => $giftConfig->bonus_instantly,
  201. 'day_rewards' => $giftConfig->day_rewards ? json_decode($giftConfig->day_rewards) : null,
  202. 'betting_bonus' => $giftConfig->betting_bonus ? json_decode($giftConfig->betting_bonus) : null,
  203. 'betting_task' => $giftConfig->betting_task ? json_decode($giftConfig->betting_task) : null,
  204. ],
  205. 'time_left' => $timeLeft, // ✅ 倒计时(未购买时展示)
  206. 'expire_at' => time() + $timeLeft // ✅ 过期时间戳
  207. ]);
  208. }
  209. // ========== 已购买礼包:返回任务进度(无倒计时) ==========
  210. // 获取用户当前累计下注次数(从RecordUserGameCount表)
  211. $currentTotalBetCount = DB::table(TableName::QPRecordDB() . 'RecordUserGameCount')
  212. ->where('UserID', $user->UserID)
  213. ->sum('Cnt') ?? 0;
  214. // 获取用户当前累计下注金额(从统计表,用于下注任务)
  215. $userStats = DB::table('QPRecordDB.dbo.RecordUserTotalStatistics')
  216. ->where('UserID', $user->UserID)
  217. ->first();
  218. $currentTotalBetAmount = $userStats->TotalBet ?? 0;
  219. // 更新下注进度到礼包记录(betting_current_bet存储下注次数,用于下注奖励)
  220. DB::table('agent.dbo.first_pay_gift_records')
  221. ->where('user_id', $user->UserID)
  222. ->update([
  223. 'betting_current_bet' => $currentTotalBetCount,
  224. 'updated_at' => date('Y-m-d H:i:s')
  225. ]);
  226. // 重新获取最新记录
  227. $giftRecord = DB::table('agent.dbo.first_pay_gift_records')
  228. ->where('user_id', $user->UserID)
  229. ->first();
  230. // 解析任务数据
  231. $dayRewardsData = $giftRecord->day_rewards_data ? json_decode($giftRecord->day_rewards_data, true) : null;
  232. $bettingBonusData = $giftRecord->betting_bonus_data ? json_decode($giftRecord->betting_bonus_data, true) : null;
  233. $bettingTaskData = $giftRecord->betting_task_data ? json_decode($giftRecord->betting_task_data, true) : null;
  234. // 计算当前是购买后的第几天(所有任务都需要用到)
  235. $purchaseDate = date('Y-m-d', strtotime($giftRecord->created_at));
  236. $today = date('Y-m-d');
  237. $daysPassed = floor((strtotime($today) - strtotime($purchaseDate)) / 86400);
  238. // 构建返回数据
  239. $giftInfo = [
  240. 'gift_id' => $giftRecord->gift_id,
  241. 'gift_name' => $giftRecord->gift_name,
  242. 'total_bonus' => (float)$giftRecord->total_bonus,
  243. 'bonus_instantly' => (float)$giftRecord->bonus_instantly,
  244. 'pay_amount' => (float)$giftRecord->pay_amount,
  245. ];
  246. // 每日奖励进度
  247. if ($dayRewardsData) {
  248. $startDay = $dayRewardsData['start_day'] ?? 1;
  249. $bonusDay = $dayRewardsData['bonus_day'] ?? 0;
  250. $claimedDays = $giftRecord->day_rewards_claimed;
  251. // $startDay = $startDay-1;
  252. // 判断每日奖励状态
  253. // 0=不可领取, 1=可领取, 2=已领取, 3=过期
  254. $dayRewardStatus = 0; // 默认不可领取
  255. // 检查是否过期(购买后7天)
  256. if ($daysPassed >= 7) {
  257. $dayRewardStatus = 3; // 过期
  258. } elseif ($daysPassed >= $startDay-1) {
  259. // 计算今天是第几个奖励日(从起始天数开始)
  260. $rewardIndex = $daysPassed - ($startDay-1);
  261. if ($rewardIndex < $bonusDay) {
  262. // 在奖励期内
  263. if ($claimedDays > $rewardIndex) {
  264. $dayRewardStatus = 2; // 已领取
  265. } else {
  266. // 即便前几天漏领,后续奖励仍可继续领取(漏掉的视为作废)
  267. $dayRewardStatus = 1; // 可领取
  268. }
  269. } else {
  270. // 超过奖励天数
  271. $dayRewardStatus = 2; // 已领取完
  272. }
  273. }
  274. $giftInfo['day_rewards'] = [
  275. 'total_bonus' => (float)$giftRecord->day_rewards_total,
  276. 'bonus_day' => $bonusDay,
  277. 'start_day' => $startDay,
  278. 'bonus' => $dayRewardsData['bonus'] ?? [],
  279. 'daysPassed' => $daysPassed,
  280. 'claimed_days' => $claimedDays,
  281. 'progress' => $claimedDays . '/' . $bonusDay,
  282. 'status' => $dayRewardStatus, // 0=不可领取, 1=可领取, 2=已领取, 3=过期
  283. 'status_text' => [
  284. __('web.gift.status_cannot_claim'),
  285. __('web.gift.status_can_claim'),
  286. __('web.gift.status_claimed'),
  287. __('web.gift.status_expired')
  288. ][$dayRewardStatus] ?? __('web.gift.status_unknown')
  289. ];
  290. }
  291. // 下注奖励进度(使用下注次数)
  292. if ($bettingBonusData) {
  293. $perBet = $bettingBonusData['per_bet'] ?? 100; // 每次下注次数要求
  294. $perBetBonus = $bettingBonusData['per_bet_bonus'] ?? 2; // 每次奖励金额(不是百分比)
  295. $currentBetCount = $giftRecord->betting_current_bet; // 当前累计下注次数
  296. $totalBonusLimit = $giftRecord->betting_bonus_total; // 总奖励上限
  297. $claimedAmount = $giftRecord->betting_bonus_claimed; // 已领取金额
  298. $remainingBonus = $totalBonusLimit - $claimedAmount; // 剩余可领取金额
  299. // 每次可领取的金额(直接使用配置的值,不是百分比计算)
  300. $perReward = (float)$perBetBonus;
  301. // 根据当前下注次数计算已达成的次数
  302. $completedTimes = floor($currentBetCount / $perBet);
  303. // 已领取的次数
  304. $claimedTimes = $claimedAmount > 0 ? floor($claimedAmount / $perReward) : 0;
  305. // 当前可领取次数(但不能超过剩余总额)
  306. $canClaimTimes = $completedTimes - $claimedTimes;
  307. $maxCanClaimTimes = floor($remainingBonus / $perReward); // 剩余总额最多可领次数
  308. $canClaimTimes = min($canClaimTimes, $maxCanClaimTimes);
  309. // 当前可领取金额
  310. $canClaimAmount = min($canClaimTimes * $perReward, $remainingBonus);
  311. // 计算下次领取需要的下注次数
  312. $nextClaimBet = 0;
  313. if ($remainingBonus > 0 && $canClaimTimes == 0) {
  314. // 还有剩余奖励但当前不能领取,计算还需下注多少次
  315. $nextClaimBet = ($claimedTimes + 1) * $perBet - $currentBetCount;
  316. }
  317. // 判断下注奖励状态
  318. // 0=不可领取(可领取金额为0), 1=可领取, 2=已领取(所有奖励都领完), 3=过期
  319. $bettingBonusStatus = 0; // 默认不可领取
  320. // 检查是否过期(购买后7天)
  321. if ($daysPassed >= 7) {
  322. $bettingBonusStatus = 3; // 过期
  323. } elseif ($remainingBonus <= 0) {
  324. $bettingBonusStatus = 2; // 已领取完
  325. } elseif ($canClaimAmount > 0) {
  326. $bettingBonusStatus = 1; // 可领取
  327. } else {
  328. $bettingBonusStatus = 0; // 不可领取(下注次数不足)
  329. }
  330. $giftInfo['betting_bonus'] = [
  331. 'total_bonus' => (float)$totalBonusLimit, // 总奖励上限
  332. 'per_bet' => $perBet, // 每次下注次数要求
  333. 'per_bet_bonus' => $perReward, // 每次奖励金额(实际金额)
  334. // 'per_reward' => $perReward, // 每次奖励金额(保持兼容)
  335. 'current_bet' => (float)$currentBetCount, // 当前累计下注次数
  336. 'claimed_amount' => (float)$claimedAmount, // 已领取金额
  337. 'remaining_bonus' => (float)$remainingBonus, // 剩余可领金额
  338. 'can_claim_amount' => (float)$canClaimAmount, // 当前可领取金额
  339. 'can_claim_times' => max(0, $canClaimTimes), // 当前可领取次数
  340. 'next_claim_bet' => max(0, $nextClaimBet), // 下次领取还需下注次数
  341. 'progress' => round($currentBetCount, 0) . '/' . round($claimedTimes * $perBet + $perBet, 0), // 当前进度/下次领取目标(次数)
  342. 'status' => $bettingBonusStatus, // 0=不可领取, 1=可领取, 2=已领取, 3=过期
  343. 'status_text' => [
  344. __('web.gift.status_cannot_claim'),
  345. __('web.gift.status_can_claim'),
  346. __('web.gift.status_claimed'),
  347. __('web.gift.status_expired')
  348. ][$bettingBonusStatus] ?? __('web.gift.status_unknown')
  349. ];
  350. }
  351. // 下注任务进度(使用下注金额)
  352. if ($bettingTaskData) {
  353. $betPayTimes = $bettingTaskData['bet_pay_times'] ?? 60;
  354. $requiredBet = $giftRecord->pay_amount * $betPayTimes;
  355. $currentProgress = $currentTotalBetAmount / NumConfig::NUM_VALUE; // 使用下注金额,不是次数
  356. $taskCompleted = $currentProgress >= $requiredBet;
  357. $isClaimed = $giftRecord->betting_task_claimed == 1;
  358. // 判断下注任务状态
  359. // 0=不可领取, 1=可领取, 2=已领取, 3=过期
  360. $bettingTaskStatus = 0; // 默认不可领取
  361. // 检查是否过期(购买后7天)
  362. if ($daysPassed >= 7) {
  363. $bettingTaskStatus = 3; // 过期
  364. } elseif ($isClaimed) {
  365. $bettingTaskStatus = 2; // 已领取
  366. } elseif ($taskCompleted) {
  367. $bettingTaskStatus = 1; // 可领取(任务完成且未领取)
  368. } else {
  369. $bettingTaskStatus = 0; // 不可领取(任务未完成)
  370. }
  371. $giftInfo['betting_task'] = [
  372. 'total_bonus' => (float)$giftRecord->betting_task_total,
  373. 'bet_pay_times' => $betPayTimes,
  374. 'required_bet' => $requiredBet, // 需要下注的金额
  375. 'current_bet' => (float)$currentProgress, // 当前累计下注
  376. 'progress' => round($currentProgress, 2) . '/' . $requiredBet,
  377. 'status' => $bettingTaskStatus, // 0=不可领取, 1=可领取, 2=已领取, 3=过期
  378. 'status_text' => [
  379. __('web.gift.status_cannot_claim'),
  380. __('web.gift.status_can_claim'),
  381. __('web.gift.status_claimed'),
  382. __('web.gift.status_expired')
  383. ][$bettingTaskStatus] ?? __('web.gift.status_unknown')
  384. ];
  385. }
  386. $giftInfo['expired'] = strtotime(date('Y-m-d',strtotime($giftRecord->created_at)))+86400*7;
  387. return apiReturnSuc([
  388. 'has_purchased' => true, // 已购买标记
  389. 'gift_info' => $giftInfo
  390. // ✅ 已购买用户不返回倒计时
  391. ]);
  392. }
  393. /**
  394. * 领取首充礼包奖励
  395. */
  396. public function claimFirstPayGiftReward(Request $request)
  397. {
  398. $user = $request->user();
  399. $userId = $user->UserID;
  400. $rewardType = $request->input('reward_type'); // 'day_reward', 'betting_bonus', 'betting_task'
  401. $this->setUserLocale($request);
  402. // 获取礼包记录
  403. $giftRecord = DB::table('agent.dbo.first_pay_gift_records')
  404. ->where('user_id', $userId)
  405. ->first();
  406. if (!$giftRecord) {
  407. return apiReturnFail(['web.gift.not_purchased', __('web.gift.not_purchased')]);
  408. }
  409. $rewardAmount = 0;
  410. try {
  411. // 每日奖励领取
  412. if ($rewardType === 'day_reward') {
  413. $dayRewardsData = json_decode($giftRecord->day_rewards_data, true);
  414. if (!$dayRewardsData) {
  415. return apiReturnFail(['web.gift.no_day_rewards_config', __('web.gift.no_day_rewards_config')]);
  416. }
  417. $bonusDay = $dayRewardsData['bonus_day'] ?? 0;
  418. $startDay = $dayRewardsData['start_day'] ?? 1;
  419. $bonusArray = $dayRewardsData['bonus'] ?? [];
  420. $claimedDays = $giftRecord->day_rewards_claimed;
  421. // 检查是否还有可领取的天数
  422. if ($claimedDays >= $bonusDay) {
  423. return apiReturnFail(['web.gift.day_rewards_all_claimed', __('web.gift.day_rewards_all_claimed')]);
  424. }
  425. // 计算当前是购买后的第几天
  426. $purchaseDate = date('Y-m-d', strtotime($giftRecord->created_at));
  427. $currentDate = date('Y-m-d');
  428. $daysPassed = floor((strtotime($currentDate) - strtotime($purchaseDate)) / 86400);
  429. // 检查是否到了可以领取的天数(从第start_day天开始)
  430. if ($daysPassed < $startDay-1) {
  431. return apiReturnFail(['web.gift.day_rewards_not_time', str_replace(':day', $startDay, __('web.gift.day_rewards_not_time'))]);
  432. }
  433. // 计算今天应该领取第几天的奖励
  434. // 例如:start_day=2,今天是第3天,应该领取第1个奖励(索引0)
  435. $todayRewardIndex = $daysPassed - ($startDay-1);
  436. // 检查是否超过奖励天数
  437. if ($todayRewardIndex >= $bonusDay) {
  438. return apiReturnFail(['web.gift.day_rewards_expired', __('web.gift.day_rewards_expired')]);
  439. }
  440. // 检查今天是否已领取
  441. $lastClaimDate = $giftRecord->day_last_claim_date;
  442. if ($lastClaimDate && $lastClaimDate === $currentDate) {
  443. return apiReturnFail(['web.gift.day_rewards_claimed_today', __('web.gift.day_rewards_claimed_today')]);
  444. }
  445. // 检查是否跳过了某些天(过期不补领)
  446. // 如果今天应该领第5天的奖励,但用户只领了3天,那就直接领第5天的
  447. if ($todayRewardIndex > $claimedDays) {
  448. // 跳过了一些天,更新已领取天数为今天的索引
  449. $claimedDays = $todayRewardIndex;
  450. }
  451. // 计算今天可领取的奖励(使用todayRewardIndex作为索引)
  452. $todayBonusPercent = $bonusArray[$todayRewardIndex] ?? 0;
  453. $rewardAmount = round($giftRecord->pay_amount * $todayBonusPercent / 100, 2);
  454. // 更新记录
  455. DB::table('agent.dbo.first_pay_gift_records')
  456. ->where('user_id', $userId)
  457. ->update([
  458. 'day_rewards_claimed' => $todayRewardIndex + 1, // 已领取到第几天(索引+1)
  459. 'day_last_claim_date' => $currentDate,
  460. 'updated_at' => date('Y-m-d H:i:s')
  461. ]);
  462. }
  463. // 下注奖励领取(使用下注次数)
  464. elseif ($rewardType === 'betting_bonus') {
  465. $bettingBonusData = json_decode($giftRecord->betting_bonus_data, true);
  466. if (!$bettingBonusData) {
  467. return apiReturnFail(['web.gift.no_betting_bonus_config', __('web.gift.no_betting_bonus_config')]);
  468. }
  469. // 检查是否过期(购买后7天)
  470. $purchaseDate = date('Y-m-d', strtotime($giftRecord->created_at));
  471. $currentDate = date('Y-m-d');
  472. $daysPassed = floor((strtotime($currentDate) - strtotime($purchaseDate)) / 86400);
  473. if ($daysPassed >= 7) {
  474. return apiReturnFail(['web.gift.betting_bonus_expired', __('web.gift.betting_bonus_expired')]);
  475. }
  476. // 获取最新的下注次数
  477. $currentBetCount = DB::table(TableName::QPRecordDB() . 'RecordUserGameCount')
  478. ->where('UserID', $userId)
  479. ->sum('Cnt') ?? 0;
  480. $perBet = $bettingBonusData['per_bet'] ?? 100; // 每次下注次数要求
  481. $perBetBonus = $bettingBonusData['per_bet_bonus'] ?? 2; // 每次奖励金额(不是百分比)
  482. $totalBonusLimit = $giftRecord->betting_bonus_total; // 总奖励上限
  483. $claimedAmount = $giftRecord->betting_bonus_claimed; // 已领取金额
  484. $remainingBonus = $totalBonusLimit - $claimedAmount; // 剩余可领金额
  485. // 检查是否还有剩余奖励
  486. if ($remainingBonus <= 0) {
  487. return apiReturnFail(['web.gift.betting_bonus_all_claimed', __('web.gift.betting_bonus_all_claimed')]);
  488. }
  489. // 每次可领取的金额(直接使用配置的值,不是百分比计算)
  490. $perReward = (float)$perBetBonus;
  491. // 根据当前下注次数计算已达成的次数
  492. $completedTimes = floor($currentBetCount / $perBet);
  493. // 已领取的次数
  494. $claimedTimes = $claimedAmount > 0 ? floor($claimedAmount / $perReward) : 0;
  495. // 可领取次数(下注达成的次数 - 已领取次数)
  496. $canClaimTimes = $completedTimes - $claimedTimes;
  497. // 检查是否可以领取
  498. if ($canClaimTimes <= 0) {
  499. $neededBets = (($claimedTimes + 1) * $perBet - $currentBetCount);
  500. return apiReturnFail(['web.gift.betting_bonus_insufficient', str_replace(':times', $neededBets, __('web.gift.betting_bonus_insufficient'))]);
  501. }
  502. // ✅ 一次性领取所有已达成的奖励(但不能超过剩余总额)
  503. $totalCanClaimAmount = $canClaimTimes * $perReward; // 理论可领取总额
  504. $rewardAmount = min($totalCanClaimAmount, $remainingBonus); // 实际领取金额(不超过剩余总额)
  505. $actualClaimTimes = floor($rewardAmount / $perReward); // 实际领取次数
  506. // 更新记录(同时更新下注次数)
  507. DB::table('agent.dbo.first_pay_gift_records')
  508. ->where('user_id', $userId)
  509. ->update([
  510. 'betting_bonus_claimed' => $giftRecord->betting_bonus_claimed + $rewardAmount,
  511. 'betting_current_bet' => $currentBetCount, // 更新最新下注次数
  512. 'updated_at' => date('Y-m-d H:i:s')
  513. ]);
  514. \Log::info('下注奖励领取', [
  515. 'user_id' => $userId,
  516. 'can_claim_times' => $canClaimTimes,
  517. 'actual_claim_times' => $actualClaimTimes,
  518. 'reward_amount' => $rewardAmount
  519. ]);
  520. }
  521. // 下注任务领取(使用下注金额)
  522. elseif ($rewardType === 'betting_task') {
  523. if ($giftRecord->betting_task_claimed == 1) {
  524. return apiReturnFail(['web.gift.betting_task_claimed', __('web.gift.betting_task_claimed')]);
  525. }
  526. $bettingTaskData = json_decode($giftRecord->betting_task_data, true);
  527. if (!$bettingTaskData) {
  528. return apiReturnFail(['web.gift.no_betting_task_config', __('web.gift.no_betting_task_config')]);
  529. }
  530. // 检查是否过期(购买后7天)
  531. $purchaseDate = date('Y-m-d', strtotime($giftRecord->created_at));
  532. $currentDate = date('Y-m-d');
  533. $daysPassed = floor((strtotime($currentDate) - strtotime($purchaseDate)) / 86400);
  534. if ($daysPassed >= 7) {
  535. return apiReturnFail(['web.gift.betting_task_expired', __('web.gift.betting_task_expired')]);
  536. }
  537. // 获取最新的下注金额
  538. $userStats = DB::table('QPRecordDB.dbo.RecordUserTotalStatistics')
  539. ->where('UserID', $userId)
  540. ->first();
  541. $currentBetAmount = ($userStats->TotalBet ?? 0) / NumConfig::NUM_VALUE;
  542. $betPayTimes = $bettingTaskData['bet_pay_times'] ?? 60;
  543. $requiredBet = $giftRecord->pay_amount * $betPayTimes;
  544. if ($currentBetAmount < $requiredBet) {
  545. return apiReturnFail(['web.gift.betting_task_insufficient', str_replace(':amount', $requiredBet, __('web.gift.betting_task_insufficient'))]);
  546. }
  547. $rewardAmount = $giftRecord->betting_task_total;
  548. // 更新记录
  549. DB::table('agent.dbo.first_pay_gift_records')
  550. ->where('user_id', $userId)
  551. ->update([
  552. 'betting_task_claimed' => 1,
  553. 'updated_at' => date('Y-m-d H:i:s')
  554. ]);
  555. }
  556. else {
  557. return apiReturnFail(['web.gift.invalid_reward_type', __('web.gift.invalid_reward_type')]);
  558. }
  559. // 添加奖励到用户账户
  560. if ($rewardAmount > 0) {
  561. OuroGameService::AddScore($userId, $rewardAmount * NumConfig::NUM_VALUE, 52, true); // 52=首充礼包奖励
  562. \Log::info('首充礼包奖励领取', [
  563. 'user_id' => $userId,
  564. 'reward_type' => $rewardType,
  565. 'amount' => $rewardAmount
  566. ]);
  567. }
  568. return apiReturnSuc([
  569. 'amount' => $rewardAmount,
  570. 'message' => str_replace(':amount', $rewardAmount, __('web.gift.claim_success'))
  571. ]);
  572. } catch (\Exception $e) {
  573. \Log::error('首充礼包奖励领取失败', [
  574. 'user_id' => $userId,
  575. 'error' => $e->getMessage()
  576. ]);
  577. return apiReturnFail(['web.gift.claim_failed', str_replace(':error', $e->getMessage(), __('web.gift.claim_failed'))]);
  578. }
  579. }
  580. /**
  581. * 获取首充礼包数据(包含充值档位列表)
  582. * @param $firstPayGift 礼包配置
  583. * @param $timeLeft 剩余秒数(已经是用户实际剩余时间)
  584. */
  585. private function getFirstPayGiftData($firstPayGift, $timeLeft)
  586. {
  587. // 获取支付方式
  588. // $names = DB::table('agent.dbo.admin_configs')
  589. // ->where([
  590. // 'type' => 'pay_method',
  591. // 'status' => 1,
  592. // ])
  593. // ->selectRaw('id, name, status, new_pay_type as type')
  594. // ->orderByDesc('sort')
  595. // ->get()
  596. // ->toArray();
  597. // 获取充值档位
  598. $list = DB::table('agent.dbo.recharge_gear')
  599. ->select('money', 'favorable_price', 'give','gear')
  600. ->orderBy('money', 'asc')
  601. ->where('status', 1)
  602. ->where('in_shop', 1)
  603. ->get();
  604. // $gear = \GuzzleHttp\json_encode($names);
  605. foreach ($list as &$val) {
  606. $val->favorable_price = $val->favorable_price + $val->give;
  607. // $val->gear = $gear;
  608. $val->recommend = 0;
  609. if ($val->money == $firstPayGift->recommend) {
  610. $val->recommend = 1;
  611. }
  612. if (!empty($val->gear)) {
  613. $val->gear = Util::filterGearByDevice($val->gear);
  614. }
  615. }
  616. return apiReturnSuc([
  617. 'list' => $list,
  618. 'gift_info' => [
  619. 'gift_id' => $firstPayGift->gift_id,
  620. 'gift_name' => $firstPayGift->gift_name,
  621. 'total_bonus' => $firstPayGift->total_bonus,
  622. 'bonus_instantly' => $firstPayGift->bonus_instantly,
  623. 'day_rewards' => $firstPayGift->day_rewards?json_decode($firstPayGift->day_rewards):'',
  624. 'betting_bonus' => $firstPayGift->betting_bonus?json_decode($firstPayGift->betting_bonus):'',
  625. 'betting_task' => $firstPayGift->betting_task?json_decode($firstPayGift->betting_task):'',
  626. ],
  627. 'time_left' => $timeLeft, // 剩余秒数
  628. 'expire_at' => time() + $timeLeft // 过期时间戳
  629. ]);
  630. }
  631. public function firstPayMulti(Request $request)
  632. {
  633. $user = LoginController::checkLogin($request);
  634. if($user){
  635. if(env('CONFIG_24680_NFTD_99',0)==0)if($user->Channel==99)return apiReturnFail();
  636. $fpkey='Firstpay_'.$user->UserID;
  637. if(Redis::exists($fpkey)){
  638. $data=Redis::get($fpkey);
  639. $data=json_decode($data,true);
  640. $data['timeleft']=86400-(time()-$data['buytime']);
  641. return apiReturnSuc(['leftitem'=>$data]);
  642. }
  643. $user_recharge = DB::table(TableName::QPAccountsDB() . 'YN_VIPAccount')
  644. ->where('UserID', $user->UserID)
  645. ->value('Recharge') ?: 0;
  646. if($user_recharge)return apiReturnFail();
  647. }
  648. $items=DB::table('agent.dbo.recharge_gear')
  649. ->where('status',1)
  650. ->where('second_give','>',0)
  651. ->where('first_pay','>=', 1)
  652. ->select('gift_id','money','give','favorable_price','second_give')->get()->each(function($item){
  653. $item->id=28;
  654. })->toArray();
  655. $default=count($items)-1;
  656. return apiReturnSuc(compact('items','default'));
  657. }
  658. // 破产礼包
  659. public function bankruptcyGift(Request $request)
  660. {
  661. $user = $request->user();
  662. $this->setUserLocale($request);
  663. // 判断用户是否充值
  664. $user_recharge = DB::table(TableName::QPAccountsDB() . 'YN_VIPAccount')
  665. ->where('UserID', $user->UserID)
  666. ->value('Recharge') ?: 0;
  667. if ($user_recharge <= 0) {
  668. return apiReturnFail(['web.gift.user_not_recharged', __('web.gift.user_not_recharged')]);
  669. }
  670. // 获取所有破产礼包配置 (gift_id=302)
  671. $bankruptcyGifts = DB::table('agent.dbo.recharge_gift')
  672. ->where('gift_id', 302)
  673. ->get();
  674. if ($bankruptcyGifts->isEmpty()) {
  675. return apiReturnFail(['web.gift.bankruptcy_gift_not_exists', __('web.gift.bankruptcy_gift_not_exists')]);
  676. }
  677. $result = [];
  678. // 遍历每条礼包配置,根据 recommend 关联 recharge_gear
  679. foreach ($bankruptcyGifts as $gift) {
  680. $gear = DB::table('agent.dbo.recharge_gear')
  681. ->select('money', 'favorable_price', 'gear')
  682. ->where('money', $gift->recommend)
  683. ->where('status', 1)
  684. ->first();
  685. if ($gear) {
  686. $gear->gift_id = $gift->gift_id;
  687. $gear->total_bonus = $gift->total_bonus;
  688. $gear->bonus = $gift->total_bonus - 100;
  689. if (!empty($gear->gear)) {
  690. $gear->gear = Util::filterGearByDevice($gear->gear);
  691. }
  692. $result[] = $gear;
  693. }
  694. }
  695. // 按 money 排序
  696. usort($result, function($a, $b) {
  697. return $a->money <=> $b->money;
  698. });
  699. return apiReturnSuc($result);
  700. }
  701. // 每日首充礼包
  702. public function dailyFirstRechargeGift(Request $request)
  703. {
  704. $user = $request->user();
  705. $this->setUserLocale($request);
  706. // 检查用户今日是否已充值(完成任意档位充值后入口消失)
  707. $todayStart = date('Y-m-d') . ' 00:00:00';
  708. $todayEnd = date('Y-m-d') . ' 23:59:59';
  709. $todayRecharge = DB::table('agent.dbo.order')
  710. ->where('user_id', $user->UserID)
  711. ->where('pay_status', 1)
  712. ->where('GiftsID', 303)
  713. ->where('pay_at', '>=', $todayStart)
  714. ->where('pay_at', '<=', $todayEnd)
  715. ->first();
  716. // 如果今日已充值,返回入口消失标记
  717. if ($todayRecharge) {
  718. return apiReturnSuc([
  719. 'has_recharged_today' => true,
  720. 'message' => __('web.gift.recharged_today')
  721. ]);
  722. }
  723. // 获取每日首充礼包配置 (gift_id=303)
  724. $dailyGifts = DB::table('agent.dbo.recharge_gift')
  725. ->where('gift_id', 303)
  726. ->get();
  727. if ($dailyGifts->isEmpty()) {
  728. return apiReturnFail(['web.gift.daily_first_recharge_not_exists', __('web.gift.daily_first_recharge_not_exists')]);
  729. }
  730. $result = [];
  731. // 遍历每条礼包配置,根据 recommend 关联 recharge_gear
  732. foreach ($dailyGifts as $gift) {
  733. $gear = DB::table('agent.dbo.recharge_gear')
  734. ->select('money', 'favorable_price', 'gear', 'give')
  735. ->where('money', $gift->recommend)
  736. ->where('status', 1)
  737. ->first();
  738. if ($gear) {
  739. $gear->gift_id = $gift->gift_id;
  740. $gear->total_bonus = $gift->total_bonus;
  741. $gear->bonus = $gift->total_bonus - 100;
  742. $gear->recommend = $gift->first_pay?1:0;
  743. if (!empty($gear->gear)) {
  744. $gear->gear = Util::filterGearByDevice($gear->gear);
  745. }
  746. $result[] = $gear;
  747. }
  748. }
  749. // 按 money 排序
  750. usort($result, function($a, $b) {
  751. return $a->money <=> $b->money;
  752. });
  753. return apiReturnSuc([
  754. 'has_recharged_today' => false,
  755. 'list' => $result
  756. ]);
  757. }
  758. // 每日礼包(三档充值)
  759. public function dailyGift(Request $request)
  760. {
  761. $user = $request->user();
  762. $this->setUserLocale($request);
  763. // 获取每日礼包配置 (gift_id=304),应该有3档
  764. $dailyGifts = DB::table('agent.dbo.recharge_gift')
  765. ->where('gift_id', 304)
  766. ->orderBy('recommend', 'asc')
  767. ->get();
  768. if ($dailyGifts->isEmpty()) {
  769. return apiReturnFail(['web.gift.daily_gift_not_exists', __('web.gift.daily_gift_not_exists')]);
  770. }
  771. if ($dailyGifts->count() > 3) {
  772. // 如果配置超过3档,只取前3档
  773. $dailyGifts = $dailyGifts->take(3);
  774. }
  775. // 检查用户今日每档的充值状态
  776. $todayStart = date('Y-m-d') . ' 00:00:00';
  777. $todayEnd = date('Y-m-d') . ' 23:59:59';
  778. $todayRecharges = DB::table('agent.dbo.order')
  779. ->where('user_id', $user->UserID)
  780. ->where('GiftsID', 304)
  781. ->where('pay_status', 1)
  782. ->where('pay_at', '>=', $todayStart)
  783. ->where('pay_at', '<=', $todayEnd)
  784. ->pluck('amount')
  785. ->toArray();
  786. $result = [];
  787. $completedCount = 0;
  788. // 遍历每档配置
  789. foreach ($dailyGifts as $index => $gift) {
  790. $gear = DB::table('agent.dbo.recharge_gear')
  791. ->select('money', 'favorable_price', 'gear', 'give')
  792. ->where('money', $gift->recommend)
  793. ->where('status', 1)
  794. ->first();
  795. if ($gear) {
  796. // 检查该档位今日是否已充值(使用浮点数比较,允许小数点精度差异)
  797. $isCompleted = false;
  798. foreach ($todayRecharges as $rechargeAmount) {
  799. if (abs($rechargeAmount/100 - $gift->recommend) < 0.01) {
  800. $isCompleted = true;
  801. break;
  802. }
  803. }
  804. if ($isCompleted) {
  805. $completedCount++;
  806. }
  807. $gear->gift_id = $gift->gift_id;
  808. $gear->total_bonus = $gift->total_bonus;
  809. $gear->bonus = $gift->total_bonus - 100;
  810. $gear->is_completed = $isCompleted; // 是否已完成
  811. $gear->gear_index = $index + 1; // 档位序号(1,2,3)
  812. $gear->recommend = $gift->first_pay?1:0;
  813. if (!empty($gear->gear)) {
  814. $gear->gear = Util::filterGearByDevice($gear->gear);
  815. }
  816. $result[] = $gear;
  817. }
  818. }
  819. // 获取额外奖励金额(从任意一档的 task_bonus 字段获取,task_bonus 是数字字段)
  820. $taskBonus = null;
  821. $firstGift = $dailyGifts->first();
  822. if ($firstGift && $firstGift->task_bonus !== null) {
  823. $taskBonus = round((float)$firstGift->task_bonus, 2);
  824. }
  825. // 检查是否可以领取额外奖励(三档都完成)
  826. $canClaimBonus = ($completedCount >= 3 && $taskBonus > 0);
  827. // 检查是否已领取过额外奖励
  828. $hasClaimedBonus = false;
  829. if ($canClaimBonus) {
  830. $redisKey = "daily_gift_bonus_claimed_{$user->UserID}_" . date('Y-m-d');
  831. $hasClaimedBonus = Redis::exists($redisKey);
  832. }
  833. return apiReturnSuc([
  834. 'list' => $result,
  835. 'completed_count' => $completedCount,
  836. 'total_count' => count($result),
  837. 'can_claim_bonus' => $canClaimBonus && !$hasClaimedBonus,
  838. 'has_claimed_bonus' => $hasClaimedBonus,
  839. 'task_bonus' => $taskBonus
  840. ]);
  841. }
  842. // 领取每日礼包三档完成后的额外奖励
  843. public function claimDailyGiftBonus(Request $request)
  844. {
  845. $user = $request->user();
  846. $userId = $user->UserID;
  847. $this->setUserLocale($request);
  848. // 检查三档是否都已完成
  849. $todayStart = date('Y-m-d') . ' 00:00:00';
  850. $todayEnd = date('Y-m-d') . ' 23:59:59';
  851. // 获取每日礼包配置
  852. $dailyGifts = DB::table('agent.dbo.recharge_gift')
  853. ->where('gift_id', 304)
  854. ->orderBy('recommend', 'asc')
  855. ->get()
  856. ->take(3);
  857. if ($dailyGifts->isEmpty()) {
  858. return apiReturnFail(['web.gift.daily_gift_not_exists', __('web.gift.daily_gift_not_exists')]);
  859. }
  860. // 检查每档今日是否都已充值
  861. $todayRecharges = DB::table('agent.dbo.order')
  862. ->where('user_id', $userId)
  863. ->where('GiftsID', 304)
  864. ->where('pay_status', 1)
  865. ->where('pay_at', '>=', $todayStart)
  866. ->where('pay_at', '<=', $todayEnd)
  867. ->pluck('amount')
  868. ->toArray();
  869. $completedCount = 0;
  870. foreach ($dailyGifts as $gift) {
  871. // 检查该档位是否已充值(使用浮点数比较)
  872. $isCompleted = false;
  873. foreach ($todayRecharges as $rechargeAmount) {
  874. if (abs($rechargeAmount/100 - $gift->recommend) < 0.01) {
  875. $isCompleted = true;
  876. break;
  877. }
  878. }
  879. if ($isCompleted) {
  880. $completedCount++;
  881. }
  882. }
  883. if ($completedCount < 3) {
  884. return apiReturnFail(['web.gift.three_tiers_not_completed', __('web.gift.three_tiers_not_completed')]);
  885. }
  886. // 检查是否已领取过
  887. $redisKey = "daily_gift_bonus_claimed_{$userId}_" . date('Y-m-d');
  888. if (Redis::exists($redisKey)) {
  889. return apiReturnFail(['web.gift.bonus_already_claimed_today', __('web.gift.bonus_already_claimed_today')]);
  890. }
  891. // 获取奖励金额(从任意一档的 task_bonus 获取,task_bonus 是数字字段)
  892. $firstGift = $dailyGifts->first();
  893. $rewardAmount = 0;
  894. if ($firstGift && $firstGift->task_bonus !== null) {
  895. $rewardAmount = round((float)$firstGift->task_bonus, 2);
  896. }
  897. if ($rewardAmount <= 0) {
  898. return apiReturnFail(['web.gift.bonus_config_not_exists', __('web.gift.bonus_config_not_exists')]);
  899. }
  900. try {
  901. // 发放奖励
  902. OuroGameService::AddScore($userId, $rewardAmount * NumConfig::NUM_VALUE, 52, true); // 52=礼包奖励
  903. // 标记已领取
  904. Redis::setex($redisKey, 86400, 1); // 24小时过期
  905. \Log::info('每日礼包额外奖励领取成功', [
  906. 'user_id' => $userId,
  907. 'reward_amount' => $rewardAmount
  908. ]);
  909. return apiReturnSuc([
  910. 'amount' => $rewardAmount,
  911. 'message' => str_replace(':amount', $rewardAmount, __('web.gift.claim_success'))
  912. ]);
  913. } catch (\Exception $e) {
  914. \Log::error('每日礼包额外奖励领取失败', [
  915. 'user_id' => $userId,
  916. 'error' => $e->getMessage()
  917. ]);
  918. return apiReturnFail(['web.gift.claim_failed', str_replace(':error', $e->getMessage(), __('web.gift.claim_failed'))]);
  919. }
  920. }
  921. public function getSecondGive(Request $request)
  922. {
  923. $user = $request->user();
  924. $fpkey='Firstpay_'.$user->UserID;
  925. if(Redis::exists($fpkey)){
  926. $data=Redis::get($fpkey);
  927. $data=json_decode($data,true);
  928. $data['timeleft']=86400-(time()-$data['buytime']);
  929. if($data['timeleft']<=0) {
  930. Redis::del($fpkey);
  931. //加钱
  932. if($data['second_give']){
  933. $czReason=$data['czReason'];
  934. $cjReason=$data['cjReason'];
  935. [$OrgScore,$NowScore]=OuroGameService::AddScore($user->UserID,$data['second_give']*NumConfig::NUM_VALUE,$cjReason);
  936. //更新二次领钱记录
  937. DB::table(TableName::agent() . 'guide_payment')->where('UserID',$user->UserID)->update([
  938. 'GetSecondTime' => now(),
  939. 'SecondScoreNum'=>$data['second_give']*NumConfig::NUM_VALUE
  940. ]);
  941. return apiReturnSuc(compact('OrgScore','NowScore'));
  942. }
  943. return apiReturnSuc();
  944. }
  945. }
  946. return apiReturnFail(['web.withdraw.try_again_later','Tente novamente mais tarde']);
  947. }
  948. /**
  949. * 连续未充值 VIP 礼包(gift_id=305)—— 检查条件和返回档位
  950. */
  951. public function vipInactiveGift(Request $request)
  952. {
  953. $user = $request->user();
  954. $this->setUserLocale($request);
  955. $userId = $user->UserID;
  956. // 1. VIP 判断:是否有过充值(YN_VIPAccount.Recharge > 0)
  957. $userRecharge = DB::table(TableName::QPAccountsDB() . 'YN_VIPAccount')
  958. ->where('UserID', $userId)
  959. ->value('Recharge') ?: 0;
  960. if ($userRecharge <= 0) {
  961. // 不满足条件:不是 VIP 用户
  962. return apiReturnSuc([
  963. 'status' => 0,
  964. 'message' => __('web.gift.vip_inactive_not_vip')
  965. ]);
  966. }
  967. // 2. 检查最近一次充值时间,计算连续未充值天数
  968. $lastOrder = DB::table('agent.dbo.order')
  969. ->where('user_id', $userId)
  970. ->where('pay_status', 1)
  971. ->where('GiftsID','<>', 305)
  972. ->orderBy('pay_at', 'desc')
  973. ->first();
  974. if (!$lastOrder) {
  975. return apiReturnSuc([
  976. 'status' => 0,
  977. 'message' => __('web.gift.vip_inactive_not_vip')
  978. ]);
  979. }
  980. $lastDate = date('Y-m-d', strtotime($lastOrder->pay_at));
  981. $today = date('Y-m-d');
  982. $diffDays = (strtotime($today) - strtotime($lastDate)) / 86400;
  983. // 连续未充值天数:如果最后一次充值是昨天,则未充值天数为0;如果是前天,则为1;以此类推
  984. // 需要 >= 3 天,即最后一次充值至少是3天前
  985. $inactiveDays = max(0, (int)$diffDays - 1);
  986. if ($inactiveDays < 3) {
  987. // 不满足条件:连续未充值天数不足
  988. return apiReturnSuc([
  989. 'status' => 0,
  990. 'message' => __('web.gift.vip_inactive_days_insufficient'),
  991. 'inactive_days' => $inactiveDays
  992. ]);
  993. }
  994. // 3. 计算总充值与平均单笔(从 RecordUserTotalStatistics)
  995. $stat = DB::table(TableName::QPRecordDB() . 'RecordUserTotalStatistics')
  996. ->where('UserID', $userId)
  997. ->select('Recharge', 'RechargeTimes')
  998. ->first();
  999. $totalRecharge = (float)($stat->Recharge ?? 0); // 转换为元
  1000. $rechargeTimes = (int)($stat->RechargeTimes ?? 0);
  1001. if ($totalRecharge <= 0 || $rechargeTimes <= 0) {
  1002. return apiReturnSuc([
  1003. 'status' => 0,
  1004. 'message' => __('web.gift.vip_inactive_not_vip')
  1005. ]);
  1006. }
  1007. $avgRecharge = $totalRecharge / $rechargeTimes;
  1008. // 4. 按规则选择礼包金额
  1009. $amount = null;
  1010. if ($totalRecharge < 50) {
  1011. $amount = $avgRecharge < 15 ? 9.99 : 19.99;
  1012. } else {
  1013. if ($avgRecharge < 15) {
  1014. $amount = 19.99;
  1015. } elseif ($avgRecharge >= 15 && $avgRecharge < 20) {
  1016. $amount = 29.99;
  1017. } else {
  1018. $amount = 39.99;
  1019. }
  1020. }
  1021. // 5. 检查是否已经买过 305 礼包
  1022. $hasBought = DB::table('agent.dbo.order')
  1023. ->where('user_id', $userId)
  1024. ->where('GiftsID', 305)
  1025. ->where('pay_status', 1)
  1026. ->exists();
  1027. // 6. 查询 7 日礼包记录状态
  1028. $record = DB::table('agent.dbo.inactive_vip_gift_records')
  1029. ->where('user_id', $userId)
  1030. ->where('gift_id', 305)
  1031. ->orderBy('id', 'desc')
  1032. ->first();
  1033. /*
  1034. * status 定义:
  1035. * 0 不满足条件
  1036. * 1 满足条件未充值
  1037. * 2 满足条件已充值,奖励未全部领取
  1038. * 3 满足条件已充值,奖励全部领取
  1039. * 4 满足条件已充值,7天礼包已过期
  1040. */
  1041. $status = 1;
  1042. $timeLeft = 0; // 倒计时剩余秒数
  1043. if ($hasBought) {
  1044. if (!$record) {
  1045. $status = 2;
  1046. } else {
  1047. // 检查 7 天礼包是否已过期
  1048. if (strtotime($record->expired_at) < time()) {
  1049. $status = 4; // 7天礼包已过期
  1050. } else {
  1051. // 检查 7 天是否全部领完:claimed_days_mask 的低 7 位全部为 1
  1052. $allClaimedMask = (1 << 7) - 1; // 0b1111111
  1053. $status = (($record->claimed_days_mask & $allClaimedMask) == $allClaimedMask) ? 3 : 2;
  1054. }
  1055. }
  1056. } else {
  1057. // 满足条件但未充值:检查24小时倒计时(每天重置)
  1058. $today = date('Y-m-d');
  1059. $timerKey = "vip_inactive_gift_timer_{$userId}_{$today}";
  1060. $timerData = Redis::get($timerKey);
  1061. if ($timerData) {
  1062. $timerData = json_decode($timerData, true);
  1063. $expireTime = $timerData['expire_time'] ?? 0;
  1064. $timeLeft = max(0, $expireTime - time());
  1065. if ($timeLeft <= 0) {
  1066. // 今天的倒计时已结束,不再显示礼包
  1067. $status = 0;
  1068. }
  1069. } else {
  1070. // 今天首次检测到满足条件,初始化24小时倒计时
  1071. // 从当前时间开始,24小时后过期
  1072. $expireTime = time() + 86400; // 24小时后
  1073. $ttl = 86400 + 3600; // Redis过期时间设为25小时,确保跨天也能获取
  1074. Redis::setex($timerKey, $ttl, json_encode([
  1075. 'expire_time' => $expireTime,
  1076. 'created_at' => time(),
  1077. 'date' => $today
  1078. ]));
  1079. $timeLeft = 86400;
  1080. }
  1081. }
  1082. $payload = [
  1083. 'status' => $status,
  1084. 'inactive_days' => $inactiveDays,
  1085. // 'total_recharge' => $totalRecharge,
  1086. // 'avg_recharge' => round($avgRecharge, 2),
  1087. 'time_left' => $timeLeft,
  1088. 'expire_at' => $timeLeft > 0 ? (time() + $timeLeft) : null,
  1089. 'message' => $status == 1 ? __('web.gift.vip_inactive_can_recharge') :
  1090. ($status == 2 ? __('web.gift.vip_inactive_claimed_partial') :
  1091. ($status == 3 ? __('web.gift.vip_inactive_claimed_all') :
  1092. __('web.gift.vip_inactive_seven_days_expired')))
  1093. ];
  1094. // status=1 时返回充值档位信息(参考 bankruptcyGift),gift_id 固定 305,加总奖励百分比
  1095. if ($status == 1 && $amount !== null) {
  1096. $sevenPercent = 140 + max(0, $inactiveDays - 3) * 10;
  1097. $sevenPercent = min($sevenPercent, 200);
  1098. $totalRewardPercent = 20 + $sevenPercent; // 120% 立即 + 7日礼包%
  1099. $gear = DB::table('agent.dbo.recharge_gear')
  1100. ->select('money', 'favorable_price', 'gear', 'give')
  1101. ->where('money', $amount)
  1102. ->where('status', 1)
  1103. ->first();
  1104. $favorablePrice = round($amount * 120 / 100, 2); // 305 固定 120% 立即到账
  1105. $give = $favorablePrice - $amount;
  1106. if ($gear) {
  1107. $gear->gift_id = 305;
  1108. $gear->favorable_price = $favorablePrice;
  1109. $gear->give = $give;
  1110. $gear->total_bonus = $totalRewardPercent;
  1111. $gear->bonus = $totalRewardPercent;
  1112. $gear->total_reward_percent = $totalRewardPercent;
  1113. $gear->recommend = 1;
  1114. if (!empty($gear->gear)) {
  1115. $gear->gear = Util::filterGearByDevice($gear->gear);
  1116. }
  1117. $payload['list'] = [$gear];
  1118. } else {
  1119. $payload['list'] = [(object)[
  1120. 'money' => $amount,
  1121. 'favorable_price' => $favorablePrice,
  1122. 'give' => $give,
  1123. 'gear' => null,
  1124. 'gift_id' => 305,
  1125. 'total_bonus' => $totalRewardPercent,
  1126. 'bonus' => $totalRewardPercent,
  1127. 'total_reward_percent' => $totalRewardPercent,
  1128. 'recommend' => 1,
  1129. ]];
  1130. }
  1131. $payload['amount'] = $amount;
  1132. $payload['total_reward_percent'] = $totalRewardPercent;
  1133. $payload['extra_reward'] = round($amount*$totalRewardPercent/100,2);
  1134. $payload['total_reward'] = round($amount*$totalRewardPercent/100+$amount,2);
  1135. } else {
  1136. $payload['amount'] = $amount;
  1137. if($record){
  1138. $payload['total_reward_percent'] = $record->total_percent-100;
  1139. }
  1140. }
  1141. return apiReturnSuc($payload);
  1142. }
  1143. /**
  1144. * 连续未充值 VIP 礼包(gift_id=305)—— 获取 7 日礼包信息
  1145. */
  1146. public function vipInactiveGiftSevenDays(Request $request)
  1147. {
  1148. $user = $request->user();
  1149. $this->setUserLocale($request);
  1150. $userId = $user->UserID;
  1151. // 获取 7 日礼包记录
  1152. $record = DB::table('agent.dbo.inactive_vip_gift_records')
  1153. ->where('user_id', $userId)
  1154. ->where('gift_id', 305)
  1155. ->orderBy('id', 'desc')
  1156. ->first();
  1157. if (!$record) {
  1158. return apiReturnFail(['web.gift.vip_inactive_no_record', __('web.gift.vip_inactive_no_record')]);
  1159. }
  1160. // 计算从充值完成后的第几天(第1天为充值当天)
  1161. // 如果 created_at 是 2024-01-01,今天是 2024-01-01,daysPassed=0,表示可以领取第1天的奖励
  1162. $createdDate = date('Y-m-d', strtotime($record->created_at));
  1163. $today = date('Y-m-d');
  1164. $daysPassed = floor((strtotime($today) - strtotime($createdDate)) / 86400);
  1165. // daysPassed = 0 表示充值当天(第1天),1 表示第2天,以此类推
  1166. // 检查是否已过期(超过7天)
  1167. $expiredAt = strtotime($record->expired_at);
  1168. $isExpired = time() > $expiredAt;
  1169. $perDayAmount = (float)$record->per_day_amount;
  1170. $claimedMask = (int)$record->claimed_days_mask;
  1171. // 构建每一天的状态(第1天为充值当天,对应 daysPassed = 0)
  1172. $days = [];
  1173. for ($day = 1; $day <= 7; $day++) {
  1174. $dayIndex = $day - 1; // 位索引:day1对应bit0
  1175. $isClaimed = ($claimedMask & (1 << $dayIndex)) > 0;
  1176. // 计算这一天对应的日期(充值后第 day-1 天;第1天为充值当天)
  1177. $targetDate = date('Ymd', strtotime($record->created_at . ' +' . ($day - 1) . ' days'));
  1178. // 判断状态
  1179. // 0=不可领取, 1=可领取, 2=已领取, 3=过期
  1180. $dayStatus = 0;
  1181. $betAmount = 0; // 初始化
  1182. // 第4-7天需要查询流水信息(无论状态如何,都要展示进度)
  1183. if ($day >= 4) {
  1184. // var_dump($userId,$day,$targetDate);
  1185. $todayBet = DB::table('QPRecordDB.dbo.RecordUserDataStatisticsNew')
  1186. ->where('UserID', $userId)
  1187. ->where('DateID', $targetDate)
  1188. ->value('TotalBet') ?? 0;
  1189. $betAmount = $todayBet / NumConfig::NUM_VALUE; // 转换为元
  1190. }
  1191. $dayOffset = $day - 1; // 第1天对应 offset=0
  1192. if ($isClaimed) {
  1193. $dayStatus = 2; // 已领取
  1194. } elseif ($daysPassed > $dayOffset) {
  1195. // 已过这一天但未领取:过期
  1196. // 例如:今天是第4天(daysPassed=4),但第3天的奖励还没领取,则第3天过期
  1197. $dayStatus = 3; // 过期
  1198. } elseif ($daysPassed < $dayOffset) {
  1199. // 还没到这一天:第 day 天的奖励需要在充值后的第 day-1 天才能领取
  1200. // 例如:第1天奖励需要 daysPassed >= 0(充值当天)才能领取
  1201. $dayStatus = 0; // 不可领取
  1202. } elseif ($isExpired || $daysPassed >= 7) {
  1203. // 整体过期(超过7天)时,未领取的奖励都过期
  1204. $dayStatus = 3; // 过期
  1205. } else {
  1206. // 到了这一天,判断是否可以领取
  1207. if ($day <= 3) {
  1208. // 前3天:直接领取
  1209. $dayStatus = 1; // 可领取
  1210. } else {
  1211. // 第4-7天:需要当天游戏流水 >= 100(流水信息已在上面查询)
  1212. if ($betAmount >= 100) {
  1213. $dayStatus = 1; // 可领取
  1214. } else {
  1215. $dayStatus = 0; // 不可领取(流水不足)
  1216. }
  1217. }
  1218. }
  1219. // 计算进度条数据(仅第4-7天)
  1220. $betProgress = null;
  1221. if ($day >= 4) {
  1222. $requiredBet = 100;
  1223. $currentBetValue = round($betAmount, 2);
  1224. $progressPercent = $requiredBet > 0 ? min(100, round(($currentBetValue / $requiredBet) * 100, 2)) : 0;
  1225. $betProgress = [
  1226. 'current' => $currentBetValue, // 当前流水
  1227. 'required' => $requiredBet, // 需要流水
  1228. 'progress_percent' => $progressPercent, // 进度百分比(0-100)
  1229. 'is_completed' => $currentBetValue >= $requiredBet // 是否完成
  1230. ];
  1231. }
  1232. $days[] = [
  1233. 'day' => $day,
  1234. 'amount' => $perDayAmount,
  1235. 'status' => $dayStatus,
  1236. 'status_text' => [
  1237. __('web.gift.status_cannot_claim'),
  1238. __('web.gift.status_can_claim'),
  1239. __('web.gift.status_claimed'),
  1240. __('web.gift.status_expired')
  1241. ][$dayStatus] ?? __('web.gift.status_unknown'),
  1242. 'target_date' => $targetDate,
  1243. 'bet_progress' => $betProgress // 第4-7天的流水进度信息
  1244. ];
  1245. }
  1246. // 检查是否有倒计时(未充值时的24小时倒计时)
  1247. $timerKey = "vip_inactive_gift_timer_{$userId}";
  1248. $timerData = Redis::get($timerKey);
  1249. $timeLeft = 0;
  1250. if ($timerData) {
  1251. $timerData = json_decode($timerData, true);
  1252. $expireTime = $timerData['expire_time'] ?? 0;
  1253. $timeLeft = max(0, $expireTime - time());
  1254. }
  1255. return apiReturnSuc([
  1256. 'record' => [
  1257. 'pay_amount' => (float)$record->pay_amount,
  1258. 'total_percent' => (float)$record->total_percent-100,
  1259. 'seven_days_percent' => (float)$record->seven_days_percent,
  1260. 'per_day_amount' => $perDayAmount,
  1261. 'inactive_days' => (int)$record->inactive_days,
  1262. 'created_at' => $record->created_at,
  1263. 'expired_at' => $record->expired_at
  1264. ],
  1265. 'days' => $days,
  1266. 'current_day' => min($daysPassed + 1, 7), // 当前是第几天
  1267. 'is_expired' => $isExpired,
  1268. 'time_left' => $timeLeft, // 未充值时的倒计时(秒)
  1269. 'expire_at' => $expiredAt
  1270. ]);
  1271. }
  1272. /**
  1273. * 连续未充值 VIP 礼包(gift_id=305)—— 领取某日奖励
  1274. */
  1275. public function claimVipInactiveGiftDayReward(Request $request)
  1276. {
  1277. $user = $request->user();
  1278. $this->setUserLocale($request);
  1279. $userId = $user->UserID;
  1280. $day = (int)$request->input('day', 0);
  1281. // if ($day < 1 || $day > 7) {
  1282. // return apiReturnFail(['web.gift.invalid_reward_type', __('web.gift.invalid_reward_type')]);
  1283. // }
  1284. // 获取 7 日礼包记录
  1285. $record = DB::table('agent.dbo.inactive_vip_gift_records')
  1286. ->where('user_id', $userId)
  1287. ->where('gift_id', 305)
  1288. ->orderBy('id', 'desc')
  1289. ->first();
  1290. if (!$record) {
  1291. return apiReturnFail(['web.gift.vip_inactive_no_record', __('web.gift.vip_inactive_no_record')]);
  1292. }
  1293. // 检查是否已过期
  1294. if (strtotime($record->expired_at) < time()) {
  1295. return apiReturnFail(['web.gift.vip_inactive_expired', __('web.gift.vip_inactive_expired')]);
  1296. }
  1297. // 计算从充值完成后的第几天(第1天为充值当天)
  1298. $createdDate = date('Y-m-d', strtotime($record->created_at));
  1299. $today = date('Y-m-d');
  1300. $daysPassed = floor((strtotime($today) - strtotime($createdDate)) / 86400);
  1301. $day = $daysPassed+1;
  1302. // 检查是否已领取
  1303. $claimedMask = (int)$record->claimed_days_mask;
  1304. $dayIndex = $day - 1;
  1305. if ($claimedMask & (1 << $dayIndex)) {
  1306. return apiReturnFail(['web.gift.vip_inactive_day_claimed', str_replace(':day', $day, __('web.gift.vip_inactive_day_claimed'))]);
  1307. }
  1308. // 第 day 天的奖励只能在充值后的第 day-1 天领取(daysPassed == day-1)
  1309. $dayOffset = $day - 1;
  1310. // 检查是否到了这一天
  1311. if ($daysPassed < $dayOffset) {
  1312. return apiReturnFail(['web.gift.vip_inactive_day_not_time', str_replace(':day', $day, __('web.gift.vip_inactive_day_not_time'))]);
  1313. }
  1314. // 检查是否已过期:如果已经过了这一天(daysPassed > day),则不能领取
  1315. if ($daysPassed > $dayOffset) {
  1316. return apiReturnFail(['web.gift.vip_inactive_day_expired', str_replace(':day', $day, __('web.gift.vip_inactive_day_expired'))]);
  1317. }
  1318. // 第4-7天需要检查当天游戏流水 >= 100
  1319. if ($day >= 4) {
  1320. $targetDate = date('Ymd', strtotime($record->created_at . ' +' . $dayOffset . ' days'));
  1321. $todayBet = DB::table('QPRecordDB.dbo.RecordUserDataStatisticsNew')
  1322. ->where('UserID', $userId)
  1323. ->where('DateID', $targetDate)
  1324. ->value('TotalBet') ?? 0;
  1325. $betAmount = $todayBet / NumConfig::NUM_VALUE; // 转换为元
  1326. if ($betAmount < 100) {
  1327. return apiReturnFail(['web.gift.vip_inactive_bet_insufficient', str_replace(':amount', 100, __('web.gift.vip_inactive_bet_insufficient'))]);
  1328. }
  1329. }
  1330. $amount = (float)$record->per_day_amount;
  1331. try {
  1332. // 发放奖励
  1333. OuroGameService::AddScore($userId, $amount * NumConfig::NUM_VALUE, 52, true); // 52=礼包奖励
  1334. // 更新位标记
  1335. $newMask = $claimedMask | (1 << $dayIndex);
  1336. DB::connection('write')->table('agent.dbo.inactive_vip_gift_records')
  1337. ->where('id', $record->id)
  1338. ->update([
  1339. 'claimed_days_mask' => $newMask,
  1340. 'updated_at' => date('Y-m-d H:i:s')
  1341. ]);
  1342. \Log::info('连续未充值VIP礼包奖励领取成功', [
  1343. 'user_id' => $userId,
  1344. 'day' => $day,
  1345. 'amount' => $amount
  1346. ]);
  1347. return apiReturnSuc([
  1348. 'amount' => $amount,
  1349. 'day' => $day,
  1350. 'message' => str_replace(':amount', $amount, __('web.gift.claim_success'))
  1351. ]);
  1352. } catch (\Exception $e) {
  1353. \Log::error('连续未充值VIP礼包奖励领取失败', [
  1354. 'user_id' => $userId,
  1355. 'day' => $day,
  1356. 'error' => $e->getMessage()
  1357. ]);
  1358. return apiReturnFail(['web.gift.claim_failed', str_replace(':error', $e->getMessage(), __('web.gift.claim_failed'))]);
  1359. }
  1360. }
  1361. }