<?php

namespace App\Http\Controllers\Game;

use App\dao\Estatisticas\RechargeWithDraw;
use App\Facade\TableName;
use App\Game\GlobalUserInfo;
use App\Game\RePayConfig;
use App\Game\Services\AgentService;
use App\Game\Services\LZCompressor\LZString as LZ;
use App\Game\Services\OuroGameService;
use App\Game\Services\RouteService;
use App\Game\Services\ServerService;
use App\Game\WebActivity;
use App\Game\WebChannelConfig;
use App\Http\Controllers\Controller;

use App\Game\RedEnvelopeConfig;
use App\Game\RedEnvelopeLog;
use App\Http\helper\Helper;
use App\Http\helper\NumConfig;
use App\Jobs\AfEvent;
use App\Models\AccountsInfo;
use App\Models\Order;
use App\Models\PrivateMail;
use App\Models\RecordUserDataStatistics;
use App\Models\Treasure\GameScoreInfo;
use App\Notification\TelegramBot;
use App\Services\OrderServices;
use App\Services\PayConfig;
use App\Services\SmartFastPay;
use App\Services\StoredProcedure;
use App\Util;
use Illuminate\Http\Request;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use PDO;

class ActivityController extends Controller
{
    public function index()
    {

    }
    public function List(Request $request)
    {

        return apiReturnSuc(['list'=>WebActivity::query()->whereRaw(RouteService::getStateToWhereRaw($request))->get()->toArray()]);

    }
    public function GetProtectNum(Request $request)
    {

        $user=$request->user();
        if(ServerService::GetGlobalServerInfoByGUID($user->GlobalUID)['Subsite']=='Europe'){
            //欧洲暂时封闭
            return apiReturnSuc();
        }
        $UserID=$user->UserID;
        $res=DB::connection('sqlsrv')->select("exec QPAccountsDB.dbo.GSP_GP_QueryProtect $UserID");

        return apiReturnSuc($res);
    }
    public function AddProtectNum(Request $request)
    {

        $user=$request->user();
        $UserID=$user->UserID;

        if(ServerService::GetGlobalServerInfoByGUID($user->GlobalUID)['Subsite']=='Europe'){
            //欧洲暂时封闭
            return apiReturnSuc();
        }
        $dbh = DB::connection()->getPdo();

        $sql="
        set nocount on use QPAccountsDB;
        DECLARE @return_value INT;
        EXEC @return_value = QPAccountsDB.dbo.GSP_GP_AddProtect @dwUserID = $UserID;
        SELECT @return_value as ReturnValue;";

        $stmt = $dbh->prepare($sql);

        $stmt->execute();

        $result = $stmt->fetch(\PDO::FETCH_ASSOC);

//            dd($user,$result);
        // 获取返回值和错误描述
        $returnValue = $result['ReturnValue']??0;


//        $result=DB::connection('sqlsrv')->select('EXEC @return_value = QPAccountsDB.dbo.GSP_GP_AddProtect @dwUserID = '.$UserID.'; SELECT @return_value AS ReturnValue;');
        // 获取返回值
//        $returnValue = $result[1]->ReturnValue;
        if ($returnValue == 0) {
            return apiReturnSuc($result);
        } else if ($returnValue == 1) {
            return apiReturnFail(['web.protect.score_limit','Score limit reached']);
        } else if ($returnValue == 3) {
            return apiReturnFail(['web.protect.times_limit','Protect times limit reached']);
        } else {
            return apiReturnFail(['web.withdraw.try_again_later','Unknown error']);
        }
    }
    public function GetCheckInInfoConfig(Request $request)
    {
        $user=$request->user();
        $UserID=$user->UserID;
        $res=DB::connection('sqlsrv')->select("exec QPAccountsDB.dbo.GSP_GP_GetUserSignInInfo $UserID");
        $res2=DB::table('QPAccountsDB.dbo.UserSignInInfo')->where('UserID',$UserID)->first();
        $max=count($res);
        $res2=(array)$res2;

        if($res2['NextDayNumber']>$max) {
            $res2['NextDayNumber']= $res2['NextDayNumber'] % $max + 1;
            $res2['RecordDay']='';
            for($i=0;$i<$max;$i++) {

                $res2['RecordDay'].=$i<($res2['NextDayNumber']-1)?'1':'0';
            }
        }
        $res2['config']=$res;
        return apiReturnSuc($res2);

    }
    public function GetCheckInInfo(Request $request)
    {
        $user=$request->user();
        $UserID=$user->UserID;
        try {
            // 定义输出参数
            $errorDescribe = '';

            // 调用存储过程
//            $result = DB::connection('sqlsrv')->select('
//                use QPAccountsDB;
//                DECLARE @strErrorDescribe NVARCHAR(127);
//                DECLARE @return_value INT;
//                EXEC @return_value = QPAccountsDB.dbo.GSP_GP_UserSignIn @dwUserID = $UserID, @strErrorDescribe = @strErrorDescribe OUTPUT;
//                SELECT @return_value as ReturnValue, @strErrorDescribe as ErrorDescribe;
//            ', [$UserID]);
//


            $dbh = DB::connection()->getPdo();

            $sql="
        set nocount on use QPAccountsDB;
        DECLARE @strErrorDescribe NVARCHAR(127);
        DECLARE @return_value INT;
        EXEC @return_value = QPAccountsDB.dbo.GSP_GP_UserSignIn @dwUserID = $UserID, @strErrorDescribe = @strErrorDescribe OUTPUT;
        SELECT @return_value as ReturnValue, @strErrorDescribe as ErrorDescribe;";

            $stmt = $dbh->prepare($sql);

            $stmt->execute();

            $result = $stmt->fetch(\PDO::FETCH_ASSOC);

//            dd($user,$result);
            // 获取返回值和错误描述
            $returnValue = $result['ReturnValue']??0;
//            $errorDescribe = $result['ErrorDescribe'];

            // 根据返回值和错误描述处理
            switch ($returnValue) {
                case 1:
                    return apiReturnFail(['web.checkin.user_signin_error', 'Failed to get user sign-in information']);
                case 2:
                    return apiReturnFail(['web.checkin.user_already_signed_in', 'You have already signed in today']);
                case 3:
                    return apiReturnFail(['web.checkin.signin_event_ended', 'The sign-in activity has ended']);
                case 4:
                    return apiReturnFail(['web.checkin.signin_data_error', 'Failed to read sign-in data']);
                case 5:
                    return apiReturnFail(['web.checkin.recharge_required', 'Recharge is required to sign in'],[],777);
                case 0:
                    return apiReturnSuc($result);
                default:
                    return apiReturnFail(['web.checkin.unknown_error', 'Unknown error']);
            }
        } catch (\Exception $e) {
            TelegramBot::getDefault()->sendProgramNotify("Game Checkin:", $e->getMessage());
            // 捕获异常并返回错误响应
            return apiReturnFail(['web.checkin.exception_occurred', 'An error occurred while processing your request'], [], 500);
        }
    }
    public function RedConfig(Request $request){
        $config=Redis::get("RedEnvelopeConfig");
        if(!$config){
            $config=RedEnvelopeConfig::query()->get();
            Redis::set("RedEnvelopeConfig",json_encode($config));
            Redis::expire("RedEnvelopeConfig",600);
        }else{
            $config=json_decode($config,true);
        }
        return apiReturnSuc($config);
    }
    public function RedCheck(Request $request)
    {
        $maxRedpack=24680;
        $currentDateTime = Carbon::now();
        $currentTime = $currentDateTime->format('H:i:s');

        // 查找当前时间段内的红包配置
        $config = RedEnvelopeConfig::where('StartTime', '<=', $currentTime)
            ->where('EndTime', '>=', $currentTime)
            ->first();


        if ($config) {
            $getted=false;
            if($request->user()) {
                $userID=$request->user()->UserID;
                $checkKey = "redpack_$userID";
                $getted=Redis::exists($checkKey);

            }
            return apiReturnSuc(['status' => $getted?-1:1,'max'=>$maxRedpack]);
        } else {
            // 计算下一个红包时间
            $nextConfig = RedEnvelopeConfig::where('StartTime', '>', $currentTime)
                ->orderBy('StartTime', 'asc')
                ->first();

            if (!$nextConfig) {
                // 如果今天没有更多红包时间段，则查找明天的第一个红包时间段
                $nextConfig = RedEnvelopeConfig::orderBy('StartTime', 'asc')->first();
                $nextTime = Carbon::tomorrow()->setTimeFromTimeString($nextConfig->StartTime);
            } else {
                $nextTime = Carbon::today()->setTimeFromTimeString($nextConfig->StartTime);
            }

            $diffMinutes = $currentDateTime->diffInSeconds($nextTime);

            return apiReturnSuc(['status' => 0,'max'=>$maxRedpack, 'next_in_seconds' => $diffMinutes],['activity.redpack.please_wait','Please wait until next time.']);
        }
    }

