<?php


namespace App\Http\Controllers\Admin;


use App\dao\Estatisticas\RechargeWithDraw;
use App\Facade\RedisConnect;
use App\Facade\TableName;
use App\Http\helper\Helper;
use App\Http\helper\NumConfig;
use App\Http\logic\admin\AccountsRecordLogic;
use App\Http\logic\admin\WithdrawalLogic;
use App\Models\AccountsInfo;
use App\Models\AddDrawBase;
use App\Models\PrivateMail;
use App\Models\RecordScoreInfo;
use App\Models\RecordUserDataStatistics;
use App\Models\SystemStatusInfo;
use App\Services\CashierMessage;
use App\Services\CreateLog;
use App\Services\LogDayStatisticalByDayAndChannel;
use App\Services\StoredProcedure;
use App\Utility\SetNXLock;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Validator;

class WithdrawalController extends BaseController
{
    protected $logic;

    public function __construct()
    {
        $this->logic = new WithdrawalLogic();
    }

    // 待审核列表
    public function waitWithdrawal(Request $request)
    {
        $create_time_sort = $request->create_time_sort ?: '';
        $GameID = (int)$request->get('GameID') ?: '';
        $withdraw_search = (int)$request->get('withdraw_search') ?: '';
        $withdraw = $request->get('withdraw') ?? '';
        $state = $request->get('state') ?? '';
        $start_time = $request->get('start_time') ?? '';
        $end_time = $request->get('end_time') ?? '';
        $final_start_time = $request->get('final_start_time') ?? '';
        $final_end_time = $request->get('final_end_time') ?? '';
        $orderID = $request->get('orderID') ?? '';
        $excel = $request->get('excel') ?? '';
        $Channel = $request->get('Channel');
        $payState = $request->get('payState');
        $PackgeName = $request->PackgeName ?: '';

        $toNormalCs=Redis::get("normalCsOpen")??"close";

        $list = $this->logic->waitWithdrawal($GameID, $withdraw_search, $withdraw, $state, $start_time, $end_time, '', false, $create_time_sort, $orderID, $final_start_time, $final_end_time, $excel, $Channel, $payState, '', 0, '', '', $PackgeName,$toNormalCs=="open"?2:0);
        $list['api_url']='/admin/withdrawal/waitWithdrawal';
        $list['normalCsOpen']=$toNormalCs;
        $list['specialCs']=false;
        return view('admin.Withdrawal.waitWithdrawal', $list);
    }
    public function changeNewWithdrawOpen(Request $request)
    {
        //普通客服开放新用户审核开关
        $toNormalCs=$request->input("normalCsOpen");
        Redis::set("normalCsOpen",$toNormalCs);
        return apiReturnSuc([],"","操作成功：".($toNormalCs=="open"?"开启":"关闭"));
    }
    public function waitWithdrawalNewPlayer(Request $request)
    {
        $toNormalCs=Redis::get("normalCsOpen")??"close";

        $create_time_sort = $request->create_time_sort ?: '';
        $GameID = (int)$request->get('GameID') ?: '';
        $withdraw_search = (int)$request->get('withdraw_search') ?: '';
        $withdraw = $request->get('withdraw') ?? '';
        $state = $request->get('state') ?? '';
        $start_time = $request->get('start_time') ?? '';
        $end_time = $request->get('end_time') ?? '';
        $final_start_time = $request->get('final_start_time') ?? '';
        $final_end_time = $request->get('final_end_time') ?? '';
        $orderID = $request->get('orderID') ?? '';
        $excel = $request->get('excel') ?? '';
        $Channel = $request->get('Channel');
        $payState = $request->get('payState');
        $PackgeName = $request->PackgeName ?: '';
        $list = $this->logic->waitWithdrawal($GameID, $withdraw_search, $withdraw, $state, $start_time, $end_time, '', false, $create_time_sort, $orderID, $final_start_time, $final_end_time, $excel, $Channel, $payState, '', 0, '', '', $PackgeName,1);
        $list['api_url']='/admin/withdrawal/waitWithdrawalNewPlayer';
        $list['normalCsOpen']=$toNormalCs;
        $list['specialCs']=true;

        return view('admin.Withdrawal.waitWithdrawal', $list);
    }
    public function state5List(Request $request){
        $data = $request->all();

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

            $ID=$data['OrderId'];
            DB::connection('write')->table('QPAccountsDB.dbo.OrderWithDraw')->where('OrderId',$ID)->update(['State'=>1]);
            return json_encode(['id'=>$ID]);
        }
        $list=DB::connection('write')->table(DB::raw('QPAccountsDB.dbo.OrderWithDraw WITH (NOLOCK)'))
            ->where('State','=',5)
            ->get()->toArray();
//        print_r($list);die;
        return view('admin.Withdrawal.statelist', ['list'=>$list]);
    }

    // 提现审核
    public function verify(Request $request)
    {

        $data = $request->all();

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

            if ($data['type'] == 'agree') { // 通过
                $open=(int)SystemStatusInfo::OnlyGetCacheValue(SystemStatusInfo::$KEY_WithDrawSwitch);
                $list = $this->logic->verify_agree($data['ids']);
                $list['open']=$open;
                return view('admin.Withdrawal.verify_agree', $list);

            } elseif ($data['type'] == 'refuse') { // 清退

                $list = $this->logic->verify_agree($data['ids']);
                return view('admin.Withdrawal.verify_refuse', $list);
            } elseif ($data['type'] == 'turn_down') { // 拒绝

                $list = $this->logic->verify_agree($data['ids']);
                return view('admin.Withdrawal.turn_down', $list);
            }
        } else {
            $admin_id = $request->session()->get('admin')->id;
            $save = $this->logic->save($data, $admin_id);
            return $save;
        }
    }

    // 已审核提现订单查询
    public function verify_finish(Request $request)
    {
        $GameID = (int)$request->get('GameID') ?: '';
        $withdraw_search = (int)$request->get('withdraw_search') ?: '';
        $withdraw = $request->get('withdraw') ?: '';
        $state = $request->get('state') ?? '';
        $agent = $request->get('agent') ?? '';
        $start_time = $request->get('start_time') ?? '';
        $end_time = $request->get('end_time') ?? '';
        $orderID = $request->get('orderID') ?? '';

        $excel = $request->get('excel') ?? '';
        $final_start_time = $request->get('final_start_time') ?? '';
        $final_end_time = $request->get('final_end_time') ?? '';
        $take_effect = $request->get('take_effect') ?? '';

        $Channel = $request->get('Channel');
        $payState = $request->get('payState');

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

        $isEmpty = $request->get('isEmpty') ?: '';

        $PackgeName = $request->PackgeName ?: '';

        $register_start_time = $request->input('register_start_time');
        $register_end_time = $request->input('register_end_time');

        $list = $this->logic->waitWithdrawal($GameID, $withdraw_search, $withdraw, $state, $start_time, $end_time, $agent, true, '', $orderID, $final_start_time, $final_end_time, $excel, $Channel, $payState, $take_effect, $isEmpty, $register_start_time, $register_end_time, $PackgeName,2);
        $list['agents'] = DB::table(DB::raw('agent.dbo.admin_configs WITH (NOLOCK)'))
            ->where('type', 'cash')
            ->get();
        $list['request'] = $request;
        $admin = session('admin');
        $list['viewAll'] = $admin && isset($admin->roles[0]->id) && in_array($admin->roles[0]->id, [1, 12, 2010, 2011]) ? 1 : 0;
        return view('admin.Withdrawal.verify_finish', $list);
    }

    // 提现拒绝
    public function turn_down(Request $request)
    {
        $redis = new RedisConnect();
        $limitKey = 'turn_down';

        $res = $redis->redis()->set($limitKey, 1, 3);
        if (empty($res)) return apiReturnFail('频繁操作');

        $post = $request->post();
        $ids = explode(',', $post['ids']);
        if (count($ids) < 1) {
            return apiReturnFail('数据不存在!');
        }

        foreach ($ids as $val) {

            // 查找订单
            $OrderWithDraw = DB::table(TableName::QPAccountsDB() . 'OrderWithDraw')
                ->where('RecordID', $val)
                ->selectRaw('UserID,OrderID,WithDraw,ServiceFee')
                ->first();

            // 修改订单状态   locking=>[2清退不返打码量 3 拒绝返打码量]
            DB::table(TableName::QPAccountsDB() . 'OrderWithDraw')
                ->where('RecordID', $val)
                ->update(['State' => -1, 'locking' => 3]);

            $remarks = $post['remarks'] ?? '';
            $admin_id = session('admin')['id'];

            // 添加用户提现操作记录
            (new AccountsRecordLogic())->create_record($val, 1, -2, $remarks, $admin_id, 1);

            $amount = $OrderWithDraw->WithDraw + $OrderWithDraw->ServiceFee;
            PrivateMail::refuseMail($OrderWithDraw->UserID, $OrderWithDraw->OrderID, $amount, true);
        }
        $redis->redis()->del($limitKey);
        return apiReturnSuc();
    }

    // 提现数值修改
    public function config()
    {

//        $fee = DB::connection('write')->table('QPAccountsDB.dbo.SystemStatusInfo as si')
//            ->leftJoin('agent.dbo.SystemStatusInfo_log as log', function($join) {
//                $join->on(DB::raw('si.StatusName COLLATE SQL_Latin1_General_CP1_CI_AS'), '=', DB::raw('log.StatusName COLLATE SQL_Latin1_General_CP1_CI_AS'));
//            })
//            ->leftJoin('agent.dbo.admin_users as au', 'log.admin_id', '=', 'au.id')
//            ->where('si.StatusName', 'WithDrawTax')
//            ->select('StatusValue', 'account', 'create_at')
//            ->first();

        $fee = DB::connection('write')->table(DB::raw('QPAccountsDB.dbo.SystemStatusInfo as si WITH (NOLOCK)'))
            ->leftJoin(DB::raw('agent.dbo.SystemStatusInfo_log as log WITH (NOLOCK)'), function($join) {
                $join->on(DB::raw('si.StatusName COLLATE SQL_Latin1_General_CP1_CI_AS'), '=', DB::raw('log.StatusName COLLATE SQL_Latin1_General_CP1_CI_AS'));
            })
            ->leftJoin(DB::raw('agent.dbo.admin_users as au WITH (NOLOCK)'), 'log.admin_id', '=', 'au.id')
            ->where('si.StatusName', 'WithDrawTax')
            ->select('StatusValue', 'account', 'create_at')
            ->first();

        $artificial = DB::connection('write')->table(DB::raw('QPAccountsDB.dbo.SystemStatusInfo as si WITH (NOLOCK)'))
            ->leftJoin(DB::raw('agent.dbo.SystemStatusInfo_log as log WITH (NOLOCK)'), function($join) {
                $join->on(DB::raw('si.StatusName COLLATE SQL_Latin1_General_CP1_CI_AS'), '=', DB::raw('log.StatusName COLLATE SQL_Latin1_General_CP1_CI_AS'));
            })
            ->leftJoin(DB::raw('agent.dbo.admin_users as au WITH (NOLOCK)'), 'log.admin_id', '=', 'au.id')
            ->where('si.StatusName', 'WithDrawAILimit')
            ->select('StatusValue', 'account', 'create_at')
            ->first();
        $proportion = DB::connection('write')->table(DB::raw('QPAccountsDB.dbo.SystemStatusInfo as si WITH (NOLOCK)'))
            ->leftJoin(DB::raw('agent.dbo.SystemStatusInfo_log as log WITH (NOLOCK)'), function($join) {
                $join->on(DB::raw('si.StatusName COLLATE SQL_Latin1_General_CP1_CI_AS'), '=', DB::raw('log.StatusName COLLATE SQL_Latin1_General_CP1_CI_AS'));
            })
            ->leftJoin(DB::raw('agent.dbo.admin_users as au WITH (NOLOCK)'), 'log.admin_id', '=', 'au.id')
            ->where('si.StatusName', 'WithDrawRate')
            ->select('StatusValue', 'account', 'create_at')
            ->first();
        $WithDrawMin = DB::connection('write')->table(DB::raw('QPAccountsDB.dbo.SystemStatusInfo as si WITH (NOLOCK)'))
            ->leftJoin(DB::raw('agent.dbo.SystemStatusInfo_log as log WITH (NOLOCK)'), function($join) {
                $join->on(DB::raw('si.StatusName COLLATE SQL_Latin1_General_CP1_CI_AS'), '=', DB::raw('log.StatusName COLLATE SQL_Latin1_General_CP1_CI_AS'));
            })
            ->leftJoin(DB::raw('agent.dbo.admin_users as au WITH (NOLOCK)'), 'log.admin_id', '=', 'au.id')
            ->where('si.StatusName', 'WithDrawMin')
            ->select('StatusValue', 'account', 'create_at')
            ->first();

        $WithDrawMax = DB::connection('write')->table(DB::raw('QPAccountsDB.dbo.SystemStatusInfo as si WITH (NOLOCK)'))
            ->leftJoin(DB::raw('agent.dbo.SystemStatusInfo_log as log WITH (NOLOCK)'), function($join) {
                $join->on(DB::raw('si.StatusName COLLATE SQL_Latin1_General_CP1_CI_AS'), '=', DB::raw('log.StatusName COLLATE SQL_Latin1_General_CP1_CI_AS'));
            })
            ->leftJoin(DB::raw('agent.dbo.admin_users as au WITH (NOLOCK)'), 'log.admin_id', '=', 'au.id')
            ->where('si.StatusName', 'WithDrawMax')
            ->select('StatusValue', 'account', 'create_at')
            ->first();

        $WithDrawPoint = DB::connection('write')->table(DB::raw('QPAccountsDB.dbo.SystemStatusInfo as si WITH (NOLOCK)'))
            ->leftJoin(DB::raw('agent.dbo.SystemStatusInfo_log as log WITH (NOLOCK)'), function($join) {
                $join->on(DB::raw('si.StatusName COLLATE SQL_Latin1_General_CP1_CI_AS'), '=', DB::raw('log.StatusName COLLATE SQL_Latin1_General_CP1_CI_AS'));
            })
            ->leftJoin(DB::raw('agent.dbo.admin_users as au WITH (NOLOCK)'), 'log.admin_id', '=', 'au.id')
            ->where('si.StatusName', 'WithDrawPoint')
            ->select('StatusValue', 'account', 'create_at')
            ->first();

        $MaxTXNotRecharge = DB::connection('write')->table(DB::raw('QPAccountsDB.dbo.SystemStatusInfo as si WITH (NOLOCK)'))
            ->leftJoin(DB::raw('agent.dbo.SystemStatusInfo_log as log WITH (NOLOCK)'), function($join) {
                $join->on(DB::raw('si.StatusName COLLATE SQL_Latin1_General_CP1_CI_AS'), '=', DB::raw('log.StatusName COLLATE SQL_Latin1_General_CP1_CI_AS'));
            })
            ->leftJoin(DB::raw('agent.dbo.admin_users as au WITH (NOLOCK)'), 'log.admin_id', '=', 'au.id')
            ->where('si.StatusName', 'MaxTXNotRecharge')
            ->select('StatusValue', 'account', 'create_at')
            ->first();

        $fee->StatusValue = number_float(-$fee->StatusValue / NumConfig::NUM_VALUE);
        $artificial->StatusValue = number_float($artificial->StatusValue / NumConfig::NUM_VALUE);
        $proportion->StatusValue = number_float((10000 - $proportion->StatusValue) / NumConfig::NUM_VALUE);
        $WithDrawMin->StatusValue = number_float(($WithDrawMin->StatusValue) / NumConfig::NUM_VALUE);
        $WithDrawMax->StatusValue = number_float(($WithDrawMax->StatusValue) / NumConfig::NUM_VALUE);
        $WithDrawPoint->StatusValue = number_float(($WithDrawPoint->StatusValue) / NumConfig::NUM_VALUE);
        $MaxTXNotRecharge->StatusValue = number_float(($MaxTXNotRecharge->StatusValue) / NumConfig::NUM_VALUE);

        $compact = compact('fee', 'artificial', 'proportion', 'WithDrawMin', 'WithDrawMax', 'WithDrawPoint', 'MaxTXNotRecharge');
        return view('admin.Withdrawal.config', $compact);
    }

    // 提现保底额度
    public function WithDrawPoint(Request $request)
    {
        if ($request->isMethod('post')) {
            $StatusValue = abs((int)$request->StatusValue * 100) ?: '';

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

            $admin_id = session('admin')->id;
            CreateLog::SystemStatusInfo_log($admin_id, 'WithDrawPoint');
            return apiReturnSuc('success');
        }

        $result = DB::table(DB::raw('QPAccountsDB.dbo.SystemStatusInfo WITH (NOLOCK)'))->where('StatusName', 'WithDrawPoint')->value('StatusValue') / 100 ?? 0;
        return view('admin.Withdrawal.WithDrawPoint', ['info' => $result]);
    }

    // 提现手续费设置
    public function fee(Request $request)
    {

        if ($request->isMethod('post')) {
            $StatusValue = abs((int)$request->StatusValue) ?: '';
            if ($StatusValue > 1000) {
                return apiReturnFail('手续费最大值为1000');
            }
            $result = DB::table('QPAccountsDB.dbo.SystemStatusInfo')->where('StatusName', 'WithDrawTax')->update(['StatusValue' => $StatusValue]);

            $admin_id = session('admin')->id;
            CreateLog::SystemStatusInfo_log($admin_id, 'WithDrawPoint');

            return apiReturnSuc('success');
        }

        $result = DB::table(DB::raw('QPAccountsDB.dbo.SystemStatusInfo WITH (NOLOCK)'))->where('StatusName', 'WithDrawTax')->value('StatusValue');
        return view('admin.Withdrawal.fee', ['info' => $result]);
    }

    // 提现金额比例设置
    public function artificial(Request $request)
    {
        if ($request->isMethod('post')) {

            $StatusValue = abs((int)$request->StatusValue) ?: '';

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

            $admin_id = session('admin')->id;
            CreateLog::SystemStatusInfo_log($admin_id, 'WithDrawPoint');

            return apiReturnSuc('success');
        }
        $result = DB::table(DB::raw('QPAccountsDB.dbo.SystemStatusInfo WITH (NOLOCK)'))->where('StatusName', 'WithDrawAILimit')->value('StatusValue');
        $result = $result / 100;

        return view('admin.Withdrawal.artificial', ['info' => $result]);
    }

    //人工审核额度设置
    public function proportion(Request $request)
    {
        if ($request->isMethod('post')) {
            $StatusValue = (int)$request->StatusValue ?: '';

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

            $admin_id = session('admin')->id;
            CreateLog::SystemStatusInfo_log($admin_id, 'WithDrawPoint');
            return apiReturnSuc('success');
        }
        $result = DB::table(DB::raw('QPAccountsDB.dbo.SystemStatusInfo WITH (NOLOCK)'))->where('StatusName', 'WithDrawRate')->value('StatusValue');

        return view('admin.Withdrawal.proportion', ['info' => $result]);
    }

    // 0充玩家提现限制最高额度
    public function MaxTXNotRecharge(Request $request)
    {
        if ($request->isMethod('post')) {
            $StatusValue = (int)$request->StatusValue ?: '';

            $StatusValue = $StatusValue * NumConfig::NUM_VALUE;
            $result = DB::table('QPAccountsDB.dbo.SystemStatusInfo')->where('StatusName', 'MaxTXNotRecharge')->update(['StatusValue' => $StatusValue]);

            $admin_id = session('admin')->id;
            CreateLog::SystemStatusInfo_log($admin_id, 'MaxTXNotRecharge');
            return apiReturnSuc('success');
        } else {
            $result = DB::table(DB::raw('QPAccountsDB.dbo.SystemStatusInfo WITH (NOLOCK)'))->where('StatusName', 'MaxTXNotRecharge')->value('StatusValue');

            $result = $result > 0 ? floatval($result / NumConfig::NUM_VALUE) : 0;

            return view('admin.Withdrawal.max_tx_not_recharge', ['info' => $result]);
        }

    }

    // 查看返回值
    public function show($sn = '')
    {

        $notify = DB::table(DB::raw('QPAccountsDB.dbo.withdraw_notify WITH (NOLOCK)'))->where('order_sn', $sn)->select('extra')->first()->extra ?? '';

        if ($notify) {
            $notify = \GuzzleHttp\json_decode($notify);
        }


        return view('admin.Withdrawal.show', ['info' => $notify]);
    }

    // 提现最大值修改
    public function WithDrawMax(Request $request)
    {
        if ($request->isMethod('post')) {
            $StatusValue = (int)$request->StatusValue ?: '';

            $StatusValue = abs($StatusValue) * NumConfig::NUM_VALUE;
            $result = DB::table('QPAccountsDB.dbo.SystemStatusInfo')->where('StatusName', 'WithDrawMax')->update(['StatusValue' => $StatusValue]);
            $admin_id = session('admin')->id;
            CreateLog::SystemStatusInfo_log($admin_id, 'WithDrawPoint');
            return apiReturnSuc('success');
        }
        $result = DB::table(DB::raw('QPAccountsDB.dbo.SystemStatusInfo WITH (NOLOCK)'))->where('StatusName', 'WithDrawMax')->value('StatusValue');

        $result /= 100;
        return view('admin.Withdrawal.WithDrawMax', ['info' => $result]);
    }

    // 提现最小值修改
    public function WithDrawMin(Request $request)
    {
        if ($request->isMethod('post')) {
            $StatusValue = (int)$request->StatusValue ?: '';

            $StatusValue = abs($StatusValue) * NumConfig::NUM_VALUE;
            $result = DB::table('QPAccountsDB.dbo.SystemStatusInfo')->where('StatusName', 'WithDrawMin')->update(['StatusValue' => $StatusValue]);

            $admin_id = session('admin')->id;
            CreateLog::SystemStatusInfo_log($admin_id, 'WithDrawPoint');
            return apiReturnSuc('success');
        }
        $result = DB::table(DB::raw('QPAccountsDB.dbo.SystemStatusInfo WITH (NOLOCK)'))->where('StatusName', 'WithDrawMin')->value('StatusValue');
        $result /= 100;
        return view('admin.Withdrawal.WithDrawMin', ['info' => $result]);
    }

    // 风险评估
    public function risk_assessment(Request $request, $UserID)
    {

        $gear = $request->gear ?: '';

        $info = DB::connection('read')->table(DB::raw('QPAccountsDB.dbo.AccountsInfo as ai WITH (NOLOCK)'))
            ->join(DB::raw('QPAccountsDB.dbo.AccountsInfo as ain WITH (NOLOCK)'), 'ai.RegisterIP', 'ain.RegisterIP')
            ->where('ai.UserID', $UserID)
            ->whereNotNull('ai.RegisterIP')
            ->selectRaw('count(1) count,ai.RegisterIP,ai.RegisterDate,ai.GameID,ai.NickName')
            ->groupBy('ai.GameID', 'ai.NickName', 'ai.RegisterIP', 'ai.RegisterDate')
            ->first();
        // 总对局数
        $info->playerNum = DB::connection('read')->table(DB::raw(TableName::QPRecordDB() . 'RecordUserGameCount WITH (NOLOCK)'))
            ->where('UserID', $UserID)
            ->sum('Cnt');

        // 推广佣金已领取 。
        $info->commission = DB::connection('read')->table(DB::raw('QPRecordDB.dbo.RecordUserScoreStatisticsNew WITH (NOLOCK)'))
                ->where('ScoreType', 53)
                ->where('UserID', $UserID)
                ->selectRaw('IsNull(sum(Score),0) Score')
                ->first()->Score / NumConfig::NUM_VALUE ?? 0;

        // 推广佣金可领取 。
        $waitCommission = DB::connection('read')->table(DB::raw('QPAccountsDB.dbo.UserAgent WITH (NOLOCK)'))
                ->where('UserID', $UserID)
                ->selectRaw('IsNull((Balance1 + Balance2),0) as  Balance')
                ->first()->Balance ?? 0;
        $info->waitCommission = $waitCommission > 0 ? $waitCommission / NumConfig::NUM_VALUE : 0;


        //今日彩金 -- 今日提现 -- 今日盈利 -- 今日充值
        $info->today = DB::connection('read')->table(DB::raw('QPRecordDB.dbo.RecordUserDataStatisticsNew WITH (NOLOCK)'))
            ->where('UserID', $UserID)
            ->where('DateID', date('Ymd'))
            ->selectRaw('IsNull(sum(Handsel),0)Handsel,IsNull(sum(Withdraw),0) Withdraw,IsNull((sum(WinScore) + sum(LostScore)), 0) Score,sum(Recharge) Recharge')
            ->first();

        // 全部彩金 -- 总提现 -- 总盈利 -- 总充值
        $info->total = DB::connection('read')->table(DB::raw('QPRecordDB.dbo.RecordUserTotalStatistics WITH (NOLOCK)'))
            ->where('UserID', $UserID)
            ->selectRaw('IsNull(sum(Handsel),0)Handsel,IsNull(sum(Withdraw),0) Withdraw,IsNull((sum(WinScore) + sum(LostScore)) , 0) Score,sum(Recharge) Recharge')
            ->first();

        isset($info->total->Score) && $info->total->Score = number_float($info->total->Score / NumConfig::NUM_VALUE);
        isset($info->total->Handsel) && $info->total->Handsel = number_float($info->total->Handsel / NumConfig::NUM_VALUE);
        isset($info->total->Withdraw) && $info->total->Withdraw = number_float($info->total->Withdraw / NumConfig::NUM_VALUE);
        isset($info->total->Recharge) && $info->total->Recharge = number_float($info->total->Recharge);
        isset($info->today->Score) && $info->today->Score = number_float($info->today->Score / NumConfig::NUM_VALUE);
        isset($info->today->Handsel) && $info->today->Handsel = number_float($info->today->Handsel / NumConfig::NUM_VALUE);
        isset($info->today->Withdraw) && $info->today->Withdraw = number_float($info->today->Withdraw / NumConfig::NUM_VALUE);
        isset($info->today->Recharge) && $info->today->Recharge = number_float($info->today->Recharge);

        // 游戏对局数--分游戏
        $gameCount = DB::connection('read')->table(DB::raw(TableName::QPRecordDB() . 'RecordUserGameCount WITH (NOLOCK)'))
            ->where('UserID', $UserID)
            ->select('Cnt', 'GameID')
            ->pluck('Cnt', 'GameID')->toArray();


        // 提现完成时间
        $info->finalTime = DB::connection('read')->table(DB::raw('QPAccountsDB.dbo.withdraw_notify WITH (NOLOCK)'))->where('user_id', $UserID)->orderByDesc('created_at')->value('finish_at');


        $accountsInfo=new AccountsInfo();
        $info->BankNO=$accountsInfo->sameBankNo($UserID);
        $info->sameWithDrawName=$accountsInfo->sameWithDrawBankNameByUserID($UserID);
        $info->sameWithDrawMail=$accountsInfo->sameWithDrawEmailByUserID($UserID);

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

//        if (!empty($getUserTab) && $TabType == 1) {
//
//            $Type12 = $getUserTab[0]->Type12 ?? 0;
//
//            $userTab = DB::connection('read')->table('QPAccountsDB.dbo.AccountsTabExplain as el')
//                ->where('TabID', $Type12)
//                ->first()->TypeName;
//        }

        return view('admin.Withdrawal.risk_assessment', [
            'info' => $info,
            'gear' => $gear,
            'userTab' => $userTab ?? '',
            'gameCount' => $gameCount,
            'gameName'=>config("games.gameName")
        ]);
    }

    // 数据查重
    public function duplicate_checking(Request $request)
    {
        $type = $request->type ?: '';
        $val = $request->val ?: '';

        $list = [];

        switch ($type) {
            case 'RegisterIP':
                $type = '注册IP';
                $list = DB::table(DB::raw('QPAccountsDB.dbo.AccountsInfo WITH (NOLOCK)'))
                    ->where('RegisterIP', $val)
                    ->where('IsAndroid', 0)
                    ->select('GameID', 'UserID')
                    ->get();
                break;
            case 'BankNo':
                $type = '卡号';
                $list = DB::table(DB::raw('QPAccountsDB.dbo.AccountWithDrawInfo as di WITH (NOLOCK)'))
                    ->join(DB::raw('QPAccountsDB.dbo.AccountsInfo as ai WITH (NOLOCK)'), 'di.UserID', 'ai.UserID')
                    ->select('ai.GameID', 'ai.UserID')
                    ->where('di.BankNo', $val)
                    ->where('IsAndroid', 0)
                    ->get();
                break;
            case 'LastLogonIP':
                $type = '登录IP';
                $list = DB::table(DB::raw('QPAccountsDB.dbo.AccountsInfo WITH (NOLOCK)'))
                    ->where('LastLogonIP', $val)
                    ->where('IsAndroid', 0)
                    ->select('GameID', 'UserID')
                    ->get();
                break;
        }
        return view('admin.Withdrawal.duplicate_checking', ['list' => $list, 'type' => $type]);


    }

    // 添加备注
    public function remarks(Request $request, $id)
    {
        $remark = $request->remark ?: '';
        $type = $request->type ?: 1;
        $admin_id = session('admin')->id;
        $RecordData = [
            'admin_id' => $admin_id,
            'remarks' => $remark,
            'RecordID' => $id,
            'create_at' => date('Y-m-d H:i:s'),
            'update_at' => date('Y-m-d H:i:s'),
            'type' => $type
        ];

        DB::connection('write')->table('QPAccountsDB.dbo.AccountsRecord')->updateOrInsert(['RecordID' => $id, 'type' => $type], $RecordData);
        return apiReturnSuc();

    }

    // 提现回收
    public function recovery($id)
    {

        $admin_id = session('admin')->id;
        $first = DB::table('QPAccountsDB.dbo.OrderWithDraw')
            ->where('RecordID', $id)
            ->select('UserID', 'WithDraw', 'State', 'ServiceFee', 'OrderId', 'RecordID', 'locking')
            ->first();

        if (!$first) {
            return apiReturnFail('订单不存在');
        }

        if ($first->State != 1) {
            return apiReturnFail('订单重复操作');
        }

        // 添加提现回收数据
        $data = [
            'UserID' => $first->UserID,
            'WithDraw' => $first->WithDraw,
            'ServiceFee' => $first->ServiceFee,
            'OrderId' => $first->OrderId,
            'admin_id' => $admin_id
        ];
//        DB::table('QPAccountsDB.dbo.WithDrawRecovery')->insert($data);

        // 添加提现记录
        $RecordData = [
            'admin_id' => $admin_id,
            'before_state' => $first->State,
            'after_state' => 4,
            'RecordID' => $first->RecordID,
            'create_at' => date('Y-m-d H:i:s'),
            'update_at' => date('Y-m-d H:i:s')
        ];

        // 添加用户提现操作记录
        DB::table('QPAccountsDB.dbo.AccountsRecord')->updateOrInsert(['RecordID' => $first->RecordID, 'type' => 1], $RecordData);

        // 修改订单状态
        DB::table('QPAccountsDB.dbo.OrderWithDraw')
            ->where('RecordID', $first->RecordID)
            ->update(['State' => 4, 'locking' => 0]);

        // 发送邮件

//        $TitleString = 'Your withdrawal order application failed';
//        $TextString = "1.Your withdrawal order: {$first->OrderId} application failed.
//        2.Reasons for order submission failure:The system has detected malicious cheating on your account and recovered your chips
//        3.If you have any questions, please contact customer service.
//        ";
        PrivateMail::RecoveryMail($first->UserID,$first->OrderId);

        return apiReturnSuc();
    }

    // 锁定订单
    public function locking($id)
    {
        $first = DB::connection('write')->table('QPAccountsDB.dbo.OrderWithDraw')->where('RecordID', $id)->first();

        if (!$first) {
            return apiReturnFail('订单不存在!');
        }

        if ($first->locking == 1) { // 解锁
            DB::connection('write')->table('QPAccountsDB.dbo.OrderWithDraw')
                ->where('RecordID', $id)
                ->update(['locking' => 0]);
        } else { // 加锁
            DB::connection('write')->table('QPAccountsDB.dbo.OrderWithDraw')
                ->where('RecordID', $id)
                ->update(['locking' => 1]);
        }

        return apiReturnSuc();
    }

    // 提现免审
    public function exempt_review()
    {
        $list = DB::connection('read')->table(DB::raw('agent.dbo.withdrawal_position_config as wp WITH (NOLOCK)'))
            ->leftJoin(DB::raw('agent.dbo.admin_configs as cf WITH (NOLOCK)'), function ($join) {
                $join->on('cf.config_value', '=', 'wp.agent');
                $join->where('cf.type', 'cash');
            })
            ->select('wp.*', 'cf.name as agent_name')
            ->paginate(10);
        foreach ($list as $value) {
//            $value->quota = $value->quota / NumConfig::NUM_VALUE;
//            $value->total_quota = $value->total_quota / NumConfig::NUM_VALUE;
            $value->useQuota = DB::connection('read')->table(DB::raw('agent.dbo.withdrawal_position_log WITH (NOLOCK)'))
                    ->whereDate('create_at', date('Y-m-d'))
                    ->where('config_id', $value->id)
                    ->sum('use_quota') / NumConfig::NUM_VALUE;
        }

        return view('admin.Withdrawal.exempt_review', [
            'list' => $list,

        ]);
    }

    // 免审添加
    public function exempt_review_add(Request $request)
    {
        if ($request->isMethod('get')) {
            $agent = DB::table(DB::raw('agent.dbo.admin_configs WITH (NOLOCK)'))
                ->where('type', 'cash')
                ->where('status', 1)
                ->get();
            return view('admin.Withdrawal.exempt_review_add', [
                'agent' => $agent
            ]);
        } else {
            $admin_id = session('admin')['id'];

            $post = $request->all();

            if (isset($post['recharge_checkbox'])) {
                $first = DB::table('agent.dbo.withdrawal_position_config')
                    ->where('recharge_min', '>=', $post['recharge_min'])
                    ->where('recharge_max', '<=', $post['recharge_max'])
                    ->first();
                if ($first) {
                    return apiReturnFail('已有重复的充值额度档位!');
                }
            }

            $data = [
                'name' => $post['name'],
                'recharge_min' => $post['recharge_min'],
                'recharge_max' => $post['recharge_max'],
                'type' => $post['type'],
                'quota' => $post['quota'] ?: 0,
                'total_quota' => $post['total_quota'],
                'admin_id' => $admin_id,
                'status' => $post['status'],
                'agent' => $post['agent'],
                'draw_gt_recharge' => $post['draw_gt_recharge'],
                'draw_total' => $post['draw_total'],
                'draw_bi' => $post['draw_bi'],
                'game_time' => $post['game_time'] * 60,  // 小时转换分
                'recharge_checkbox' => isset($post['recharge_checkbox']) ? 1 : 0  // 小时转换分
            ];


            DB::table('agent.dbo.withdrawal_position_config')->insert($data);
            return apiReturnSuc();
        }
    }

    // 免审修改
    public function exempt_review_update(Request $request, $id)
    {
        if ($request->isMethod('get')) {

            // 获取所有代付渠道配置（包括关闭的）
            $agent = DB::table(DB::raw('agent.dbo.admin_configs WITH (NOLOCK)'))
                ->where('type', 'cash')
                ->get();
            $info = DB::table(DB::raw('agent.dbo.withdrawal_position_config WITH (NOLOCK)'))->find($id);

            $info->game_time = $info->game_time > 0 ? $info->game_time / 60 : 0;
            return view('admin.Withdrawal.exempt_review_update', [
                'info' => $info,
                'agent' => $agent
            ]);
        } else {

            $admin_id = session('admin')['id'];

            $post = $request->all();

            if (isset($post['recharge_checkbox'])) {
                $first = DB::table('agent.dbo.withdrawal_position_config')
                    ->where('recharge_min', '>=', $post['recharge_min'])
                    ->where('recharge_max', '<=', $post['recharge_max'])
                    ->first();

                if ($first && $id != $first->id) {
                    return apiReturnFail('已有重复的充值额度档位!');
                }
            }

            $data = [
                'name' => $post['name'],
                'recharge_min' => $post['recharge_min'],
                'recharge_max' => $post['recharge_max'],
                'type' => $post['type'],
                'quota' => $post['quota'] ?: 0,
                'total_quota' => $post['total_quota'],
                'admin_id' => $admin_id,
                'status' => $post['status'],
                'draw_gt_recharge' => $post['draw_gt_recharge'],
                'draw_total' => $post['draw_total'],
                'draw_bi' => $post['draw_bi'],
                'game_time' => $post['game_time'] * 60,  // 小时转换分
                'recharge_checkbox' => isset($post['recharge_checkbox']) ? 1 : 0
            ];
            DB::table('agent.dbo.withdrawal_position_config')->where('id', $id)->update($data);
            return apiReturnSuc();
        }
    }

    // 提现渠道配置（新增和修改权重）
    public function cashier_channel_config(Request $request)
    {
        if ($request->isMethod('get')) {
            // 获取所有提现渠道
            $list = DB::table(DB::raw('agent.dbo.admin_configs WITH (NOLOCK)'))
                ->leftJoin(DB::raw('agent.dbo.admin_users as u WITH (NOLOCK)'), 'admin_configs.admin_id', '=', 'u.id')
                ->select('admin_configs.*', 'u.account')
                ->where('admin_configs.type', 'cash')
                ->orderBy('admin_configs.id', 'asc')
                ->get();
            
            return view('admin.Withdrawal.cashier_channel_config', ['list' => $list]);
        } else {
            // POST 提交 - 修改权重
            $validator = Validator::make($request->all(), [
                'config.*.sort' => 'required|int',
                'config.*.status' => 'required|in:1,-1',
            ]);
            
            if ($validator->fails()) {
                return apiReturnFail($validator->errors()->first());
            }
            
            $config = $request->input('config');
            
            // 验证权重总和
            $opened = array_filter($config, function ($item) {
                return $item['status'] == 1;
            });
            
            if (empty($opened)) {
                return apiReturnFail('至少需要开启一个提现渠道');
            }
            
            if (array_sum(array_column($opened, 'sort')) != 100) {
                return apiReturnFail('权重值分配不正确，开启的渠道权重总和必须为100');
            }
            
            // 更新配置
            foreach ($config as $id => $v) {
                $v['admin_id'] = session('admin')['id'];
                $v['updated_at'] = date('Y-m-d H:i:s');
                if ($v['status'] == -1) {
                    $v['sort'] = 0;
                }
                DB::table('agent.dbo.admin_configs')->where('id', $id)->update($v);
            }
            
            return apiReturnSuc();
        }
    }
    
    // 新增提现渠道
    public function cashier_channel_add(Request $request)
    {
        if ($request->isMethod('get')) {
            return view('admin.Withdrawal.cashier_channel_add');
        } else {
            // POST 提交
            $validator = Validator::make($request->all(), [
                'name' => 'required',
                'config_value' => 'required',
                'status' => 'required|in:1,-1',
            ]);
            
            if ($validator->fails()) {
                return apiReturnFail($validator->errors()->first());
            }
            
            // 获取最大ID
            $maxId = DB::table('agent.dbo.admin_configs')->max('id');
            
            $data = [
                'id' => $maxId + 1,
                'name' => $request->name,
                'config_key' => $request->config_key ?: $request->name,
                'config_value' => $request->config_value,
                'type' => 'cash',
                'status' => $request->status,
                'sort' => (int)($request->sort ?: 0),
                'remarks' => $request->remarks ?: '',
                'admin_id' => session('admin')['id'],
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s'),
            ];
            
            try {
                DB::table('agent.dbo.admin_configs')->insert($data);
                return apiReturnSuc();
            } catch (\Exception $e) {
                return apiReturnFail('添加失败：' . $e->getMessage());
            }
        }
    }
    
    // 修改提现渠道
    public function cashier_channel_update(Request $request, $id)
    {
        if ($request->isMethod('get')) {
            $info = DB::table(DB::raw('agent.dbo.admin_configs WITH (NOLOCK)'))
                ->where('id', $id)
                ->where('type', 'cash')
                ->first();
            
            if (!$info) {
                return redirect()->back()->with('error', '渠道不存在');
            }
            
            return view('admin.Withdrawal.cashier_channel_update', ['info' => $info]);
        } else {
            // POST 提交
            $validator = Validator::make($request->all(), [
                'name' => 'required',
                'config_value' => 'required',
                'status' => 'required|in:1,-1',
            ]);
            
            if ($validator->fails()) {
                return apiReturnFail($validator->errors()->first());
            }
            
            $data = [
                'name' => $request->name,
                'config_key' => $request->config_key ?: $request->name,
                'config_value' => $request->config_value,
                'status' => $request->status,
                'sort' => (int)($request->sort ?: 0),
                'remarks' => $request->remarks ?: '',
                'admin_id' => session('admin')['id'],
                'updated_at' => date('Y-m-d H:i:s'),
            ];
            
            try {
                DB::table('agent.dbo.admin_configs')
                    ->where('id', $id)
                    ->where('type', 'cash')
                    ->update($data);
                return apiReturnSuc();
            } catch (\Exception $e) {
                return apiReturnFail('修改失败：' . $e->getMessage());
            }
        }
    }

    // 免审开关
    public function block(Request $request, $id)
    {
        $status = $request->status ?: '';
        if (empty($status)) {
            return apiReturnFail('参数错误！');
        }

        DB::table('agent.dbo.withdrawal_position_config')->where('id', $id)->update(['status' => $status]);
        return apiReturnSuc();
    }

    // 用户提充统计
    public function userWithdrawalStatistics(Request $request)
    {
        $date = $request->date ?: date('Y-m-d');
        $excel = $request->excel ?: 0;
        $gameID = $request->GameID ?: '';
        $channel = $request->Channel ?: '';
        [$list, $channelList] = $this->logic->userWithdrawalStatistics($date, $excel, $gameID, $channel);
        return view('admin.Withdrawal.userWithdrawalStatistics', compact('list', 'channelList', 'date', 'gameID','channel'));
    }

    // 回调补偿
    public function compensateNotify($RecordID, Request $request)
    {
        $redisKey = 'Withdrawal_compensateNotify_'.$RecordID;
        $res = SetNXLock::getExclusiveLock($redisKey, 5);
        if (!$res) {
            return apiReturnFail('操作频繁');
        }
        $withdrawOrder = DB::table('QPAccountsDB.dbo.OrderWithDraw')->where('RecordID', $RecordID)
            ->first();
        if (!$withdrawOrder) {
            SetNXLock::release($redisKey);
            return apiReturnFail('订单不存在');
        }
        if ($withdrawOrder->State != 5 && $withdrawOrder->State != 7) {
            SetNXLock::release($redisKey);
            return apiReturnFail('订单状态不正确, 请刷新页面重试');
        }
        Log::info('提现模拟回调', [
            'recordID' => $RecordID,
            'params' => $request->all()
        ]);
        /** @var WithdrawalLogic $logic */
        $logic = app()->make(WithdrawalLogic::class);
        $res = $logic->compensateNotify($withdrawOrder);
        SetNXLock::release($redisKey);
        if ($res) {
            return apiReturnSuc();
        }
        return apiReturnFail('修改失败');
    }

    public function monitorOrderFailCall($OrderID, Request $request)
    {
        $redisKey = 'Withdrawal_monitorOrderFailCall_' . $OrderID;
        $res = SetNXLock::getExclusiveLock($redisKey, 5);
        if (!$res) {
            return apiReturnFail('操作频繁');
        }
        $withdrawOrder = DB::table('QPAccountsDB.dbo.OrderWithDraw')
            ->where('OrderId', $OrderID)
            ->first();
        if (!$withdrawOrder) {
            SetNXLock::release($redisKey);
            return apiReturnFail('订单不存在');
        }
        if ($withdrawOrder->State != 5 && $withdrawOrder->State != 7) {
            SetNXLock::release($redisKey);
            return apiReturnFail('订单状态不正确, 请刷新页面重试');
        }
        Log::info('提现手动设置失败', [
            'OrderID' => $OrderID,
            'params' => $request->all()
        ]);
        $agent = $withdrawOrder->agent;
        $TakeMoney = $withdrawOrder->WithDraw + $withdrawOrder->ServiceFee;
        $msg = (new CashierMessage())
            ->returnMsg($agent)
            ->msgStr('Encomenda rejeitada pelo banco');
        $bonus = '30000,' . $TakeMoney;
        PrivateMail::failMail($withdrawOrder->UserID, $OrderID, $TakeMoney, $msg, $bonus);
        // 修改订单状态为失败
        $withdraw_data = ['State' => 6, 'agent' => $agent];
        $notify_data = ['state' => 2];
        $RecordData = [
            'before_state' => $withdrawOrder->State,
            'after_state' => $withdraw_data['State'] ?? 0,
            'RecordID' => $withdrawOrder->RecordID,
            'update_at' => date('Y-m-d H:i:s')
        ];
        // 添加用户提现操作记录
        DB::connection('write')->table('QPAccountsDB.dbo.AccountsRecord')->updateOrInsert(['RecordID' => $withdrawOrder->RecordID, 'type' => 1], $RecordData);
        DB::connection('write')->table('QPAccountsDB.dbo.withdraw_notify')->updateOrInsert(['order_sn' => $OrderID], $notify_data);
        DB::connection('write')->table('QPAccountsDB.dbo.OrderWithDraw')->where('OrderId', $withdrawOrder->OrderId)->update($withdraw_data);

        if (isset($withdraw_data['State']) && $withdraw_data['State'] == 2) {
            // 单控标签
            StoredProcedure::user_label($withdrawOrder->UserID, 2, $TakeMoney);
            // 渠道后台埋点
            (new LogDayStatisticalByDayAndChannel())->updateData($withdrawOrder->UserID, 2);
        }
        SetNXLock::release($redisKey);

        return apiReturnSuc();
    }

    public function drawBaseChangeLog(Request $request)
    {
        $query = AddDrawBase::query();
        if ($request->input('GameID')) {
            $userID = AccountsInfo::where('GameID', $request->input('GameID'))->value('UserID');
            $query->where('user_id', intval($userID));
        }
        $officials = DB::table(DB::raw('QPAccountsDB.dbo.IDWhiteUser WITH (NOLOCK)'))->pluck('UserID')->toArray();

        $list = $query->orderBy('id', 'desc')->paginate(20);
        return view('admin.Withdrawal.draw_base_change_log', [
            'list' => $list,
            'request' => $request,
            'officials' => $officials
        ]);
    }

    // 回调补偿
    public function initData($RecordID, Request $request)
    {
        $redisKey = 'Withdrawal_init_'.$RecordID;
        $res = SetNXLock::getExclusiveLock($redisKey, 5);
        if (!$res) {
            return apiReturnFail('操作频繁');
        }
        $withdrawOrder = DB::table('QPAccountsDB.dbo.OrderWithDraw')->where('RecordID', $RecordID)
            ->first();
        if (!$withdrawOrder) {
            SetNXLock::release($redisKey);
            return apiReturnFail('订单不存在');
        }
        DB::connection('write')->table('QPAccountsDB.dbo.OrderWithDraw')
            ->where('RecordID', $withdrawOrder->RecordID)
            ->update(['State' => 1,'OrderId' => $withdrawOrder->OrderId.rand(1,9)]);
        SetNXLock::release($redisKey);
        return apiReturnSuc();
    }

    /**
     * 同步最新提款账号信息
     * 只针对第三方订单失败（State=6）且金额小于30的订单
     */
    public function syncAccountInfo(Request $request, $RecordID)
    {
        try {
            // 获取订单信息
            $order = DB::connection('read')->table('QPAccountsDB.dbo.OrderWithDraw')
                ->where('RecordID', $RecordID)
                ->first();

            if (!$order) {
                return apiReturnFail('订单不存在');
            }

            // 检查订单状态和金额
            if ($order->State != 6) {
                return apiReturnFail('只能同步第三方订单失败的订单');
            }

            // 金额小于30（WithDraw字段是decimal(10,2)，所以30就是30.00）
            if ($order->WithDraw >= 3000) {
                return apiReturnFail('只能同步金额小于30的订单');
            }

            // 获取最新的账号信息
            $latestInfo = DB::connection('read')->table('QPAccountsDB.dbo.AccountWithDrawInfo')
                ->where('UserID', $order->UserID)
                ->first();

            if (!$latestInfo) {
                return apiReturnFail('用户账号信息不存在');
            }

            // 比较需要同步的字段
            $fieldsToCompare = [
                'BankUserName',
                'EmailAddress',
                'PhoneNumber',
                'PixNum',
                'PixType',
                'BankNO',
                'AccountsBank',
                'IFSCNumber',
                'PANNumber',
                'AdhaarNumber',
                'BranchBank'
            ];

            $isSame = true;
            $updateData = [];

            foreach ($fieldsToCompare as $field) {
                $orderValue = trim($order->$field ?? '');
                $latestValue = trim($latestInfo->$field ?? '');

                if ($orderValue !== $latestValue) {
                    $isSame = false;
                    $updateData[$field] = $latestValue;
                }
            }

            // 如果信息一致，返回失败
            if ($isSame) {
                return apiReturnFail('账号信息一致，无需同步');
            }

            // 更新订单信息
            DB::connection('write')->table('QPAccountsDB.dbo.OrderWithDraw')
                ->where('RecordID', $RecordID)
                ->update($updateData);

            return apiReturnSuc(['updated_fields' => array_keys($updateData)], '同步成功');
        } catch (\Exception $e) {
            Log::error('同步账号信息失败', [
                'RecordID' => $RecordID,
                'error' => $e->getMessage()
            ]);
            return apiReturnFail('同步失败：' . $e->getMessage());
        }
    }

    /**
     * 获取订单账号信息（用于编辑）
     */
    public function getAccountInfo($RecordID)
    {
        try {
            $order = DB::connection('read')->table('QPAccountsDB.dbo.OrderWithDraw')
                ->where('RecordID', $RecordID)
                ->first();

            if (!$order) {
                return apiReturnFail('订单不存在');
            }

            // 检查订单状态
            if ($order->State != 6) {
                return apiReturnFail('只能编辑失败订单的账号信息');
            }

            return apiReturnSuc([
                'RecordID' => $order->RecordID,
                'UserID' => $order->UserID,
                'BankUserName' => $order->BankUserName ?? '',
                'EmailAddress' => $order->EmailAddress ?? '',
                'PhoneNumber' => $order->PhoneNumber ?? '',
                'PixNum' => $order->PixNum ?? '',
                'PixType' => $order->PixType ?? 0,
                'BankNO' => $order->BankNO ?? '',
                'AccountsBank' => $order->AccountsBank ?? '',
                'IFSCNumber' => $order->IFSCNumber ?? '',
                'PANNumber' => $order->PANNumber ?? '',
                'AdhaarNumber' => $order->AdhaarNumber ?? '',
                'BranchBank' => $order->BranchBank ?? '',
            ]);
        } catch (\Exception $e) {
            Log::error('获取订单账号信息失败', [
                'RecordID' => $RecordID,
                'error' => $e->getMessage()
            ]);
            return apiReturnFail('获取信息失败：' . $e->getMessage());
        }
    }

    /**
     * 更新订单账号信息（同时更新OrderWithDraw和AccountWithDrawInfo）
     */
    public function updateAccountInfo(Request $request, $RecordID)
    {
        try {
            $validator = Validator::make($request->all(), [
                'BankUserName' => 'nullable|string|max:100',
                'EmailAddress' => 'nullable|string|max:80',
                'PhoneNumber' => 'nullable|string|max:20',
                'PixNum' => 'nullable|string|max:32',
                'PixType' => 'nullable|integer|in:0,1,2,3',
                'BankNO' => 'nullable|string|max:30',
                'AccountsBank' => 'nullable|string|max:100',
                'IFSCNumber' => 'nullable|string|max:20',
                'PANNumber' => 'nullable|string|max:10',
                'AdhaarNumber' => 'nullable|string|max:80',
                'BranchBank' => 'nullable|string|max:100',
            ]);

            if ($validator->fails()) {
                return apiReturnFail($validator->errors()->first());
            }

            // 获取订单信息
            $order = DB::connection('read')->table('QPAccountsDB.dbo.OrderWithDraw')
                ->where('RecordID', $RecordID)
                ->first();

            if (!$order) {
                return apiReturnFail('订单不存在');
            }

            // 检查订单状态
            if ($order->State != 6) {
                return apiReturnFail('只能编辑失败订单的账号信息');
            }

            // 准备更新数据
            $updateData = [];
            $fields = [
                'BankUserName', 'EmailAddress', 'PhoneNumber', 'PixNum', 'PixType',
                'BankNO', 'AccountsBank', 'IFSCNumber', 'PANNumber', 'AdhaarNumber', 'BranchBank'
            ];

            foreach ($fields as $field) {
                if ($request->has($field)) {
                    $updateData[$field] = trim($request->input($field, ''));
                }
            }

            if (empty($updateData)) {
                return apiReturnFail('没有需要更新的数据');
            }

            DB::beginTransaction();
            try {
                // 更新 OrderWithDraw 表
                DB::connection('write')->table('QPAccountsDB.dbo.OrderWithDraw')
                    ->where('RecordID', $RecordID)
                    ->update($updateData);

                // 更新 AccountWithDrawInfo 表
                DB::connection('write')->table('QPAccountsDB.dbo.AccountWithDrawInfo')
                    ->where('UserID', $order->UserID)
                    ->update($updateData);

                DB::commit();

                // 记录操作日志
                $admin_id = session('admin')->id ?? 0;
                (new AccountsRecordLogic())->create_record($RecordID, $order->State, $order->State, '编辑提款账号信息', $admin_id, 2);

                return apiReturnSuc(['updated_fields' => array_keys($updateData)], '更新成功');
            } catch (\Exception $e) {
                DB::rollBack();
                throw $e;
            }
        } catch (\Exception $e) {
            Log::error('更新订单账号信息失败', [
                'RecordID' => $RecordID,
                'error' => $e->getMessage(),
                'data' => $request->all()
            ]);
            return apiReturnFail('更新失败：' . $e->getMessage());
        }
    }

    public function withdrawRank(Request $request)
    {
        $date = Carbon::now();
        $start_time = $request->input('start_time', $date->format('Y-m-d'));
        $end_time = $request->input('end_time', $date->format('Y-m-d'));
        $where = [];

        !empty($start_time) && $where[] = ['DateID', '>=', Carbon::parse($start_time)->format('Ymd')];
        !empty($end_time) && $where[] = ['DateID', '<', Carbon::parse($end_time)->addDay(1)->format('Ymd')];




        $order_sql = 'Withdraw DESC';

        if (true) {

            $list = DB::table(DB::raw(TableName::QPRecordDB() . 'RecordUserDataStatisticsNew as ds WITH (NOLOCK)'))
                ->where('Withdraw', '>', 0)
                ->where($where)
                ->join(DB::raw(TableName::QPAccountsDB() . 'AccountsInfo as ai WITH (NOLOCK)'), 'ds.UserID', 'ai.UserID')
                ->leftjoin(DB::raw('QPAccountsDB.dbo.AccountPhone as ap WITH (NOLOCK)'), 'ds.UserID', 'ap.UserID')
                ->select('ai.UserID', 'ai.GameID', 'ai.NickName', 'ai.Channel', 'ap.PhoneNum', 'ai.PlayTimeCount', 'ai.LastLogonDate', 'ai.RegisterDate')
                ->orderByRaw($order_sql)
                ->paginate(10);
            $rechargeSum = DB::table(DB::raw(TableName::QPRecordDB() . 'RecordUserDataStatisticsNew as ds WITH (NOLOCK)'))
                ->where('Withdraw', '>', 0)
                ->where($where)
                ->selectRaw('sum(ds.Withdraw) Withdraw,UserID')
                ->groupBy('UserID')
                ->pluck('Withdraw', 'UserID')->toArray();

            $UserIDs = [];
            foreach ($list as $value) {
                $UserIDs[] = $value->UserID;
            }


            foreach ($list as $key => &$value) {
                $second = $value->PlayTimeCount;
                $day = floor($second / (3600 * 24));
                $second = $second % (3600 * 24);//除去整天之后剩余的时间
                $hour = floor($second / 3600);
                $second = $second % 3600;//除去整小时之后剩余的时间
                $minute = floor($second / 60);
                //返回字符串
                $value->Experience = $day . '天' . $hour . '小时' . $minute . '分';

                $value->type = '玩家';
                $value->rank = $key + 1;

                $value->money = $rechargeSum[$value->UserID] ?? 0;

                $value->money  = $value->money /100;

                $value->time = Carbon::parse(now())->diffInDays($value->LastLogonDate, true);

            }

            return view('admin.Withdrawal.rank', [
                'list' => $list,
                'end_time' => $end_time,
                'start_time' => $start_time,

            ]);
        }
    }
    public function nameStatics(){
//        DB::table(TableName::QPAccountsDB() . 'OrderWithDraw')
//          ->selectRaw('count(distinct (UserID)) as nums,BankUserName')
//          ->groupBy("BankUserName")
//          ->orderBy("nums","desc");



        $sql = "select nums,BankUserName from (select count(distinct (UserID)) as nums,BankUserName from QPAccountsDB.dbo.OrderWithDraw WITH (NOLOCK) group by BankUserName ) s where nums>1";
//        $sql = "select * from OrderWithDraw where BankUserName in (select BankUserName from (select count(distinct (UserID)) as nums,BankUserName from QPAccountsDB.dbo.OrderWithDraw group by BankUserName ) s where nums>1) order by BankUserName";
        $multiNames = DB::select($sql);

        $sql="select nums,EmailAddress from (select count(distinct (UserID)) as nums,EmailAddress from QPAccountsDB.dbo.OrderWithDraw WITH (NOLOCK) group by EmailAddress ) s where nums>1";
        $multiEmails = DB::select($sql);

//        $res=DB::table(TableName::QPAccountsDB() . 'OrderWithDraw')
//          ->selectRaw('count(distinct (UserID)) as nums')
//          ->where("EmailAddress","ciceroedsondasilvasantos19@gmail.com")
//          ->first();

//        print_r($res)
        return view('admin.Withdrawal.statics', [
            'names' => $multiNames,
            'emails' => $multiEmails,

        ]);


//        select count(distinct (UserID)) as nums,BankUserName from QPAccountsDB.dbo.OrderWithDraw group by BankUserName order by nums desc;
    }
}
