<?php


namespace App\Http\logic\admin;


use App\dao\Estatisticas\RechargeWithDraw;
use App\Facade\RedisConnect;
use App\Facade\TableName;
use App\Game\Services\AgentSystemService;
use App\Http\helper\Helper;
use App\Http\helper\NumConfig;
use App\Models\AccountsInfo;
use App\Models\AccountWithDrawInfo;
use App\Models\PrivateMail;
use App\Models\Cpf;
use App\Models\RecordUserDataStatistics;
use App\Models\Withdrawal;
use App\Models\WithdrawalChannelPositionConfig;
use App\Services\CashService;
use App\Services\LogDayStatisticalByDayAndChannel;
use App\Services\StoredProcedure;
use App\Util;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Request;
use Mockery\Exception;

class WithdrawalLogic extends BaseLogicController
{

    protected $agent;   // 代付方

    public function __construct()
    {
        $this->agent = DB::table('agent.dbo.admin_configs')
            ->where('type', 'cash')
            ->where('status', 1)
            ->get();
    }


    public function waitWithdrawal($GameID, $withdraw_search, $withdraw, $state, $start_time, $end_time, $agent = '', $flag = false, $create_time_sort = '', $orderID = '', $final_start_time = '', $final_end_time = '', $excel = '', $Channel = '', $payState = '', $take_effect = '', $isEmpty = 0, $register_start_time = '', $register_end_time = '', $PackgeName = '',$firstWithDraw=0)
    {

        $SQL = DB::connection('write')->table('QPAccountsDB.dbo.OrderWithDraw as ow')
            ->join('QPAccountsDB.dbo.AccountsInfo as ai', 'ow.UserID', 'ai.UserID')
            ->leftJoin('QPAccountsDB.dbo.withdraw_notify as wn', 'ow.OrderID', '=', 'wn.order_sn')
            ->leftJoin('QPAccountsDB.dbo.AccountsRecord as ar', function ($join) {
                $join->on('ow.RecordID', 'ar.RecordID');
                $join->where('ar.type', 1);
            });
        if($firstWithDraw<2){
            $SQL->join(TableName::QPRecordDB() . 'RecordUserTotalStatistics as rds', function ($join) use ($firstWithDraw) {
                $join->on('rds.UserID', 'ow.UserID');
                $join->where('rds.Withdraw', $firstWithDraw>0?'=':'<>',0);
            });
        }

        if (!$flag) {
            empty($state) && $state = 1;
        } else {
            empty($state) && $state = 100;
            if ($isEmpty == 0) {
                empty($start_time) && $start_time = date('Y-m-d 00:00:00');
                empty($end_time) && $end_time = date('Y-m-d 23:59:59');
            } elseif ($isEmpty == 2) {
                empty($final_start_time) && $final_start_time = date('Y-m-d 00:00:00');
                empty($final_end_time) && $final_end_time = date('Y-m-d 23:59:59');
            }
        }
        !empty($GameID) && $where[] = ['ai.GameID', $GameID];
//        !empty($withdraw_search) && $SQL->whereRaw("ow.WithDraw+ow.ServiceFee=$withdraw_search");
//        switch ($withdraw) {
//            case 100:
//                $SQL = $SQL->havingRaw('sum(ow.WithDraw + ow.ServiceFee) < ?', [100]);
//                break;
//            case 500:
//                $SQL = $SQL->havingRaw('sum(ow.WithDraw + ow.ServiceFee) >= ?', [100]);
//                $SQL = $SQL->havingRaw('sum(ow.WithDraw + ow.ServiceFee) <= ?', [500]);
//                break;
//            case 1000:
//                $SQL = $SQL->havingRaw('sum(ow.WithDraw + ow.ServiceFee) >= ?', [500]);
//                $SQL = $SQL->havingRaw('sum(ow.WithDraw + ow.ServiceFee) <= ?', [1000]);
//                break;
//            case 1001:
//                $SQL = $SQL->havingRaw('sum(ow.WithDraw + ow.ServiceFee) > ?', [1000]);
//                break;
//        }

        if (empty($state)) {
            $where[] = ['ow.State', '=', 0];
        } elseif ($state == 100) {
            $where[] = ['ow.State', '<>', ''];

        } elseif ($state == 4) {
            $where[] = ['ow.State', '=', $state];
        } else {
            $where[] = ['ow.State', '=', $state];

        }

        !empty($start_time) && $where[] = ['CreateDate', '>=', str_replace('T', ' ', $start_time)];
        !empty($end_time) && $where[] = ['CreateDate', '<=', str_replace('T', ' ', $end_time)];
        if (!empty($agent)) {
            $SQL = $SQL->join('agent.dbo.admin_configs as ac', 'ow.agent', '=', 'ac.id');
            $where[] = ['agent', $agent];
        }
        !empty($orderID) && $where[] = ['OrderID', $orderID];
        !empty($final_start_time) && $where[] = ['finishDate', '>=', str_replace('T', ' ', $final_start_time)];
        !empty($final_end_time) && $where[] = ['finishDate', '<=', str_replace('T', ' ', $final_end_time)];
        if(Request::input('final_start_time_cn')) {
            $where[] = ['finishDate', '>=',
                date('Y-m-d H:i:s', strtotime(
                    str_replace('T', ' ', Request::input('final_start_time_cn')). ' - 11 hours'
                ))
            ];
        }
        if(Request::input('final_end_time_cn')) {
            $where[] = ['finishDate', '<=',
                date('Y-m-d H:i:s', strtotime(
                    str_replace('T', ' ', Request::input('final_end_time_cn')). ' - 11 hours'
                ))
            ];
        }
        (!empty($Channel) || $Channel === '0') && $where[] = ['ai.Channel', $Channel];
        if ($payState == 1) {
            $SQL = $SQL->join('QPRecordDB.dbo.RecordUserTotalStatistics as rs', 'ow.UserID', 'rs.UserID')->where('Recharge', '>', 0);
        }
        if ($take_effect == -1) {
            $SQL = $SQL->join('agent.dbo.withdrawal_position_log as log', function ($join) {
                $join->on('log.order_sn', '=', 'ow.OrderID');
            });
        } else {
            if (!empty($take_effect)) {
                $SQL = $SQL->Join('agent.dbo.admin_users as us', 'ar.admin_id', '=', 'us.id');
                $where[] = ['ar.admin_id', '=', $take_effect];
            }
        }
        !empty($register_start_time) && $where[] = ['RegisterDate', '>=', str_replace('T', ' ', $register_start_time) ];
        !empty($register_end_time) && $where[] = ['RegisterDate', '<=', str_replace('T', ' ', $register_end_time)];
        if (!empty($PackgeName)) {
            $SQL = $SQL->leftJoin('QPRecordDB.dbo.RecordPackageName as rn', 'ai.UserID', 'rn.UserID');
            $where[] = ['PackgeName', $PackgeName];
        }
        $adminChannels=session('admin_channels');

        if(count($adminChannels)<5)$SQL=$SQL->whereIn('ai.Channel', $adminChannels);
//        dd($where);
        if (!$flag && $excel) {

            AccountWithDrawInfo::verifyOrderDownExcel($SQL, $where);

        } elseif ($flag && $excel) {

            AccountWithDrawInfo::orderOverDownExcel($SQL, $where);

        } else {
            $field = ['ai.RegisterIP','ow.locking', 'ar.remarks','ow.remark', 'ow.RecordID', 'ar.RecordID as ar_RecordID', 'wn.state as wn_state', 'ai.NickName', 'ow.AccountsBank', 'ow.BankUserName', 'ow.WithDraw', 'ow.State', 'ow.BankNO', 'ow.ServiceFee', 'OrderId', 'ai.GameID', 'ai.UserID', 'ai.Channel', 'ar.admin_id', 'ow.agent', 'finishDate', 'PixNum', 'PixType', 'ow.EmailAddress', 'ow.PhoneNumber', 'ow.AdhaarNumber', 'ow.IFSCNumber'];
            $SQL1 = clone $SQL;
            $SQL2 = clone $SQL;
            $model = new AccountWithDrawInfo();


            $list = $SQL
                ->where($where)
                ->lock('with(nolock)')
                ->select($field)
                ->selectRaw('ar.update_at, CreateDate')
                ->orderBy('ow.RecordID', 'desc')
                ->paginate(10);

            // 申请人数，笔数，金额
            $applyUserCount = $SQL1
                ->where($where)
                ->lock('with(nolock)')
                ->selectRaw('count(distinct(ow.UserID)) userCount,(sum(cast(ow.WithDraw as bigint))+sum(cast(ow.ServiceFee as bigint))) WithDraw,count(ow.RecordID) count')->lock('with(nolock)')->first();
            if (isset($applyUserCount->WithDraw)) {
                $applyUserCount->WithDraw = number_float($applyUserCount->WithDraw / NumConfig::NUM_VALUE);
            }

            // 到账人数，金额
            $overUserCount = $SQL2->where($where)->where('ow.State', 2)->selectRaw('count(distinct(ow.UserID)) userCount,sum(cast(ow.WithDraw as bigint)) WithDraw,count(ow.RecordID) count')
                ->lock('with(nolock)')
                ->first();
            if (isset($overUserCount->WithDraw)) {
                $overUserCount->WithDraw = number_float($overUserCount->WithDraw / NumConfig::NUM_VALUE);
            }

            $userIDs = [];
            $adminIDs = [];
            $agentIDs = [];
            $accountsInfo=new AccountsInfo();
            foreach ($list as &$val) {
                $val->actual_arrival = number_float(($val->WithDraw + $val->ServiceFee) / 100); // 实际提现金额
                $val->ServiceFee = number_float($val->ServiceFee / 100);
                $val->WithDraw = number_float($val->WithDraw / 100);
                $val->sameNameNum=$accountsInfo->sameWithDrawBankName($val->BankUserName);
                $val->sameEmailNum=$accountsInfo->sameWithDrawEmail($val->EmailAddress);
                $val->sameMac=$accountsInfo->sameLoginMacCount($val->UserID);
                $val->sameCpfCount=Cpf::getCpfCount($val->UserID);
                $val->sameIP=$accountsInfo->sameRegisterIPCount($val->RegisterIP);
//                $val->sameLIP=$accountsInfo->sameLoginIPCount($val->UserID);

                $userIDs[] = $val->UserID;

                !empty($val->admin_id) && $adminIDs[] = $val->admin_id;
                !empty($val->agent) && $agentIDs[] = $val->agent;
            }
            unset($val);

            $agentName = DB::connection('write')->table('agent.dbo.admin_configs')
                ->whereIn('id', $agentIDs)
                ->pluck('name', 'id')->toArray();

            $adminName = DB::connection('write')->table('agent.dbo.admin_users')
                ->whereIn('id', $adminIDs)
                ->pluck('account', 'id')->toArray();
            $userIDs = array_unique($userIDs);

            // 银行卡绑定信息评估
            $BankNO = $model->BankNO($userIDs);
            $IP = $model->ip($userIDs);


            $orders = DB::connection('read')->table('QPAccountsDB.dbo.YN_VIPAccount')->whereIn('UserID', $userIDs)
                ->selectRaw('Recharge,UserID')
                ->lock('with(nolock)')
                ->pluck('Recharge', 'UserID')->toArray();

            $Withdrawal_M = new Withdrawal();
            // 评估档位
            foreach ($list as &$val) {
                /*
                * 评估档位     累计充值金额       获得佣金
                * 低            ≥100            ≥100
                * 普通          >0<100          >0<100
                * 较高          0               >0
                * 高            0               0
                * */
                $cz_money = $orders[$val->UserID] ?? 0;

                if (isset($IP[$val->UserID]) && $IP[$val->UserID] > 1) {
                    $gear = '高';
                } elseif (isset($BankNO[$val->UserID]) && $BankNO[$val->UserID] > 1) {
                    $gear = '高';
                } elseif ($cz_money >= 100) {
                    $gear = '低';
                } elseif ($cz_money > 0 && $cz_money < 100) {
                    $gear = '普通';
                } elseif ($cz_money > 0) {
                    $gear = '较高';
                } elseif ($cz_money == 0) {
                    $gear = '高';
                }

                $val->gear = $gear ?? '';
                $val->assessment = $Withdrawal_M->assessment($cz_money);
                $val->States = $Withdrawal_M->stateText($val->State, $val->locking);
                $val->account = isset($adminName[$val->admin_id]) ? $adminName[$val->admin_id] : '';
                $val->name = isset($agentName[$val->agent]) ? $agentName[$val->agent] : '';
            }
        }

        // 改已读
//        DB::table('QPAccountsDB.dbo.OrderWithDraw')->update(['admin_read' => 1]);

        $allChannel = $adminChannels;//DB::connection('read')->table('QPPlatformDB.dbo.ChannelPackageName')->selectRaw('Channel')->groupBy('Channel')->pluck('Channel');
        $start_time = Helper::timeChange($start_time);
        $end_time = Helper::timeChange($end_time);
        $final_start_time = Helper::timeChange($final_start_time);
        $final_end_time = Helper::timeChange($final_end_time);

        // 提现管理员
        $withdrawal_administrator = DB::connection('write')->table('agent.dbo.withdrawal_administrator')->pluck('account', 'admin_id');

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

        return compact('applyUserCount', 'overUserCount', 'list', 'payState', 'allChannel', 'Channel', 'GameID', 'withdraw_search', 'withdraw', 'state', 'start_time', 'end_time', 'agent', 'orderID', 'final_start_time', 'final_end_time', 'take_effect', 'withdrawal_administrator', 'isEmpty', 'register_start_time', 'register_end_time', 'PackgeName', 'ChannelPackageName');
    }


