<?php

namespace App\Http\Controllers\Admin;

use App\Facade\TableName;
use App\Game\GameCard;
use App\Http\Controllers\Controller;
use App\Http\helper\HttpCurl;
use App\Http\helper\NumConfig;
use App\Http\logic\admin\GlobalLogicController;
use App\Models\AccountsInfo;
use App\Models\AdminScore;
use App\Models\Control;
use App\Models\ControlRecord;
use App\Models\Cpf;
use App\Models\Order;
use App\Models\RecordPlatformData;
use App\Models\Withdrawal;
use App\Services\CreateLog;
use App\Services\GameRoomInfo;
use App\Services\GlobalUser;
use App\Services\Paging;
use App\Services\StoredProcedure;
use App\Util;
use App\Utility\Helper;
use Illuminate\Http\Request;
use Illuminate\Pagination\Paginator;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class GlobalController extends Controller
{

    public function index(Request $request)
    {
        $start_time = $request->start_time ?: date('Y-m-d 00:00:00');
        $end_time = $request->end_time ?: date('Y-m-d 23:59:59');

        if (!empty($request->post('date'))) {
            switch ($request->post('date')) {
                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");
                    //$first =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'));
                    $end_time = date('Y-m-d 23:59:59', strtotime("$start_time +6 days"));
                    break;
                case 4:
                    $start_time = date("Y-m-01 00:00:00");
                    $end_time = date("Y-m-t 23:59:59");
                    break;
            }
        }

        $StartDataID = date('Ymd', strtotime($start_time));
        $EndDataID = date('Ymd', strtotime($end_time));

        $RecordPlatformDataModel = new RecordPlatformData();
        $GlobalUserService = new GlobalUser();
        ///////////////////////////////////////////////////
        // 用户相关
        ///////////////////////////////////////////////////
        $accounts = $GlobalUserService->accounts();
        ///////////////////////////////////////////////////
        // 游戏相关
        ///////////////////////////////////////////////////
        $games = $GlobalUserService->games($StartDataID, $EndDataID);
        ///////////////////////////////////////////////////
        // 彩金相关
        ///////////////////////////////////////////////////
        // 用户彩金
        $winnings = $GlobalUserService->winnings($start_time, $end_time);
        // 按日期搜索注册用户
        $dayAccountInfo = $RecordPlatformDataModel->dayAccountInfo($StartDataID, $EndDataID);

        $start_time = date('Y-m-d', strtotime($start_time)) . 'T' . date('H:i:s', strtotime($start_time));
        $end_time = date('Y-m-d', strtotime($end_time)) . 'T' . date('H:i:s', strtotime($end_time));
        return view('admin.global.index', compact('accounts', 'games', 'winnings', 'dayAccountInfo', 'start_time', 'end_time'));
    }

    //全局报表
    public function index1(Request $request)
    {

        //总充值金额
        $order = Order::pay_sum();
        $pay_sum = isset($order->pay_sum) ? number_float($order->pay_sum / NumConfig::NUM_VALUE) : 0;

        // 签到总奖励
        $totalSignIn = DB::connection('read')->table('QPAccountsDB.dbo.UserSignInInfo')
                ->selectRaw('IsNull(sum(TotalReward),0) TotalReward')
                ->first()->TotalReward / 100 ?? 0;

        //总付费用户
        $pay_user_count = $order->pay_user_count ?? 0;


        // 历史流水和税收
        $gameInfo = DB::connection('read')->table('QPRecordDB.dbo.RecordUserTotalStatistics')
            ->selectRaw('IsNull((abs(sum(LostScore)) + sum(WinScore)),0) flowing_water,Isnull(sum(Revenue),0) as Revenue,IsNull((sum(LostScore) + sum(WinScore)),0) Score,IsNull(sum(Withdraw),0) WithDraw,Isnull(SUM(Handsel),0) as ChangeScore')
            ->first();

        // 累计提现金额
        $txAmount = $gameInfo->WithDraw / 100 ?? 0;

        // 累计提现回收金额
        $WithDrawRecovery = DB::connection('read')->table('QPAccountsDB.dbo.OrderWithDraw as ow')
                ->where('State', 4)
                ->selectRaw('sum(WithDraw+ServiceFee) as WithDraw')
                ->first()->WithDraw ?? 0;

        $AllWorkingScore = number_float(($gameInfo->flowing_water + $gameInfo->Revenue) / 100);

        //赠送总金豆
        $cellData = $gameInfo->ChangeScore;

        $z_give = number_float($cellData / 100);

        //总注册用户
        $user_count = AccountsInfo::user_count();

        //休眠用户
        $dormancy_user = AccountsInfo::dormancy_user();

        //流失用户
        $ls_user = AccountsInfo::ls_user();


        /*                        根据时间搜索查询数据                                        */
        $start_time = $request->start_time ?? date('Y-m-d 00:00:00');
        $end_time = $request->end_time ?? date('Y-m-d 23:59:59');


        if (!empty($request->post('start_time'))) $start_time = $request->post('start_time');
        if (!empty($request->post('end_time'))) $end_time = $request->post('end_time');

        $start_time = str_replace('T', ' ', $start_time);
        $end_time = str_replace('T', ' ', $end_time);

        if (!empty($request->post('date'))) {
            switch ($request->post('date')) {
                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");
                    //$first =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'));
                    $end_time = date('Y-m-d 23:59:59', strtotime("$start_time +6 days"));
                    break;
                case 4:
                    $start_time = date("Y-m-01 00:00:00");
                    $end_time = date("Y-m-t 23:59:59");
                    break;
            }
        }

        /*                     活动数据              */

        // 用户彩金
        $ScoreType = [21, 33, 36, 37, 42, 44, 45, 49, 51, 52, 53, 59, 70];
        // 21、绑定手机赠送 33、注册赠送 36、推广赚金(彩金) 37、人工增加金币 42、邮件附件(充值彩金) 45、充值彩金 49、月卡彩金 51、首充礼包(彩金)  52、邮件附件（群发彩金） 53、推广赚金(佣金)
        $RecordUserScoreStatistics = DB::connection('read')->table('QPRecordDB.dbo.RecordUserScoreStatisticsNew')
            ->whereBetween('DateID', [date('Ymd', strtotime($start_time)), date('Ymd', strtotime($end_time))])
            ->whereIn('ScoreType', $ScoreType)
            ->select('ScoreType')
            ->selectRaw('Isnull(SUM(Score),0) as Score')
            ->groupBy('ScoreType')
            ->pluck('Score', 'ScoreType')->toArray();

        $list['bd'] = isset($RecordUserScoreStatistics['21']) ? number_float($RecordUserScoreStatistics['21'] / NumConfig::NUM_VALUE) : 0;
        $list['zc'] = isset($RecordUserScoreStatistics['33']) ? number_float($RecordUserScoreStatistics['33'] / NumConfig::NUM_VALUE) : 0;
        $list['tg'] = isset($RecordUserScoreStatistics['36']) ? number_float($RecordUserScoreStatistics['36'] / NumConfig::NUM_VALUE) : 0;
        $list['rg'] = isset($RecordUserScoreStatistics['37']) ? number_float($RecordUserScoreStatistics['37'] / NumConfig::NUM_VALUE) : 0;
        $list['mailCellData'] = isset($RecordUserScoreStatistics['42']) ? number_float($RecordUserScoreStatistics['42'] / NumConfig::NUM_VALUE) : 0;
        $list['cz'] = isset($RecordUserScoreStatistics['45']) ? number_float($RecordUserScoreStatistics['45'] / NumConfig::NUM_VALUE) : 0;
        $list['yk'] = isset($RecordUserScoreStatistics['49']) ? number_float($RecordUserScoreStatistics['49'] / NumConfig::NUM_VALUE) : 0;
        $list['sc'] = isset($RecordUserScoreStatistics['51']) ? number_float($RecordUserScoreStatistics['51'] / NumConfig::NUM_VALUE) : 0;
        $list['qf'] = isset($RecordUserScoreStatistics['52']) ? number_float($RecordUserScoreStatistics['52'] / NumConfig::NUM_VALUE) : 0;
        $list['commission'] = isset($RecordUserScoreStatistics['53']) ? number_float($RecordUserScoreStatistics['53'] / NumConfig::NUM_VALUE) : 0;
        $list['weekCard'] = isset($RecordUserScoreStatistics['59']) ? number_float($RecordUserScoreStatistics['59'] / NumConfig::NUM_VALUE) : 0;
        $list['Backwater'] = isset($RecordUserScoreStatistics['70']) ? number_float($RecordUserScoreStatistics['70'] / NumConfig::NUM_VALUE) : 0;


        // 签到
        $signIn = DB::connection('read')->table('QPRecordDB.dbo.RecordSignIn')
                ->where('SignInDate', '>=', date("Y-m-d 00:00:00", strtotime("$start_time")))
                ->where('SignInDate', '<=', date("Y-m-d 23:59:59", strtotime("$end_time")))
                ->selectRaw('IsNull(sum(RewardScore),0) RewardScore')
                ->first()->RewardScore / 100 ?? 0;


        // 推广总奖励
        $TotalReward = DB::connection('read')->table('QPAccountsDB.dbo.SystemAgentReward')->select('TotalReward')->first()->TotalReward;


        $data['TotalReward'] = number_float($TotalReward / 100);


        // 非正式会员的彩金
        $notMemberProfit = DB::connection('read')->table('QPRecordDB.dbo.RecordUserScoreStatisticsNew as rs')
            ->join('QPAccountsDB.dbo.AccountsInfo as ai', 'ai.UserID', 'rs.UserID')
            ->where('Channel', 100)
            ->whereIn('ScoreType', $ScoreType)
            ->whereBetween('DateID', [date('Ymd', strtotime($start_time)), date('Ymd', strtotime($end_time))])
            ->selectRaw('Isnull(SUM(Score),0) as Score')
            ->first()->Score;

        // 正式会员彩金
        $MemberProfit = DB::connection('read')->table('QPRecordDB.dbo.RecordUserScoreStatisticsNew as rs')
            ->join('QPAccountsDB.dbo.AccountsInfo as ai', 'ai.UserID', 'rs.UserID')
            ->whereIn('ScoreType', $ScoreType)
            ->where('Channel', '<>', 100)
            ->whereBetween('DateID', [date('Ymd', strtotime($start_time)), date('Ymd', strtotime($end_time))])
            ->selectRaw('Isnull(SUM(Score),0) as Score')
            ->first()->Score;

        // 总彩金 = 邮件送金 + 充值送金 + 注册送金 + 月卡 + 绑定 + 签到 +  群发邮件 + 人工增加金币 +  周卡 + 返水 + 谷歌会员 + 正式会员
        $data['cellData'] = array_sum($list) + $signIn + ($notMemberProfit / 100) + ($MemberProfit / 100);

        // 非正式会员人数-- 进入TP试玩场人数

        $notMemberNum = DB::connection('read')->table('QPTreasureDB.dbo.RecordUserInout as ri')
                ->join('QPPlatformDB.dbo.GameRoomInfo as gi', 'ri.ServerID', 'gi.ServerID')
                ->where('gi.ServerType', 2)
                ->where('GameID', 1005)
                ->where('ri.EnterTime', '>=', date("Y-m-d 00:00:00", strtotime("$start_time")))
                ->where('ri.EnterTime', '<=', date("Y-m-d 23:59:59", strtotime("$end_time")))
                ->selectRaw('count(distinct(ri.UserID)) count_u')
                ->first()->count_u ?? 0;

        // 谷歌渠道--付费人数--付费金额
        $google_pay = DB::connection('read')->table('agent.dbo.order as o')
            ->join('QPAccountsDB.dbo.AccountsInfo as ai', 'o.user_id', '=', 'ai.UserID')
            ->where('Channel', 100)
            ->where('o.pay_at', '>=', "$start_time")
            ->where('o.pay_at', '<=', "$end_time")
            ->selectRaw('IsNull(sum(amount),0) as amount,count(distinct(o.user_id)) as c_user_id')
            ->first();


        /*                     用户数据              */

        //注册用户
        $data['today_register'] = DB::connection('read')->table('QPAccountsDB.dbo.AccountsInfo')
            ->selectRaw('count(*) as today_register')
            ->where('IsAndroid', 0)
            ->where('RegisterDate', '>=', "$start_time")
            ->where('RegisterDate', '<=', "$end_time")
            ->first()->today_register;

        //充值人数
        $pay_count = DB::connection('read')->table('agent.dbo.order')
            ->where('pay_at', '>=', "$start_time")
            ->where('pay_at', '<=', "$end_time")
            ->selectRaw('count(DISTINCT user_id) as today_pay_count,cast(sum(amount) as int) as today_pay_sum')
            ->first();

        // 提现人数
        $cash = DB::connection('read')->table('QPAccountsDB.dbo.OrderWithDraw')
            ->where('finishDate', '>=', "$start_time")
            ->where('finishDate', '<=', "$end_time")
            ->selectRaw('count(DISTINCT UserID) as cash_count,cast(sum(WithDraw) as int) as cash_sum,count(RecordID) cash_bi')
            ->first();

        $data['today_pay_count'] = $pay_count->today_pay_count;
        //活跃用户数
        $data['lively_num'] = DB::connection('read')->table('QPRecordDB.dbo.RecordUserLogin')->selectRaw('count(distinct(UserID)) as lively_num')
            ->where('DateID', '>=', date('Ymd', strtotime($start_time)))
            ->where('DateID', '<=', date('Ymd', strtotime($start_time)))
            ->first()->lively_num;


        //ios 安卓新增用户
        $player_list = DB::connection('read')->table('QPAccountsDB.dbo.AccountsInfo')
            ->where('IsAndroid', 0)
            ->whereIn('LastLogonMobile', ['Android', 'IOS'])
            ->where('RegisterDate', '>=', "$start_time")
            ->where('RegisterDate', '<=', "$end_time")
            ->get();

        $data['android_num'] = $data['ios_num'] = 0; //安卓 ios 人数
        foreach ($player_list as $key => $value) {
            if ($value->LastLogonMobile === 'Android') {
                $data['android_num'] += 1;//安卓用户数
            } else {
                $data['ios_num'] += 1;//IOS用户数
            }
        }
        /*                    充值数据                            */
        //累计充值 总额
        $data['today_pay_sum'] = number_float($pay_count->today_pay_sum / 100);

        $data['android_recharge'] = $data['ios_recharge'] = 0;//安卓 ios 累计充值金额
        $data['android_recharge_num'] = $data['ios_recharge_num'] = 0;//安卓 ios 充值用户数

        // 累计提现
        $data['cash_sum'] = number_float($cash->cash_sum / 100);
        $data['cash_count'] = $cash->cash_count;
        $data['cash_bi'] = $cash->cash_bi;

        $pay = DB::table(TableName::QPRecordDB() . 'RecordUserDataStatisticsNew as rsn')
            ->where('DateID', '>=', date('Ymd', strtotime($start_time)))
            ->where('DateID', '<=', date('Ymd', strtotime($end_time)))
            ->join('QPAccountsDB.dbo.AccountsInfo as ai', 'rsn.UserID', 'ai.UserID')
            ->where('LastLogonMobile', 'Android')
            ->selectRaw('count(rsn.UserID) count_u,sum(Recharge) amount')
            ->first();
        $data['android_recharge'] = isset($pay->amount) ? number_float($pay->amount) : 0;
        $data['android_recharge_num'] = $pay->count_u ?? 0;//安卓用户数


        // 游客人数
        $tourist = DB::connection('read')->table('QPAccountsDB.dbo.AccountsInfo')
            ->where('WebLogonTimes', 1)
            ->where('IsAndroid', 0)
            ->where('RegisterDate', '>=', $start_time)
            ->where('RegisterDate', '<=', $end_time)
            ->count();

        // 手机账号人数-包括游客升级来的
        $phoneNum = DB::connection('read')->table('QPAccountsDB.dbo.AccountPhone')
            ->where('BindDate', '>=', $start_time)
            ->where('BindDate', '<=', $end_time)
            ->count();

        // Facebook 人数
        $facebookNum = DB::connection('read')->table('QPAccountsDB.dbo.AccountsInfo')
            ->where('RegisterDate', '>=', $start_time)
            ->where('RegisterDate', '<=', $end_time)
            ->where('IsAndroid', 0)
            ->where('WebLogonTimes', 0)
            ->count();


        $data['android_recharge'] = number_float($data['android_recharge'] / 100);
        $data['ios_recharge'] = number_float($data['ios_recharge'] / 100);
        $data['amount'] = number_float($google_pay->amount / 100);          // 谷歌渠道付费金额
        $data['c_user_id'] = $google_pay->c_user_id;    // 谷歌渠道付费人数
        $list['notMemberProfit'] = number_float($notMemberProfit / NumConfig::NUM_VALUE);
        $list['MemberProfit'] = number_float($MemberProfit / NumConfig::NUM_VALUE);
        $list['signIn'] = number_float($signIn);
        // 总税收
        $z_revenue = number_float($gameInfo->Revenue / 100);
        //输赢总额 保留2位小数(平台总输赢)
        $z_robot_gold = number_float(-$gameInfo->Score / 100);

        // 库存统计 -- 玩家总额
        $sum = (new GlobalLogicController())->sum();

        foreach ($sum as &$val) {
            $val = number_float($val / 100);
        }

        $logic = new GlobalLogicController();
        // 月卡信息
        $MonthCard = $logic->MonthCard();
        // 首冲信息
        //$FirstRechargeGifts = $logic->FirstRechargeGifts();

        // 周卡信息
        $WeeklyCard = $logic->WeeklyCard();

        /*                     游戏房间数据              */
        $gameRoomInfo = DB::connection('read')->table('QPRecordDB.dbo.RecordServerDataStatistics')
            ->where('DateID', '>=', date('Ymd', strtotime($start_time)))
            ->where('DateID', '<=', date('Ymd', strtotime($start_time)))
            ->selectRaw('Isnull((sum(WinScore) + abs(sum(LostScore))),0) as flowing_water,Isnull(sum(Revenue),0) as Revenue,Isnull((sum(WinScore) + sum(LostScore)),0) as win_lose')
            ->first();

        //平台输赢 目前计算的是机器人输赢
        $gameRoomInfo->win_lose = isset($gameRoomInfo->win_lose) ? number_float($gameRoomInfo->win_lose / NumConfig::NUM_VALUE) : 0;
        //流水
        $gameRoomInfo->flowing_water = isset($gameRoomInfo->flowing_water) ? number_float(($gameRoomInfo->flowing_water) / NumConfig::NUM_VALUE) : 0;
        //税收
        $gameRoomInfo->Revenue = isset($gameRoomInfo->Revenue) ? number_float($gameRoomInfo->Revenue / NumConfig::NUM_VALUE) : 0;
        // 累计玩游戏人数
        $gameRoomInfo->GameCountUser = DB::connection('read')->table('QPRecordDB.dbo.PD_RecordScoreInfo')
            ->where('AtDate', '>=', date('Ymd', strtotime($start_time)))
            ->where('AtDate', '<=', date('Ymd', strtotime($end_time)))
            ->count(DB::raw('DISTINCT UserID'));


        $game_list = DB::connection('read')->table('QPPlatformDB.dbo.GameRoomInfo as gi')
            ->leftJoin('QPRecordDB.dbo.RecordServerDataStatistics as rds', 'rds.ServerID', 'gi.ServerID')
            ->where('DateID', '>=', date('Ymd', strtotime($start_time)))
            ->where('DateID', '<=', date('Ymd', strtotime($start_time)))
            ->select('gi.GameID', 'gi.ServerName', 'gi.ServerID')
            ->selectRaw('gi.ServerID,Isnull((sum(WinScore) + abs(sum(LostScore))),0) as flowing_water,Isnull(sum(rds.Revenue),0) as Revenue,Isnull((sum(WinScore) + sum(LostScore)),0) as win_lose')
            ->groupBy('gi.GameID', 'gi.ServerName', 'gi.ServerID')
            ->orderByDesc('flowing_water')
            ->get();
        // 玩过游戏的人
        $playGameUser = DB::connection('write')->table(TableName::QPRecordDB() . 'RecordUserGameCount')
            ->where('AtDate', '>=', date('Ymd', strtotime($start_time)))
            ->where('AtDate', '<=', date('Ymd', strtotime($end_time)))
            ->selectRaw('count(distinct(UserID)) as count_u,ServerID')
            ->groupBy('ServerID')
            ->pluck('count_u', 'ServerID')->toArray();


        foreach ($game_list as &$value) {
            $value->Score = number_float(($value->win_lose / NumConfig::NUM_VALUE));   // 平台输赢
            $value->ri_Revenue = number_float($value->Revenue / NumConfig::NUM_VALUE); // 税收
            $value->liushui = number_float(($value->flowing_water) / NumConfig::NUM_VALUE); // 流水
            $value->count_u = $playGameUser[$value->ServerID] ?? 0;

        }

        $start_time = strtotime($start_time);
        $end_time = strtotime($end_time);
        $start_time = str_replace('T', ' ', $start_time);
        $end_time = str_replace('T', ' ', $end_time);
        return view('admin.global.index', [
            'pay_sum' => $pay_sum, //总充值金额
            'totalSignIn' => $totalSignIn, //签到总奖励
            'pay_user_count' => $pay_user_count, //总付费用户
            'z_revenue' => $z_revenue,//总税收
            'AllWorkingScore' => $AllWorkingScore,//总流水
            'z_robot_gold' => $z_robot_gold,//机器人输赢总额 保留2位小数(平台总输赢)
            'txAmount' => number_float($txAmount),//机器人输赢总额 保留2位小数(平台总输赢)
            'WithDrawRecovery' => number_float($WithDrawRecovery / 100),//机器人输赢总额 保留2位小数(平台总输赢)
            'z_give' => $z_give,//赠送总金豆
            'user_count' => $user_count, //总注册用户
            'dormancy_user' => $dormancy_user,//休眠用户
            'ls_user' => $ls_user, //流失用户
            'data' => $data,//统计数据
            'list' => $list, //表格数据
            'tourist' => $tourist,
            'start_time' => date('Y-m-d', $start_time) . 'T' . date('H:i:s', $start_time),
            'end_time' => date('Y-m-d', $end_time) . 'T' . date('H:i:s', $end_time),
            'phoneNum' => $phoneNum,
            'facebookNum' => $facebookNum,
            'notMemberNum' => $notMemberNum,
            'sum' => $sum,
            'MonthCard' => $MonthCard,
            'WeeklyCard' => $WeeklyCard,
            //'FirstRechargeGifts' => $FirstRechargeGifts,
            'gameRoomInfo' => $gameRoomInfo,
            'game_list' => $game_list,

        ]);
    }

    //房间实时数据
    public function room(Request $request)
    {

        $field = ['LostUserCount', 'WinUserCount', 'gi.GameID', 'gi.Nullity', 'gi.SortID', 'gi.ServerName', 'gi.ServerID', 'gi.RoomStock', 'WinInning', 'LostInning', 'TotalInning', 'Revenue', 'LostScore', 'WinScore'];
        $list = DB::connection('read')->table('QPPlatformDB.dbo.GameRoomInfo as gi')
            ->whereIn('GameID', config('games.openKGame'))
            ->leftJoin('QPRecordDB.dbo.RecordServerDataStatistics as rds', 'gi.ServerID', '=', 'rds.ServerID')
            ->leftJoin('QPTreasureDB.dbo.GameScoreLocker as gl', function ($query) {
                $query->on('gl.ServerID', 'gi.ServerID')->selectRaw('gl.ServerID')->groupBy('ServerID')->whereRaw('datediff(hh,gl.CollectDate,getdate())<=5');
            })
            ->where('rds.DateID', date('Ymd'))
            ->select($field)
            ->selectRaw('IsNull(count(DISTINCT gl.UserID),0) as game_count')
            ->groupBy($field)
            ->orderBy('gi.GameID', 'asc')
            ->orderBy('gi.ServerName', 'asc')
            ->get()->toArray();

        $list = (new GlobalLogicController())->room($list);

        // 游戏在线人数
//        $line = DB::connection('read')->table('QPTreasureDB.dbo.GameScoreLocker')
//            ->selectRaw('count(DISTINCT UserID) as game_count')
//            ->whereDate('CollectDate', date('Y-m-d'))
//            ->first()->game_count;
        $line = DB::connection('read')->table('QPTreasureDB.dbo.GameScoreLocker')
            ->selectRaw('count(DISTINCT UserID) as game_count')
            ->whereRaw('datediff(hh,CollectDate,getdate())<=5')
            ->first()->game_count;

        $dt_line = 0;

        // 检查当前用户权限
        $admin = session('admin');
        $role_id = $admin->roles[0]->id;

        return view('admin.global.room', ['list' => $list, 'line' => $line, 'dt_line' => $dt_line, 'role_id' => $role_id]);
    }

    // 展示房间配置
    public function show_config($ServerID)
    {
        $GameKindItem = DB::connection('read')->table('QPPlatformDB.dbo.GameRoomInfo as gi')
            ->join('QPPlatformDB.dbo.GameKindItem as gk', 'gi.GameID', 'gk.GameID')
            ->where('gi.ServerID', $ServerID)
            ->value('KindName');

        $logic = new GlobalLogicController();
        $result = $logic->teenpatti($ServerID);

        if ($GameKindItem == 'teenpatti') { // teenpatti

            return view('admin.global.teenpatti', $result);

        } else { // rummy

            //$result = $logic->rummy($ServerID);
            return view('admin.global.rummy', $result);

        }
    }

    //用户列表
    public function userlist(Request $request)
    {

        $adminChannels=session('admin_channels');
        $UserID = (int)$request->UserID ?: "";
        $MachineID = $request->MachineID ?: "";
        $gameID = (int)$request->GameID ?: "";
        $phoneNum = $request->PhoneNum ?? "";
        $spreaderID = (int)$request->SpreaderID ?: "";
        $nickName = $request->NickName ?? "";
        $startTime = str_replace('T', ' ', $request->start_time ?? "");
        $endTime = str_replace('T', ' ', $request->end_time ?? "");

        $startLoginTime = str_replace('T', ' ', $request->start_logintime ?? "");
        $endLoginTime = str_replace('T', ' ', $request->end_logintime ?? "");

        $obj = $request->obj ?? "";
        $vip = $request->vip ?? '';
        $excel = $request->excel ?? "";
        $accounts_type = $request->accounts_type ?: 0;
        $score = $request->Score ?: '';
        $channel = $request->channel;
        $user_tab = $request->user_tab ?: '';
        $packgeName = $request->PackgeName ?: '';

        // 快速搜索
        $quickSearch = $request->quickSearch ?: '';


        $list = (new GlobalUser())->userlist($gameID, $phoneNum, $spreaderID, $nickName, $startTime, $endTime, $obj, $vip, $excel, $accounts_type, $channel, $user_tab, $packgeName, $quickSearch, $score,$MachineID,$startLoginTime,$endLoginTime);
//        $channels = DB::connection('read')->table('QPAccountsDB.dbo.AccountsInfo')->where('IsAndroid', 0)->groupBy('Channel')->pluck('Channel');
        $channels=$adminChannels;
//        $webLogonTimes = [1 => 'facebook', 2 => '游客', 3 => '手机号'];
        $webLogonTimes = [ 2 =>  __('auto.游客'), 3 =>  __('auto.手机号')];
        // 获取包名
        $ChannelPackageName = DB::connection('write')->table('QPPlatformDB.dbo.ChannelRechargeGameOpen')
            ->select('ChannelPackageName')
            ->pluck('ChannelPackageName')->toArray();

//        $ChannelPackageName[] = 'com.teenpatti.queen';

        $typeList = [1 => __('auto.游戏中'), 2 => __('auto.未实名'), 3 => __('auto.无手机号'), 5 =>  __('auto.无渠道'), 6 =>  __('auto.未充值'), 7 =>  __('auto.无上级'), 8 =>  __('auto.封号中'), 9 => __('auto.官方账号')];
        return view('admin.global.userlist', compact('list','MachineID', 'gameID', 'phoneNum', 'spreaderID', 'nickName', 'startTime', 'endTime','startLoginTime', 'endLoginTime', 'obj', 'vip', 'excel', 'accounts_type'
            , 'channel', 'user_tab', 'packgeName', 'channels', 'webLogonTimes', 'ChannelPackageName', 'score', 'quickSearch', 'typeList'
        ));

    }

    //用户列表
    public function userlist1(Request $request)
    {
        $list = DB::connection('read')->table('QPAccountsDB.dbo.AccountsInfo as ai')
            ->leftJoin('QPAccountsDB.dbo.AccountsInfo as ai1', 'ai.SpreaderID', '=', 'ai1.UserID')
            ->leftJoin('QPTreasureDB.dbo.GameScoreInfo as gi', 'ai.UserID', '=', 'gi.UserID')
            ->leftJoin('QPTreasureDB.dbo.GameScoreLocker as gsl', 'gsl.UserID', '=', 'ai.UserID')
            ->leftJoin('QPPlatformDB.dbo.GameRoomInfo as gri', 'gsl.ServerID', '=', 'gri.ServerID')
            ->leftJoin('QPAccountsDB.dbo.AccountPhone as ap', 'ai.UserID', 'ap.UserID')
            ->leftJoin('QPAccountsDB.dbo.IDWhiteUser as iu', 'ai.UserID', 'iu.UserID')
            ->leftJoin('QPRecordDB.dbo.RecordPackageName as rn', 'ai.UserID', 'rn.UserID')
            ->where('ai.IsAndroid', 0);

        $UserID = (int)$request->UserID ?: "";
        $GameID = (int)$request->GameID ?: "";
        $RegisterMobile = $request->RegisterMobile ?? "";
        $SpreaderID = (int)$request->SpreaderID ?: "";
        $Compellation = $request->Compellation ?? "";
        $start_time = $request->start_time ?? "";
        $end_time = $request->end_time ?? "";

        $obj = $request->obj ?? "";
        $vip = $request->vip ?? '';
        $excel = $request->excel ?? "";
        $accounts_type = $request->accounts_type ?: '';
        $Score = $request->Score ?: '';
        $channel = $request->channel;
        $user_tab = $request->user_tab ?: '';
        $PackgeName = $request->PackgeName ?: '';

        $start_time = str_replace('T', ' ', $start_time);
        $end_time = str_replace('T', ' ', $end_time);

        if (!empty($PackgeName)) {
            $list->where('PackgeName', $PackgeName);
        }
        if (!empty($UserID)) {
            $list->where('ai.UserID', $UserID);
        }
        if (!empty($GameID)) {
            $list->where('ai.GameID', $GameID);
        }
        if (!empty($RegisterMobile)) {
            $RegisterMobile = str_replace(' ', '', $RegisterMobile);
            $list->where('ap.PhoneNum', 'like', $RegisterMobile . '%');
        }
        if (!empty($SpreaderID)) {
            $getSpreaderID = AccountsInfo::where('GameID', $SpreaderID)->value('UserID');
            $list->where('ai.SpreaderID', $getSpreaderID);
        }
        if (!empty($Compellation)) {
            $list->where('ai.NickName', 'like', '%' . $Compellation . '%');
        }
        if (!empty($start_time)) {
            $list->where('ai.RegisterDate', '>=', $start_time);
            $start_time = date('Y-m-d', strtotime($start_time)) . 'T' . date('H:i:s', strtotime($start_time));
        }
        if (!empty($end_time)) {
            $list->where('ai.RegisterDate', '<=', $end_time);
            $end_time = date('Y-m-d', strtotime($end_time)) . 'T' . date('H:i:s', strtotime($end_time));
        }

        if (!empty($user_tab)) {
            $user_tabArr = explode('_', $user_tab);
            $list->where($user_tabArr[0], $user_tabArr[1])->count();

        }

        (!empty($channel) || $channel === '0') && $list->where('ai.Channel', $channel);

        switch ($accounts_type) {
            case 1:
                $list->where('ai.WebLogonTimes', 0)->whereNull('PhoneNum');
                break;
            case 2:
                $list->where('ai.WebLogonTimes', 1)->whereNull('PhoneNum');
                break;
            case 3:
                $list->WhereNotNull('PhoneNum');
                break;
            case 4:
                $list->where('ai.Channel', 100);
                break;
        }

        if (!empty($Score)) {
            $list->orderBy('Score', $Score);
        } else {
            $list->orderBy('ai.RegisterDate', 'desc');
        }


        $build_str = $request->build_str ?: '';
        $arr = [];
        if (!empty($build_str)) {
            parse_str($build_str, $arr);
        }
        $build_query = '';
        $data = $request->post('search', []);
        $data = array_merge($data, $arr);
        if (!empty($data)) {
            $arr_filter = array_filter($data);
            $build_query = http_build_query($arr_filter);

        }

        $r = (new GlobalLogicController())->user_search($list, $data);
        $list = $r['build_sql'];
        $data = $r['data'];


        if (!empty($vip)) {
            $list->where('ai.MemberOrder', $vip);
        }

        //是否导出excel
        if (!empty($excel)) {
            $list = $list->selectRaw('ai.GameID,ai.NickName,ap.PhoneNum,ai.RegisterIP,gi.Score,ai1.GameID as SpreaderID,ai.MemberOrder,ai.RegisterDate,ai.Channel,ai.Accounts,ai.Nullity')
                ->limit(10000)->get();
            foreach ($list as $key => &$value) {
                $value->Score = number_float($value->Score / 100);
                switch ($value->Nullity) {
                    case '0':
                        $value->Nullity = '正常';
                        break;
                    case '1':
                        $value->Nullity = '封禁';
                        break;
                }
            }
            $title = ['会员ID', '姓名', '手机号', 'IP', '金豆余额', '上级ID', 'vip等级', '注册日期', '渠道名称', '账号', '账号状态'];
            $list = json_decode(json_encode($list), true);
            downloadExcel($list, $title, '房间输赢统计' . date('YmdHis'));
        } else {
            $list = $list
                ->select('ai.*', 'gi.Score', 'ai1.GameID as ain_GameID', 'gi.Revenue', 'gi.InsureScore', 'gsl.CollectDate', 'gi.BankScore', 'gri.ServerName', 'ap.PhoneNum', 'PackgeName')
                ->paginate(10);

            // 查找官方账号
            $userID = [];
            foreach ($list as $val) {
                $userID[] = $val->UserID;
            }

            // 游戏中用户

            $query_UserID = DB::connection('read')->table('QPAccountsDB.dbo.IDWhiteUser')->whereIn('UserID', $userID)->pluck('UserID')->toArray();

            // 禁止查看敏感信息
            $helper = new Helper();
            $flag = $helper->privacy($request);
            if ($flag) {
                foreach ($list->items() as &$val) {
                    $val->LastLogonMobile = !empty($this->LastLogonMobile) ? $helper->sub_mobile($val->LastLogonMobile) : '';
                }
            }

            // 获取包名
            $ChannelPackageName = DB::connection('write')->table('QPPlatformDB.dbo.ChannelRechargeGameOpen')
                ->select('ChannelPackageName')
                ->pluck('ChannelPackageName')->toArray();

            $ChannelPackageName[] = 'com.teenpatti.queen';
            foreach ($list as &$val) {
                $val->Score = $val->Score / 100;

                $val->ipAddress = '';

                switch ($val->Nullity) {
                    case '0':
                        $val->Nullity = '正常';
                        break;
                    case 1:
                        $val->Nullity = '封禁';
                        break;
                }


                if (in_array($val->UserID, $query_UserID)) {
                    $val->Nullity .= '<span style="color: Orange">(官方)</span>';
                }

            }


            $WebLogonTimes = [1 => 'facebook', 2 => '游客', 3 => '手机号'];

            $channels = DB::connection('read')->table('QPAccountsDB.dbo.AccountsInfo')->where('IsAndroid', 0)->groupBy('Channel')->pluck('Channel');
            return view('admin.global.userlist', [
                'list' => $list,
                'UserID' => $UserID,
                'GameID' => $GameID,
                'RegisterMobile' => $RegisterMobile,
                'SpreaderID' => $SpreaderID,
                'Compellation' => $Compellation,
                'start_time' => $start_time,
                'end_time' => $end_time,
                'obj' => $data,
                'vip' => $vip,
                'WebLogonTimes' => $WebLogonTimes,
                'accounts_type' => $accounts_type,
                'build_str' => $build_query,
                'channel' => $channel,
                'Score' => $Score,
                'user_tab' => $user_tab,
                'channels' => $channels,
                'ChannelPackageName' => $ChannelPackageName,
                'PackgeName' => $PackgeName
            ]);
        }

    }

    //用户修改
    public function user_update(Request $request)
    {
        if ($request->isMethod('get')) {
            $userID = $request->id;
            $list = DB::connection('read')->table('QPAccountsDB.dbo.AccountsInfo as ai')
                ->leftJoin('QPAccountsDB.dbo.AccountsInfo as ain', 'ai.SpreaderID', '=', 'ain.UserID')
                ->where('ai.UserID', $userID)
                ->selectRaw('ai.UserID,ai.NickName,ai.Nullity,ai.Compellation,ai.SpreaderID,ai.GameID as ai_GameID,IsNull(ain.GameID,0) as GameID')
                ->first();
            $IDWhiteUser = DB::connection('read')->table('QPAccountsDB.dbo.IDWhiteUser')->where('UserID', $userID)->first();
            return view('admin.global.user_update', ['list' => $list, 'IDWhiteUser' => $IDWhiteUser]);

        } elseif ($request->isMethod('post')) {

            $SpreaderID = (int)$request->post('SpreaderID') ?: "";
            $UserID = $request->post('UserID');
            $Nullity = $request->post('Nullity', '');

            $official = $request->post('official');

            $query = $IDWhiteUser = DB::connection('read')->table('QPAccountsDB.dbo.IDWhiteUser')->where('UserID', $UserID)->first();


            $arr = [];

            if (!empty(trim($SpreaderID))) {
                $account = DB::connection('read')->table('QPAccountsDB.dbo.AccountsInfo')->where('GameID', $SpreaderID)->selectRaw('UserID')->first();

                $arr['SpreaderID'] = $account->UserID;
            }
            if ($Nullity !== "" || $Nullity === 0) {
                $arr['Nullity'] = $Nullity;
            }
            try {
                DB::table('QPAccountsDB.dbo.AccountsInfo')->where('UserID', $UserID)->update($arr);

                if ($official == 1) {   // 设置官方账号
                    if (!$query) {
                        DB::table('QPAccountsDB.dbo.IDWhiteUser')->insert(['UserID' => $UserID]);
                    }
                } else {
                    if ($query) {
                        DB::table('QPAccountsDB.dbo.IDWhiteUser')->where('UserID', $UserID)->delete();
                    }
                }

            } catch (\Exception $e) {
                return $this->json(500, '修改失败');
            }
            return $this->json(200, '修改成功');
        }
    }

    //封号1 解封2
    public function ban(Request $request)
    {
        $url = config('transfer.stock')['url'] . 'banAccounts';
        try {
            if ($request->ban == 1) {
                $id = explode(',', $request->id);
                DB::table('QPAccountsDB.dbo.AccountsInfo')->whereIn('UserID', $id)->update(['Nullity' => 1]);

                // 查询用户gameId
                $gameID = DB::connection('read')->table('QPAccountsDB.dbo.AccountsInfo')->whereIn('UserID', $id)->select('GameID')->get();
                $data = [];


                foreach ($gameID as $value) {
                    $data[] = [
                        'GameID' => $value->GameID,
                        'CreateDate' => date('Y-m-d H:i:s'),
                        'State' => 0
                    ];
                    // 给中转服发送通知
                    $admin = session('admin');
                    $account = $admin->account ?: '';
                    $password = $admin->password ?: '';
                    $yc_data = [
                        'accounts' => $account,
                        'passworld' => $password,
                        'gameID' => $value->GameID,
                    ];

                    $build_query = $url . '?' . http_build_query($yc_data);

                    $output = (new HttpCurl())->curl_get($build_query);
                }
                // 添加封号
                DB::table('QPAccountsDB.dbo.BanAccounts')->insert($data);

            } elseif ($request->ban == 2) {
                // 给中转服发送通知
                $admin = session('admin');
                $account = $admin->account ?: '';
                $password = $admin->password ?: '';
                $yc_data = [
                    'accounts' => $account,
                    'passworld' => $password,
                    'gameID' => 0,
                ];

                $build_query = $url . '?' . http_build_query($yc_data);

                $output = (new HttpCurl())->curl_get($build_query);

                $id = explode(',', $request->id);
                DB::table('QPAccountsDB.dbo.AccountsInfo')->whereIn('UserID', $id)->update(['Nullity' => 0]);
            } else {
                return $this->json(400, '操作失败');
            }
        } catch (\Exception $e) {
            return $this->json(500, $e->getMessage());
        }
        return $this->json(200, '操作成功');
    }

    //用户列表 ID跳转
    public function id_find(Request $request)
    {
        $UserID = $request->UserID;
        $OpenPage = $request->OpenPage ?: '';
        $r = (new GlobalLogicController())->id_find($UserID, $OpenPage);
        return view('admin.global.id_list', $r);
    }

    //关联 姓名 设备 IP
    public function join(Request $request)
    {
        $id = $request->id;

        if ($id == 1) {
            $ip = $request->RegisterIP;
            $list = DB::connection('read')->table('QPAccountsDB.dbo.AccountsInfo')
                ->where('RegisterIP', $ip)
                ->where('IsAndroid', 0)
                ->selectRaw('RegisterDate,LastLogonDate,GameID,Compellation,Channel,NickName,UserID')
                ->paginate(100);

            return view('admin.global.join_ip', ['list' => $list, 'id' => $id, 'ip' => $ip]);
        } elseif ($id == 2) {
            $userid = $request->UserID;

            $mac = DB::connection('read')->table('QPRecordDB.dbo.RecordUserLogonStatistics')
                     ->where('UserID', $userid)
                     ->where('mac', '<>','')
                     ->pluck('mac')->toArray();
            $mac=array_unique($mac);


            $list=[];
            if($mac) {
                $userids= DB::connection('read')->table('QPRecordDB.dbo.RecordUserLogonStatistics')
                         ->whereIn('mac', $mac)
                         ->pluck('UserID')
                         ->toArray();
                $userids=array_unique($userids);
                $list = DB::connection('read')->table('QPAccountsDB.dbo.AccountsInfo')
                          ->whereIn('UserID', $userids)
                          ->selectRaw('RegisterDate,LastLogonDate,GameID,Compellation,Channel,NickName,UserID')
                          ->paginate(100);
            }



            foreach ($list as &$value) {
                $value->login_count = DB::table('QPRecordDB.dbo.RecordUserLogin')->where('UserID', $value->UserID)->count();
            }
            return view('admin.global.join_facility', ['list' => $list, 'mac' => implode(",",$mac), 'id' => $id]);
        } elseif ($id == 3) {

            $BankNo = $request->Phone;
            $list = DB::connection('read')->table('QPAccountsDB.dbo.AccountPhone as di')
                ->join('QPAccountsDB.dbo.AccountsInfo as ai', 'di.UserID', 'ai.UserID')
                ->where('di.PhoneNum', $BankNo)
                ->selectRaw('RegisterDate,LastLogonDate,ai.GameID,Compellation,ai.Channel,ai.NickName,ai.UserID')
                ->paginate(10);
            return view('admin.global.join_bankNo', ['list' => $list, 'id' => $id, 'BankNo' => $BankNo]);
        } elseif ($id == 4) {
            $BankNo = $request->BankUserName;
            $list = DB::connection('read')->table('QPAccountsDB.dbo.AccountWithDrawInfo as di')
                ->join('QPAccountsDB.dbo.AccountsInfo as ai', 'di.UserID', 'ai.UserID')
                ->where('di.BankUserName', $BankNo)
                ->selectRaw('RegisterDate,LastLogonDate,ai.GameID,Compellation,Channel,ai.NickName,ai.UserID')
                ->paginate(10);
            return view('admin.global.join_bankNo', ['list' => $list, 'id' => $id, 'BankNo' => $BankNo]);
        } elseif ($id == 5) {
            $BankNo = $request->EmailAddress;
            $list = DB::connection('read')->table('QPAccountsDB.dbo.AccountWithDrawInfo as di')
                ->join('QPAccountsDB.dbo.AccountsInfo as ai', 'di.UserID', 'ai.UserID')
                ->where('di.EmailAddress', $BankNo)
                ->selectRaw('RegisterDate,LastLogonDate,ai.GameID,Compellation,Channel,ai.NickName,ai.UserID')
                ->paginate(100);
            return view('admin.global.join_bankNo', ['list' => $list, 'id' => $id, 'BankNo' => $BankNo]);
        } elseif ($id == 6) {   // 关联IP

            $UserID = $request->UserID;

            $UserIDs = DB::connection('read')->table('QPRecordDB.dbo.RecordUserLogonStatistics as rs')
                ->join('QPRecordDB.dbo.RecordUserLogonStatistics as rs1', function ($join) {
                    $join->on('rs.LogonIP', 'rs1.LogonIP');
                })
                ->where('rs.UserID', $UserID)
                ->select('rs1.UserID')
                ->groupBy('rs1.UserID')
                ->limit(2000)
                ->pluck('rs1.UserID');

            $list = DB::connection('read')->table('QPAccountsDB.dbo.AccountsInfo as ai')
                ->whereIn('ai.UserID', $UserIDs)
                ->where('IsAndroid', 0)
                ->selectRaw('RegisterDate,LastLogonDate,GameID,Compellation,Channel,NickName,ai.UserID')
                ->paginate(1000);


            return view('admin.global.join_LastLogonIP', ['list' => $list, 'id' => $id, 'UserID' => $UserID]);
        } elseif ($id == 7) { // 登录IP记录
            $UserID = $request->UserID;

            $list = DB::connection('read')->table('QPRecordDB.dbo.RecordUserLogonStatistics as rls')
                ->join('QPAccountsDB.dbo.AccountsInfo as ai', 'rls.UserID', 'ai.UserID')
                ->where('rls.UserID', $UserID)
                ->where('IsAndroid', 0)
                ->select('rls.UserID','LastLogonDate', 'LogonIP', 'LastDate', 'ai.GameID', 'NickName', 'Channel')
                ->orderByDesc('LastDate')
                ->paginate(1000);

            return view('admin.global.join_login_ip', ['list' => $list, 'UserID' => $UserID, 'id' => $id]);
        } elseif ($id == 8) { // 关联cpf
            $UserID = $request->UserID;
            $cpf=Cpf::getCpf($UserID,1);
            $list = DB::connection('read')->table('QPAccountsDB.dbo.AccountsInfo as ai')
                      ->whereIn('ai.UserID', Cpf::getCpf($UserID))
                      ->where('IsAndroid', 0)
                      ->selectRaw('RegisterDate,LastLogonDate,GameID,Compellation,Channel,NickName,ai.UserID')
                      ->paginate(1000);

            return view('admin.global.join_bankNo', ['list' => $list, 'id' => $id,  'UserID' => $UserID, 'BankNo' => implode(",",$cpf)]);
        }
    }

    //用户单控系统
    public function dk(Request $request)
    {
        $start_time = $request->start_time ?: date('Y-m-d 00:00:00');
        $end_time = $request->end_time ?: date('Y-m-d 23:59:59');
        $date = $request->date ?: '';

        $r = (new GlobalLogicController())->dk($start_time, $end_time, $date);
        return view('admin.global.dk', $r);
    }

    //用户单控系统-详细用户列表
    public function dk_userlist(Request $request)
    {
        $GameID = (int)$request->GameID ?: "";

        $SpreaderID = (int)$request->SpreaderID ?: "";
        $NickName = (string)$request->NickName ?: "";
        $start_time = $request->start_time ?: "";
        $end_time = $request->end_time ?: "";
        $user_label = $request->label ?: "";
        $label_sort = $request->label_sort ?: "";
        $is_line = $request->is_line ?: "";
        $game_room = $request->game_room ?: "";
        $UserScoreControl = $request->UserScoreControl ?: "";
        $ScoreSort = $request->Score ?: "";
        $amountSort = $request->amount ?: "";
        $sort_tx = $request->sort_tx ?: "";
        $sort_date = $request->sort_date ?: "";
        $ChangeScoreSort = $request->ChangeScore ?: '';
        $Channel = $request->Channel;
        $ServerNameSort = $request->ServerNameSort ?: '';

        $start_time = str_replace('T', ' ', $start_time);
        $end_time = str_replace('T', ' ', $end_time);

        $list = (new GlobalUser())->dk_userlist($GameID, $SpreaderID, $NickName, $start_time, $end_time, $user_label, $is_line, $game_room, $UserScoreControl, $ScoreSort, $amountSort, $sort_tx, $sort_date, $ChangeScoreSort, $Channel, $label_sort, $ServerNameSort);
        $game_room_line = DB::connection('read')->table(TableName::QPPlatformDB() . 'GameRoomInfo')->select('ServerName', 'ServerID')->get();
        $allChannel = DB::connection('read')->table(TableName::QPPlatformDB() . 'ChannelPackageName')->pluck('Channel');
        $page = Paginator::resolveCurrentPage('page');

        $start_time = \App\Http\helper\Helper::timeChange($start_time);
        $end_time = \App\Http\helper\Helper::timeChange($end_time);
        $user_labels = [1 => '普通会员', 2 => '首充会员', 3 => '复充会员', 4 => '优质会员', 5 => '尊贵会员', 6 => '发育不良', 7 => '异常观察', 8 => '重点关注', 20 => '其他1', 21 => '其他2'];
        return view('admin.global.dk_userlist', compact('list', 'GameID', 'SpreaderID', 'NickName', 'start_time', 'end_time', 'user_label'
            , 'label_sort', 'is_line', 'game_room', 'UserScoreControl', 'ScoreSort', 'amountSort', 'sort_tx', 'sort_date', 'ChangeScoreSort', 'Channel', 'ServerNameSort'
            , 'game_room_line', 'allChannel', 'page', 'user_labels'
        ));
    }


    //用户单控系统-详细用户列表 修改
    public function dk_userlist_edit(Request $request)
    {
        $UserID = $request->UserID ?? '';
        $TempID = $request->TempID ?? '';

        $ControlModel = new Control();
        $build_sql = DB::connection('write')->table('QPTreasureDB.dbo.UserScoreControl');

        if ($request->isMethod('post')) {

            $post = $request->post();

            if (!empty($post['Template'])) {
                $cc=new ControlController();
                $Template=(array)$cc->getConfigByID($post['Template']);
                $post = array_merge($Template, $post);
            }


//            if (!empty($post['TPBai']) && empty($post['TpBaiGear'])) {
//                return apiReturnFail('TP百人额度未设置');
//            }
//            if (!empty($post['ABBai']) && empty($post['ABBaiGear'])) {
//                return apiReturnFail('A&B额度未设置');
//            }
//            if (empty($post['Template']) && empty($post['TP']) && empty($post['TPAK47']) && empty($post['TPJOKER']) && empty($post['Rummy5']) && empty($post['Rummy2'])) {
//                return apiReturnFail('概率没有配置，无法提交！');
//            }
            DB::connection('write')->table('QPTreasureDB.dbo.UserControlServer')->where('UserID', $UserID)->delete();

            $ControlScore = $post['ControlScore'];
            $Remarks = $post['Remarks'];
            $admin_id = session('admin')->id;
            $admin_user = DB::connection('read')->table('agent.dbo.admin_users')->where('id', $admin_id)->first();
            /*管理员彩金控制*/
            if ($ControlScore > 0) {
                if ($admin_user->recharge_amount < $ControlScore) return apiReturnFail('管理员彩金额度不足！');
                AdminScore::add_score($admin_user, abs($ControlScore), 2);
            }

            /*用户单控记录添加*/
            $GameData = (new Control())->GameData;
            foreach ($post as $key => &$value) {
                if ($key == 'ABBaiGear') {
                    continue;
                }
                if (!isset($GameData[$key])) {
                    unset($post[$key]);
                }
            }

            // 控制分数
            $prefix = $ControlScore < 0 ? '输' : '赢';
            // 概率
            $str = '';
            foreach ($post as $key => $value) {
                $str .= $key . '：' . number_float($value) . '% ，';
            }
            $content = $prefix . $ControlScore . '/' . rtrim($str, '，');
            $score = DB::connection('read')->table('QPTreasureDB.dbo.GameScoreInfo')->where('UserID', $UserID)->select('Score')->first()->Score ?? 0;
            ControlRecord::record_add($UserID, $admin_id, $content, $score);
            // 用户控制游戏和场次
            $ControlModel->userControl($post, $UserID);
            $data = [
                'ControlScore' => (int)($ControlScore * NumConfig::NUM_VALUE),
                'EffectiveScore' => 0,
                'ControlKindID' => -1,
                'Remarks' => $Remarks,
                'InsertDate' => date('Y-m-d H:i:s'),
                'ControlRadian' => 0,
                'UserID'=>$UserID
            ];

            $build_sql->updateOrInsert(['UserID' => $UserID], $data);


            // 埋点，执行存储过程
            // 执行存储过程，-- 用户单控标签
            StoredProcedure::user_label($UserID, 3);

            return $this->json(200, "修改成功");
        }

        $ControlScore = $build_sql->where('UserID', $UserID)->first()->ControlScore ?? '0';

        $GameKindItem = DB::connection('read')->table('QPPlatformDB.dbo.GameKindItem')->pluck('KindID')->toArray();

        $UserControlKind = DB::connection('write')->table('QPTreasureDB.dbo.UserControlKind')
            ->where('UserID', $UserID)
            ->selectRaw('(ControlRadian) ControlRadian,KindID')
            ->pluck('ControlRadian', 'KindID')->toArray();

        $GameData = array_flip($ControlModel->GameData);


        foreach ($GameKindItem as $value) {
            if (!empty($GameData[$value] ?? '')) $UserControlKind[$GameData[$value]] = $UserControlKind[$value] ?? '';
        }


//        $TPBai = $UserControlKind['TPBai'];
//        $ABBai = $UserControlKind['ABBai'];

//        $substr = substr($TPBai, -3);
//        $UserControlKind['TPBai'] = (int)$substr;
//        $UserControlKind['TPBaiGear'] = !empty($TPBai) ? ($TPBai - $substr) / 1000 : '';

//        $substr = substr($ABBai, -3);
//        $UserControlKind['ABBai'] = (int)$substr;
//        $UserControlKind['ABBaiGear'] = !empty($ABBai) ? ($ABBai - $substr) / 1000 : '';

        $amount = DB::connection('write')->table('agent.dbo.order')
                ->where('user_id', $UserID)
                ->where('pay_status', 1)
                ->orderByDesc('pay_at')
                ->first()->amount ?? '';


        !empty($amount) && $amount = (int)($amount / 100);
//        $ControlScore = empty($ControlScore) ? $amount : $ControlScore / NumConfig::NUM_VALUE;
        $ControlScore =  $ControlScore / NumConfig::NUM_VALUE;


//        $list = DB::connection('write')->table('agent.dbo.ControlConfig')->get();
        $cc=new ControlController();
        $list=$cc->getList();


//        $TpBaiGear = DB::connection('write')->table('agent.dbo.ControlGear')->where('KindID', 2010)->get();
        $ABBai = DB::connection('write')->table('agent.dbo.ControlGear')->where('KindID', 2012)->get();

        $ControlModel = new Control();

        $GameDataText=$ControlModel->GameDataText;

        $data = compact('UserID', 'UserControlKind', 'ControlScore', 'list', 'TempID', 'ABBai','GameDataText');

        return view('admin.global.dk_userlist_edit', $data);

    }

    // 取消单控
    public function cancel_dk(Request $request)
    {

        $UserID = $request->id ?? '';
        $build_sql = DB::connection('write')->table('QPTreasureDB.dbo.UserScoreControl');
        //$query = $build_sql->where('UserID',$UserID)->first();

        $res = $build_sql->where('UserID', $UserID)->delete();

        /*用户单控记录添加*/
        $admin_id = session()->get('admin')->id;


        if ($res) {
            $score = DB::connection('read')->table('QPTreasureDB.dbo.GameScoreInfo')->where('UserID', $UserID)->select('Score')->first()->Score ?? 0;
            ControlRecord::record_add($UserID, $admin_id, '取消单控', $score);

            // 埋点，执行存储过程
            // 执行存储过程，-- 用户单控标签
            StoredProcedure::user_label($UserID, 5);

            return apiReturnSuc("已取消单控");
        }

        return apiReturnFail('取消单控失败');

    }


    //输赢报表
    public function winloser(Request $request)
    {
        $UserID = (int)trim($request->UserID) ?: '';
        $UniqueCode = trim($request->UniqueCode) ?: '';
        $room = trim($request->room) ?: '';
        $searchGame = trim($request->searchGame) ?: '';
        $start_time = trim($request->start_time) ?: '';
        $end_time = trim($request->end_time) ?: '';
        $start_time = str_replace('T', ' ', $start_time);
        $end_time = str_replace('T', ' ', $end_time);
        $excel = $request->excel ?: '';
        $id_list = $request->id_list ?: '';
        $ChangeScoreMin = $request->ChangeScoreMin;
        $ChangeScoreMax = $request->ChangeScoreMax;
        $PlayGames = $request->PlayGames ?: '';
        $ChangeScoreSort = $request->ChangeScoreSort ?: '';
        $afterScoreSort = $request->afterScoreSort ?: '';
        $Jump = (int)$request->Jump ?? 0;

        $result = (new GlobalLogicController())->winloser($UserID, $UniqueCode, $room, $start_time, $end_time, $excel, $id_list, $ChangeScoreMin, $ChangeScoreMax, $ChangeScoreSort, $afterScoreSort, $searchGame);
        $Jump += 1;
        $result['Jump'] = $Jump;
        return view('admin.global.win_loser_list', $result);
    }

    // 查看战绩
    public function game_record(Request $request)
    {

        $UniqueCode = $request->UniqueCode ?? '';
        $gameId = $request->gameId ?? '';
        $month = $request->month ?? '';
        $result = (new GlobalLogicController())->game_record($UniqueCode, $gameId, $month);
        return view('admin.global.game_record', $result);
    }

    //推广员奖励报表
    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);

        $result = (new GlobalLogicController())->reward($UserID, $SpreaderID, $start_time, $end_time, $Type);
        return view('admin.global.reward_list', $result);
    }

    // 奖励来源玩家
    public function userSource(Request $request)
    {
        $orderIds = $request->orderIds ?: '';
        $Type = $request->Type ?: '';
        $Id = $request->Id ?: '';
        $GameID = $request->GameID ?: '';

        switch ($Type) {
            case 1:
                $OrderIDs = explode(',', $orderIds);

                $list = DB::connection('write')->table('agent.dbo.extension_user_profit_log')
                    ->whereIn('OrderID', $OrderIDs)
                    ->where('OrderID', '>', 0)
                    ->where('Type', $Type)
                    ->paginate(10);

                foreach ($list as &$value) {
                    $value->toGold /= NumConfig::NUM_VALUE;
                }
                unset($value);

                $view = 'admin.extension.user_source';
                break;
            case 2:
                break;
            case 3:
                $list = DB::connection('read')->table('QPRecordDB.dbo.RecordUserAgent as ua')
                    ->join('QPAccountsDB.dbo.accountsInfo as ai', 'ua.UserID', 'ai.UserID')
                    ->leftJoin('QPAccountsDB.dbo.accountsInfo as ain', 'ain.UserID', '=', 'ua.SourceUserID')
                    ->select('ai.GameID', 'ain.GameID as SourceUserID', 'DirectRebate', 'SendTime', 'OrderSn', 'ain.UserID', 'ua.Level')
                    ->where('ua.Id', $Id)
                    ->orderBy('SendTime', 'desc')
                    ->paginate(10);
                foreach ($list as &$value) {
                    $value->DirectRebate = number_float($value->DirectRebate / NumConfig::NUM_VALUE);
                }
                $view = 'admin.extension.user_recharge_source';
                break;

        }

        return view($view, compact('list', 'Type', 'orderIds', 'GameID'));
    }

    // 设置房间开关
    public function update(Request $request)
    {
        $server_id = $request->post('server_id');
        $type = $request->post('type');


        $Nullity = ($type == 'on') ? 0 : 1;

        DB::table('QPPlatformDB.dbo.GameRoomInfo')
            ->where('ServerID', $server_id)
            ->update(['Nullity' => $Nullity]);

        // 向服务端发送通知
        $url = config('transfer.stock')['url'] . 'serverState';

        $data = [
            'serverid' => $server_id,
            'state' => $Nullity,
        ];
        (new HttpCurl())->service($url, $data);

        return apiReturnSuc();
    }

    // 查看对局信息
    public function match_information($RoomCode)
    {

        $list = cache()->remember('match_information_' . $RoomCode, 10, function () use ($RoomCode) {
            return DB::connection('game')->table(TableName::QPRecordDB() . 'RecordUniqueScoreCode')
                ->where('uniquescorecode', $RoomCode)
                ->get();
        });

        if (count($list) < 1 || empty($list)) {
            $info = DB::connection('game')->table(TableName::QPRecordDB() . 'RecordGamePlayNew')
                ->where('RoomCode', $RoomCode)
                ->value('RecordJson');

            try {

                $data = json_decode($info, true);
                if (json_last_error() !== JSON_ERROR_NONE) {
                    echo "<p>JSON 解码出错：" . json_last_error_msg() . "</p>";
                } else {
                    // 4. 美化输出，保留中文
                    echo '<pre>' . htmlspecialchars(json_encode($data, JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT)) . '</pre>';
                }

                //echo $this->jsonFormat($info);
            } catch (\Exception $exception) {
                dump($info);
            }
        } else {
            header('Content-Type: text/html; charset=utf-8');
            foreach ($list as $value) {
                $uniquecode = $value->uniquecode;
                $info = cache()->remember('match_information_info_' . $uniquecode, 10, function () use ($uniquecode) {
                    return DB::connection('game')->table(TableName::QPRecordDB() . 'RecordGamePlayNew')
                        ->where('RoomCode', $uniquecode)
                        ->value('RecordJson');
                });

                try {
//                    $info = \GuzzleHttp\json_decode($info, true);
//                    echo "<script>document.write('$info')</script>";
//                    dump($info);
                    //echo $this->jsonFormat($info);

                    // 3. 解析 JSON
                    $data = json_decode($info, true);
                    if (json_last_error() !== JSON_ERROR_NONE) {
                        echo "<p>JSON 解码出错：" . json_last_error_msg() . "</p>";
                    } else {
                        echo '<pre>' . htmlspecialchars(json_encode($data, JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT)) . '</pre>';
                    }

                } catch (\Exception $exception) {
                    dump($info);
                }
            }
        }
    }

    public function jsonFormat($data)
    {

        // 对数组中每个元素递归进行urlencode操作，保护中文字符
        array_walk_recursive($data, function (&$val) {
            if ($val !== true && $val !== false && $val !== null) {
                $val = urlencode($val);
            }
        });


        // json encode
        $data = json_encode($data);

        // 将urlencode的内容进行urldecode
        $data = urldecode($data);

        // 缩进处理
        $ret = '';
        $pos = 0;
        $length = strlen($data);
        $indent = isset($indent) ? $indent : '    ';
        $newline = "\n";
        $prevchar = '';
        $outofquotes = true;

        for ($i = 0; $i <= $length; $i++) {

            $char = substr($data, $i, 1);

            if ($char == '"' && $prevchar != '\\') {
                $outofquotes = !$outofquotes;
            } elseif (($char == '}' || $char == ']') && $outofquotes) {
                $ret .= $newline;
                $pos--;
                for ($j = 0; $j < $pos; $j++) {
                    $ret .= $indent;
                }
            }

            $ret .= $char;

            if (($char == ',' || $char == '{' || $char == '[') && $outofquotes) {
                $ret .= $newline;
                if ($char == '{' || $char == '[') {
                    $pos++;
                }

                for ($j = 0; $j < $pos; $j++) {
                    $ret .= $indent;
                }
            }

            $prevchar = $char;
        }

        return $ret;
    }

    // 在线用户
    public function online_user(Request $request)
    {
        $index = $request->index ?: 0;


        $globalService = new GlobalUser();
        $onLineUser = $globalService->onLineUser($index);
        $pageNum = 10;
        $total = (isset($onLineUser['total']) && !empty($onLineUser)) ? $onLineUser['total'] : 0;
        $link = 'http://' . $request->getHttpHost() . '/admin/global/online_user?index=';
        $service = new Paging($pageNum, $total, $index, ($total / $pageNum), $link);

        $list = DB::connection('read')->table('QPAccountsDB.dbo.AccountsInfo as ai')
            ->leftJoin('QPTreasureDB.dbo.GameScoreLocker as lck', 'ai.UserID', 'lck.UserID')
            ->leftJoin('QPPlatformDB.dbo.GameRoomInfo as gi', 'lck.ServerID', '=', 'gi.ServerID')
            ->whereIn('ai.UserID', $onLineUser['UserIDs'])
            ->select('ai.GameID', 'NickName', 'ai.UserID', 'gi.ServerName')->get();
        $page = $service->subPageCss2();

        return view('admin.global.online_user', [
            'list' => $list,
            'pages' => $page,
            'total' => $total
        ]);
    }

    // 无感维护开关
    public function GameRoomSwitch_view()
    {
        $list = DB::connection('read')->table('QPPlatformDB.dbo.GameRoomInfo as gi')
            //->leftJoin('QPRecordDB.dbo.RecordGameInfo as ri', 'gi.ServerID', '=', 'ri.ServerID')
            ->leftJoin('QPTreasureDB.dbo.GameScoreLocker as gl', function ($query) {
                $query->on('gl.ServerID', 'gi.ServerID')->selectRaw('gl.ServerID')->groupBy('ServerID')->whereDate('CollectDate', date('Y-m-d'));
            })
            ->whereIn('gi.GameID', [1005, 2030, 2050])
            ->whereNotIn('gi.ServerID', [32, 33, 39])
            ->selectRaw('gi.Nullity,gi.GameID,gi.SortID,gi.ServerName,gi.ServerID,gi.RoomStock,count(DISTINCT gl.UserID) as game_count')
            ->groupBy('gi.GameID', 'gi.SortID', 'gi.ServerName', 'gi.ServerID', 'gi.RoomStock', 'gi.Nullity')
            ->get();

        return view('admin.global.game_room_switch', [
            'list' => $list
        ]);
    }

    // 无感操作开关操作
    public function GameRoomSwitch(Request $request)
    {
        $serverID = $request->serverID ?: '';
        $type = $request->type ?: '';

        $serverID = explode(',', rtrim($serverID, ','));

        if (empty($type)) {
            return apiReturnFail('缺少操作类型');
        }

        switch ($type) {
            case 'on' :
                $Nullity = 0;
                break;
            case 'off':
                $Nullity = 1;
                break;
        }
        DB::table('QPPlatformDB.dbo.GameRoomInfo')->whereIn('ServerID', $serverID)->update(['Nullity' => $Nullity]);
        return apiReturnSuc();
    }

    // 关闭禁止提现标签
    public function relieve($id)
    {

        // 用户标签
        $getUserTab = StoredProcedure::getUserTab($id);
        $TabType = $getUserTab[0]->TabType ?? '';

        if (!empty($getUserTab) && $TabType == 1) {

            $Type12 = $getUserTab[0]->Type12 ?? 0;

            if (in_array($Type12, [1301, 1302, 1303])) {

                DB::table('QPAccountsDB.dbo.AccountWithDrawInfo')
                    ->where('UserID', $id)
                    ->update(['Switch' => 0]);
            }

        }


        return apiReturnSuc();
    }

    // 单控用户备注
    public function remarks(Request $request, $id)
    {
        $remark = $request->remark ?: '';
        DB::table('QPAccountsDB.dbo.IndividualDatum')
            ->where('UserID', $id)
            ->update(['UserNote' => $remark]);

        return apiReturnSuc();
    }

    // 模拟器开关
    public function androidCheck(Request $request)
    {
        if ($request->isMethod('post')) {
            $StatusValue = (int)$request->StatusValue;
            DB::connection('write')->table('QPAccountsDB.dbo.SystemStatusInfo')
                ->where('StatusName', 'AndroidCheck')
                ->update(['StatusValue' => $StatusValue]);

            $admin_id = session('admin')->id;
            CreateLog::SystemStatusInfo_log($admin_id, 'AgentCommisionState');
            return apiReturnSuc();
        } else {
            $list = DB::connection('write')->table('QPAccountsDB.dbo.SystemStatusInfo as si')
                ->leftJoin('agent.dbo.SystemStatusInfo_log as log', 'si.StatusName', 'log.StatusName')
                ->leftJoin('agent.dbo.admin_users as au', 'log.admin_id', '=', 'au.id')
                ->select('StatusString', 'StatusValue', 'account', 'create_at')
                ->where('si.StatusName', 'AndroidCheck')
                ->get();

            return view('admin.global.androidCheck', [
                'list' => $list
            ]);
        }
    }

    // 推广赚金池数值修改
    public function agent_reward(Request $request)
    {
        if ($request->method() == 'POST') {
            $val = abs($request->StatusValue) ?: 0;
            $val *= 100;
            $r = DB::table('QPAccountsDB.dbo.SystemAgentReward')->update(['InitReward' => $val]);
            if ($r) {
                return apiReturnSuc();
            }
            return apiReturnFail('推广赚金池数值修改失败');
        } else {
            $value = DB::table('QPAccountsDB.dbo.SystemAgentReward')->value('InitReward');
            $value = $value / 100;
            return view('admin.global.agent_reward', compact('value'));
        }
    }

    // 修改用户标签
    public function update_label(Request $request, $id)
    {
        $type = $request->type ?: '';
        if ($request->isMethod('post')) {

            switch ($type) {
                case 1:
                    StoredProcedure::user_label($id, 8);
                    break;
                case 20:
                    StoredProcedure::user_label($id, 6);
                    break;
                case 21:
                    StoredProcedure::user_label($id, 7);
                    break;
            }

            return apiReturnSuc();
        } else {
            $type = DB::connection('read')->table('QPAccountsDB.dbo.AccountLabelDanControlLabel')->where('UserID', $id)->value('type');
            $label = [
                20 => '其他1',
                21 => '其他2'
            ];

            return view('admin.global.update_label', [
                'label' => $label,
                'type' => $type,
                'UserID' => $id
            ]);
        }
    }

    // 推广佣金开关
    public function AgentCommisionState(Request $request)
    {
        if ($request->isMethod('post')) {
            $StatusValue = (int)$request->StatusValue;

            DB::table('QPAccountsDB.dbo.SystemStatusInfo')
                ->where('StatusName', 'AgentCommisionState')
                ->update(['StatusValue' => $StatusValue]);

            $admin_id = session('admin')->id;
            CreateLog::SystemStatusInfo_log($admin_id, 'AgentCommisionState');
            return apiReturnSuc();
        } else {
            $list = DB::connection('write')->table('QPAccountsDB.dbo.SystemStatusInfo as si')
                ->leftJoin('agent.dbo.SystemStatusInfo_log as log', 'si.StatusName', 'log.StatusName')
                ->leftJoin('agent.dbo.admin_users as au', 'log.admin_id', '=', 'au.id')
                ->select('StatusString', 'StatusValue', 'account', 'create_at')
                ->where('si.StatusName', 'AgentCommisionState')
                ->get();
            return view('admin.global.agentCommisionState', [
                'list' => $list
            ]);
        }
    }


    // 清理玩家卡房间
    public function deleteRoom($UserID)
    {

        DB::connection('write')->table('QPTreasureDB.dbo.GameScoreLocker')
            ->where('UserID', $UserID)
            ->delete();
        return apiReturnSuc();
    }

    public function control_statistics()
    {
        // +-------------------------------------
        // 普通玩家
        // +-------------------------------------

        $now_time = '2021-11-17 14:25:00';

        // 普通玩家 -- 控制分数
        $ptAccounts = DB::connection('read')->table('QPAccountsDB.dbo.AccountsInfo as ai')
                ->leftJoin('QPAccountsDB.dbo.IDWhiteUser as iu', 'ai.UserID', 'iu.UserID')
                ->join('QPRecordDB.dbo.RecordUserScoreControl as rc', 'ai.UserID', 'rc.UserID')
                ->whereNull('iu.UserID')
                ->where('ControlDate', '>', $now_time)
                ->where('ControlState', 0)
                ->selectRaw('sum(abs(ControlScore)) / 100 ControlScore')
                ->first()->ControlScore ?? 0;

        // 普通玩家 -- 控制赢分数
        $ptWinAccounts = DB::connection('read')->table('QPAccountsDB.dbo.AccountsInfo as ai')
            ->leftJoin('QPAccountsDB.dbo.IDWhiteUser as iu', 'ai.UserID', 'iu.UserID')
            ->join('QPRecordDB.dbo.RecordUserScoreControl as rc', 'ai.UserID', 'rc.UserID')
            ->whereNull('iu.UserID')
            ->where('ControlDate', '>', $now_time)
            ->where('ControlState', 0)
            ->where('ControlScore', '>', 0)
            ->selectRaw('sum(ControlScore) /100  ControlScore,sum(EffectiveScore) /100 EffectiveScore')
            ->first();


        // 普通玩家 -- 控制输分数
        $ptLoseAccounts = DB::connection('read')->table('QPAccountsDB.dbo.AccountsInfo as ai')
                ->leftJoin('QPAccountsDB.dbo.IDWhiteUser as iu', 'ai.UserID', 'iu.UserID')
                ->join('QPRecordDB.dbo.RecordUserScoreControl as rc', 'ai.UserID', 'rc.UserID')
                ->whereNull('iu.UserID')
                ->where('ControlDate', '>', $now_time)
                ->where('ControlState', 0)
                ->where('ControlScore', '<', 0)
                ->selectRaw('sum(ControlScore) / 100 ControlScore')
                ->first()->ControlScore ?? 0;


        // +-------------------------------------
        // 分界线--------------------------------官方玩家-----------------------------------------------------
        // +-------------------------------------

        // 官方玩家 -- 控制分数
        $gfAccounts = DB::connection('read')->table('QPAccountsDB.dbo.AccountsInfo as ai')
                ->join('QPAccountsDB.dbo.IDWhiteUser as iu', 'ai.UserID', 'iu.UserID')
                ->join('QPRecordDB.dbo.RecordUserScoreControl as rc', 'ai.UserID', 'rc.UserID')
                ->where('ControlState', 0)
                ->where('ControlDate', '>', $now_time)
                ->selectRaw('sum(abs(ControlScore)) / 100 ControlScore')
                ->first()->ControlScore ?? 0;

        // 官方玩家 -- 控制赢分数
        $gfWinAccounts = DB::connection('read')->table('QPAccountsDB.dbo.AccountsInfo as ai')
            ->join('QPAccountsDB.dbo.IDWhiteUser as iu', 'ai.UserID', 'iu.UserID')
            ->join('QPRecordDB.dbo.RecordUserScoreControl as rc', 'ai.UserID', 'rc.UserID')
            ->where('ControlState', 0)
            ->where('ControlDate', '>', $now_time)
            ->where('ControlScore', '>', 0)
            ->selectRaw('sum(ControlScore) / 100 ControlScore,sum(EffectiveScore) /100 EffectiveScore')
            ->first();

        // 官方玩家 -- 控制输分数
        $gfLoseAccounts = DB::connection('read')->table('QPAccountsDB.dbo.AccountsInfo as ai')
                ->join('QPAccountsDB.dbo.IDWhiteUser as iu', 'ai.UserID', 'iu.UserID')
                ->join('QPRecordDB.dbo.RecordUserScoreControl as rc', 'ai.UserID', 'rc.UserID')
                ->where('ControlState', 0)
                ->where('ControlDate', '>', $now_time)
                ->where('ControlScore', '<', 0)
                ->selectRaw('sum(ControlScore) / 100 ControlScore')
                ->first()->ControlScore ?? 0;

        $ptTotal = $ptLoseAccounts + ($ptWinAccounts->EffectiveScore ?? 0);
        $gfTotal = $gfLoseAccounts + ($gfWinAccounts->EffectiveScore ?? 0);
        $data = compact('ptAccounts', 'ptLoseAccounts', 'ptWinAccounts', 'gfAccounts', 'gfLoseAccounts', 'gfWinAccounts', 'ptTotal', 'gfTotal');
        return view('admin.global.control_statistics', $data);
    }

    // 用户头像审核列表
    public function headAudit(Request $request)
    {
        $GameID = $request->GameID ?: '';
        $start_time = $request->start_time ?: '';
        $end_time = $request->end_time ?: '';
        $where[] = ['Status', 0];
        if (!empty($UserID)) {
            $UserID = AccountsInfo::GetUserID($GameID);
            $where[] = ['ua.UserID', $UserID];
        }
        if (!empty($start_time)) $where[] = ['CreateTime', '>=', $start_time];
        if (!empty($end_time)) $where[] = ['CreateTime', '<=', $end_time];

        $list = DB::table(TableName::agent() . 'UserHeadAuditoria as ua')
            ->join(TableName::QPAccountsDB() . 'AccountsInfo as ai', 'ua.UserID', 'ai.UserID')
            ->select('Image', 'GameID', 'ua.UserID', 'ua.CreateTime')
            ->where($where)->paginate(10);

        return view('admin.global.head_audit', compact('list', 'GameID', 'start_time', 'end_time'));
    }

    // 头像审核
    public function headAuditUpdate(Request $request, $UserID)
    {
        $status = $request->Status;

        DB::table(TableName::agent() . 'UserHeadAuditoria')
            ->where('UserID', $UserID)
            ->update(['Status' => $status]);
        if ($status == 1) {
            $Image = DB::table(TableName::agent() . 'UserHeadAuditoria')->where('UserID', $UserID)->value('Image');
            DB::connection('write')->table(TableName::QPAccountsDB() . 'AccountHead')
                ->updateOrInsert(['UserID' => $UserID], ['UserID' => $UserID, 'Image' => 'http://' . $request->getHttpHost() . DIRECTORY_SEPARATOR . $Image, 'LastTime' => now()]);
        }
        return apiReturnSuc();
    }

    // 增加用户可提额度
    public function add_draw_base(Request $request, $UserID)
    {

        if ($request->isMethod('post')) {

            $draw_base = (int)$request->add_draw_base;

            if ($draw_base < 0) return apiReturnFail('请输入正确的可提额度');

            $draw_base = $draw_base * NumConfig::NUM_VALUE;

            // 判断额度
            $dayVerify = DB::table(TableName::agent() . 'add_draw_base')->where('user_id', $UserID)->whereDate('create_time', date('Y-m-d'))->sum('draw_base');
            if ($dayVerify >= 10000 * NumConfig::NUM_VALUE) {
                return apiReturnFail('单日用户最大额度一万');
            }

            $allVerify = DB::table(TableName::agent() . 'add_draw_base')->sum('draw_base');
            if ($allVerify >= 100000 * NumConfig::NUM_VALUE) {
                return apiReturnFail('总额度不足，联系管理员，最大额度五万');
            }

            // 增加可提额度
            if (DB::table(TableName::QPRecordDB() . 'RecordUserTotalStatistics')->where('UserID', $UserID)->first()) {

                DB::table(TableName::QPRecordDB() . 'RecordUserTotalStatistics')->where('UserID', $UserID)->increment('DrawBase', $draw_base);
            } else {
                DB::table(TableName::QPRecordDB() . 'RecordUserTotalStatistics')->insert(['UserID' => $UserID, 'DrawBase' => $draw_base]);
            }

            // 增加记录
            DB::table(TableName::agent() . 'add_draw_base')
                ->insert([
                    'user_id' => $UserID,
                    'draw_base' => $draw_base,
                    'create_time' => now(),
                    'admin_id' => session('admin')['id']
                ]);

            return apiReturnSuc();
        }

        return view('admin.global.add_draw_base', compact('UserID'));
    }


    public function add_tax(Request $request, $UserID)
    {

        if ($request->isMethod('post')) {

            $add_tax = (int)$request->add_tax;


            $draw_base = $add_tax * NumConfig::NUM_VALUE;
            //if($draw_base>0){
            DB::table(TableName::QPRecordDB() . 'RecordUserTotalStatistics')->where('UserID', $UserID)->increment('Revenue', $draw_base);
            //}



            return apiReturnSuc();
        }

        return view('admin.global.add_tax', compact('UserID'));
    }


    // 推广限制开关
    public function register_invite_switches(Request $request, $UserID)
    {

        $Value = $request->Value;
        $redis = Redis::connection();
        $redis->set('register_invite_switches_' . $UserID, $Value);

        return apiReturnSuc();
    }

    public function platformRecord(Request $request)
    {
        $date = $request->date ?: date('Y-m-d',strtotime('-1 days'));
        $dateFormat = date('Ymd',strtotime($date));

        if($dateFormat == date('Ymd')){
            $list = [];
            $platform = ['only','atmosfera','pg','pp'];
            foreach ($platform as $pItem) {
                $platformRecord = [
                    'lid' => 0,
                    'ldate' => $dateFormat,
                    'platform' => $pItem,
                    'all_bet' => Redis::get('platform_' . $pItem . '_bet') ?: 0,
                    'all_win' => Redis::get('platform_' . $pItem . '_win') ?: 0,
                    'current_bet' => Redis::get('platform_' . $pItem . '_bet_' . $dateFormat) ?: 0,
                    'current_win' => Redis::get('platform_' . $pItem . '_win_' . $dateFormat) ?: 0,
                    'current_play' => Redis::get('platform_' . $pItem . '_play_' . $dateFormat) ?: 0,
                    // 'sub_detail' => ''
                ];
                array_push($list, $platformRecord);
            }
            $list = json_decode(json_encode($list));
        }else{
            $list = DB::connection('mysql')->table('record_platform_data')->where('ldate', $dateFormat)->get();
        }

        $monthStart = date('Ym',strtotime($date)).'01';
        $monthEnd = date('Ym',strtotime($date)).'31';

        $where= [['ldate', '<=', $monthEnd],['ldate', '>=', $monthStart]];

        $monthData = DB::connection('mysql')->table('record_platform_data')
            ->where($where)
            ->selectRaw('sum(current_bet) month_bet,sum(current_win) month_win,platform')
            ->groupBy('platform')
            ->get();

        return view('admin.global.platformRecord', compact('list',  'date', 'monthData'));
    }

    public function  platformSub($id)
    {
//        if($id>0){
//            $record = DB::connection('mysql')->table('record_platform_data')->where('lid', $id)->first();
//        }else{
//            $DateID = date('Ymd');
//
//            $only=GameCard::where('brand','OnlyPlay')->where('state','<>',0)->pluck('gid')->toArray();
//
//            $atmosfera=[71,74,85,86,87,88,89,92,93];
//            $platform = ['only','atmosfera'];
//            foreach ($platform as $pItem){
//
//                $gameType = ($pItem == 'only'?$only:$atmosfera);
//                if(is_array($gameType)){
//                    $subData = [];
//                    foreach ($gameType as $item){
//                        $betkey = 'platform_'.$pItem.'_'.$item. '_bet_' . $DateID;
//
//                        $winkey = 'platform_'.$pItem.'_'.$item. '_win_' . $DateID;
//
//                        $playkey = 'platform_'.$pItem.'_'.$item.'_play_' . $DateID;
//                        $subData[$item] = ['current_bet' => Redis::get($betkey)?:0,'current_win' =>Redis::get($winkey)?:0,'current_play' =>Redis::get($playkey)?:0 ];
//                    }
//                    $platformRecord['sub_detail'] = json_encode($subData);
//                }
//            }
//        }

        $record = DB::connection('mysql')->table('record_platform_data')->where('lid', $id)->first();

        $subDetail = [];
        $atmosferaMap=[
            71 => 'Live-Roulette-EN',
            74 => 'Keno',
            85 => 'Auto-Roulette',
            86 => 'Blackjack-A',
            87 => 'Blackjack-B',
            88 => 'Blackjack-C',
            89 => 'Blackjack-D',
            92 => 'Cocktail-Roulette',
            93 => 'Blackjack-E'
        ];
        if($record){
            if($record->sub_detail){
                $subDetail = json_decode($record->sub_detail,true);
                if(is_array($subDetail)){
                    if($record->platform == 'atmosfera'){
                        $newArr = [];
                        foreach ($subDetail as $kk => $vv){
                            $newArr[$atmosferaMap[$kk]] = $vv;
                        }
                        $subDetail = $newArr;
                    }
//                    current_play
                    $subDetail = Util::arraySort($subDetail,'current_play',SORT_DESC);
                }
            }
        }

        return view('admin.global.platform_sub_data', compact('id',  'subDetail'));
    }
}