    public function RedReceive(Request $request)
    {

        return apiReturnSuc(['status' => -1,'amount'=>0]);
        $user=$request->user();
        $userID = $user->UserID;
        $currentDateTime = Carbon::now();
        $currentTime = $currentDateTime->format('H:i:s');

        $checkKey="redpack_$userID";

        if(Redis::exists($checkKey)){
            return apiReturnSuc(['status' => -1,'amount'=>0]);
        }

        // 查找当前时间段内的红包配置
        $config = RedEnvelopeConfig::where('StartTime', '<=', $currentTime)
            ->where('EndTime', '>=', $currentTime)
            ->first();



        if ($config) {

            // 在红包活动时间段内，生成红包金额
            $amount = $this->generateRedEnvelopeAmount($user,$config);
            if(is_array($amount))return $amount;

            // 记录领取日志
            RedEnvelopeLog::create([
                'UserID'     => $userID,
                'ReceivedAt' => $currentDateTime,
                'Amount'     => $amount,
                'Comment'    => '红包雨活动'
            ]);
            Redis::set($checkKey,1);
            Redis::expire($checkKey,3600);

            return apiReturnSuc(['amount' => $amount,'status' => 1]);
        } else {
            // 不在红包活动时间段内
            return apiReturnFail(['web.activity.redpack_not_available','There is no RedPack']);
        }
    }

