<?php

namespace App\Http\Controllers\Api;

use App\Facade\TableName;
use App\Game\Services\OuroGameService;
use App\Http\Controllers\Controller;
use App\Http\helper\NumConfig;
use App\Models\AccountsInfo;
use App\Models\AgentDepositCommission;
use App\Models\AgentLevel;
use App\Models\AgentMaterial;
use App\Models\AgentTask;
use App\Models\AgentUserInfo;
use App\Models\AgentUserRecord;
use App\Models\AgentUserReward;
use App\Models\AgentUserTaskCompletion;
use App\Models\User;
use App\Models\AgentWithdrawal;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;

class AgentController extends Controller
{
    /**
     * 获取当前用户的代理信息
     */
    public function getInfo(Request $request)
    {
        $userId = $request->UserID;

        // 获取代理信息
        $agentInfo = AgentUserInfo::where('UserID', $userId)->first();

        if (!$agentInfo) {
            // 如果用户没有代理信息，创建一个新的
            $agentInfo = $this->createAgentInfo($userId);
        }

        // 获取用户的级别信息
        $levelInfo = AgentLevel::where('level', $agentInfo->level)->first();
//        $levelInfo = $agentInfo->agentLevel();

        // 获取下级用户数量
        $referralCount = AgentUserRecord::where('SpreaderID', $userId)
                                        ->where('is_valid', 1)
                                        ->count();
        $total_friends = AgentUserRecord::where('SpreaderID', $userId)
                                        ->count();
        //更新玩家
        if($total_friends!=$agentInfo->total_friends){
            $agentInfo->total_friends = $total_friends;
            $agentInfo->save();
        }

        //升级逻辑
        if($referralCount != $agentInfo->valid_referrals){
            // 更新有效邀请人数
            $agentInfo->valid_referrals = $referralCount;
            $agentInfo->save();

            // 检查并更新用户级别
            $this->updateUserLevel($userId);

            // 检查任务完成情况
//            $this->checkTaskCompletion($userId);
        }

        // 获取任务完成情况
        $completedTasks = AgentUserTaskCompletion::where('UserID', $userId)
                                                ->where('completed', 1)
                                                ->pluck('task_id')
                                                ->toArray();

        // 获取所有任务
        $allTasks = AgentTask::where('status', 1)
                            ->orderBy('required_referrals')
                            ->get();

        $tasks = [];
        foreach ($allTasks as $task) {
            $completed = in_array($task->id, $completedTasks);
            $canClaim = $agentInfo->valid_referrals >= $task->required_referrals && !$completed;
            $tasks[] = [
                'id' => $task->id,
                'taskid' => $task->taskid,
                'title' => $task->task_title,
                'required_referrals' => $task->required_referrals,
                'reward_amount' => $task->reward_amount,
                'completed' => $completed,
                'progress' => min($referralCount, $task->required_referrals),
                'total' => $task->required_referrals,
                'can_claim' => $canClaim
            ];
        }

        // 获取今日和昨日佣金
//        $todayCommission = $agentInfo->today_commission;
//        $yesterdayCommission = $agentInfo->yesterday_commission;
//        $totalCommission = $agentInfo->total_commission;

        // 获取下一级别
        $nextLevel = null;
        if ($levelInfo->level < 6) { // 假设6是最高级别
            $nextLevel = AgentLevel::where('level', $levelInfo->level + 1)->first();
        }

        return apiReturnSuc([
                'user_id' => $userId,
                'referral_code' => $agentInfo->referral_code,
                'referral_link' => env('SHARE_BASE_URL').'/'.$agentInfo->referral_code.'?ad='.rand(1,3),
                'level' => [
                    'name' => $levelInfo->level_name,
                    'level' => $levelInfo->level,
                    'commission_rate' => $levelInfo->commission_rate . '%',
                ],
                'next_level' => $nextLevel ? [
                    'name' => $nextLevel->level_name,
                    'level' => $nextLevel->level,
                    'required_referrals' => $nextLevel->required_referrals,
                    'commission_rate' => $nextLevel->commission_rate . '%',
                ] : null,
                'statistics' => $agentInfo,
                'tasks' => $tasks,
                'progress' => [
                    'current' => $agentInfo->valid_referrals,
                    'next_target' => $nextLevel ? $nextLevel->required_referrals : null,
                ],
                'share_materials'=>[
                    'text'=>AgentMaterial::where('type',2)->where('status',1)->value('content'),
                    'imgs'=>AgentMaterial::select('photo','title','content')->where('type',1)->where('status',1)->get(),
                ],
                'withdraws'=>$this->getRecentWithdrawals()
            ]
        );
    }