    public function verify_agree($ids)
    {
        $id_arr = explode(',', $ids);

        $order = ['WithDraw', 'ServiceFee', 'ow.RecordID', 'ai.GameID', 'ai.UserID', 'ai.Channel','PixType'];
        $list = DB::connection('write')->table('QPAccountsDB.dbo.OrderWithDraw as ow')
            ->join('QPAccountsDB.dbo.AccountsInfo as ai', 'ow.UserID', 'ai.UserID')
            ->whereIn('RecordID', $id_arr)
            ->select($order)
            ->lock('with(nolock)')
            ->paginate(10);
        $channelConfigs = [];
        $res = WithdrawalChannelPositionConfig::where('status', 1)->get();
        foreach ($res as $v) {
            $channelConfigs[$v->channel] = $v;
        }
//        $config = DB::table(TableName::agent() . 'withdrawal_position_config')
//            ->where('status', 1)
//            ->first();
        foreach ($list as &$value) {
            $value->WithDraw = number_float(($value->WithDraw + $value->ServiceFee) / 100);
            if($value->PixType==66){
                //代理订单
                $value->agent=
                $this->agent=[(object)[
                                  "id"           => "6666",
                                  "name"         => "代理申请为玩家提现",
                                  "config_key"   => "AgentCashOut",
                                  "config_value" => "66",
                                  "type"         => "cash",
                                  "created_at"   => null,
                                  "updated_at"   => null,
                                  "admin_id"     => "11",
                                  "status"       => "1",
                                  "sort"         => "0",
                                  "remarks"      => null,
                                  "new_pay_type" => "0",
                                  "pic_num"      => null,
                                  "pay_error"    => "0",
                                  "cpf_first"    => "0"
                              ]];
                continue;
            }
            if(isset($channelConfigs[$value->Channel]) && $channelConfigs[$v->channel]->limit_manual_review_show) {
                $c = $channelConfigs[$value->Channel];
                $value->agent = array_filter($this->agent->toArray(), function ($item) use ($c) {
                   return $item->config_value == $c->agent;
                });
            }
        }



        $agent = $this->agent;

        return compact('list', 'agent');
    }