    /**
     * @param $user
     * @param RedEnvelopeConfig $config
     * @return array|int
     */
    private function generateRedEnvelopeAmount($user, $config)
    {
        //超过限额
        if($config->PrizePool>=3000){
            return 0;
        }
        $UserID=$user->UserID;
//        $recharinfo=DB::connection('write')->table('QPAccountsDB.dbo.YN_VIPAccount')
//            ->where('UserID', $UserID)->first();
//        // 根据用户的充值金额决定红包金额


        $userTotal = DB::connection('write')->table('QPRecordDB.dbo.RecordUserTotalStatistics')
            ->where('UserID', $UserID)
            ->first();
        $deposit = 0;
        $withdraw = 0;
        $revenue = 0;
        if($userTotal){
            $deposit = $userTotal->Recharge;
            $withdraw = $userTotal->Withdraw;
            $revenue = $userTotal->Revenue;
        }

        $amount = 0;

        if ($deposit == 0) {
            // 未充值用户无法领取红包
            return apiReturnFail(['web.activity.redpack_no_recharge', 'message' => 'You need deposit first!']);
        } elseif ($deposit < 50) {
            // 50以下
            if (rand(1, 100) <= 50) {
                $amount=0;
            } else {
                $amount = rand(1, 2);
            }
        } elseif ($deposit < 100) {
            // 50-100
            if (rand(1, 100) <= 40) {
                $amount=0;
            } else {
                $amount = rand(1, 5);
            }
        } elseif ($deposit < 500) {
            // 100-500
            if (rand(1, 100) <= 25) {
                $amount=0;
            } else {
                $amount = rand(5, 10);
            }
        } elseif ($deposit < 1000) {
            // 500-1000
            if (rand(1, 100) <= 20) {
                $amount=0;
            } else {
                $amount = rand(5, 15);
            }
        } elseif ($deposit < 5000) {
            // 1000-5000
            if (rand(1, 100) <= 10) {
                $amount=0;
            } else {
                $amount = rand(10, 30);
            }
        } elseif ($deposit < 20000) {
            // 5000-20000
            $amount = rand(20, 100);
        } elseif ($deposit < 200000) {
            // 20000-200000
            $amount = rand(100, 150);
        } else {
            // 200000以上
            $amount = rand(100, 300);
        }

        if($amount){


            //平台资产》充 减半
            if($withdraw + $revenue > $deposit*100 && $deposit>1000){
                $rate = max(($withdraw + $revenue) / ($deposit*100) * 2,2);
                $amount  = intval($amount/$rate);
            }

            //出》入 0
            if($withdraw > $deposit*100){
                $amount  = 0;
            }
        }


        if($amount){
            $config->increment('PrizePool', $amount);
            OuroGameService::AddScore($UserID,$amount*NumConfig::NUM_VALUE,OuroGameService::REASON_RedEnvelope);
//            OuroGameService::AddDrawBase($UserID,$amount*100,2);
        }
        return $amount;
    }
    public function repayFirst()
    {

        $str="10014268,2000,BRA2851903748065310014268
10014270,2000,BRA2855489212693610014270
10014271,2000,BRA2852393071882610014271
10014274,1000,BRA2853030100749910014274
10014276,1000,BRA2853245554392310014276
10014277,2000,BRA2853344779876810014277
10014277,2000,BRA2855290186893810014277
10014277,2000,BRA2864525856913410014277
10014281,1000,BRA2854641828657010014281
10014282,2000,BRA2854744724737410014282
10014285,2000,BRA2855039889866610014285
10014287,2000,BRA2855391649287010014287
10014288,1000,BRA2855464384803010014288
10014292,2000,BRA2856246492161510014292
10014297,1000,BRA2857229048633010014297
10014300,2000,BRA2858261561088610014300
10014301,2000,BRA2858433689840310014301
10014302,1000,BRA2858522897364510014302
10014305,2000,BRA2859083559189210014305
10014306,2000,BRA2859074387476010014306
10014308,2000,BRA2859253433784710014308
10014309,2000,BRA2859266221396810014309
10014311,1000,BRA2859721671820010014311
10014314,2000,BRA2860714714541810014314
10014316,2000,BRA2861078506701410014316
10014318,2000,BRA2861340050408610014318
10014324,2000,BRA2863987369403910014324
10014326,2000,BRA2862573151411810014326
10014327,2000,BRA2862997500499910014327
10014330,1000,BRA2863297592217210014330
10014332,2000,BRA2863120608306010014332
10014335,1000,BRA2975317980447310014335
10014339,2000,BRA2864730304211810014339
10014351,2000,BRA2869670282797610014351
10014352,2000,BRA2971319703907510014352
10014358,2000,BRA2973553150552010014358
10014372,2000,BRA2995159192410010014372
10014373,2000,BRA2995376698241510014373
10014375,2000,BRA2996350286730710014375
10014383,2000,BRA2902200217093410014383";
        $arr=explode("\n",$str);
        $sort=[];
        $g201 = DB::table('agent.dbo.recharge_gear')->where('gift_id', 201)->select('gift_id', 'money', 'give', 'favorable_price', 'second_give')->first();
        $g211 = DB::table('agent.dbo.recharge_gear')->where('gift_id', 211)->select('gift_id', 'money', 'give', 'favorable_price', 'second_give')->first();
        foreach ($arr as $k=>$v){
            [$UserID,$amount,$sn]=explode(',',$v);
            if(isset($sort[$UserID]))continue;
            $sort[$UserID]=$amount;

            if($amount==1000)$first=$g201;
            else $first=$g211;

            if ($first && $first->second_give > 0) {
                $bonus = '30000,' . $amount;
                PrivateMail::sendMail(2, $UserID, "Suplemento de erro de primeiro depósito", "Nós adicionamos para você, por favor, aceite.", $bonus, $sn, $amount);
                $fpkey = 'Firstpay_' . $UserID;
                $data = (array)$first;
                $data['buytime'] = time();
                $data['czReason'] = 1;
                $data['cjReason'] = 45;
                Redis::set($fpkey, json_encode($data));
                DB::table(TableName::agent() . 'guide_payment')->updateOrInsert([
                    'UserID'     => $UserID,
                    'GiftID'     => $amount==1000?201:211,
                    'CreateTime' => now()
                ], ['UserID' => $UserID]);
            }
        }
        dd($sort);

    }
    public static function decrypt($str){
        if (!isset($str)||!$str||empty($str)) {
            # code...
            return '';
        }
        $str=implode("+",explode(" ",$str));
        try {
            $destr=LZ::decompressFromBase64($str);
        }catch (\Exception $exception){
            Util::WriteLog('gamelz',$str);
            TelegramBot::getDefault()->sendProgramNotify("Game LZ decrypt:".$str);
            TelegramBot::getDefault()->sendProgramNotify("Game LZ decrypt:", $exception->getMessage().$exception->getTraceAsString());
            $destr=$str;
        }
        return $destr;


    }