    /**
     * 创建用户的代理信息
     */
    private function createAgentInfo($userId)
    {
        try {
            // 生成唯一邀请码
            $referralCode = $this->generateReferralCode($userId);

            // 创建代理信息
            $agentInfo = new AgentUserInfo();
            $agentInfo->UserID = $userId;
            $agentInfo->referral_code = $referralCode;
            $agentInfo->level = 1; // 默认级别为1
            $agentInfo->valid_referrals = 0;
            $agentInfo->total_commission = 0;
            $agentInfo->today_commission = 0;
            $agentInfo->yesterday_commission = 0;
            $agentInfo->save();
            return $agentInfo;
        }catch (\Exception $e){
            // 检查是否已存在代理信息
            return AgentUserInfo::where('UserID', $userId)->first();
        }

    }

    /**
     * 生成唯一的推广码
     */
    private function generateReferralCode($userId)
    {
        $baseCode = base_convert($userId, 10, 36); // 将用户ID转换为36进制
        $code = strtoupper(substr($baseCode, 0, 6)); // 截取前6位并转为大写

        // 确保唯一性
        while (AgentUserInfo::where('referral_code', $code)->exists()) {
            $random = Str::random(3);
            $code = strtoupper(substr($baseCode, 0, 3) . $random);
        }

        return $code;
    }

    /**
     * 获取用户的邀请记录
     */
    public function getReferrals(Request $request)
    {
        $userId = $request->UserID;
        $page = $request->input('page', 1);
        $perPage = $request->input('per_page', 20);

        // 获取所有下级用户
        $referrals = AgentUserRecord::where('SpreaderID', $userId)
                                    ->orderBy('created_at', 'desc')
                                    ->paginate($perPage, ['*'], 'page', $page);

        $items = [];
        foreach ($referrals as $referral) {
            $items[] = [
                'user_id' => $referral->UserID,
                'username' => AccountsInfo::find($referral->UserID)->NickName,
                'register_time' => $referral->created_at,
                'is_valid' => (bool)$referral->is_valid,
                'valid_time' => $referral->valid_at,
            ];
        }

        return apiReturnSuc([
                'total' => $referrals->total(),
                'per_page' => $referrals->perPage(),
                'current_page' => $referrals->currentPage(),
                'last_page' => $referrals->lastPage(),
                'items' => $items
            ]
        );
    }

    /**
     * 获取用户的佣金记录
     */
    public function getCommissions(Request $request)
    {
        $userId = $request->UserID;
        $page = $request->input('page', 1);
        $perPage = $request->input('per_page', 20);

        // 获取佣金记录
        $commissions = AgentDepositCommission::where('SpreaderID', $userId)
                                            ->orderBy('created_at', 'desc')
                                            ->paginate($perPage, ['*'], 'page', $page);

        $items = [];
        foreach ($commissions as $commission) {
            $items[] = [
                'id' => $commission->id,
                'user_id' => $commission->UserID,
                'username' => AccountsInfo::find($commission->UserID)->NickName,
                'order_sn' => $commission->order_sn,
                'deposit_amount' => $commission->deposit_amount,
                'commission_rate' => $commission->commission_rate . '%',
                'commission_amount' => $commission->commission_amount,
                'status' => $commission->status,
                'created_at' => $commission->created_at,
            ];
        }

        return apiReturnSuc([
                'total' => $commissions->total(),
                'per_page' => $commissions->perPage(),
                'current_page' => $commissions->currentPage(),
                'last_page' => $commissions->lastPage(),
                'items' => $items
            ]
        );
    }