    public function save($data, $admin_id)
    {

        $redis = new RedisConnect();
        $limitKey = 'withdraw';

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

        $WithdrawalModel = new Withdrawal();
        $id_arr = explode(',', $data['ids']);
        // 代付方
        $agent = $data['agent'] ?? '';


        if (empty($agent) && $data['agree'] == 'true') {
            return apiReturnFail('请选择代付方');
        }

        if ($data['agree'] == 'true') {
            $state = 2;
        } else {
            $state = -1;
        }
        try {
            foreach ($id_arr as $val) {

                $query = DB::connection('write')->table('QPAccountsDB.dbo.OrderWithDraw')->where('RecordID', $val)->first();

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

                    if ($query->locking == 1) {
                        return apiReturnFail('订单已被锁定');
                    }


                    $redis1 = Redis::connection();
                    $order_sn = $query->OrderId;
                    if ($redis1->exists($order_sn . 'key1')) {
                        return apiReturnFail('订单已被锁定new');
                    }
                    $redis1->set($order_sn.'key1', $order_sn, 3600 * 24);
                }

                // 拒绝提现 ，发邮件给用户
                if ($state == -1) {
                    // 发送邮件给玩家
                    $WithDraw = $query->WithDraw + $query->ServiceFee;
                    PrivateMail::ClearDrawMail($query->UserID, $query->OrderId, $WithDraw);
                    // 修改订单状态
                    DB::table('QPAccountsDB.dbo.OrderWithDraw')->where('RecordID', $val)->update(['State' => $state, 'locking' => 2]);
                    $remarks = $data['remarks'] ?? '';
                    // 添加用户提现操作记录
                    (new AccountsRecordLogic())->create_record($val, 1, $state, $remarks, $admin_id, 1);
                    if($query->PixType==66)AgentSystemService::FailWithdraw($query);
                } else if($query->PixType==66){
                    DB::table('QPAccountsDB.dbo.OrderWithDraw')->where('RecordID', $val)->update(['State' => 5, 'agent' => 660000+$query->AccountsBank]);
                    //通知AgentSystem完成，并锁定
                    AgentSystemService::FinishWithdraw($query);

                } else {  // 发起提现

                    // 验证用户提现方式
                    $verifyAccountWithdrawal = $WithdrawalModel->AccountWithDrawInfo($query->PixNum, $agent);
                    if (!$verifyAccountWithdrawal) return apiReturnFail('不支持的提现格式！');

                    $state = 5;
                    # 获取哪个三方提现
                    $orderAgent = $WithdrawalModel->getAgentChannel($agent);
                    // 改变状态处理中
                    DB::table('QPAccountsDB.dbo.OrderWithDraw')->where('RecordID', $val)->update(['State' => $state, 'agent' => $orderAgent]);

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

                    $RecordID = $query->RecordID;
                    $amount = $query->WithDraw;
                    $accountName = $query->BankUserName;
                    $email = $query->EmailAddress;
                    $phone = $query->PhoneNumber;
                    $PixNum = $query->PixNum;
                    $PixType = $query->PixType;
                    $OrderId = $query->OrderId;
                    $IFSCNumber = $query->IFSCNumber;
                    $BranchBank = $query->BranchBank;
                    $BankNO = $query->BankNO;

                    if($PixType>10){
                        Util::WriteLog("pixerror",$query);
                        $oldRecord=DB::table('QPAccountsDB.dbo.OrderWithDraw')->where('UserID', $query->UserID)->where('State',2)->first();
                        if(isset($oldRecord)&&isset($oldRecord->PixType)){
                            $PixType=$oldRecord->PixType;
                        }else{
                            $PixType=1;
                        }

                    }

                    $service = CashService::payment($agent);

                    $result = $service->payment($RecordID, $amount, $accountName, $phone, $email, $OrderId, $PixNum, $PixType, $IFSCNumber, $BranchBank, $BankNO);
                    if ($result === 'fail') {
                        return apiReturnFail('订单提现失败');
                    }
                }

                // 判断管理员是否已经存在
                $withdrawal_administrator = DB::connection('write')->table('agent.dbo.withdrawal_administrator')->where('admin_id', $admin_id)->first();
                if (!$withdrawal_administrator) {
                    $dataArr = [
                        'admin_id' => $admin_id,
                        'account' => session('admin')->account ?? ''
                    ];
                    DB::connection('write')->table('agent.dbo.withdrawal_administrator')->insert($dataArr);
                }
            }
            $redis->redis()->del($limitKey);
            return apiReturnSuc();
        } catch (Exception $e) {
            $redis->redis()->del($limitKey);
            return apiReturnFail($e->getMessage());
        }

    }

    // 用户提充统计
    public function userWithdrawalStatistics($date, $excel, $gameID, $channel)
    {

        $dateID = Carbon::parse($date)->format('Ymd');

        $where[] = ['Withdraw', '>', 0];
        !empty($date) && $where[] = ['DateID', $dateID];
        !empty($gameID) && $where[] = ['GameID', $gameID];
        (!empty($channel) || $channel === 0) && $where[] = ['Channel', $channel];

        $buildSql = DB::table(TableName::QPRecordDB() . 'RecordUserDataStatisticsNew as rn')
            ->where($where)
            ->join(TableName::QPAccountsDB() . 'AccountsInfo as ai', 'rn.UserID', 'ai.UserID')
            ->select('GameID', 'rn.UserID', 'Withdraw', 'Recharge')
            ->orderBy('Withdraw', 'desc');
        // 昨天的提现用户，昨日提现多少，昨日充值多少，历史充值多少，历史提现多少
        $list = $excel ? $buildSql->get() : $buildSql->paginate(15);

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

        $total = DB::table(TableName::QPRecordDB() . 'RecordUserTotalStatistics')
            ->whereIn('UserID', $UserIDs)
            ->select('Withdraw', 'Recharge', 'UserID')
            ->get();
        foreach ($list as &$value) {

            $value->Withdraw = number_float($value->Withdraw / 100);
            foreach ($total as $val) {
                if ($val->UserID == $value->UserID) {
                    $value->HisWithdraw = number_float($val->Withdraw / 100);
                    $value->HisRecharge = $val->Recharge;
                }
            }
        }

        if ($excel) {

            $title = ['游戏ID', '用户ID', '今日提现', '今日充值', '历史提现', '历史充值'];
            $list = json_decode(json_encode($list), true);
            downloadExcel($list, $title, '统计' . date('YmdHis'));
            return;
        } else {

            $channelList = DB::table(TableName::QPPlatformDB().'ChannelPackageName')
                ->select('Channel')
                ->groupBy('Channel')
                ->pluck('Channel','Channel')->toArray();
            return [$list,$channelList];
        }


    }

    /**
     * 后台模拟触发提现回调
     * @param $withdrawOrder
     * @return bool
     */
    public function compensateNotify($withdrawOrder)
    {
        $withdraw_data = [
            'State' => 2,
            'finishDate' => now(),
        ];
        $UserID = $withdrawOrder->UserID;
        $TakeMoney = $withdrawOrder->WithDraw + $withdrawOrder->ServiceFee;
        // 增加提现记录
        $first = DB::connection('write')->table('QPAccountsDB.dbo.UserTabData')->where('UserID', $UserID)->first();
        if ($first) {
            DB::connection('write')->table('QPAccountsDB.dbo.UserTabData')->where('UserID', $UserID)->increment('TakeMoney', $TakeMoney);
        } else {
            DB::connection('write')->table('QPAccountsDB.dbo.UserTabData')->insert(['TakeMoney' => $TakeMoney, 'UserID' => $UserID]);
        }
        // 免审的时候，修改免审状态
        $withdrawal_position_log = DB::connection('write')
            ->table('agent.dbo.withdrawal_position_log')->where('order_sn', $withdrawOrder->OrderId)
            ->first();
        if ($withdrawal_position_log) {
            DB::connection('write')->table('agent.dbo.withdrawal_position_log')
                ->where('order_sn', $withdrawOrder->OrderId)
                ->update(['take_effect' => 2, 'update_at' => date('Y-m-d H:i:s')]);
        }
        $ServiceFee = $withdrawOrder->ServiceFee;
        // 增加用户提现值
        RecordUserDataStatistics::updateOrAdd($UserID, $TakeMoney, 0, $ServiceFee);

        // 给用户发邮件
        PrivateMail::successMail($UserID, $withdrawOrder->OrderId, $TakeMoney);

        StoredProcedure::addPlatformData($UserID, 4, $TakeMoney);

        // 数据统计后台 -- 提现记录添加
        (new RechargeWithDraw())->withDraw($UserID, $TakeMoney);

        $redis = Redis::connection();
        $redis->incr('draw_'.date('Ymd').$UserID);

        $RecordData = [
            'before_state' => $withdrawOrder->State,
            'after_state' => $withdraw_data['State'] ?? 0,
            'RecordID' => $withdrawOrder->RecordID,
            'update_at' => date('Y-m-d H:i:s')
        ];

        $notify_data = [
            'state' => 1,
            'finish_at' => now(),
            'casOrdNo' => '',
            'extra' => '{}',
            'created_at' => now(),
            'updated_at' => now(),
            'order_sn' => $withdrawOrder->OrderId,
            'amount' => $TakeMoney,
        ];
        // 添加用户提现操作记录
        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' => $withdrawOrder->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($UserID, 2, $TakeMoney);
            // 渠道后台埋点
            (new LogDayStatisticalByDayAndChannel())->updateData($UserID, 2);
        }

        return true;
    }
}