    // ==================== VIP提现诱导功能 ====================

    /**
     * 获取用户VIP提现任务进度
     */
    public function getVipWithdrawTasks(Request $request)
    {
        $user = $request->user();
        $userId = $user->UserID;

        // 检查用户是否已充值
        $user_recharge = DB::table(TableName::QPAccountsDB() . 'YN_VIPAccount')
            ->where('UserID', $userId)
            ->value('Recharge') ?: 0;

        if ($user_recharge <= 0 &&!$request->input('is_test', 0)) {
            return apiReturnFail('请先充值后再查看任务-'.$userId);
        }

        // 获取用户任务数据
        $taskData = $this->getUserTaskData($userId);
        
        // 获取任务配置
        $taskConfig = $this->getTaskConfig();

        // 判断奖励状态：0-不能领取, 1-待领取, 2-已领取
        $stage1_reward_status = 0; // 不能领取
        if ($taskData['stage1_completed']) {
            $stage1_reward_status = $taskData['stage1_withdrawn'] ? 2 : 1; // 已领取 : 待领取
        }

        $stage2_reward_status = 0; // 不能领取
        if ($taskData['stage1_completed']) { // 阶段2需要阶段1完成才能解锁
            if ($taskData['stage2_completed']) {
                $stage2_reward_status = $taskData['stage2_withdrawn'] ? 2 : 1; // 已领取 : 待领取
            }
        }

        $stage3_task1_status = 0; // 不能领取
        $stage3_task2_status = 0; // 不能领取
        if ($taskData['stage2_completed']) { // 阶段3需要阶段2完成才能解锁
            // 循环任务：基于累计下注判断是否可领取（不使用已领取状态）
            if (($taskData['stage3_current_bet'] ?? 0) >= 6000) {
                $stage3_task1_status = 1; // 待领取
            }
            if (($taskData['stage3_current_bet'] ?? 0) >= 12000) {
                $stage3_task2_status = 1; // 待领取
            }
        }

        // 构建阶段1任务列表
        $stage1Tasks = [];
        foreach ($taskConfig['stage1']['tasks'] as $taskCfg) {
            $taskKey = $taskCfg['id'];
            $progressKey = $taskCfg['progress_key'];
            $completed = $taskData[$taskKey] ?? false;
            
            $stage1Tasks[] = [
                'id' => $taskCfg['id'],
                'title' => $taskCfg['title'],
                'type' => $taskCfg['type'],
                'completed' => $completed,
                'status' => $completed ? 1 : 0,
                'status_text' => $completed ? '已完成' : '未完成',
                'progress' => $taskData[$progressKey] ?? 0,
                'target' => $taskCfg['target']
            ];
        }

        // 构建任务结构
        $tasks = [
            'stage1' => [
                'stage' => 1,
                'title' => '阶段任务1',
                'reward' => $taskConfig['stage1']['reward'],
                'completed' => $taskData['stage1_completed'],
                'reward_status' => $stage1_reward_status,
                'reward_status_text' => ['不能领取', '待领取', '已领取'][$stage1_reward_status],
                'can_claim' => $stage1_reward_status === 1,
                'tasks' => $stage1Tasks
            ],
            'stage2' => [
                'stage' => 2,
                'title' => '阶段任务2',
                'reward' => $taskConfig['stage2']['reward'],
                'unlocked' => $taskData['stage1_completed'],
                'completed' => $taskData['stage2_completed'],
                'reward_status' => $stage2_reward_status,
                'reward_status_text' => ['不能领取', '待领取', '已领取'][$stage2_reward_status],
                'can_claim' => $stage2_reward_status === 1,
                'tasks' => array_map(function($taskCfg) use ($taskData) {
                    $taskKey = $taskCfg['id'];
                    $progressKey = $taskCfg['progress_key'];
                    $completed = $taskData[$taskKey] ?? false;
                    
                    return [
                        'id' => $taskCfg['id'],
                        'title' => $taskCfg['title'],
                        'type' => $taskCfg['type'],
                        'completed' => $completed,
                        'status' => $completed ? 1 : 0,
                        'status_text' => $completed ? '已完成' : '未完成',
                        'progress' => $taskData[$progressKey] ?? 0,
                        'target' => $taskCfg['target']
                    ];
                }, $taskConfig['stage2']['tasks'])
            ],
            'stage3' => [
                'stage' => 3,
                'title' => '阶段任务3（循环任务）',
                'unlocked' => $taskData['stage2_completed'],
                'is_loop' => true,
                'current_loop' => $taskData['stage3_loop_count'],
                'tasks' => array_map(function($taskCfg) use ($taskData, $stage3_task1_status, $stage3_task2_status) {
                    $taskKey = $taskCfg['id'];
                    $progressKey = $taskCfg['progress_key'];
                    $completed = $taskData[$taskKey] ?? false;
                    $rewardStatus = $taskKey === 'stage3_task1' ? $stage3_task1_status : $stage3_task2_status;
                    
                    return [
                        'id' => $taskCfg['id'],
                        'title' => $taskCfg['title'],
                        'type' => $taskCfg['type'],
                        'reward' => $taskCfg['reward'],
                        'completed' => $completed,
                        'reward_status' => $rewardStatus,
                        'reward_status_text' => ['不能领取', '待领取', '可重复领取'][$rewardStatus],
                        'can_claim' => $rewardStatus === 1,
                        'progress' => $taskData[$progressKey] ?? 0,
                        'target' => $taskCfg['target']
                    ];
                }, $taskConfig['stage3']['tasks'])
            ]
        ];

        return apiReturnSuc($tasks);
    }