    /**
     * 获取宣传素材
     */
    public function getMaterials(Request $request)
    {
        // 获取所有活跃的素材
        $materials = AgentMaterial::where('status', 1)
                                ->where('type', 1)
                                ->orderBy('sort_order')
                                ->get();

        $items = [];
        foreach ($materials as $material) {
            $items[] = [
                'photo' => $material->photo,
                'title' => $material->title,
                'content' => $material->content,
            ];
        }

        return apiReturnSuc($items);
    }

    /**
     * 获取用户的任务列表
     */
    public function getTasks(Request $request)
    {
        $userId = $request->UserID;

        // 获取代理信息
        $agentInfo = AgentUserInfo::where('UserID', $userId)->first();

        if (!$agentInfo) {
            return apiReturnFail('Agent information not found');
        }

        // 获取任务完成情况
        $completedTasks = AgentUserTaskCompletion::where('UserID', $userId)
                                                ->where('completed', 1)
                                                ->pluck('task_id')
                                                ->toArray();

        // 获取所有任务
        $allTasks = AgentTask::where('status', 1)
                            ->orderBy('required_referrals')
                            ->get();

        $tasks = [];
        foreach ($allTasks as $task) {
            $completed = in_array($task->id, $completedTasks);

            // 判断任务是否可领取：必须满足要求且未完成
            $canClaim = $agentInfo->valid_referrals >= $task->required_referrals && !$completed;

            $tasks[] = [
                'id' => $task->id,
                'taskid' => $task->taskid,
                'title' => $task->task_title,
                'required_referrals' => $task->required_referrals,
                'reward_amount' => $task->reward_amount,
                'completed' => $completed,
                'progress' => min($agentInfo->valid_referrals, $task->required_referrals),
                'total' => $task->required_referrals,
                'can_claim' => $canClaim
            ];
        }

        return apiReturnSuc($tasks);
    }

    /**
     * 领取任务奖励
     */
    public function claimTaskReward(Request $request)
    {
        $userId = $request->UserID;
        $taskId = $request->input('task_id');

        // 验证任务ID
        $task = AgentTask::find($taskId);
        if (!$task || $task->status != 1) {
            return apiReturnFail('Invalid task');
        }

        // 获取代理信息
        $agentInfo = AgentUserInfo::where('UserID', $userId)->first();
        if (!$agentInfo) {
            return apiReturnFail('Agent information not found');
        }

        // 检查是否有足够的有效邀请人数
        if ($agentInfo->valid_referrals < $task->required_referrals) {
            return apiReturnFail('Not enough valid referrals');
        }

        // 检查任务是否已完成
        $taskCompletion = AgentUserTaskCompletion::where('UserID', $userId)
                                                ->where('task_id', $taskId)
                                                ->first();

        if ($taskCompletion && $taskCompletion->completed) {
            return apiReturnFail('Task already completed');
        }

        try {
            DB::beginTransaction();

            // 标记任务为已完成
            if (!$taskCompletion) {
                $taskCompletion = new AgentUserTaskCompletion();
                $taskCompletion->UserID = $userId;
                $taskCompletion->task_id = $taskId;
                $taskCompletion->taskid = $task->taskid;
            }

            $taskCompletion->completed = 1;
            $taskCompletion->completed_at = now();
            $taskCompletion->save();

            // 创建奖励记录
            $reward = new AgentUserReward();
            $reward->UserID = $userId;
            $reward->reward_type = 1; // 任务奖励
            $reward->source_id = $taskId;
            $reward->taskid = $task->taskid;
            $reward->amount = $task->reward_amount;
            $reward->remark = 'Completed invitation task reward: ' . $task->task_title;
            $reward->status = 1; // 已发放
            $reward->save();

            // 更新用户可提现余额
            $agentInfo->now_rewards += $task->reward_amount;
            $agentInfo->save();

            DB::commit();
            return apiReturnSuc([
                'reward_amount' => $task->reward_amount,
                'task_title' => $task->task_title
            ], '','Task reward claimed successfully');

        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('Error claiming task reward: ' . $e->getMessage());

            return apiReturnFail('Failed to claim task reward');
        }
    }

