<?php


namespace App\Services;


use App\dao\Estatisticas\RechargeWithDraw;
use App\Facade\TableName;
use App\Game\GlobalUserInfo;
use App\Game\Services\AgentService;
use App\Http\Controllers\Api\AgentController;
use App\Http\helper\Helper;
use App\Http\helper\HttpCurl;
use App\Http\helper\NumConfig;
use App\Jobs\AfEvent;
use App\Models\AgentUser;
use App\Models\RecordScoreInfo;
use App\Models\RecordUserDataStatistics;
use App\Services\HolidayWheelService;
use App\Util;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class  OrderServices
{
    public $FirstCharge = 30;
    public $FirstChargeGive = 20;

    public $FirstGiftID = 301;
    private $first_pay = null;

    public function __construct()
    {

    }

    /**
     * 获取支付金额
     * @param int $GiftsID 礼包ID
     * @param int $user_id 用户ID
     * @param int $payAmt 支付金额（元）
     * @return array|void [$give, $favorable_price, $Recharge, $czReason, $cjReason] 赠送金额，赠送金额+充值金额，充值金额，充值原因，彩金原因
     */
    public function getPayInfo($GiftsID, $user_id, $payAmt)
    {
        $give = $czReason = $cjReason = $Recharge = $favorable_price = $second_give = 0;
        $shouldCreateGiftRecord = false;  // 是否需要创建首充礼包记录

        // 判断是不是首冲礼包
        if (!empty($GiftsID)) {

            if ($GiftsID == 301) { // 礼包--首冲
                // 检查用户是否已购买过首充礼包
                $hasPurchased = DB::connection('write')->table('agent.dbo.first_pay_gift_records')
                    ->where('user_id', $user_id)
                    ->exists();
                
                if ($hasPurchased) {
                    // 已购买首充礼包，走普通充值逻辑（只加本金）
                    $Recharge = $payAmt;
                    $give = 0;               
                    $favorable_price = $Recharge + $give;
                    $czReason = 1;
                    $cjReason = 45;
                } else {
                    // 首次购买首充礼包，走赠送逻辑（立即获得bonus_instantly%）
                    $Gifts = DB::connection('write')->table('agent.dbo.recharge_gift')->where('gift_id', $GiftsID)->first();
                    $favorable_price = round($Gifts->bonus_instantly*$payAmt/100,2);
                    $give = $favorable_price-$payAmt;
                    $Recharge = $payAmt;
                    $czReason = 50;
                    $cjReason = 51;
                    
                    // 创建首充礼包记录
                    try {
                        $this->createFirstPayGiftRecord($user_id, $GiftsID, $payAmt);
                    } catch (\Exception $e) {
                        \Log::error('首充礼包记录创建失败', [
                            'user_id' => $user_id,
                            'gift_id' => $GiftsID,
                            'error' => $e->getMessage()
                        ]);
                    }
                }
            } else if ($GiftsID == 302) { // 破产礼包
                // 检查用户今日是否已充值过破产礼包
                $todayRecharge = DB::connection('write')->table('agent.dbo.order')
                    ->where('user_id', $user_id)
                    ->where('GiftsID', 302)
                    ->where('pay_status', 1)
                    ->whereDate('created_at', date('Y-m-d'))
                    ->first();
                // 今日首次购买破产礼包，走赠送逻辑
                $Gifts = DB::connection('write')->table('agent.dbo.recharge_gift')->where('gift_id', $GiftsID)->where('recommend', $payAmt)->first();
                if($Gifts && !$todayRecharge){
                    $favorable_price = round($Gifts->bonus_instantly*$payAmt/100,2);
                    $give = $favorable_price-$payAmt;
                    $Recharge = $payAmt;
                    $czReason = 50;
                    $cjReason = 51;
                }else{
                    $Recharge = $payAmt;
                    $give = 0;
                    $favorable_price = $Recharge + $give;
                    $czReason = 1;
                    $cjReason = 45;
                }

            }else if ($GiftsID == 303) { // 每日首充礼包
                // 检查用户今日是否已充值过每日首充礼包
                $todayStart = date('Y-m-d') . ' 00:00:00';
                $todayEnd = date('Y-m-d') . ' 23:59:59';
                
                $todayRecharge = DB::connection('write')->table('agent.dbo.order')
                    ->where('user_id', $user_id)
                    ->where('GiftsID', 303)
                    ->where('pay_status', 1)
                    ->where('pay_at', '>=', $todayStart)
                    ->where('pay_at', '<=', $todayEnd)
                    ->first();
                
                if ($todayRecharge) {
                    // 今日已充值过，只发放本金（不发放奖励）
                    $Recharge = $payAmt;
                    $give = 0;
                    $favorable_price = $Recharge + $give;
                    $czReason = 1;
                    $cjReason = 45;
                } else {
                    // 今日未充值过，按照礼包配置的比例发放
                    $Gifts = DB::connection('write')->table('agent.dbo.recharge_gift')
                        ->where('gift_id', $GiftsID)
                        ->where('recommend', $payAmt)
                        ->first();
                    
                    if($Gifts){
                        $favorable_price = round($Gifts->bonus_instantly*$payAmt/100,2);
                        $give = $favorable_price-$payAmt;
                        $Recharge = $payAmt;
                        $czReason = 50;
                        $cjReason = 51;
                    }else{
                        // 如果没有找到对应的礼包配置，按照普通充值处理
                        $Recharge = $payAmt;
                        $give = 0;
                        $favorable_price = $Recharge + $give;
                        $czReason = 1;
                        $cjReason = 45;
                    }
                }

            }else if ($GiftsID == 304) { // 每日礼包（三档充值）
                // 检查用户今日是否已充值过该档位的每日礼包
                $todayStart = date('Y-m-d') . ' 00:00:00';
                $todayEnd = date('Y-m-d') . ' 23:59:59';
                
                $todayRecharge = DB::connection('write')->table('agent.dbo.order')
                    ->where('user_id', $user_id)
                    ->where('GiftsID', 304)
                    ->where('amount', $payAmt) // 检查该档位金额
                    ->where('pay_status', 1)
                    ->where('pay_at', '>=', $todayStart)
                    ->where('pay_at', '<=', $todayEnd)
                    ->first();
                
                if ($todayRecharge) {
                    // 今日已充值过该档位，只发放本金（不发放奖励）
                    $Recharge = $payAmt;
                    $give = 0;
                    $favorable_price = $Recharge + $give;
                    $czReason = 1;
                    $cjReason = 45;
                } else {
                    // 今日未充值过该档位，按照礼包配置的比例发放
                    $Gifts = DB::connection('write')->table('agent.dbo.recharge_gift')
                        ->where('gift_id', $GiftsID)
                        ->where('recommend', $payAmt)
                        ->first();
                    
                    if($Gifts){
                        $favorable_price = round($Gifts->bonus_instantly*$payAmt/100,2);
                        $give = $favorable_price-$payAmt;
                        $Recharge = $payAmt;
                        $czReason = 50;
                        $cjReason = 51;
                    }else{
                        // 如果没有找到对应的礼包配置，按照普通充值处理
                        $Recharge = $payAmt;
                        $give = 0;
                        $favorable_price = $Recharge + $give;
                        $czReason = 1;
                        $cjReason = 45;
                    }
                }

            }else if ($GiftsID == 305) { // 连续未充值 VIP 新礼包
                // 305 改为按“轮次”判断：上一轮过期后可再次充值并获得新一轮奖励
                $latestRecord = DB::connection('write')->table('agent.dbo.inactive_vip_gift_records')
                    ->where('user_id', $user_id)
                    ->where('gift_id', 305)
                    ->orderBy('id', 'desc')
                    ->first();
                // 有记录：根据是否领满7天判断状态
                $allClaimedMask = (1 << 7) - 1;
                $canStartNewRound = !$latestRecord || ((($latestRecord->claimed_days_mask & $allClaimedMask) == $allClaimedMask));

                if (!$canStartNewRound) {
                    // 当前轮次未过期：只发放本金（不发放奖励）
                    $Recharge = $payAmt;
                    $give = 0;
                    $favorable_price = $Recharge + $give;
                    $czReason = 1;
                    $cjReason = 45;
                } else {
                    // 开启新一轮 305：无立即奖励，全部奖励通过 7 天签到领取
                    $Recharge = $payAmt;
                    $give = 0;
                    $favorable_price = $payAmt;
                    $czReason = 50;
                    $cjReason = 51;

                    // 确定奖励百分比
                    $bonusPercent = 100;
                    $stat = DB::connection('write')->table('QPRecordDB.dbo.RecordUserTotalStatistics')
                        ->where('UserID', $user_id)
                        ->select('Recharge', 'RechargeTimes')
                        ->first();
                    $totalRecharge = (float)($stat->Recharge ?? 0);
                    $rechargeTimes = (int)($stat->RechargeTimes ?? 0);
                    if ($rechargeTimes > 0) {
                        $avgRecharge = $totalRecharge / $rechargeTimes;
                        $tiers = $this->getRecallGiftTiers($avgRecharge);
                        foreach ($tiers as $tier) {
                            if ((float)$tier['amount'] == (float)$payAmt) {
                                $bonusPercent = $tier['bonus_percent'];
                                break;
                            }
                        }
                    }

                    $this->createInactiveVipGiftRecord($user_id, $payAmt, $bonusPercent);
                }

            } else if ($GiftsID == 306) { // free bonus礼包
                $Recharge = $payAmt;
                $give = 0;
                $favorable_price = $Recharge + $give;
                $czReason = 50;
                $cjReason = 51;
            } else if ($GiftsID > 400) {
                $Status = 1;
                $recharge_gear = DB::connection('write')->table('agent.dbo.recharge_gear')->where('status', $Status)->where('money', $payAmt)->select('favorable_price', 'give')->first();
                if(!$recharge_gear){
                    $Recharge=$payAmt;
                    $give=0;
                }else{
                    $Recharge = $recharge_gear->favorable_price;
                    $give = $recharge_gear->give;
                }

                $favorable_price = $Recharge + $give;
                $czReason = 1;
                $cjReason = 45;
            }

        } else { // 普通订单

            $Status = 1;
            $recharge_gear = DB::connection('write')->table('agent.dbo.recharge_gear')->where('status', $Status)->where('money', $payAmt)->select('favorable_price', 'give')->first();
            if(!$recharge_gear){
                $Recharge=$payAmt;
                $give=0;
            }else{
                $Recharge = $recharge_gear->favorable_price;
                $give = $recharge_gear->give;
            }

            $favorable_price = $Recharge + $give;
            $czReason = 1;
            $cjReason = 45;
        }

        return [$give, $favorable_price, $Recharge, $czReason, $cjReason, $second_give];

    }

    /**
     * 添加玩家充值记录
     * @param $user_id
     * @param $payAmt
     * @param $favorable_price
     * @param $order_sn
     * @param $GiftsID
     * @param $Recharge
     * @param $czReason
     * @param $give
     * @param $cjReason
     * @param $AdId
     * @param $eventType
     * @param mixed $fee 支付手续费
     */
    public function addRecord($user_id, $payAmt, $favorable_price, $order_sn, $GiftsID, $Recharge, $czReason, $give, $cjReason, $AdId, $eventType, $fee = 0)
    {

        if ($payAmt > 0) {

            // 增加玩家充值金额
            $query = DB::connection('write')->table('QPAccountsDB.dbo.YN_VIPAccount')
                ->where('UserID', $user_id)
                ->value('Recharge');
            if ($query) {
                DB::connection('write')->table('QPAccountsDB.dbo.YN_VIPAccount')
                    ->where('UserID', $user_id)
                    ->increment('Recharge', $payAmt);
            } else {
                DB::connection('write')->table('QPAccountsDB.dbo.YN_VIPAccount')
                    ->where('UserID', $user_id)
                    ->insert(['Recharge' => $payAmt, 'UserID' => $user_id]);

                // 首次充值：金币银币切换 + 数据清理
                /*
 * 金币银币切换 GameScoreInfo 将score的数据复制到 InsureScore 把Score 字段置0 把 ScoreChange字段设置成1
 * 清理用户的数据
 * GameScoreInfo的MaxScore MaxWinscore清0
 * RecordUserTotalStatistics 表 数据清0
 * RecordUserDataStatisticsNew 表数据 清0
 * RecordUserGameCount 关于用户的数据删除
 *
*/

                try {
                    $this->switchToInsureScoreAndCleanData($user_id);
                } catch (\Exception $e) {
                    \Log::error('首次充值-金币银币切换失败', [
                        'user_id' => $user_id,
                        'error' => $e->getMessage()
                    ]);
                }

            }

            //在这里更新 RecordUserTotalStatistics 数据 将LastRechargeValue字段更新为payAmt 如果不存在则插入
            DB::connection('write')->table('QPRecordDB.dbo.RecordUserTotalStatistics')
                ->updateOrInsert(['UserID' => $user_id], ['LastRechargeValue' => $payAmt]);

            // 节假日大转盘：根据充值金额增加转盘次数（首充礼包/破产礼包不计入）
            try {
                (new HolidayWheelService())->grantTimesOnRecharge($user_id, $payAmt, (int)$GiftsID);
            } catch (\Throwable $e) {
                \Log::error('holiday wheel grant times failed', [
                    'user_id' => $user_id,
                    'payAmt' => $payAmt,
                    'GiftsID' => $GiftsID,
                    'error' => $e->getMessage(),
                ]);
            }

            // 圣诞大转盘：根据充值金额增加转盘次数（首充礼包/破产礼包不计入）
            try {
                (new \App\Services\ChristmasWheelService())->grantTimesOnRecharge($user_id, $payAmt, (int)$GiftsID);
            } catch (\Throwable $e) {
                \Log::error('christmas wheel grant times failed', [
                    'user_id' => $user_id,
                    'payAmt' => $payAmt,
                    'GiftsID' => $GiftsID,
                    'error' => $e->getMessage(),
                ]);
            }


        }
        if ($Recharge > 0) {
            // 添加日志记录表
            StoredProcedure::addPlatformData($user_id, 3, $Recharge * NumConfig::NUM_VALUE);
            // 增加用户金币变化记录
            $AfterScore = RecordScoreInfo::addScore($user_id, ($Recharge * NumConfig::NUM_VALUE), $czReason); #充值
            if ($AfterScore) {
                RecordScoreInfo::addScore($user_id, ($give * NumConfig::NUM_VALUE), $cjReason, $AfterScore); #赠送彩金
            }
            // vip额外赠送
            if ($GiftsID == 0) {
                $userRecharge = $query ?: 0;
                $VIP = VipService::calculateVipLevel($user_id,$userRecharge);
                $level = VipService::getVipByField('VIP', $VIP);
                if ($level && $level->RechargeExtraSendRate > 0) {
                    $vipSendChips = floor($Recharge * NumConfig::NUM_VALUE * ($level->RechargeExtraSendRate/100));
                    if ($vipSendChips > 0) {
                        RecordScoreInfo::addScore($user_id, $vipSendChips, RecordScoreInfo::REASON_VIP_SEND_CHIPS, $AfterScore);
                        app(PaidRewardStatisticsService::class)
                            ->incrementRecordByDateIDAndType(date('Ymd'), 'vip_recharge', $vipSendChips);
                    }
                }
            }

            if (in_array($GiftsID, [0, 301, 302, 304, 305, 402]) && $give > 0) {
                $typeMap= [
                    0 => 'normal_recharge',
                    301 => 'first_recharge_gift',
                    302 => 'bankrupt_gift',
                    304 => 'daily_gift',
                    305 => 'vip_inactive_gift',
                    402 => 'christmas_gift',
                ];
                $type = $typeMap[intval($GiftsID)] ?? 'unknown_gift';
                app(PaidRewardStatisticsService::class)
                    ->incrementRecordByDateIDAndType(date('Ymd'), $type, $give * NumConfig::NUM_VALUE);
            }
            $typeMap= [
                0 => 'normal_recharge_chips',
                301 => 'first_recharge_gift_chips',
                302 => 'bankrupt_gift_chips',
                304 => 'daily_gift_chips',
                305 => 'vip_inactive_gift_chips',
                306 => 'free_bonus_gift_chips',
                402 => 'christmas_gift_chips',
            ];
            $type = $typeMap[intval($GiftsID)] ?? 'unknown_chips';
            app(PaidRewardStatisticsService::class)
                ->incrementRecordByDateIDAndType(date('Ymd'), $type, ($Recharge+$give) * NumConfig::NUM_VALUE);
            app(PaidRewardStatisticsService::class)
                ->incrementRecordByDateIDAndType(date('Ymd'), 'recharge_real', $Recharge * NumConfig::NUM_VALUE);


        }
        // free bonus 礼包：充值后赠送 InsureScore（单位为分）
        if (in_array($GiftsID, [306]) && $payAmt > 0) {
            $gift = DB::table('agent.dbo.recharge_gift')->lock('with(nolock)')
                ->where(['gift_id' => $GiftsID, 'recommend' => $Recharge])
                ->first();
            if ($gift && $gift->task_bonus > 0) {
                $bonus = (int) round($gift->task_bonus * NumConfig::NUM_VALUE);
                if ($bonus > 0) {
                    DB::table('QPTreasureDB.dbo.GameScoreInfo')
                        ->where('UserID', $user_id)
                        ->increment('InsureScore', $bonus);
                    app(PaidRewardStatisticsService::class)
                        ->incrementRecordByDateIDAndType(date('Ymd'), 'free_bonus_gift', $give * NumConfig::NUM_VALUE);
                }
            }
        }
        $favorable_price =  (int) round($favorable_price * NumConfig::NUM_VALUE) + ($vipSendChips ?? 0);
        $firstScore = DB::connection('write')->table('QPTreasureDB.dbo.GameScoreInfo')->where('UserID', $user_id)->value('Score');
        $Score = $favorable_price + $firstScore;




        if ($payAmt > 0) {

            // 记录订单变化后金币
            DB::connection('write')->table('agent.dbo.order')
                ->where('order_sn', $order_sn)
                ->update(['after_amount' => $Score]);

            // 增加用户充值变化值
            RecordUserDataStatistics::updateOrAdd($user_id, 0, $payAmt);

        }
        // 不是周卡的时候执行
        if ($GiftsID < 100 || $GiftsID >= 200) {
            // 增加用户金币
            DB::connection('write')->table('QPTreasureDB.dbo.GameScoreInfo')->where('UserID', $user_id)->increment('Score', $favorable_price);
        }


        // 充值推广佣金
//        (new AgentUser())->reward($user_id, $payAmt, $order_sn);
//


        // 周卡 -- 执行存储过程
//        if (isset($GiftsID) && $GiftsID > 100 && $GiftsID < 200) {
//            $CardID = (int)$GiftsID - 100;
//            StoredProcedure::BuyMonthCard($user_id, $CardID, $order_sn);
//            // 开始执行时间
//            $startTime = Helper::millisecond();
//            Log::info('GSP_GP_BuyMonthCard 执行时间：' . ((Helper::millisecond() - $startTime) / 1000));
//        }


        //设置第二天要领取
//        if (isset($GiftsID) && $GiftsID >= 200 && $GiftsID < 300 ) {
//            $first = DB::table('agent.dbo.recharge_gear')->where('gift_id', $GiftsID)->select('gift_id', 'money', 'give', 'favorable_price', 'second_give')->first();
//            if ($first && $first->second_give > 0) {
//                $fpkey = 'Firstpay_' . $user_id;
//                $data = (array)$first;
//                $data['buytime'] = time();
//                $data['czReason'] = $czReason;
//                $data['cjReason'] = $cjReason;
//                Redis::set($fpkey, json_encode($data));
//                DB::table(TableName::agent() . 'guide_payment')->updateOrInsert([
//                    'UserID'     => $user_id,
//                    'GiftID'     => $GiftsID,
//                    'CreateTime' => now()
//                ], ['UserID' => $user_id]);
//            }
//        }

        //设置第二天要领取
//        if (!empty($GiftsID) && $GiftsID >= 300 && $GiftsID < 400 ) {
//            Redis::del('repay_temp_'.$user_id);
//        }

        // 数据统计后台 -- 充值记录添加
        (new RechargeWithDraw())->recharge($user_id, $payAmt, $fee);
//        (new RechargeWithDraw())->recharge($user_id, $Recharge);

        // 连续未充值 VIP 新礼包（gift_id=305）—— 充值成功后写入 7 日礼包记录（仅在首次充值时）
//        if (!empty($GiftsID) && (int)$GiftsID === 305 && $payAmt > 0) {
//            // 检查是否已经充值过305礼包，只有在首次充值时才创建7日礼包记录
//            $hasPurchased305 = DB::connection('write')->table('agent.dbo.order')
//                ->where('user_id', $user_id)
//                ->where('GiftsID', 305)
//                ->where('pay_status', 1)
////                ->where('order_sn', '!=', $order_sn) // 排除当前订单
//                ->exists();
//
//            if (!$hasPurchased305) {
//                // 首次充值，创建7日礼包记录
//                try {
//                    $this->createInactiveVipGiftRecord($user_id, $payAmt);
//                } catch (\Exception $e) {
//                    \Log::error('inactive vip gift record create failed', [
//                        'user_id' => $user_id,
//                        'payAmt'  => $payAmt,
//                        'error'   => $e->getMessage(),
//                    ]);
//                }
//            }
//        }

//        if ($AdId && $payAmt) AfEvent::dispatch([$user_id, $payAmt, $AdId, $eventType]);
        try {
            //新邀请
            //(new AgentController())->processDeposit($user_id, $payAmt,$order_sn);

            AgentService::recordPerformance($user_id, $payAmt * NumConfig::NUM_VALUE);
        } catch (\Exception $exception) {
            Util::WriteLog("AgentService", $exception->getTraceAsString());
        }
        return [$Score];
    }

    /**
     * 执行存储过程
     * @param $user_id
     * @param $payAmt
     * @param $favorable_price
     * @param $Score
     * @param $GiftsID
     */
    public function storedProcedure($user_id, $payAmt, $favorable_price, $Score, $GiftsID)
    {


        // 开始执行时间
        $startTime = Helper::millisecond();

        // 执行存储过程 -- 防刷机制
        StoredProcedure::SetUserTabType($user_id);

        Log::info('GSP_GP_SetUserTabType12 执行时间：' . ((Helper::millisecond() - $startTime) / 1000));

        # 单控标签 -- 执行存储过程
        StoredProcedure::user_label($user_id, 1, $payAmt);

        Log::info('CheckAccountsLabel 执行时间：' . ((Helper::millisecond() - $startTime) / 1000));


        // 服务器通知
//        $url = config('transfer.stock')['url'] . 'notifyPay';
//        Log::info('中转服参数 ' . json_encode([
//                'userid'  => $user_id, 'getScore' => $favorable_price, 'score' => $Score,
//                'giftsid' => empty($GiftsID) ? 0 : $GiftsID,
//                'url'     => $url
//            ]));
//        $res = (new HttpCurl())->service($url, ['userid' => $user_id, 'getScore' => $favorable_price, 'score' => $Score, 'giftsid' => empty($GiftsID) ? 0 : $GiftsID]);
//
//        Log::info('中转服 执行时间：' . ((Helper::millisecond() - $startTime) / 1000), [
//            'res' => $res,
//        ]);


        // AF 事件
//        (new AppflyerEvent())->event($user_id, '', 'af_purchase_new', $payAmt);
//        Log::info('AF 执行时间：' . ((Helper::millisecond() - $startTime) / 1000));

    }

    /**
     * 首次充值：金币银币切换 + 数据清理
     * @param int $user_id 用户ID
     */
    private function switchToInsureScoreAndCleanData($user_id)
    {
        \Log::info('开始执行金币银币切换', ['user_id' => $user_id]);

        try {
            // 1. GameScoreInfo: 将Score的数据复制到InsureScore，把Score字段置0，把ScoreChange字段设置成1
            $scoreInfo = DB::connection('write')->table('QPTreasureDB.dbo.GameScoreInfo')
                ->where('UserID', $user_id)
                ->first();

            $freeSecond = 0;

            if ($scoreInfo) {
                DB::connection('write')->table('QPTreasureDB.dbo.GameScoreInfo')
                    ->where('UserID', $user_id)
                    ->update([
                        'InsureScore' => max($scoreInfo->Score,10000),  // 将Score复制到InsureScore
                        'Score' => 0,                         // Score置0
                        'ScoreChange' => 1,                   // ScoreChange设置成1
                        'MaxScore' => 0,                      // MaxScore清0
                        'MaxWinScore' => 0,                    // MaxWinScore清0
                        'PlayTimeCount' => 0,                   //重置游戏时间
                        'OnLineTimeCount' => $scoreInfo->PlayTimeCount, //赋值免费游戏时间
                    ]);
                $freeSecond =  $scoreInfo->PlayTimeCount;
                //TODO
                \Log::info('GameScoreInfo切换成功', [
                    'user_id' => $user_id,
                    'original_score' => $scoreInfo->Score,
                    'insure_score' => $scoreInfo->Score
                ]);
            }

            // 2. RecordUserTotalStatistics 表数据清0
            $totalStats = DB::connection('write')->table('QPRecordDB.dbo.RecordUserTotalStatistics')
                ->where('UserID', $user_id)
                ->first();

            if ($totalStats) {
                DB::connection('write')->table('QPRecordDB.dbo.RecordUserTotalStatistics')
                    ->where('UserID', $user_id)
                    ->update([
                        'WinInning' => 0,
                        'LostInning' => 0,
                        'Revenue' => 0,
                        'WinScore' => 0,
                        'LostScore' => 0,
                        'Handsel' => 0,
                        'DrawBase' => 0,
                        'TotalBet' => 0,
//                        'TotalScore' => 0,
                        'MaxDrawBase' => 0,
                        'MaxScore' => 0,
                        'MaxWinScore' => 0,
                        'Rounds' => 0,
                        'ProtectedRounds' => 0
                    ]);

                \Log::info('RecordUserTotalStatistics清0成功', ['user_id' => $user_id]);
            }

            // 3. RecordUserDataStatisticsNew 表数据清0
            DB::connection('write')->table('QPRecordDB.dbo.RecordUserDataStatisticsNew')
                ->where('UserID', $user_id)
                ->delete();

            \Log::info('RecordUserDataStatisticsNew清0成功', ['user_id' => $user_id]);

            $freeCount = DB::connection('read')->table(TableName::QPRecordDB() . 'RecordUserGameCount')
                ->where('UserID', $user_id)
                ->sum('Cnt');

            // 4. RecordUserGameCount 关于用户的数据删除
            DB::connection('write')->table('QPRecordDB.dbo.RecordUserGameCount')
                ->where('UserID', $user_id)
                ->delete();

            DB::connection('write')->table('QPRecordDB.dbo.RecordUserGameDayCount')
                ->where('UserID', $user_id)
                ->delete();



            $userModel = GlobalUserInfo::getGameUserInfo('UserID', $user_id);
            if ($userModel && $userModel->RegisterDate){
                $RecordPlatformDataModel = new \App\Models\RecordPlatformData();
                $RecordPlatformDataModel->UpdateFreeGameTime($userModel->Channel,$userModel->RegisterDate,$freeSecond,$freeCount);
            }

            \Log::info('RecordUserGameCount清除成功', ['user_id' => $user_id]);

            \Log::info('金币银币切换完成', [
                'user_id' => $user_id,
                'insure_score' => $scoreInfo->Score ?? 0
            ]);

        } catch (\Exception $e) {
            \Log::error('金币银币切换异常', [
                'user_id' => $user_id,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            throw $e;
        }
    }

    /**
     * 获取召回礼包（gift_id=305）三档金额及对应奖励百分比
     * 可用档位：9.99, 19.99, 29.99, 39.99, 49.99, 59.99, 79.99, 99.99
     * 初档 100% 加成，后续每档增加 15%
     * @param float $avgRecharge 用户平均充值金额
     * @return array [['amount'=>float, 'bonus_percent'=>int], ...] 三档信息
     */
    private function getRecallGiftTiers($avgRecharge)
    {
        $amounts = [9.99, 19.99, 29.99, 39.99, 49.99, 59.99, 79.99, 99.99];
        $bonusPercents = [100, 115, 130];

        $index = count($amounts);
        foreach ($amounts as $i => $amt) {
            if ($avgRecharge <= $amt) {
                $index = $i;
                break;
            }
        }
        if ($index > count($amounts) - 3) {
            $index = count($amounts) - 3;
        }

        $tiers = [];
        for ($i = 0; $i < 3; $i++) {
            $tiers[] = [
                'amount'        => $amounts[$index + $i],
                'bonus_percent' => $bonusPercents[$i],
            ];
        }

        return $tiers;
    }

    /**
     * 召回礼包（gift_id=305）—— 创建 7 日签到礼包记录
     * @param int   $user_id
     * @param float $payAmt       本次充值金额（元）
     * @param int   $bonusPercent 奖励百分比（70/85/100）
     */
    private function createInactiveVipGiftRecord($user_id, $payAmt, $bonusPercent = 70)
    {
        // 获取上一次充值订单
        $prevOrder = DB::connection('write')->table('agent.dbo.order')
            ->where('user_id', $user_id)
            ->where('pay_status', 1)
            ->where('GiftsID', '!=', 305)
            ->orderBy('pay_at', 'desc')
            ->first();

        $inactiveDays = 7;
        if ($prevOrder) {
            $prevDate = date('Y-m-d', strtotime($prevOrder->pay_at));
            $today = date('Y-m-d');
            $diffDays = (strtotime($today) - strtotime($prevDate)) / 86400;
            $inactiveDays = max(7, (int)$diffDays - 1);
        }

        // 总奖励百分比 = 100% 本金 + bonusPercent% 奖励
        $totalPercent = 100 + $bonusPercent;
        $sevenDaysPercent = $bonusPercent;

        // 7 天签到总奖励金额（全部通过签到领取）
        $totalBonus = round($payAmt * $bonusPercent / 100, 2);

        $now   = date('Y-m-d H:i:s');
        // 签到从充值次日开始，共 7 天，所以过期时间为创建时间 + 7 天
        $expAt = date('Y-m-d H:i:s', strtotime('+7 days'));

        DB::connection('write')->table('agent.dbo.inactive_vip_gift_records')->insert([
            'user_id'            => $user_id,
            'gift_id'            => 305,
            'pay_amount'         => $payAmt,
            'total_percent'      => $totalPercent,
            'seven_days_percent' => $sevenDaysPercent,
            'per_day_amount'     => $totalBonus, // 存储总奖励金额，按比例分配
            'inactive_days'      => $inactiveDays,
            'claimed_days_mask'  => 0,
            'created_at'         => $now,
            'updated_at'         => $now,
            'expired_at'         => $expAt,
        ]);
    }

    /**
     * 创建首充礼包记录
     */
    public function createFirstPayGiftRecord($user_id, $gift_id, $payAmt)
    {
        // 检查是否已有记录
        $existing = DB::connection('write')->table('agent.dbo.first_pay_gift_records')
            ->where('user_id', $user_id)
            ->first();
        
        if ($existing) {
            \Log::info('首充礼包记录已存在', ['user_id' => $user_id]);
            return;
        }
        
        // 获取礼包配置
        $giftConfig = DB::connection('write')->table('agent.dbo.recharge_gift')
            ->where('gift_id', $gift_id)
            ->first();
        
        if (!$giftConfig) {
            \Log::error('首充礼包配置不存在', ['gift_id' => $gift_id]);
            return;
        }
        
        // 计算金额
        $totalBonusAmount = round($giftConfig->total_bonus * $payAmt / 100, 2);
        $bonusInstantlyAmount = round($giftConfig->bonus_instantly * $payAmt / 100, 2);
        
        // 解析JSON数据
        $dayRewards = $giftConfig->day_rewards ? json_decode($giftConfig->day_rewards, true) : null;
        $bettingBonus = $giftConfig->betting_bonus ? json_decode($giftConfig->betting_bonus, true) : null;
        $bettingTask = $giftConfig->betting_task ? json_decode($giftConfig->betting_task, true) : null;
        
        // 计算各部分金额
        $dayRewardsTotal = $dayRewards ? round($dayRewards['total_bonus'] * $payAmt / 100, 2) : 0;
        $bettingBonusTotal = $bettingBonus ? round($bettingBonus['total_bonus'] * $payAmt / 100, 2) : 0;
        $bettingTaskTotal = $bettingTask ? round($bettingTask['total_bonus'] * $payAmt / 100, 2) : 0;
        
        // 创建记录
        $data = [
            'user_id' => $user_id,
            'gift_id' => $gift_id,
            'pay_amount' => $payAmt,
            'total_bonus' => $totalBonusAmount,
            'bonus_instantly' => $bonusInstantlyAmount,
            'gift_name' => $giftConfig->gift_name,
            
            // 每日奖励
            'day_rewards_total' => $dayRewardsTotal,
            'day_rewards_claimed' => 0,
            'day_rewards_data' => $giftConfig->day_rewards,
            'day_last_claim_date' => null,
            
            // 下注奖励
            'betting_bonus_total' => $bettingBonusTotal,
            'betting_bonus_claimed' => 0,
            'betting_bonus_data' => $giftConfig->betting_bonus,
            'betting_current_bet' => 0,
            
            // 下注任务
            'betting_task_total' => $bettingTaskTotal,
            'betting_task_claimed' => 0,
            'betting_task_data' => $giftConfig->betting_task,
            
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s')
        ];
        
        DB::connection('write')->table('agent.dbo.first_pay_gift_records')->insert($data);

        $dayRewardsTotal = $dayRewards ? round($dayRewards['total_bonus'] * $payAmt / 100, 2) : 0;
        $bettingBonusTotal = $bettingBonus ? round($bettingBonus['total_bonus'] * $payAmt / 100, 2) : 0;
        $bettingTaskTotal = $bettingTask ? round($bettingTask['total_bonus'] * $payAmt / 100, 2) : 0;
        
        \Log::info('首充礼包记录创建成功', [
            'user_id' => $user_id,
            'gift_id' => $gift_id,
            'pay_amount' => $payAmt,
            'total_bonus' => $totalBonusAmount,
            'rw' => [
                $dayRewardsTotal,
                $bettingBonusTotal,
                $bettingTaskTotal,
                round($dayRewards['total_bonus'] * $payAmt / 100, 2),
                round($bettingBonus['total_bonus'] * $payAmt / 100, 2),
                round($bettingTask['total_bonus'] * $payAmt / 100, 2)
            ]

        ]);
    }
}