    /**
     * 领取任务奖励（提现）
     */
    public function claimVipWithdrawReward(Request $request)
    {
        $user = $request->user();
        $userId = $user->UserID;
        $stage = (int)$request->input('stage');
        $taskId = $request->input('task_id', '');

        $redisLockKey = "vip_withdraw_claim_{$userId}";
        if (!Redis::set($redisLockKey, 1, 'EX', 10, 'NX')) {
            return apiReturnFail('操作太频繁，请稍后再试');
        }

        try {
            // 获取用户任务数据
            $taskData = $this->getUserTaskData($userId);
            $rewardAmount = 0;

            // 阶段1
            if ($stage === 1) {
                if (!$taskData['stage1_completed']) {
                    Redis::del($redisLockKey);
                    return apiReturnFail('任务未完成');
                }
                if ($taskData['stage1_withdrawn']) {
                    Redis::del($redisLockKey);
                    return apiReturnFail('奖励已领取');
                }
                $rewardAmount = 10;
                $this->updateTaskProgress($userId, 'stage1_withdrawn', 1);
            }
            // 阶段2
            elseif ($stage === 2) {
                if (!$taskData['stage2_completed']) {
                    Redis::del($redisLockKey);
                    return apiReturnFail('任务未完成');
                }
                if ($taskData['stage2_withdrawn']) {
                    Redis::del($redisLockKey);
                    return apiReturnFail('奖励已领取');
                }
                $rewardAmount = 10;
                $this->updateTaskProgress($userId, 'stage2_withdrawn', 1);
            }
            // 阶段3
            elseif ($stage === 3) {
                if ($taskId === 'stage3_task1') {
                    // 每满600可领取20，领取后扣除600下注进度
                    if (($taskData['stage3_current_bet'] ?? 0) < 6000) {
                        Redis::del($redisLockKey);
                        return apiReturnFail('任务未完成');
                    }
                    $rewardAmount = 20;
                    $this->updateTaskProgress($userId, 'stage3_current_bet', max(0, ($taskData['stage3_current_bet'] - 6000)));
                } 
                elseif ($taskId === 'stage3_task2') {
                    // 每满1200可领取40，领取后扣除1200下注进度
                    if (($taskData['stage3_current_bet'] ?? 0) < 12000) {
                        Redis::del($redisLockKey);
                        return apiReturnFail('任务未完成');
                    }
                    $rewardAmount = 40;
                    $this->updateTaskProgress($userId, 'stage3_current_bet', max(0, ($taskData['stage3_current_bet'] - 12000)));
                }
            } else {
                Redis::del($redisLockKey);
                return apiReturnFail('无效的阶段');
            }

            // 添加提现额度到用户账户
            if ($rewardAmount > 0) {
                OuroGameService::AddScore($userId, $rewardAmount * NumConfig::NUM_VALUE, 91, true);
                
                // 记录日志
                \Log::info('VIP提现任务奖励', [
                    'user_id' => $userId,
                    'stage' => $stage,
                    'task_id' => $taskId,
                    'amount' => $rewardAmount
                ]);
            }

            Redis::del($redisLockKey);
            return apiReturnSuc([
                'amount' => $rewardAmount,
                'message' => "成功领取 {$rewardAmount} 提现额度"
            ]);

        } catch (\Exception $e) {
            Redis::del($redisLockKey);
            \Log::error('VIP提现任务领取失败', [
                'user_id' => $userId,
                'error' => $e->getMessage()
            ]);
            return apiReturnFail('领取失败：' . $e->getMessage());
        }
    }