    /**
     * 处理用户注册通过邀请码
     * 此方法需要在用户注册流程中调用
     */
    public function processReferral($newUserId, $referralCode)
    {
        // 查找邀请码对应的推广者
        $spreader = AgentUserInfo::where('referral_code', $referralCode)->first();

        if (!$spreader) {
            return false;
        }
        if($spreader->UserID==$newUserId)return false;

        // 创建邀请记录
        $referral = new AgentUserRecord();
        $referral->SpreaderID = $spreader->UserID;
        $referral->UserID = $newUserId;
        $referral->is_valid = 0; // 初始设为无效，需等待首次充值
        $referral->save();


        return $spreader;
    }

    /**
     * 处理用户充值后的佣金计算
     * 此方法需要在用户充值成功后调用
     */
    public function processDeposit($userId, $amount, $orderSn)
    {
        // 查找该用户的邀请记录
        $referral = AgentUserRecord::where('UserID', $userId)->first();

        if (!$referral) {
            return false; // 没有邀请关系
        }

        $spreaderId = $referral->SpreaderID;
        $isValid = $referral->is_valid;

        // 检查是否需要将邀请关系标记为有效（累计充值金额达到Rs200）
        if (!$isValid) {
            // 检查用户总充值金额
            $totalDeposit=DB::table('QPAccountsDB.dbo.YN_VIPAccount')->where('UserID', $userId)->value('Recharge') ?? 0;
            $totalDeposit += $amount; // 这里应加上用户历史充值

            if ($totalDeposit >= 200) {
                // 更新邀请记录为有效
                $referral->is_valid = 1;
                $referral->valid_at = now();
                $referral->save();

                // 更新邀请人的有效邀请数
                $spreaderInfo = AgentUserInfo::where('UserID', $spreaderId)->first();
                if ($spreaderInfo) {
                    $spreaderInfo->valid_referrals += 1;
                    $spreaderInfo->save();

                    // 检查并更新邀请人的级别
                    $this->updateUserLevel($spreaderId);

                    // 检查任务完成情况
//                    $this->checkTaskCompletion($spreaderId);
                }
            }
        }

        // 计算佣金
        $spreaderInfo = AgentUserInfo::where('UserID', $spreaderId)->first();
        if (!$spreaderInfo) {
            return false;
        }

        $levelInfo = AgentLevel::where('level', $spreaderInfo->level)->first();
        $commissionRate = $levelInfo ? $levelInfo->commission_rate : 0;

        $commissionAmount = $amount * ($commissionRate / 100);

        // 记录佣金
        $commission = new AgentDepositCommission();
        $commission->SpreaderID = $spreaderId;
        $commission->UserID = $userId;
        $commission->order_sn = $orderSn;
        $commission->deposit_amount = $amount;
        $commission->commission_rate = $commissionRate;
        $commission->commission_amount = $commissionAmount;
        $commission->status = 1; // 已发放
        $commission->save();


        // 更新用户佣金统计
        $spreaderInfo->total_commission += $commissionAmount;
        $spreaderInfo->today_commission += $commissionAmount;
        $spreaderInfo->now_rewards += $commissionAmount;
        $spreaderInfo->save();

        $agentInfo = AgentUserInfo::where('UserID', $spreaderId)->first();

        $agentInfo->now_rewards += $commissionAmount;
        $agentInfo->total_rewards += $commissionAmount;
        $agentInfo->save();

        return true;
    }

    /**
     * 更新用户的级别
     */
    private function updateUserLevel($userId)
    {
        // 获取用户当前有效邀请人数
        $agentInfo = AgentUserInfo::where('UserID', $userId)->first();

        if (!$agentInfo) {
            return false;
        }

        $validReferrals = $agentInfo->valid_referrals;

        // 找到对应的新级别
        $newLevel = AgentLevel::where('required_referrals', '<=', $validReferrals)
                            ->orderByDesc('required_referrals')
                            ->first();

        if ($newLevel && $newLevel->level != $agentInfo->level) {
            $agentInfo->level = $newLevel->level;
            $agentInfo->save();

            // 这里可以添加级别提升的通知逻辑

            return true;
        }

        return false;
    }

