<?php


namespace App\Console\Commands;


use App\Facade\TableName;
use App\Models\AccountsInfo;
use App\Models\Cpf;
use App\Models\SystemStatusInfo;
use App\Models\Withdrawal;
use App\Models\WithdrawalChannelPositionConfig;
use App\Services\CashService;
use App\Util;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;


class ExemptReview extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'exempt_review';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '提现免审--定时扫表订单';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {

        $open=(int)SystemStatusInfo::OnlyGetCacheValue(SystemStatusInfo::$KEY_WithDrawSwitch);
        if(!$open)return;

        $WithdrawalModel = new Withdrawal();
        $OrderWithDraw = DB::connection('write')->table('QPAccountsDB.dbo.OrderWithDraw')->where('State', 1)
                           ->whereRaw('locking = 0')->orderBy('CreateDate', 'desc')->get();

        foreach ($OrderWithDraw as $value) {
            if ($value->State != 1) {
                continue;
            }
            // 验证免审条件
            $verifyRes = (new \App\Services\Withdrawal())->configVerify($value->UserID, $value->WithDraw,
                                                                        $value->OrderId);
            if (!$verifyRes) {
                continue;
            }
            //防止刷子补充
            $AccountsInfoModel = new AccountsInfo();

            //            $mailNums=DB::table(TableName::QPAccountsDB() . 'OrderWithDraw')
            //                        ->selectRaw('count(distinct (UserID)) as nums')
            //                        ->where("EmailAddress",$value->EmailAddress)
            //                        ->first();
            $sameCountCheck = 1;
            $sameCountCheckIP = 1;

            if ($verifyRes == 4) {
                $sameCountCheck = 2;
                $sameCountCheckIP = 3;
            } elseif ($verifyRes == 5) {
                $sameCountCheck = 10;
                $sameCountCheckIP = 200;
            } elseif ($verifyRes == 2) {
                $sameCountCheck = 3;
                $sameCountCheckIP = 100;
            } elseif ($verifyRes == 3) {
                $sameCountCheck = 3;
                $sameCountCheckIP = 100;
            }

            if($verifyRes==1||$verifyRes==9){
                Log::info('首次审核阻拦自动免审:'.$value->OrderId);
                continue;
            }
            if ($AccountsInfoModel->sameWithDrawEmail($value->EmailAddress) > $sameCountCheck) {
                Log::info('EMAIL重复过多阻拦自动免审:'.$value->OrderId.":::".$value->EmailAddress);
                continue;
            }

            //            $nameNums=DB::table(TableName::QPAccountsDB() . 'OrderWithDraw')
            //              ->selectRaw('count(distinct (UserID)) as nums')
            //              ->where("EmailAddress",$value->BankUserName)
            //              ->first();


            //            if($AccountsInfoModel->sameWithDrawBankName($value->BankUserName)>4){
            //                Log::info('名字重复过多阻拦自动免审:'.$value->OrderId.":::".$value->BankUserName);
            //                continue;
            //            }

            if ($AccountsInfoModel->sameRegisterIPCountByUserID($value->UserID) > $sameCountCheckIP) {
                Log::info('注册IP重复过多阻拦自动免审:'.$value->OrderId);
                continue;
            }

            if ($AccountsInfoModel->sameLoginIPCount($value->UserID) > $sameCountCheckIP) {
                Log::info('登录IP重复过多阻拦自动免审:'.$value->OrderId);
                continue;
            }
            if ($AccountsInfoModel->sameLoginMacCount($value->UserID) > $sameCountCheck) {
                Log::info('MAC地址码重复阻拦自动免审:'.$value->OrderId);
                continue;
            }
            if(Cpf::getCpfCount($value->UserID)>$sameCountCheck){
                Log::info("CPF重复阻拦自动免审:".$value->OrderId);
                continue;
            }
            // 读取免审配置
            $config = DB::table(TableName::agent().'withdrawal_position_config')->where('status', 1)->first();
            if ($config) {

                $agent = $config->agent;
                if (empty($agent)) { // 默认第一家
                    $agent = DB::connection('write')->table('agent.dbo.admin_configs')->where('config_value', 1)
                               ->where('type', 'cash')->where('status', 1)->first()->config_value;
                }

                // 验证用户提现方式
                $verifyAccountWithdrawal = $WithdrawalModel->AccountWithDrawInfo($value->UserID, $agent);
                if (!$verifyAccountWithdrawal) {
                    Log::info('不支持的提现格式'.$value->OrderId);
                    continue;
                }

                $redis = Redis::connection();
                $order_sn = $value->OrderId;
                if ($redis->exists($order_sn.'key1')) {
                    continue;
                }

                $redis->set($order_sn.'key1', $order_sn, 3600 * 24);
                $log = ['user_id'   => $value->UserID,
                        'config_id' => $config->id,
                        'use_quota' => $value->WithDraw,
                        'order_sn'  => $value->OrderId];
                DB::connection('write')->table('agent.dbo.withdrawal_position_log')
                  ->updateOrInsert(['order_sn' => $value->OrderId], $log);
                $state = 5;
                $RecordData = ['admin_id'     => 0,
                               'before_state' => 1,
                               'after_state'  => $state,
                               'RecordID'     => $value->RecordID,
                               'create_at'    => date('Y-m-d H:i:s'),
                               'update_at'    => date('Y-m-d H:i:s')];

                !empty($data['remarks']) && $RecordData['remarks'] = $data['remarks'];
                // 添加用户提现操作记录
                DB::connection('write')->table('QPAccountsDB.dbo.AccountsRecord')
                  ->updateOrInsert(['RecordID' => $value->RecordID, 'type' => 1], $RecordData);
                $RecordID = $value->RecordID;
                $amount = $value->WithDraw;
                $accountName = $value->BankUserName;
                $email = $value->EmailAddress;
                $phone = $value->PhoneNumber;
                $PixNum = $value->PixNum;
                $PixType = $value->PixType;
                $OrderId = $value->OrderId;
                $IFSCNumber = $value->IFSCNumber;
                $BranchBank = $value->BranchBank;
                $BankNO = $value->BankNO;
                // 改变状态处理中
                $agentID = DB::connection('write')->table('agent.dbo.admin_configs')->where('config_value', $agent)
                             ->select('id')->first()->id ?? '';

                DB::connection('write')->table('QPAccountsDB.dbo.OrderWithDraw')->where('OrderId', $OrderId)
                  ->update(['State' => $state, 'agent' => $agentID]);

                Log::info('自动免审:'.$OrderId.'--'.$agentID);

                $service = CashService::payment($agent);
                $result = $service->payment($RecordID, $amount, $accountName, $phone, $email, $OrderId, $PixNum,
                                            $PixType, $IFSCNumber, $BranchBank, $BankNO);
                if ($result === 'fail') {
                    Log::info('免审提现失败：'.$value->OrderId);
                }
            }
        }
    }
}