    /**
     * 获取用户任务数据（从Redis和数据库）
     */
    private function getUserTaskData($userId)
    {
        $redisKey = "vip_withdraw_task_{$userId}";
        $data = Redis::get($redisKey);

        if ($data) {
            $taskData = json_decode($data, true);
        } else {
            // 从数据库加载任务数据
            $dbData = DB::table('agent.dbo.vip_withdraw_tasks')
                ->where('user_id', $userId)
                ->first();
            
            if ($dbData) {
                $taskData = json_decode($dbData->task_data, true);
            } else {
                // 初始化任务数据
                $taskData = $this->initUserTaskData($userId);
            }
        }

        // 实时更新统计数据
        $this->updateRealTimeStats($userId, $taskData);

        // 检查任务完成状态
        $this->checkTaskCompletion($taskData);

        // 保存到数据库（持久化）
        $this->saveUserTaskData($userId, $taskData);

        // 保存到Redis（缓存24小时）
        Redis::setex($redisKey, 86400, json_encode($taskData));

        return $taskData;
    }

    /**
     * 保存用户任务数据到数据库
     */
    private function saveUserTaskData($userId, $taskData)
    {
        try {
            DB::table('agent.dbo.vip_withdraw_tasks')->updateOrInsert(
                ['user_id' => $userId],
                [
                    'task_data' => json_encode($taskData, JSON_UNESCAPED_UNICODE),
                    'updated_at' => date('Y-m-d H:i:s')
                ]
            );
        } catch (\Exception $e) {
            \Log::error('VIP提现任务数据保存失败', [
                'user_id' => $userId,
                'error' => $e->getMessage()
            ]);
        }
    }

    /**
     * 获取任务配置
     */
    private function getTaskConfig()
    {
        return [
            'stage1' => [
                'reward' => 10,
                'tasks' => [
                    [
                        'id' => 'stage1_task1',
                        'title' => '签到一次',
                        'type' => 'sign_in',
                        'target' => 1,
                        'progress_key' => 'sign_in_count'
                    ],
                    [
                        'id' => 'stage1_task2',
                        'title' => '下注金额达到100',
                        'type' => 'bet_amount',
                        'target' => 100,
                        'progress_key' => 'total_bet'
                    ],
                    [
                        'id' => 'stage1_task3',
                        'title' => '再充值一次',
                        'type' => 'recharge',
                        'target' => 1,
                        'progress_key' => 'recharge_count'
                    ]
                ]
            ],
            'stage2' => [
                'reward' => 10,
                'tasks' => [
                    [
                        'id' => 'stage2_task1',
                        'title' => '玩六款游戏',
                        'type' => 'play_games',
                        'target' => 6,
                        'progress_key' => 'played_games_count'
                    ],
                    [
                        'id' => 'stage2_task2',
                        'title' => '下注金额达到3000',
                        'type' => 'bet_amount',
                        'target' => 3000,
                        'progress_key' => 'total_bet'
                    ],
                    [
                        'id' => 'stage2_task3',
                        'title' => '发起一次邀请',
                        'type' => 'invite',
                        'target' => 1,
                        'progress_key' => 'invite_count'
                    ]
                ]
            ],
            'stage3' => [
                'tasks' => [
                    [
                        'id' => 'stage3_task1',
                        'title' => '下注金额达到6000',
                        'type' => 'bet_amount',
                        'target' => 6000,
                        'reward' => 20,
                        'progress_key' => 'stage3_current_bet'
                    ],
                    [
                        'id' => 'stage3_task2',
                        'title' => '下注金额达到12000',
                        'type' => 'bet_amount',
                        'target' => 12000,
                        'reward' => 40,
                        'progress_key' => 'stage3_current_bet'
                    ]
                ]
            ]
        ];
    }

    /**
     * 初始化用户任务数据
     */
    private function initUserTaskData($userId)
    {
        return [
            // 阶段1任务
            'stage1_task1' => false,
            'stage1_task2' => false,
            'stage1_task3' => false,
            'stage1_completed' => false,
            'stage1_withdrawn' => false,

            // 阶段2任务
            'stage2_task1' => false,
            'stage2_task2' => false,
            'stage2_task3' => false,
            'stage2_completed' => false,
            'stage2_withdrawn' => false,

            // 阶段3任务（循环）
            'stage3_task1' => false,
            'stage3_task2' => false,
            'stage3_task1_withdrawn' => false,
            'stage3_task2_withdrawn' => false,
            'stage3_loop_count' => 0,
            'stage3_current_bet' => 0,
            'stage3_available_amount' => 0,

            // 统计数据
            'total_bet' => 0,
            'recharge_count' => 0,
            'played_games_count' => 0,
            'invite_count' => 0,
            'sign_in_count' => 0
        ];
    }