    /**
     * 检查用户任务完成情况
     */
    private function checkTaskCompletion($userId)
    {
        // 获取用户当前有效邀请人数
        $agentInfo = AgentUserInfo::where('UserID', $userId)->first();

        if (!$agentInfo) {
            return false;
        }

        $validReferrals = $agentInfo->valid_referrals;

        // 按照required_referrals升序获取所有任务，确保先处理要求少的任务
        $allTasks = AgentTask::where('status', 1)
                          ->orderBy('required_referrals')
                          ->get();

        // 获取用户已完成的任务ID
        $completedTaskIds = AgentUserTaskCompletion::where('UserID', $userId)
                                                  ->where('completed', 1)
                                                  ->pluck('task_id')
                                                  ->toArray();

        // 检查每个任务是否应该完成
        foreach ($allTasks as $task) {
            // 如果有效邀请人数达到或超过任务要求
            if ($validReferrals >= $task->required_referrals) {
                // 检查该任务是否已经标记为完成
                if (!in_array($task->id, $completedTaskIds)) {
                    // 创建或更新任务完成记录
                    $completion = AgentUserTaskCompletion::firstOrNew([
                        'UserID' => $userId,
                        'task_id' => $task->id
                    ]);

                    $completion->taskid = $task->taskid;
//                    $completion->completed = 1;
//                    $completion->completed_at = now();
//                    $completion->save();
                }
            }
        }

        return true;
    }

    /**
     * 每日重置佣金统计
     * 此方法应该通过计划任务每天调用一次
     */
    public function resetDailyCommission()
    {
        try {
            AgentUserInfo::query()->where('today_commission','<>',0)->orWhere('yesterday_commission','<>',0)->update([
                    'yesterday_commission' => DB::raw('today_commission'),
                    'today_commission' => 0
                ]);

            return apiReturnSuc([], 'Daily commission reset successfully');
        } catch (\Exception $e) {
            Log::error('Error resetting daily commission: ' . $e->getMessage());

            return apiReturnFail('Failed to reset daily commission');
        }
    }

    /**
     * 申请提现
     */
    public function requestWithdrawal(Request $request)
    {
        $userId = $request->UserID;
        $amount = floatval($request->input('amount'));

        // 验证提现金额
        if ($amount <= 0) {
            return apiReturnFail('Invalid withdrawal amount');
        }

        // 获取用户的代理信息
        $agentInfo = AgentUserInfo::where('UserID', $userId)->first();
        if (!$agentInfo) {
            return apiReturnFail('Agent information not found');
        }

        // 验证用户是否有足够的余额
        if ($agentInfo->now_rewards < $amount) {
            return apiReturnFail('Insufficient balance for withdrawal', ['balance' => $agentInfo->now_rewards]);
        }

        // 检查是否有未处理的提现请求
        $pendingWithdrawal = AgentWithdrawal::where('UserID', $userId)
            ->where('status', AgentWithdrawal::STATUS_PENDING)
            ->first();

        if ($pendingWithdrawal) {
            return apiReturnFail('You already have a pending withdrawal request');
        }

        //把钱存到用户账户里
        // 更新用户余额
        $agentInfo->now_rewards -= $amount;
        $agentInfo->save();

        OuroGameService::AddScore($userId,$amount*NumConfig::NUM_VALUE,OuroGameService::REASON_AgentWithDraw);
        OuroGameService::AddDrawBase($userId,$amount*NumConfig::NUM_VALUE,OuroGameService::REASON_AgentWithDraw);


        try {
            // 开始事务
//            DB::beginTransaction();

            // 生成订单号
            $orderSn = AgentWithdrawal::generateOrderSn();

            // 创建提现记录
            $withdrawal = new AgentWithdrawal();
            $withdrawal->UserID = $userId;
            $withdrawal->amount = $amount;
            $withdrawal->before_balance = $agentInfo->now_rewards+$amount;
            $withdrawal->after_balance = $agentInfo->now_rewards;
            $withdrawal->status = AgentWithdrawal::STATUS_COMPLETED;
            $withdrawal->order_sn = $orderSn;
            $withdrawal->save();

            // 更新用户余额
//            $agentInfo->now_rewards -= $amount;
//            $agentInfo->save();
//
//            // 提交事务
//            DB::commit();
//
//            return apiReturnSuc([
//                'withdrawal_id' => $withdrawal->id,
//                'order_sn' => $orderSn,
//                'amount' => $amount,
//                'status' => 'Completed',
//                'current_balance' => $agentInfo->now_rewards
//            ], 'Withdrawal request submitted successfully');

        } catch (\Exception $e) {
            // 回滚事务
//            DB::rollBack();
            Log::error('Error processing withdrawal: ' . $e->getMessage());

//            return apiReturnFail('Failed to process withdrawal request');
        }
        return apiReturnSuc($agentInfo);
    }

