<?php


namespace App\Http\Controllers\Game;


use App\Facade\TableName;
use App\Game\Services\OuroGameService;
use App\Http\Controllers\Controller;
use App\Http\helper\NumConfig;
use App\Models\Order;
use App\Services\OrderServices;
use App\Utility\SetNXLock;
use App\Util;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class PayRechargeController extends Controller
{
    // 充值记录
    public function orderList(Request $request)
    {

        $user_id = (int)$request->globalUser->UserID;//$request->get('user_id', 1);

        $page = $request->get('page', 1);
        $pageSize = $request->get('pageSize', 7);
        $redisKey = 'PayRecharge_orderList_'.$user_id;
        if (!SetNXLock::getExclusiveLock($redisKey)) {
            return apiReturnFail(['web.withdraw.try_again_later','Tente novamente mais tarde']);
        }
        $where[] = ['user_id', $user_id];
        $where[] = ['pay_status', 1];


        $cacheTime = 60 * rand(1, 2);
//        $list = cache()->remember($user_id . '_order_list', $cacheTime, function () use ($where, $pageSize) {
//
//            return Order::where($where)
//                ->orderBy('finished_at', 'desc')
//                ->selectRaw('amount,payment_code,order_sn as payment_sn,finished_at,created_at,pay_status')
//                ->paginate(15,['*'],'page',1);
//        });


        $list = Order::query()->where($where)
            ->orderBy('finished_at', 'desc')
            ->selectRaw('amount,payment_code,order_sn as payment_sn,finished_at,created_at,pay_status,type')
            ->paginate($pageSize);
//            ->paginate(15,['*'],'page',1);

        foreach ($list as &$val) {
            $val->amount = number_format($val->amount, 2, '.', '');
        }
        SetNXLock::release($redisKey);


        return apiReturnSuc($list);
    }

    // 首充
    public function firstPay(Request $request)
    {
        $user = $request->user();
        $user_recharge = DB::table(TableName::QPAccountsDB() . 'YN_VIPAccount')
            ->where('UserID', $user->UserID)
            ->value('Recharge') ?: 0;
        if($user_recharge)return apiReturnSuc();

        $firstPayGift = DB::table('agent.dbo.recharge_gift')
            ->where('gift_id', 301)->first();
        if(!$firstPayGift) return apiReturnFail();

        $names = DB::table('agent.dbo.admin_configs')
            ->where([
                'type' => 'pay_method',
                'status' => 1,
            ])
            ->selectRaw('id, name, status, new_pay_type as type')
            ->orderByDesc('sort')->get()->toArray();

        $list = DB::table('agent.dbo.recharge_gear')
            ->select('id','money','favorable_price','give')
            ->orderBy('money', 'asc')->where('status', 1)->get();



        $gear = Util::filterGearByDevice(\GuzzleHttp\json_encode($names));
        foreach ($list as &$val) {
            $val->favorable_price = $val->favorable_price + $val->give;
            $val->gear = $gear;
            $val->recommend = 0;
            if($val->money == $firstPayGift->recommend){
                $val->recommend = 1;
            }
        }





        return apiReturnSuc(compact('list', 'firstPayGift'));
    }

    // 首充礼包（带倒计时逻辑）
    public function firstPayGift(Request $request)
    {
        $user = $request->user();
        
        // 获取礼包配置
        $giftConfig = DB::table('agent.dbo.recharge_gift')
            ->where('gift_id', 301)
            ->first();
        
        if (!$giftConfig) {
            return apiReturnFail('礼包配置不存在');
        }
        
        // 检查用户是否购买了首充礼包
        $giftRecord = DB::table('agent.dbo.first_pay_gift_records')
            ->where('user_id', $user->UserID)
            ->first();
        
        // ========== 未购买礼包：返回充值列表 + 礼包配置 + 倒计时 ==========
        if (!$giftRecord) {
            // 获取充值档位列表
            $list = DB::table('agent.dbo.recharge_gear')
                ->select('money', 'favorable_price', 'give', 'gear')
                ->orderBy('money', 'asc')
                ->where('status', 1)
                ->where('in_shop', 1)
                ->get();
            
            foreach ($list as &$val) {
                $val->favorable_price = $val->favorable_price + $val->give;
                $val->recommend = 0;
                if ($val->money == $giftConfig->recommend) {
                    $val->recommend = 1;
                }
                if (!empty($val->gear)) {
                    $val->gear = Util::filterGearByDevice($val->gear);
                }
            }
            
            // ========== 处理倒计时逻辑（仅未购买时） ==========
            $redisKey = "first_pay_gift_timer_{$user->UserID}";
            $currentTime = time();
            $timeLeft = 0;
            
            $timerData = Redis::get($redisKey);
            
            if ($timerData) {
                $timerData = json_decode($timerData, true);
                $firstRequestTime = $timerData['first_request_time'];
                $phase = $timerData['phase'];
                
                // 阶段1：valid_h倒计时
                if ($phase === 'first') {
                    $expireTime = $firstRequestTime + ($giftConfig->valid_h * 3600);
                    
                    if ($currentTime >= $expireTime) {
                        $expireDate = date('Y-m-d', $expireTime);
                        $currentDate = date('Y-m-d', $currentTime);
                        
                        if ($expireDate !== $currentDate) {
                            // 进入阶段2
                            $nextDayStart = time();
                            $newExpireTime = $nextDayStart + ($giftConfig->valid_h_2 * 3600);
                            
                            $newTimerData = [
                                'first_request_time' => $firstRequestTime,
                                'phase' => 'daily',
                                'current_cycle_start' => $nextDayStart,
                                'last_expire_time' => $newExpireTime
                            ];
                            Redis::set($redisKey, json_encode($newTimerData));
                            
                            $timeLeft = max(0, $newExpireTime - $currentTime);
                        }
                    } else {
                        $timeLeft = $expireTime - $currentTime;
                    }
                }
                // 阶段2：每日循环
                elseif ($phase === 'daily') {
                    $currentCycleStart = $timerData['current_cycle_start'];
                    $expireTime = $currentCycleStart + ($giftConfig->valid_h_2 * 3600);
                    
                    if ($currentTime >= $expireTime) {
                        $expireDate = date('Y-m-d', $expireTime);
                        $currentDate = date('Y-m-d', $currentTime);
                        
                        if ($expireDate !== $currentDate) {
                            $todayStart = time();
                            $newExpireTime = $todayStart + ($giftConfig->valid_h_2 * 3600);
                            
                            $newTimerData = [
                                'first_request_time' => $firstRequestTime,
                                'phase' => 'daily',
                                'current_cycle_start' => $todayStart,
                                'last_expire_time' => $newExpireTime
                            ];
                            Redis::set($redisKey, json_encode($newTimerData));
                            
                            $timeLeft = max(0, $newExpireTime - $currentTime);
                        }
                    } else {
                        $timeLeft = $expireTime - $currentTime;
                    }
                }
            } else {
                // 首次请求，初始化倒计时
                $expireTime = $currentTime + ($giftConfig->valid_h * 3600);
                $timerData = [
                    'first_request_time' => $currentTime,
                    'phase' => 'first',
                    'last_expire_time' => $expireTime
                ];
                Redis::set($redisKey, json_encode($timerData));
                $timeLeft = $giftConfig->valid_h * 3600;
            }
            
            return apiReturnSuc([
                'has_purchased' => false,  // 未购买标记
                'list' => $list,  // 充值档位列表
                'gift_info' => [
                    'gift_id' => $giftConfig->gift_id,
                    'gift_name' => $giftConfig->gift_name,
                    'total_bonus' => $giftConfig->total_bonus,
                    'bonus_instantly' => $giftConfig->bonus_instantly,
                    'day_rewards' => $giftConfig->day_rewards ? json_decode($giftConfig->day_rewards) : null,
                    'betting_bonus' => $giftConfig->betting_bonus ? json_decode($giftConfig->betting_bonus) : null,
                    'betting_task' => $giftConfig->betting_task ? json_decode($giftConfig->betting_task) : null,
                ],
                'time_left' => $timeLeft,  // ✅ 倒计时（未购买时展示）
                'expire_at' => time() + $timeLeft  // ✅ 过期时间戳
            ]);
        }
        
        // ========== 已购买礼包：返回任务进度（无倒计时） ==========
        
        // 获取用户当前累计下注（从统计表）
        $userStats = DB::table('QPRecordDB.dbo.RecordUserTotalStatistics')
            ->where('UserID', $user->UserID)
            ->first();
        
        $currentTotalBet = $userStats->TotalBet ?? 0;
        
        // 更新下注进度到礼包记录
        DB::table('agent.dbo.first_pay_gift_records')
            ->where('user_id', $user->UserID)
            ->update([
                'betting_current_bet' => $currentTotalBet / NumConfig::NUM_VALUE,
                'updated_at' => date('Y-m-d H:i:s')
            ]);
        
        // 重新获取最新记录
        $giftRecord = DB::table('agent.dbo.first_pay_gift_records')
            ->where('user_id', $user->UserID)
            ->first();
        
        // 解析任务数据
        $dayRewardsData = $giftRecord->day_rewards_data ? json_decode($giftRecord->day_rewards_data, true) : null;
        $bettingBonusData = $giftRecord->betting_bonus_data ? json_decode($giftRecord->betting_bonus_data, true) : null;
        $bettingTaskData = $giftRecord->betting_task_data ? json_decode($giftRecord->betting_task_data, true) : null;
        
        // 构建返回数据
        $giftInfo = [
            'gift_id' => $giftRecord->gift_id,
            'gift_name' => $giftRecord->gift_name,
            'total_bonus' => (float)$giftRecord->total_bonus,
            'bonus_instantly' => (float)$giftRecord->bonus_instantly,
            'pay_amount' => (float)$giftRecord->pay_amount,
        ];
        
        // 每日奖励进度
        if ($dayRewardsData) {
            // 计算当前是购买后的第几天
            $purchaseDate = date('Y-m-d', strtotime($giftRecord->created_at));
            $today = date('Y-m-d');
            $daysPassed = floor((strtotime($today) - strtotime($purchaseDate)) / 86400);
            
            $startDay = $dayRewardsData['start_day'] ?? 1;
            $bonusDay = $dayRewardsData['bonus_day'] ?? 0;
            $claimedDays = $giftRecord->day_rewards_claimed;
//            $startDay = $startDay-1;
            // 判断每日奖励状态
            // 0=不可领取, 1=可领取, 2=已领取, 3=过期
            $dayRewardStatus = 0;  // 默认不可领取
            
            // 检查是否过期（购买后7天）
            if ($daysPassed >= 7) {
                $dayRewardStatus = 3;  // 过期
            } elseif ($daysPassed >= $startDay-1) {
                // 计算今天是第几个奖励日（从起始天数开始）
                $rewardIndex = $daysPassed - ($startDay-1);
                
                if ($rewardIndex < $bonusDay) {
                    // 在奖励期内
                    if ($claimedDays > $rewardIndex) {
                        $dayRewardStatus = 2;  // 已领取
                    } else {
                        // 即便前几天漏领，后续奖励仍可继续领取（漏掉的视为作废）
                        $dayRewardStatus = 1;  // 可领取
                    }
                } else {
                    // 超过奖励天数
                    $dayRewardStatus = 2;  // 已领取完
                }
            }
            
            $giftInfo['day_rewards'] = [
                'total_bonus' => (float)$giftRecord->day_rewards_total,
                'bonus_day' => $bonusDay,
                'start_day' => $startDay,
                'bonus' => $dayRewardsData['bonus'] ?? [],
                'claimed_days' => $claimedDays,
                'progress' => $claimedDays . '/' . $bonusDay,
                'status' => $dayRewardStatus,  // 0=不可领取, 1=可领取, 2=已领取, 3=过期
                'status_text' => ['不可领取', '可领取', '已领取', '过期'][$dayRewardStatus] ?? '未知'
            ];
        }
        
        // 下注奖励进度
        if ($bettingBonusData) {
            $perBet = $bettingBonusData['per_bet'] ?? 100;  // 每次下注要求
            $perBetBonus = $bettingBonusData['per_bet_bonus'] ?? 2;  // 每次奖励金额（不是百分比）
            $currentBet = $giftRecord->betting_current_bet;  // 当前累计下注
            $totalBonusLimit = $giftRecord->betting_bonus_total;  // 总奖励上限
            $claimedAmount = $giftRecord->betting_bonus_claimed;  // 已领取金额
            $remainingBonus = $totalBonusLimit - $claimedAmount;  // 剩余可领取金额
            
            // 每次可领取的金额（直接使用配置的值，不是百分比计算）
            $perReward = (float)$perBetBonus;
            
            // 根据当前下注计算已达成的次数
            $completedTimes = floor($currentBet / $perBet);
            
            // 已领取的次数
            $claimedTimes = $claimedAmount > 0 ? floor($claimedAmount / $perReward) : 0;
            
            // 当前可领取次数（但不能超过剩余总额）
            $canClaimTimes = $completedTimes - $claimedTimes;
            $maxCanClaimTimes = floor($remainingBonus / $perReward);  // 剩余总额最多可领次数
            $canClaimTimes = min($canClaimTimes, $maxCanClaimTimes);
            
            // 当前可领取金额
            $canClaimAmount = min($canClaimTimes * $perReward, $remainingBonus);
            
            // 计算下次领取需要的下注金额
            $nextClaimBet = 0;
            if ($remainingBonus > 0 && $canClaimTimes == 0) {
                // 还有剩余奖励但当前不能领取，计算还需下注多少
                $nextClaimBet = ($claimedTimes + 1) * $perBet - $currentBet;
            }
            
            // 判断下注奖励状态
            // 0=不可领取（可领取金额为0）, 1=可领取, 2=已领取（所有奖励都领完）, 3=过期
            $bettingBonusStatus = 0;  // 默认不可领取
            
            // 检查是否过期（购买后7天）
            if ($daysPassed >= 7) {
                $bettingBonusStatus = 3;  // 过期
            } elseif ($remainingBonus <= 0) {
                $bettingBonusStatus = 2;  // 已领取完
            } elseif ($canClaimAmount > 0) {
                $bettingBonusStatus = 1;  // 可领取
            } else {
                $bettingBonusStatus = 0;  // 不可领取（下注不足）
            }
            
            $giftInfo['betting_bonus'] = [
                'total_bonus' => (float)$totalBonusLimit,  // 总奖励上限
                'per_bet' => $perBet,  // 每次下注要求
                'per_bet_bonus' => $perReward,  // 每次奖励金额（实际金额）
//                'per_reward' => $perReward,  // 每次奖励金额（保持兼容）
                'current_bet' => (float)$currentBet,  // 当前累计下注
                'claimed_amount' => (float)$claimedAmount,  // 已领取金额
                'remaining_bonus' => (float)$remainingBonus,  // 剩余可领金额
                'can_claim_amount' => (float)$canClaimAmount,  // 当前可领取金额
                'can_claim_times' => max(0, $canClaimTimes),  // 当前可领取次数
                'next_claim_bet' => max(0, $nextClaimBet),  // 下次领取还需下注
                'progress' => round($currentBet, 2) . '/' . round($claimedTimes * $perBet + $perBet, 2),  // 当前进度/下次领取目标
                'status' => $bettingBonusStatus,  // 0=不可领取, 1=可领取, 2=已领取, 3=过期
                'status_text' => ['不可领取', '可领取', '已领取', '过期'][$bettingBonusStatus] ?? '未知'
            ];
        }
        
        // 下注任务进度
        if ($bettingTaskData) {
            $betPayTimes = $bettingTaskData['bet_pay_times'] ?? 60;
            $requiredBet = $giftRecord->pay_amount * $betPayTimes;
            $currentProgress = $giftRecord->betting_current_bet;
            $taskCompleted = $currentProgress >= $requiredBet;
            $isClaimed = $giftRecord->betting_task_claimed == 1;
            
            // 判断下注任务状态
            // 0=不可领取, 1=可领取, 2=已领取, 3=过期
            $bettingTaskStatus = 0;  // 默认不可领取
            
            // 检查是否过期（购买后7天）
            if ($daysPassed >= 7) {
                $bettingTaskStatus = 3;  // 过期
            } elseif ($isClaimed) {
                $bettingTaskStatus = 2;  // 已领取
            } elseif ($taskCompleted) {
                $bettingTaskStatus = 1;  // 可领取（任务完成且未领取）
            } else {
                $bettingTaskStatus = 0;  // 不可领取（任务未完成）
            }
            
            $giftInfo['betting_task'] = [
                'total_bonus' => (float)$giftRecord->betting_task_total,
                'bet_pay_times' => $betPayTimes,
                'required_bet' => $requiredBet,  // 需要下注的金额
                'current_bet' => (float)$currentProgress,  // 当前累计下注
                'progress' => round($currentProgress, 2) . '/' . $requiredBet,
                'status' => $bettingTaskStatus,  // 0=不可领取, 1=可领取, 2=已领取, 3=过期
                'status_text' => ['不可领取', '可领取', '已领取', '过期'][$bettingTaskStatus] ?? '未知'
            ];
        }
        $giftInfo['expired'] = strtotime($giftRecord->created_at)+86400*7;
        return apiReturnSuc([
            'has_purchased' => true,  // 已购买标记
            'gift_info' => $giftInfo
            // ✅ 已购买用户不返回倒计时
        ]);
    }

    /**
     * 领取首充礼包奖励
     */
    public function claimFirstPayGiftReward(Request $request)
    {
        $user = $request->user();
        $userId = $user->UserID;
        $rewardType = $request->input('reward_type');  // 'day_reward', 'betting_bonus', 'betting_task'
        
        // 获取礼包记录
        $giftRecord = DB::table('agent.dbo.first_pay_gift_records')
            ->where('user_id', $userId)
            ->first();
        
        if (!$giftRecord) {
            return apiReturnFail('未购买首充礼包');
        }
        
        $rewardAmount = 0;
        
        try {
            // 每日奖励领取
            if ($rewardType === 'day_reward') {
                $dayRewardsData = json_decode($giftRecord->day_rewards_data, true);
                if (!$dayRewardsData) {
                    return apiReturnFail('没有每日奖励配置');
                }
                
                $bonusDay = $dayRewardsData['bonus_day'] ?? 0;
                $startDay = $dayRewardsData['start_day'] ?? 1;
                $bonusArray = $dayRewardsData['bonus'] ?? [];
                $claimedDays = $giftRecord->day_rewards_claimed;
                
                // 检查是否还有可领取的天数
                if ($claimedDays >= $bonusDay) {
                    return apiReturnFail('每日奖励已全部领取');
                }
                
                // 计算当前是购买后的第几天
                $purchaseDate = date('Y-m-d', strtotime($giftRecord->created_at));
                $currentDate = date('Y-m-d');
                $daysPassed = floor((strtotime($currentDate) - strtotime($purchaseDate)) / 86400);
                
                // 检查是否到了可以领取的天数（从第start_day天开始）
                if ($daysPassed < $startDay-1) {
                    return apiReturnFail('还未到可领取时间，需要从第' . $startDay . '天开始');
                }
                
                // 计算今天应该领取第几天的奖励
                // 例如：start_day=2，今天是第3天，应该领取第1个奖励（索引0）
                $todayRewardIndex = $daysPassed - ($startDay-1);
                
                // 检查是否超过奖励天数
                if ($todayRewardIndex >= $bonusDay) {
                    return apiReturnFail('每日奖励已过期');
                }
                
                // 检查今天是否已领取
                $lastClaimDate = $giftRecord->day_last_claim_date;
                if ($lastClaimDate && $lastClaimDate === $currentDate) {
                    return apiReturnFail('今天已经领取过了');
                }
                
                // 检查是否跳过了某些天（过期不补领）
                // 如果今天应该领第5天的奖励，但用户只领了3天，那就直接领第5天的
                if ($todayRewardIndex > $claimedDays) {
                    // 跳过了一些天，更新已领取天数为今天的索引
                    $claimedDays = $todayRewardIndex;
                }
                
                // 计算今天可领取的奖励（使用todayRewardIndex作为索引）
                $todayBonusPercent = $bonusArray[$todayRewardIndex] ?? 0;
                $rewardAmount = round($giftRecord->pay_amount * $todayBonusPercent / 100, 2);
                
                // 更新记录
                DB::table('agent.dbo.first_pay_gift_records')
                    ->where('user_id', $userId)
                    ->update([
                        'day_rewards_claimed' => $todayRewardIndex + 1,  // 已领取到第几天（索引+1）
                        'day_last_claim_date' => $currentDate,
                        'updated_at' => date('Y-m-d H:i:s')
                    ]);
            }
            // 下注奖励领取
            elseif ($rewardType === 'betting_bonus') {
                $bettingBonusData = json_decode($giftRecord->betting_bonus_data, true);
                if (!$bettingBonusData) {
                    return apiReturnFail('没有下注奖励配置');
                }
                
                $perBet = $bettingBonusData['per_bet'] ?? 100;  // 每次下注要求
                $perBetBonus = $bettingBonusData['per_bet_bonus'] ?? 2;  // 每次奖励金额（不是百分比）
                $currentBet = $giftRecord->betting_current_bet;  // 当前累计下注
                $totalBonusLimit = $giftRecord->betting_bonus_total;  // 总奖励上限
                $claimedAmount = $giftRecord->betting_bonus_claimed;  // 已领取金额
                $remainingBonus = $totalBonusLimit - $claimedAmount;  // 剩余可领金额
                
                // 检查是否还有剩余奖励
                if ($remainingBonus <= 0) {
                    return apiReturnFail('下注奖励已全部领取');
                }
                
                // 每次可领取的金额（直接使用配置的值，不是百分比计算）
                $perReward = (float)$perBetBonus;
                
                // 根据当前下注计算已达成的次数
                $completedTimes = floor($currentBet / $perBet);
                
                // 已领取的次数
                $claimedTimes = $claimedAmount > 0 ? floor($claimedAmount / $perReward) : 0;
                
                // 可领取次数（下注达成的次数 - 已领取次数）
                $canClaimTimes = $completedTimes - $claimedTimes;
                
                // 检查是否可以领取
                if ($canClaimTimes <= 0) {
                    return apiReturnFail('下注金额不足，还需下注 ' . (($claimedTimes + 1) * $perBet - $currentBet) . ' 才能领取');
                }
                
                // ✅ 一次性领取所有已达成的奖励（但不能超过剩余总额）
                $totalCanClaimAmount = $canClaimTimes * $perReward;  // 理论可领取总额
                $rewardAmount = min($totalCanClaimAmount, $remainingBonus);  // 实际领取金额（不超过剩余总额）
                $actualClaimTimes = floor($rewardAmount / $perReward);  // 实际领取次数
                
                // 更新记录
                DB::table('agent.dbo.first_pay_gift_records')
                    ->where('user_id', $userId)
                    ->update([
                        'betting_bonus_claimed' => $giftRecord->betting_bonus_claimed + $rewardAmount,
                        'updated_at' => date('Y-m-d H:i:s')
                    ]);
                
                \Log::info('下注奖励领取', [
                    'user_id' => $userId,
                    'can_claim_times' => $canClaimTimes,
                    'actual_claim_times' => $actualClaimTimes,
                    'reward_amount' => $rewardAmount
                ]);
            }
            // 下注任务领取
            elseif ($rewardType === 'betting_task') {
                if ($giftRecord->betting_task_claimed == 1) {
                    return apiReturnFail('下注任务奖励已领取');
                }
                
                $bettingTaskData = json_decode($giftRecord->betting_task_data, true);
                if (!$bettingTaskData) {
                    return apiReturnFail('没有下注任务配置');
                }
                
                $betPayTimes = $bettingTaskData['bet_pay_times'] ?? 60;
                $requiredBet = $giftRecord->pay_amount * $betPayTimes;
                $currentBet = $giftRecord->betting_current_bet;
                
                if ($currentBet < $requiredBet) {
                    return apiReturnFail('下注金额不足，需要下注 ' . $requiredBet);
                }
                
                $rewardAmount = $giftRecord->betting_task_total;
                
                // 更新记录
                DB::table('agent.dbo.first_pay_gift_records')
                    ->where('user_id', $userId)
                    ->update([
                        'betting_task_claimed' => 1,
                        'updated_at' => date('Y-m-d H:i:s')
                    ]);
            }
            else {
                return apiReturnFail('无效的奖励类型');
            }
            
            // 添加奖励到用户账户
            if ($rewardAmount > 0) {
                OuroGameService::AddScore($userId, $rewardAmount * NumConfig::NUM_VALUE, 52, true);  // 52=首充礼包奖励
                
                \Log::info('首充礼包奖励领取', [
                    'user_id' => $userId,
                    'reward_type' => $rewardType,
                    'amount' => $rewardAmount
                ]);
            }
            
            return apiReturnSuc([
                'amount' => $rewardAmount,
                'message' => '成功领取 ' . $rewardAmount . ' 奖励'
            ]);
            
        } catch (\Exception $e) {
            \Log::error('首充礼包奖励领取失败', [
                'user_id' => $userId,
                'error' => $e->getMessage()
            ]);
            return apiReturnFail('领取失败：' . $e->getMessage());
        }
    }

    /**
     * 获取首充礼包数据（包含充值档位列表）
     * @param $firstPayGift 礼包配置
     * @param $timeLeft 剩余秒数（已经是用户实际剩余时间）
     */
    private function getFirstPayGiftData($firstPayGift, $timeLeft)
    {
        // 获取支付方式
//        $names = DB::table('agent.dbo.admin_configs')
//            ->where([
//                'type' => 'pay_method',
//                'status' => 1,
//            ])
//            ->selectRaw('id, name, status, new_pay_type as type')
//            ->orderByDesc('sort')
//            ->get()
//            ->toArray();

        // 获取充值档位
        $list = DB::table('agent.dbo.recharge_gear')
            ->select('money', 'favorable_price', 'give','gear')
            ->orderBy('money', 'asc')
            ->where('status', 1)
            ->where('in_shop', 1)
            ->get();

//        $gear = \GuzzleHttp\json_encode($names);
        foreach ($list as &$val) {
            $val->favorable_price = $val->favorable_price + $val->give;
//            $val->gear = $gear;
            $val->recommend = 0;
            if ($val->money == $firstPayGift->recommend) {
                $val->recommend = 1;
            }
            if (!empty($val->gear)) {
                $val->gear = Util::filterGearByDevice($val->gear);
            }
        }

        return apiReturnSuc([
            'list' => $list,
            'gift_info' => [
                'gift_id' => $firstPayGift->gift_id,
                'gift_name' => $firstPayGift->gift_name,
                'total_bonus' => $firstPayGift->total_bonus,
                'bonus_instantly' => $firstPayGift->bonus_instantly,
                'day_rewards' => $firstPayGift->day_rewards?json_decode($firstPayGift->day_rewards):'',
                'betting_bonus' => $firstPayGift->betting_bonus?json_decode($firstPayGift->betting_bonus):'',
                'betting_task' => $firstPayGift->betting_task?json_decode($firstPayGift->betting_task):'',
            ],
            'time_left' => $timeLeft, // 剩余秒数
            'expire_at' => time() + $timeLeft // 过期时间戳
        ]);
    }

    public function firstPayMulti(Request $request)
    {
        $user = LoginController::checkLogin($request);
        if($user){
            if(env('CONFIG_24680_NFTD_99',0)==0)if($user->Channel==99)return apiReturnFail();
            $fpkey='Firstpay_'.$user->UserID;
            if(Redis::exists($fpkey)){
                $data=Redis::get($fpkey);
                $data=json_decode($data,true);
                $data['timeleft']=86400-(time()-$data['buytime']);
                return apiReturnSuc(['leftitem'=>$data]);
            }
            $user_recharge = DB::table(TableName::QPAccountsDB() . 'YN_VIPAccount')
                ->where('UserID', $user->UserID)
                ->value('Recharge') ?: 0;
            if($user_recharge)return apiReturnFail();
        }
        $items=DB::table('agent.dbo.recharge_gear')
            ->where('status',1)
            ->where('second_give','>',0)
            ->where('first_pay','>=', 1)
            ->select('gift_id','money','give','favorable_price','second_give')->get()->each(function($item){
                $item->id=28;
            })->toArray();
        $default=count($items)-1;

        return apiReturnSuc(compact('items','default'));
    }
    // 破产礼包
    public function bankruptcyGift(Request $request)
    {
        $user = $request->user();
        
        // 判断用户是否充值
        $user_recharge = DB::table(TableName::QPAccountsDB() . 'YN_VIPAccount')
            ->where('UserID', $user->UserID)
            ->value('Recharge') ?: 0;
        
        if ($user_recharge <= 0) {
            return apiReturnFail('用户未充值');
        }
        
        // 获取所有破产礼包配置 (gift_id=302)
        $bankruptcyGifts = DB::table('agent.dbo.recharge_gift')
            ->where('gift_id', 302)
            ->get();
        
        if ($bankruptcyGifts->isEmpty()) {
            return apiReturnFail('破产礼包配置不存在');
        }

        $result = [];
        
        // 遍历每条礼包配置，根据 recommend 关联 recharge_gear
        foreach ($bankruptcyGifts as $gift) {
            $gear = DB::table('agent.dbo.recharge_gear')
                ->select('money', 'favorable_price', 'gear')
                ->where('money', $gift->recommend)
                ->where('status', 1)
                ->first();
            
            if ($gear) {
                $gear->gift_id = $gift->gift_id;
                $gear->total_bonus = $gift->total_bonus;
                $gear->bonus = $gift->total_bonus - 100;
                if (!empty($gear->gear)) {
                    $gear->gear = Util::filterGearByDevice($gear->gear);
                }
                $result[] = $gear;
            }
        }

        // 按 money 排序
        usort($result, function($a, $b) {
            return $a->money <=> $b->money;
        });

        return apiReturnSuc($result);
    }

    public function getSecondGive(Request $request)
    {
        $user = $request->user();
        $fpkey='Firstpay_'.$user->UserID;
        if(Redis::exists($fpkey)){
            $data=Redis::get($fpkey);
            $data=json_decode($data,true);
            $data['timeleft']=86400-(time()-$data['buytime']);
            if($data['timeleft']<=0) {
                Redis::del($fpkey);
                //加钱
                if($data['second_give']){
                    $czReason=$data['czReason'];
                    $cjReason=$data['cjReason'];
                    [$OrgScore,$NowScore]=OuroGameService::AddScore($user->UserID,$data['second_give']*NumConfig::NUM_VALUE,$cjReason);

                    //更新二次领钱记录
                    DB::table(TableName::agent() . 'guide_payment')->where('UserID',$user->UserID)->update([
                        'GetSecondTime' => now(),
                        'SecondScoreNum'=>$data['second_give']*NumConfig::NUM_VALUE
                    ]);
                    return apiReturnSuc(compact('OrgScore','NowScore'));
                }
                return apiReturnSuc();
            }


        }
        return apiReturnFail(['web.withdraw.try_again_later','Tente novamente mais tarde']);

    }





}