    /**
     * 更新实时统计数据
     */
    private function updateRealTimeStats($userId, &$taskData)
    {

        $userTotalStatistics = DB::table('QPRecordDB.dbo.RecordUserTotalStatistics')
            ->where('UserID', $userId)
            ->first();

        // 获取总下注金额
        $totalBet =$userTotalStatistics ?$userTotalStatistics->TotalBet: 0;
        $taskData['total_bet'] = $totalBet / NumConfig::NUM_VALUE;

        // 获取充值次数
        $rechargeCount = $userTotalStatistics?$userTotalStatistics->RechargeTimes:0;
        $taskData['recharge_count'] = $rechargeCount;

        // 获取玩过的游戏数量（去重）
        $playedGames = DB::table('QPRecordDB.dbo.RecordUserGameCount')
            ->where('UserID', $userId)
            ->distinct()
            ->count('GameID');
        $taskData['played_games_count'] = $playedGames;

        // 邀请人数从Redis读取（通过 triggerInvite 方法触发）
        if (!isset($taskData['invite_count'])) {
            $taskData['invite_count'] = 0;
        }

        // 签到次数从Redis读取（通过 triggerSignIn 方法触发）
        if (!isset($taskData['sign_in_count'])) {
            $taskData['sign_in_count'] = 0;
        }

        // 阶段3累计下注：基于总下注的增量进行累加（非时间周期）
        if (!isset($taskData['stage3_current_bet'])) {
            $taskData['stage3_current_bet'] = 0;
        }
        if (!isset($taskData['stage3_last_total_bet'])) {
            $taskData['stage3_last_total_bet'] = $totalBet; // 记录原始总下注（原始单位）
        }
        // 计算本次新增下注（转为金额单位）
        $deltaBet = $totalBet - ($taskData['stage3_last_total_bet'] ?? 0);
        if ($deltaBet > 0) {
            $taskData['stage3_current_bet'] += ($deltaBet / NumConfig::NUM_VALUE);
            $taskData['stage3_last_total_bet'] = $totalBet;
        }
    }

    /**
     * 检查任务完成状态
     */
    private function checkTaskCompletion(&$taskData)
    {
        // 阶段1任务检查
        $taskData['stage1_task1'] = $taskData['sign_in_count'] >= 1;
        $taskData['stage1_task2'] = $taskData['total_bet'] >= 100;
        $taskData['stage1_task3'] = $taskData['recharge_count'] >= 1;
        $taskData['stage1_completed'] = $taskData['stage1_task1'] && 
                                         $taskData['stage1_task2'] && 
                                         $taskData['stage1_task3'];

        // 阶段2任务检查
        if ($taskData['stage1_completed']) {
            $taskData['stage2_task1'] = $taskData['played_games_count'] >= 6;
            $taskData['stage2_task2'] = $taskData['total_bet'] >= 3000;
            $taskData['stage2_task3'] = $taskData['invite_count'] >= 1;
            $taskData['stage2_completed'] = $taskData['stage2_task1'] && 
                                             $taskData['stage2_task2'] && 
                                             $taskData['stage2_task3'];
        }

        // 阶段3任务检查（循环）：基于累计下注，不使用时间周期
        if ($taskData['stage2_completed']) {
            $taskData['stage3_task1'] = ($taskData['stage3_current_bet'] ?? 0) >= 6000;
            $taskData['stage3_task2'] = ($taskData['stage3_current_bet'] ?? 0) >= 12000;
        }
    }

    /**
     * 更新任务进度
     */
    private function updateTaskProgress($userId, $key, $value)
    {
        $redisKey = "vip_withdraw_task_{$userId}";
        $data = Redis::get($redisKey);
        
        if ($data) {
            $taskData = json_decode($data, true);
            $taskData[$key] = $value;
            
            // ✅ 保存到数据库（持久化）
            $this->saveUserTaskData($userId, $taskData);
            
            // ✅ 更新Redis缓存（24小时）
            Redis::setex($redisKey, 86400, json_encode($taskData));
        }
    }

    /**
     * 重置阶段3循环任务
     */
    private function resetStage3Tasks($userId)
    {
        $redisKey = "vip_withdraw_task_{$userId}";
        $data = Redis::get($redisKey);
        
        if ($data) {
            $taskData = json_decode($data, true);
            $taskData['stage3_task1'] = false;
            $taskData['stage3_task2'] = false;
            $taskData['stage3_task1_withdrawn'] = false;
            $taskData['stage3_task2_withdrawn'] = false;
            $taskData['stage3_current_bet'] = 0;
            $taskData['stage3_cycle_start'] = (int)date('Ymd');
            $taskData['stage3_loop_count'] = ($taskData['stage3_loop_count'] ?? 0) + 1;
            
            // ✅ 保存到数据库（持久化）
            $this->saveUserTaskData($userId, $taskData);
            
            // ✅ 更新Redis缓存（24小时）
            Redis::setex($redisKey, 86400, json_encode($taskData));
        }
    }