    /**
     * 获取提现历史记录
     */
    public function getWithdrawalHistory(Request $request)
    {
        $userId = $request->UserID;
        $page = $request->input('page', 1);
        $perPage = $request->input('per_page', 20);

        // 获取用户的提现记录
        $withdrawals = AgentWithdrawal::where('UserID', $userId)
            ->orderBy('created_at', 'desc')
            ->paginate($perPage, ['*'], 'page', $page);

        $items = [];
        foreach ($withdrawals as $withdrawal) {
            $items[] = [
                'id' => $withdrawal->id,
                'order_sn' => $withdrawal->order_sn,
                'amount' => $withdrawal->amount,
                'status' => $withdrawal->status_text,
                'status_code' => $withdrawal->status,
                'remarks' => $withdrawal->remarks,
                'created_at' => $withdrawal->created_at->format('Y-m-d H:i:s'),
                'process_time' => $withdrawal->process_time ? $withdrawal->process_time->format('Y-m-d H:i:s') : null
            ];
        }

        return apiReturnSuc([
            'total' => $withdrawals->total(),
            'per_page' => $withdrawals->perPage(),
            'current_page' => $withdrawals->currentPage(),
            'last_page' => $withdrawals->lastPage(),
            'items' => $items
        ]);
    }

    /**
     * 获取可提现金额
     */
    public function getWithdrawalBalance(Request $request)
    {
        $userId = $request->UserID;

        // 获取用户的代理信息
        $agentInfo = AgentUserInfo::where('UserID', $userId)->first();
        if (!$agentInfo) {
            return apiReturnFail('Agent information not found');
        }

        return apiReturnSuc([
            'available_balance' => $agentInfo->now_rewards,
            'total_withdrawn' => $agentInfo->withdraw_rewards,
            'total_commission' => $agentInfo->total_commission,
            'min_withdrawal' => 100, // 最小提现金额，可根据系统设置调整
            'withdrawal_fee' => 4    // 提现手续费，可根据系统设置调整
        ]);
    }

    /**
     * 取消提现申请（仅处理中的可取消）
     */
    public function cancelWithdrawal(Request $request)
    {
        $userId = $request->UserID;
        $withdrawalId = $request->input('withdrawal_id');

        // 查找提现记录
        $withdrawal = AgentWithdrawal::where('id', $withdrawalId)
            ->where('UserID', $userId)
            ->where('status', AgentWithdrawal::STATUS_PENDING)
            ->first();

        if (!$withdrawal) {
            return apiReturnFail('Withdrawal request not found or cannot be cancelled');
        }

        try {
            // 开始事务
            DB::beginTransaction();

            // 获取用户的代理信息
            $agentInfo = AgentUserInfo::where('UserID', $userId)->first();
            if (!$agentInfo) {
                return apiReturnFail('Agent information not found');
            }

            // 更新提现状态
            $withdrawal->status = AgentWithdrawal::STATUS_REJECTED;
            $withdrawal->remarks = 'Cancelled by user';
            $withdrawal->process_time = now();
            $withdrawal->save();

            // 返还金额到用户余额
            $agentInfo->now_rewards += $withdrawal->amount;
            $agentInfo->save();

            // 提交事务
            DB::commit();

            return apiReturnSuc([
                'withdrawal_id' => $withdrawal->id,
                'current_balance' => $agentInfo->now_rewards
            ], 'Withdrawal cancelled successfully');

        } catch (\Exception $e) {
            // 回滚事务
            DB::rollBack();
            Log::error('Error cancelling withdrawal: ' . $e->getMessage());

            return apiReturnFail('Failed to cancel withdrawal request');
        }
    }

