<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\helper\Helper;
use App\Models\AgentDepositCommission;
use App\Models\AgentLevel;
use App\Models\AgentTask;
use App\Models\AgentUserInfo;
use App\Models\AgentUserRecord;
use App\Models\AgentUserReward;
use App\Models\AgentWithdrawal;
use App\Models\AccountsInfo;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class ExtensionNewController extends Controller
{
    /**
     * 推广奖金审核列表
     */
    public function verify(Request $request)
    {
        $nickName = $request->NickName ?: '';
        $gameId = $request->GameID ?: '';
        $mobile = $request->mobile ?: '';
        $spreaderId = $request->SpreaderID ?: '';
        $startTime = $request->start_time ?: '';
        $endTime = $request->end_time ?: '';
        $type = $request->Type ?: '';
        $sort = $request->Sort ?: '';

        $where = [];

        if (!empty($nickName)) {
            $where[] = ['ai.NickName', 'like', $nickName . '%'];
        }
        if (!empty($gameId)) {
            $where[] = ['ai.GameID', $gameId];
        }
        if (!empty($spreaderId)) {
            $spreaderUserId = AccountsInfo::where('GameID', $spreaderId)->value('UserID');
            if ($spreaderUserId) {
                $where[] = ['aur.SpreaderID', $spreaderUserId];
            }
        }
        if (!empty($startTime)) {
            $where[] = ['aur.created_at', '>=', $startTime];
        }
        if (!empty($endTime)) {
            $where[] = ['aur.created_at', '<=', $endTime];
        }

        // 获取待审核的佣金记录
        $query = DB::table('agent_user_records as aur')
            ->join('accounts_info as ai', 'aur.UserID', '=', 'ai.UserID')
            ->join('agent_user_info as aui', 'aur.SpreaderID', '=', 'aui.UserID')
            ->where($where)
            ->select([
                'aur.*',
                'ai.NickName',
                'ai.GameID',
                'ai.RegisterDate',
                'aui.level as spreader_level'
            ]);

        if (!empty($sort)) {
            $query->orderBy('aur.created_at', $sort);
        } else {
            $query->orderBy('aur.created_at', 'desc');
        }

        $list = $query->paginate(10);

        // 获取系统配置
        $config = [
            'min_commission' => DB::table('system_config')->where('key', 'min_commission')->value('value') ?? 0,
            'max_commission' => DB::table('system_config')->where('key', 'max_commission')->value('value') ?? 0,
            'auto_verify' => DB::connection('write')->table('QPAccountsDB.dbo.SystemStatusInfo')
                ->where('StatusName', 'AutoVerify')
                ->value('StatusValue') ?? 0
        ];

        return view('admin.extension_new.verify', compact('list', 'config'));
    }

    /**
     * 更新审核状态
     */
    public function verify_update(Request $request, $id)
    {
        $status = $request->input('status');
        $remarks = $request->input('remarks', '');

        try {
            DB::beginTransaction();

            $record = AgentUserRecord::findOrFail($id);
            $record->status = $status;
            $record->remarks = $remarks;
            $record->verified_at = now();
            $record->save();

            // 如果审核通过，发放佣金
            if ($status == 1) {
                $this->processCommission($record);
            }

            DB::commit();
            return response()->json(['code' => 0, 'msg' => '更新成功']);
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('审核更新失败: ' . $e->getMessage());
            return response()->json(['code' => 1, 'msg' => '更新失败']);
        }
    }

    /**
     * 代理等级配置
     */
    public function register_config()
    {
        $list = AgentLevel::orderBy('level')->paginate(10);
        return view('admin.extension_new.register_config', compact('list'));
    }

    /**
     * 添加代理等级
     */
    public function register_config_add(Request $request)
    {
        if ($request->isMethod('post')) {
            $data = $request->validate([
                'level_name' => 'required|string|max:50',
                'level' => 'required|integer|min:1',
                'required_referrals' => 'required|integer|min:0',
                'commission_rate' => 'required|numeric|min:0|max:100'
            ]);

            AgentLevel::create($data);
            return response()->json(['code' => 0, 'msg' => '添加成功']);
        }

        return view('admin.extension_new.register_config_add');
    }

    /**
     * 更新代理等级
     */
    public function register_config_update(Request $request, $id)
    {
        $level = AgentLevel::findOrFail($id);

        if ($request->isMethod('post')) {
            $data = $request->validate([
                'level_name' => 'required|string|max:50',
                'required_referrals' => 'required|integer|min:0',
                'commission_rate' => 'required|numeric|min:0|max:100'
            ]);

            $level->update($data);
            return response()->json(['code' => 0, 'msg' => '更新成功']);
        }

        return view('admin.extension_new.register_config_update', compact('level'));
    }

    /**
     * 设置佣金上限
     */
    public function upperLimit(Request $request)
    {
        if ($request->isMethod('post')) {
            $value = $request->input('value');
            DB::table('system_config')->updateOrInsert(
                ['key' => 'max_commission'],
                ['value' => $value]
            );
            return response()->json(['code' => 0, 'msg' => '设置成功']);
        }

        $value = DB::table('system_config')->where('key', 'max_commission')->value('value');
        return view('admin.extension_new.upper_limit', compact('value'));
    }

    /**
     * 设置最小审核金额
     */
    public function verifyScore(Request $request)
    {
        if ($request->isMethod('post')) {
            $value = $request->input('value');
            DB::table('system_config')->updateOrInsert(
                ['key' => 'min_commission'],
                ['value' => $value]
            );
            return response()->json(['code' => 0, 'msg' => '设置成功']);
        }

        $value = DB::table('system_config')->where('key', 'min_commission')->value('value');
        return view('admin.extension_new.verify_score', compact('value'));
    }

    /**
     * 查看用户来源
     */
    public function userSource(Request $request)
    {
        $userId = $request->input('user_id');
        $type = $request->input('type', 'all');

        $query = AgentUserRecord::where('SpreaderID', $userId);

        if ($type != 'all') {
            $query->where('type', $type);
        }

        $list = $query->with(['user:id,NickName,GameID', 'spreader:id,NickName,GameID'])
            ->orderBy('created_at', 'desc')
            ->paginate(10);

        return view('admin.extension_new.user_source', compact('list'));
    }

    /**
     * 已审核记录
     */
    public function verifyFinal(Request $request)
    {
        $nickName = $request->NickName ?: '';
        $gameId = $request->GameID ?: '';
        $spreaderId = $request->SpreaderID ?: '';
        $startTime = $request->start_time ?: '';
        $endTime = $request->end_time ?: '';
        $type = $request->Type ?: '';
        $sort = $request->Sort ?: '';

        $where = [];

        if (!empty($nickName)) {
            $where[] = ['ai.NickName', 'like', $nickName . '%'];
        }
        if (!empty($gameId)) {
            $where[] = ['ai.GameID', $gameId];
        }
        if (!empty($spreaderId)) {
            $spreaderUserId = AccountsInfo::where('GameID', $spreaderId)->value('UserID');
            if ($spreaderUserId) {
                $where[] = ['aur.SpreaderID', $spreaderUserId];
            }
        }
        if (!empty($startTime)) {
            $where[] = ['aur.verified_at', '>=', $startTime];
        }
        if (!empty($endTime)) {
            $where[] = ['aur.verified_at', '<=', $endTime];
        }

        $query = DB::table('agent_user_records as aur')
            ->join('accounts_info as ai', 'aur.UserID', '=', 'ai.UserID')
            ->join('agent_user_info as aui', 'aur.SpreaderID', '=', 'aui.UserID')
            ->where($where)
            ->where('aur.status', 1)
            ->select([
                'aur.*',
                'ai.NickName',
                'ai.GameID',
                'ai.RegisterDate',
                'aui.level as spreader_level'
            ]);

        if (!empty($sort)) {
            $query->orderBy('aur.verified_at', $sort);
        } else {
            $query->orderBy('aur.verified_at', 'desc');
        }

        $list = $query->paginate(10);

        return view('admin.extension_new.verify_final', compact('list'));
    }

    /**
     * 更新审核备注
     */
    public function verifyRemarks(Request $request, $id)
    {
        $remarks = $request->input('remarks');

        try {
            $record = AgentUserRecord::findOrFail($id);
            $record->remarks = $remarks;
            $record->save();

            return response()->json(['code' => 0, 'msg' => '更新成功']);
        } catch (\Exception $e) {
            Log::error('更新备注失败: ' . $e->getMessage());
            return response()->json(['code' => 1, 'msg' => '更新失败']);
        }
    }

    /**
     * 更新已审核记录备注
     */
    public function verifyFinalRemarks(Request $request, $id)
    {
        return $this->verifyRemarks($request, $id);
    }

    /**
     * 任务配置列表
     */
    public function gameCountConfig()
    {
        $list = AgentTask::orderBy('required_referrals')->paginate(10);
        return view('admin.extension_new.gamecount_config', compact('list'));
    }

    /**
     * 添加任务配置
     */
    public function gameCountConfig_add(Request $request)
    {
        if ($request->isMethod('post')) {
            $data = $request->validate([
                'task_title' => 'required|string|max:100',
                'required_referrals' => 'required|integer|min:1',
                'reward_amount' => 'required|numeric|min:0',
                'status' => 'required|boolean'
            ]);

            AgentTask::create($data);
            return response()->json(['code' => 0, 'msg' => '添加成功']);
        }

        return view('admin.extension_new.gamecount_config_add');
    }

    /**
     * 更新任务配置
     */
    public function gameCountConfig_update(Request $request, $id)
    {
        $task = AgentTask::findOrFail($id);

        if ($request->isMethod('post')) {
            $data = $request->validate([
                'task_title' => 'required|string|max:100',
                'required_referrals' => 'required|integer|min:1',
                'reward_amount' => 'required|numeric|min:0',
                'status' => 'required|boolean'
            ]);

            $task->update($data);
            return response()->json(['code' => 0, 'msg' => '更新成功']);
        }

        return view('admin.extension_new.gamecount_config_update', compact('task'));
    }

    /**
     * 设置任务奖励上限
     */
    public function gameCountLimit(Request $request)
    {
        if ($request->isMethod('post')) {
            $value = $request->input('value');
            DB::table('system_config')->updateOrInsert(
                ['key' => 'max_task_reward'],
                ['value' => $value]
            );
            return response()->json(['code' => 0, 'msg' => '设置成功']);
        }

        $value = DB::table('system_config')->where('key', 'max_task_reward')->value('value');
        return view('admin.extension_new.gamecount_limit', compact('value'));
    }

    /**
     * 自动审核开关
     */
    public function autoVerify(Request $request)
    {
        $StatusValue = $request->input('StatusValue', 0);

        $result = DB::table('system_config')
            ->updateOrInsert(
                ['key' => 'auto_verify'],
                ['key' => 'auto_verify', 'value' => $StatusValue, 'updated_at' => now()]
            );

        if ($result) {
            return response()->json(['code' => 0, 'msg' => '操作成功']);
        } else {
            return response()->json(['code' => -1, 'msg' => '操作失败']);
        }
    }

    /**
     * 充值返佣比例设置
     */
    public function recharge_rate(Request $request)
    {
//        if ($request->isMethod('post')) {
//            $data = $request->validate([
//                'level_1_rate' => 'required|numeric|min:0|max:100',
//                'level_2_rate' => 'required|numeric|min:0|max:100'
//            ]);
//
//            foreach ($data as $key => $value) {
//                DB::table('system_config')->updateOrInsert(
//                    ['key' => $key],
//                    ['value' => $value]
//                );
//            }
//
//            return response()->json(['code' => 0, 'msg' => '设置成功']);
//        }
//
//        $rates = [
//            'level_1_rate' => DB::table('system_config')->where('key', 'level_1_rate')->value('value'),
//            'level_2_rate' => DB::table('system_config')->where('key', 'level_2_rate')->value('value')
//        ];
//
//        return view('admin.extension_new.recharge_rate', compact('rates'));
    }

    /**
     * 处理佣金发放
     */
    private function processCommission($record)
    {
        try {
            DB::beginTransaction();

            // 获取推广者信息
            $spreader = AgentUserInfo::where('UserID', $record->SpreaderID)->first();
            if (!$spreader) {
                throw new \Exception('推广者信息不存在');
            }

            // 获取推广者等级信息
            $level = AgentLevel::where('level', $spreader->level)->first();
            if (!$level) {
                throw new \Exception('推广者等级信息不存在');
            }

            // 计算佣金
            $commission = $record->amount * ($level->commission_rate / 100);

            // 创建佣金记录
            $commissionRecord = new AgentDepositCommission();
            $commissionRecord->SpreaderID = $record->SpreaderID;
            $commissionRecord->UserID = $record->UserID;
            $commissionRecord->order_sn = $record->order_sn;
            $commissionRecord->deposit_amount = $record->amount;
            $commissionRecord->commission_rate = $level->commission_rate;
            $commissionRecord->commission_amount = $commission;
            $commissionRecord->status = 1;
            $commissionRecord->save();

            // 更新推广者佣金统计
            $spreader->total_commission += $commission;
            $spreader->today_commission += $commission;
            $spreader->now_rewards += $commission;
            $spreader->save();

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('处理佣金失败: ' . $e->getMessage());
            throw $e;
        }
    }

    /**
     * 每日绑定查询
     */
    public function dailyBinding(Request $request)
    {
        $start_time = str_replace('T', ' ', $request->start_time) ?: date('Y-m-d 00:00:00');
        $end_time = str_replace('T', ' ', $request->end_time) ?: date('Y-m-d 23:59:59');
        $spreaderID = $request->SpreaderID ?: '';
        $GameID = $request->GameID ?: '';
        $date = $request->date ?: '';

        switch ($date) {
            case 1:
                $start_time = date('Y-m-d 00:00:00');
                break;
            case 2:
                $start_time = date('Y-m-d 00:00:00', strtotime('-1 day'));
                $end_time = date('Y-m-d 23:59:59', strtotime('-1 day'));
                break;
            case 3:
                //当前日期
                $sdefaultDate = date("Y-m-d 00:00:00");
                // 1表示每周星期一为开始日期 0表示每周日为开始日期
                $first = 1;
                //获取当前周的第几天 周日是 0 周一到周六是 1 - 6
                $w = date('w', strtotime($sdefaultDate));
                $start_time = date('Y-m-d 00:00:00', strtotime("$sdefaultDate -" . ($w ? $w - $first : 6) . ' days'));
                break;
            case 4:
                $start_time = date("Y-m-01 00:00:00");
                break;
        }

        // 构建基础查询 - 使用agent_user_records表
        $query = DB::connection('mysql')
            ->table('webgame.agent_user_records as aur')

            ->select([
                'aur.UserID',
                'aur.created_at as RegisterDate',
                'aur.SpreaderID as SpreaderUserID'
            ]);

        // 添加条件过滤
        if (!empty($start_time)) {
            $query->where('aur.created_at', '>=', $start_time);
        }
        if (!empty($end_time)) {
            $query->where('aur.created_at', '<=', $end_time);
        }
        if (!empty($GameID)) {
            $query->where('aur.UserID', AccountsInfo::where('GameID', $GameID)
                ->value('UserID'));
        }

        // 如果指定了推广者ID，需要进行额外筛选
        if (!empty($spreaderID)) {
            $spreaderUserId = AccountsInfo::where('GameID', $spreaderID)
                ->value('UserID');

            if ($spreaderUserId) {
                $query->where('aur.SpreaderID', $spreaderUserId);
            }
        }

        // 获取总记录数用于分页
        $total = $query->count();

        // 分页参数
        $perPage = 10;
        $currentPage = $request->input('page', 1);

        // 获取当前页数据
        $paginatedRecords = $query->orderBy('aur.created_at', 'desc')
            ->forPage($currentPage, $perPage)
            ->get();

        $userIds = $paginatedRecords->pluck('UserID')->toArray();
        $spids = $paginatedRecords->pluck('SpreaderUserID')->toArray();
        $userIds=array_merge($userIds,$spids);
        $otherinfos=AccountsInfo::whereIn('UserID',$userIds)->select('UserID','GameID','LastLogonDate','RegisterDate')->get();


        // 整合数据
        $paginatedRecords = $paginatedRecords->map(function($record) use ( $otherinfos) {

            foreach($otherinfos as $otherinfo){
                if($otherinfo->UserID==$record->UserID){
                    $record->RegisterDate=$otherinfo->RegisterDate;
                    $record->LastLogonDate=$otherinfo->LastLogonDate;
                    $record->GameID=$otherinfo->GameID;
                }
                if($otherinfo->UserID==$record->SpreaderUserID){
                    $record->SpreaderID=$otherinfo->GameID;
                }
            }

            return $record;
        });
        // 创建分页实例
        $list = new \Illuminate\Pagination\LengthAwarePaginator(
            $paginatedRecords,
            $total,
            $perPage,
            $currentPage,
            ['path' => $request->url(), 'query' => $request->query()]
        );

        $start_time = Helper::timeChange($start_time);
        $end_time = Helper::timeChange($end_time);
        $dates = [1 => '今日', 2 => '昨日', 3 => '本周', 4 => '本月'];
        $data = compact('list', 'start_time', 'end_time', 'spreaderID', 'GameID', 'date', 'dates');
        return view('admin.extension_new.daily_binding', $data);
    }

    /**
     * 推广员奖励报表
     */
    public function reward(Request $request)
    {
        $UserID = (int)trim($request->UserID) ?: 0;
        $SpreaderID = (int)trim($request->SpreaderID) ?: 0;
        $start_time = trim($request->start_time) ?: '';
        $end_time = trim($request->end_time) ?: '';
        $Type = trim($request->Type) ?: '';
        $start_time = str_replace('T', ' ', $start_time);
        $end_time = str_replace('T', ' ', $end_time);

        // 构建查询 - 使用agent_deposit_commissions表
        $query = DB::connection('mysql')
            ->table('webgame.agent_deposit_commissions as adc')
            ->select([
                'adc.id',
                'adc.SpreaderID',
                'adc.UserID',
                'adc.order_sn',
                'adc.deposit_amount',
                'adc.commission_rate',
                'adc.commission_amount',
//                'adc.type',
                'adc.status',
                'adc.created_at',
            ]);

        // 添加查询条件
        if (!empty($Type)) {
//            $query->where('adc.type', $Type);
        }

        if (!empty($start_time)) {
            $query->where('adc.created_at', '>=', $start_time);
        }

        if (!empty($end_time)) {
            $query->where('adc.created_at', '<=', $end_time);
        }

        // 只查看已发放的佣金
        $query->where('adc.status', 1);

        if ($UserID > 0) {
            $query->where('adc.UserID', AccountsInfo::where('GameID',$UserID)->value('UserID'));
        }

        if ($SpreaderID > 0) {
            $query->where('adc.SpreaderID', AccountsInfo::where('GameID',$SpreaderID)->value('UserID'));
        }

        // 获取总记录数用于分页
        $total = $query->count();

        // 分页参数设置
        $perPage = 10;
        $currentPage = $request->input('page', 1);

        // 获取当前页数据
        $records = $query->orderBy('adc.created_at', 'desc')
            ->forPage($currentPage, $perPage)
            ->get();

        $userIds=$records->pluck('UserID')->toArray();
        $spreaderIds=$records->pluck('SpreaderID')->toArray();
        $userIds=array_merge($userIds,$spreaderIds);
        $otherinfos=AccountsInfo::whereIn('UserID',$userIds)->select('UserID','GameID','LastLogonDate','RegisterDate')->get();

        // 处理数据格式
        $processedRecords = $records->map(function($record) use ($otherinfos) {
            // 设置类型描述
//            $record->TypeDesc = $this->getTypeDesc($record->type);
            foreach ($otherinfos as $otherinfo){
                if($otherinfo->UserID==$record->UserID){
                    $record->RegisterDate=$otherinfo->RegisterDate;
                    $record->LastLogonDate=$otherinfo->LastLogonDate;
                    $record->GameID=$otherinfo->GameID;
                }
                if($otherinfo->UserID==$record->SpreaderID){
                    $record->SpreaderGameID=$otherinfo->GameID;
                }
            }
            return $record;
        });

        // 创建分页实例
        $list = new \Illuminate\Pagination\LengthAwarePaginator(
            $processedRecords,
            $total,
            $perPage,
            $currentPage,
            ['path' => $request->url(), 'query' => $request->query()]
        );

        // 获取自动审核状态
        $AutoVerify = DB::connection('write')->table('QPAccountsDB.dbo.SystemStatusInfo')
            ->where('StatusName', 'AutoVerify')
            ->value('StatusValue') ?? 0;

        $result = compact('list', 'UserID', 'SpreaderID', 'start_time', 'end_time', 'Type', 'AutoVerify');
        return view('admin.extension_new.reward_list', $result);
    }

    /**
     * 获取奖励类型描述
     */
    private function getTypeDesc($type)
    {
        $types = [
            1 => '注册',
            2 => '对局',
            3 => '充值',
        ];

        return $types[$type] ?? '未知';
    }

    /**
     * 绑定列表查询
     */
    public function bind_list(Request $request)
    {
        $start_time = $request->start_time ?: '';
        $end_time = $request->end_time ?: '';
        $SpreaderID = $request->SpreaderID ?: '';
        $UserID = $request->UserID ?: '';
        $sort = $request->sort ?: '';

        // 跳转页面条件
        $source = $request->source ?: 1;
        $NickName = $request->NickName ?: '';
        $GameID = $request->GameID ?: '';
        $mobile = $request->mobile ?: '';
        $Type = $request->Type ?: '';
        $Sort = $request->Sort ?: '';
        $FinalScoreSort = $request->FinalScoreSort ?: '';

        // 基础查询 - 使用新的agent_user_records表
        $query = DB::connection('mysql')
            ->table('webgame.agent_user_records')

            ->select([
                'UserID',
                'SpreaderID',
                'created_at',

            ]);

        // 构建查询条件
        if (!empty($start_time)) {
            $query->where('created_at', '>=', $start_time);
        }
        if (!empty($end_time)) {
            $query->where('created_at', '<=', $end_time);
        }
        if (!empty($UserID)) {
            $query->where('UserID', AccountsInfo::where('GameID', $UserID)
                ->value('UserID'));
        }

        if (!empty($SpreaderID)) {
            $spreaderUserId=AccountsInfo::where('GameID', $SpreaderID)
                ->value('UserID');

            if ($spreaderUserId) {
                $query->where('SpreaderID', $spreaderUserId);
            }
        }

        // 执行查询并进行分页
        $perPage = 10;
        $currentPage = $request->input('page', 1);

        // 获取总记录数用于分页
        $total = $query->count();

        // 应用排序
        $query->orderBy('created_at', 'desc');

        // 获取当前页数据
        $paginatedRecords = $query->forPage($currentPage, $perPage)->get();

        // 只获取当前页面需要的用户ID
        $userIds = $paginatedRecords->pluck('UserID')->toArray();
        $spreaderIds = $paginatedRecords->pluck('SpreaderID')->toArray();

        // 从代理系统中获取当前页面用户的信息
        $agentUsers = DB::connection('mysql')->table('webgame.agent_user_info')
            ->whereIn('UserID', array_merge($userIds, $spreaderIds))
            ->get()
            ->keyBy('UserID');

        // 针对当前页面的用户ID查询直属下级数量 (一级下级)
        $directCounts = DB::connection('mysql')
            ->table('webgame.agent_user_records')
            ->whereIn('SpreaderID', $userIds)
            ->select('SpreaderID', DB::raw('COUNT(*) as count'))
            ->groupBy('SpreaderID')
            ->get()
            ->keyBy('SpreaderID');

        // 获取二级下级数量
        $indirectCounts = collect();

        // 先获取直属下级的ID
        $directDownlines = DB::connection('mysql')
            ->table('webgame.agent_user_records')
            ->whereIn('SpreaderID', $userIds)
            ->select('SpreaderID', 'UserID')
            ->get();

        // 按SpreaderID分组直属下级
        $directDownlinesMap = [];
        foreach ($directDownlines as $record) {
            if (!isset($directDownlinesMap[$record->SpreaderID])) {
                $directDownlinesMap[$record->SpreaderID] = [];
            }
            $directDownlinesMap[$record->SpreaderID][] = $record->UserID;
        }

        $userIds=array_merge($userIds,$spreaderIds);
        $otherinfos=AccountsInfo::whereIn('UserID',$userIds)->select('UserID','GameID','LastLogonDate','RegisterDate')->get();
        // 对于每个用户，查询其直属下级的下级数量
//        foreach ($userIds as $userId) {
//            $childCount = 0;
//            if (isset($directDownlinesMap[$userId])) {
//                $directUserIds = $directDownlinesMap[$userId];
//                if (!empty($directUserIds)) {
//                    $childCount = DB::connection('mysql')
//                        ->table('webgame.agent_user_records')
//                        ->whereIn('SpreaderID', $directUserIds)
//                        ->count();
//                }
//            }
//            $indirectCounts->put($userId, $childCount);
//        }

        // 整合数据
        $processedRecords = $paginatedRecords->map(function($record) use ($agentUsers, $directCounts, $otherinfos) {
            // 添加佣金信息
            $record->Rewards = isset($agentUsers[$record->UserID]) ?
                $agentUsers[$record->UserID]->total_commission : 0;

            // 获取下级人数
            $record->downCount1 = isset($directCounts[$record->UserID]) ?
                $directCounts[$record->UserID]->count : 0;

            $record->downCount2 = 0;//$indirectCounts->get($record->UserID, 0);

            foreach($otherinfos as $otherinfo){
                if($otherinfo->UserID==$record->UserID){
                    $record->RegisterDate=$otherinfo->RegisterDate;
                    $record->LastLogonDate=$otherinfo->LastLogonDate;
                    $record->GameID=$otherinfo->GameID;
                }
                if($otherinfo->UserID==$record->SpreaderID){
                    $record->SpreaderGameID=$otherinfo->GameID;
                }
            }

            return $record;
        });

        // 如果有特殊排序要求，在这里应用
        if (!empty($sort)) {
            if ($sort == 'downCount1 + downCount2') {
                $processedRecords = $processedRecords->sortByDesc(function($record) {
                    return $record->downCount1 + $record->downCount2;
                });
            }
        }

        // 创建分页实例
        $list = new \Illuminate\Pagination\LengthAwarePaginator(
            $processedRecords,
            $total,
            $perPage,
            $currentPage,
            ['path' => $request->url(), 'query' => $request->query()]
        );

        $result = [
            'list' => $list,
            'UserID' => $UserID,
            'SpreaderID' => $SpreaderID,
            'start_time' => $start_time,
            'end_time' => $end_time,
            'source' => $source,
            'NickName' => $NickName,
            'GameID' => $GameID,
            'mobile' => $mobile,
            'Type' => $Type,
            'Sort' => $Sort,
            'FinalScoreSort' => $FinalScoreSort,
            'request' => $request
        ];

        return view('admin.extension_new.bind_list', $result);
    }
}