    /**
     * 手动触发签到（供其他地方调用）
     * 注意：只有充值用户才会计数
     */
    public function triggerSignIn($userId)
    {
        // 检查用户是否已充值
        $user_recharge = DB::table(TableName::QPAccountsDB() . 'YN_VIPAccount')
            ->where('UserID', $userId)
            ->value('Recharge') ?: 0;
        
        if ($user_recharge <= 0) {
            \Log::info('VIP提现任务-签到触发失败', [
                'user_id' => $userId,
                'reason' => '用户未充值'
            ]);
            return false;
        }
        
        $redisKey = "vip_withdraw_task_{$userId}";
        $data = Redis::get($redisKey);
        
        if ($data) {
            $taskData = json_decode($data, true);
            $taskData['sign_in_count'] = ($taskData['sign_in_count'] ?? 0) + 1;
            
            // ✅ 保存到数据库（持久化）
            $this->saveUserTaskData($userId, $taskData);
            
            // ✅ 更新Redis缓存（24小时）
            Redis::setex($redisKey, 86400, json_encode($taskData));
            
            \Log::info('VIP提现任务-签到触发成功', [
                'user_id' => $userId,
                'sign_in_count' => $taskData['sign_in_count']
            ]);
            
            return true;
        } else {
            // 如果Redis没有数据，从数据库加载或初始化
            $dbData = DB::table('agent.dbo.vip_withdraw_tasks')
                ->where('user_id', $userId)
                ->first();
            
            if ($dbData) {
                $taskData = json_decode($dbData->task_data, true);
            } else {
                $taskData = $this->initUserTaskData($userId);
            }
            
            $taskData['sign_in_count'] = ($taskData['sign_in_count'] ?? 0) + 1;
            
            // ✅ 保存到数据库（持久化）
            $this->saveUserTaskData($userId, $taskData);
            
            // ✅ 更新Redis缓存（24小时）
            Redis::setex($redisKey, 86400, json_encode($taskData));
            
            \Log::info('VIP提现任务-签到触发成功（首次）', [
                'user_id' => $userId,
                'sign_in_count' => 1
            ]);
            
            return true;
        }
    }

    /**
     * 手动触发邀请（供其他地方调用）
     * 注意：只有充值用户且阶段1完成后才会计数
     */
    public function triggerInvite($userId)
    {
        // 检查用户是否已充值
        $user_recharge = DB::table(TableName::QPAccountsDB() . 'YN_VIPAccount')
            ->where('UserID', $userId)
            ->value('Recharge') ?: 0;
        
        if ($user_recharge <= 0) {
            \Log::info('VIP提现任务-邀请触发失败', [
                'user_id' => $userId,
                'reason' => '用户未充值'
            ]);
            return false;
        }
        
        $redisKey = "vip_withdraw_task_{$userId}";
        $data = Redis::get($redisKey);
        
        if ($data) {
            $taskData = json_decode($data, true);
            
            // 检查阶段1是否完成
            if (!isset($taskData['stage1_completed']) || !$taskData['stage1_completed']) {
                // 阶段1未完成，不计数
                \Log::info('VIP提现任务-邀请触发失败', [
                    'user_id' => $userId,
                    'reason' => '阶段1未完成',
                    'stage1_completed' => $taskData['stage1_completed'] ?? false
                ]);
                return false;
            }
            
            // 阶段1已完成，增加邀请计数
            $taskData['invite_count'] = ($taskData['invite_count'] ?? 0) + 1;
            
            // ✅ 保存到数据库（持久化）
            $this->saveUserTaskData($userId, $taskData);
            
            // ✅ 更新Redis缓存（24小时）
            Redis::setex($redisKey, 86400, json_encode($taskData));
            
            \Log::info('VIP提现任务-邀请触发成功', [
                'user_id' => $userId,
                'invite_count' => $taskData['invite_count']
            ]);
            
            return true;
        } else {
            // 如果Redis没有数据，从数据库加载
            $dbData = DB::table('agent.dbo.vip_withdraw_tasks')
                ->where('user_id', $userId)
                ->first();
            
            if ($dbData) {
                $taskData = json_decode($dbData->task_data, true);
                
                // 检查阶段1是否完成
                if (!isset($taskData['stage1_completed']) || !$taskData['stage1_completed']) {
                    \Log::info('VIP提现任务-邀请触发失败', [
                        'user_id' => $userId,
                        'reason' => '阶段1未完成'
                    ]);
                    return false;
                }
                
                // 增加邀请计数
                $taskData['invite_count'] = ($taskData['invite_count'] ?? 0) + 1;
                
                // ✅ 保存到数据库（持久化）
                $this->saveUserTaskData($userId, $taskData);
                
                // ✅ 更新Redis缓存（24小时）
                Redis::setex($redisKey, 86400, json_encode($taskData));
                
                \Log::info('VIP提现任务-邀请触发成功（从数据库加载）', [
                    'user_id' => $userId,
                    'invite_count' => $taskData['invite_count']
                ]);
                
                return true;
            } else {
                // 用户数据不存在或阶段1未完成
                \Log::info('VIP提现任务-邀请触发失败', [
                    'user_id' => $userId,
                    'reason' => '用户数据不存在或阶段1未完成'
                ]);
                return false;
            }
        }
    }

}