    /**
     * 管理员处理提现请求（仅限后台管理员使用）
     */
    public function processWithdrawal(Request $request)
    {
        // 这个方法通常在管理后台使用，此处仅提供参考实现
        $withdrawalId = $request->input('withdrawal_id');
        $action = $request->input('action'); // approve 或 reject
        $remarks = $request->input('remarks', '');
        $adminId = $request->input('admin_id');
        $adminName = $request->input('admin_name');

        // 查找提现记录
        $withdrawal = AgentWithdrawal::where('id', $withdrawalId)
            ->where('status', AgentWithdrawal::STATUS_PENDING)
            ->first();

        if (!$withdrawal) {
            return apiReturnFail('Withdrawal request not found or already processed');
        }

        try {
            // 开始事务
            DB::beginTransaction();

            // 获取用户的代理信息
            $agentInfo = AgentUserInfo::where('UserID', $withdrawal->UserID)->first();
            if (!$agentInfo) {
                return apiReturnFail('Agent information not found');
            }

            if ($action === 'approve') {
                // 审核通过
                $withdrawal->status = AgentWithdrawal::STATUS_COMPLETED;
                $withdrawal->remarks = $remarks ?: 'Approved';

                // 更新用户提现总额
                $agentInfo->withdraw_rewards += $withdrawal->amount;
                $agentInfo->save();

            } elseif ($action === 'reject') {
                // 拒绝提现
                $withdrawal->status = AgentWithdrawal::STATUS_REJECTED;
                $withdrawal->remarks = $remarks ?: 'Rejected';

                // 返还金额到用户余额
                $agentInfo->now_rewards += $withdrawal->amount;
                $agentInfo->save();

            } else {
                return apiReturnFail('Invalid action');
            }

            // 更新处理信息
            $withdrawal->admin_id = $adminId;
            $withdrawal->admin_name = $adminName;
            $withdrawal->process_time = now();
            $withdrawal->save();

            // 提交事务
            DB::commit();

            return apiReturnSuc([
                'withdrawal_id' => $withdrawal->id,
                'status' => $withdrawal->status_text,
                'user_id' => $withdrawal->UserID,
                'amount' => $withdrawal->amount
            ], 'Withdrawal processed successfully');

        } catch (\Exception $e) {
            // 回滚事务
            DB::rollBack();
            Log::error('Error processing withdrawal: ' . $e->getMessage());

            return apiReturnFail('Failed to process withdrawal request');
        }
    }

    /**
     * 获取近期提现成功记录（用于首页等公开展示）
     */
    public function getRecentWithdrawals()
    {
        $recents=DB::table('QPAccountsDB.dbo.OrderWithDraw')->orderByDesc('RecordID')->limit(50)->get();

        $result=[];
        // 限制返回记录数量
        foreach ($recents as $withdrawal){
            $nickname=$withdrawal->BankUserName;

            $length = mb_strlen($nickname);
            if ($length > 6) {
                $maskedNickname = mb_substr($nickname, 0, 3) . '***' . mb_substr($nickname, -2);
            } else {
                $maskedNickname = mb_substr($nickname, 0, 1) . '***' . mb_substr($nickname, -1);
            }
            $phone=$withdrawal->PhoneNumber;
            $phone = mb_substr($phone, 0, 3) . '***' . mb_substr($phone, -2);

            $result[] = [
                'user' => $maskedNickname,
                'phone'=>$phone,
                'amount' => ($withdrawal->WithDraw+$withdrawal->ServiceFee)/NumConfig::NUM_VALUE,
                'date' => $withdrawal->CreateDate
            ];
        }

        return $result;
    }
}
