<?php


namespace App\Http\Controllers\Api;


use App\Facade\TableName;
use App\Models\AccountsInfo;
use App\Util;
use App\Utility\SetNXLock;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class WithDrawInfoController
{

    public function withDrawInfo(Request $request)
    {

//        return apiReturnFail('params error');

        $UserID = $request->input('UserID');
        $RequestDynamicPass = $request->input('DynamicPass');
        $PixType = $request->input('cbPixType');
        $BankNO = $request->input('bank');
        $AccountsBank = urldecode($request->input('account'));
        $BankUserName = urldecode($request->input('userName'));
        $BankUserName=Util::filterNickName($BankUserName);
        $PhoneNumber = $request->input('phone');
        $EmailAddress = $request->input('email');
        $IFSCNumber = $request->input('IFSC');
        $PANNumber = $request->input('PAN');
        $AdhaarNumber = $request->input('adhaar');
        $BranchBank = $request->input('branceBank');
        $PixNum = $request->input('PixNum');
        $redisKey = 'withDrawInfo_withDrawInfo_'.$UserID;
        if (!SetNXLock::getExclusiveLock($redisKey)) {
            Util::WriteLog("withdrawInfo",[1, $request->all()]);
            return apiReturnFail(__('messages.api.withdraw_info.try_again_later'));
        }

        if (!$UserID) {
            Util::WriteLog("withdrawInfo",[2, $request->all()]);
            Log::info('miss UserID', $request->all());
            SetNXLock::release($redisKey);
            return apiReturnFail(__('messages.api.withdraw_info.params_error'));
        }
        if (empty($PixType)) {
            Util::WriteLog("withdrawInfo",[3, $request->all()]);
            SetNXLock::release($redisKey);
            return apiReturnFail(__('messages.api.withdraw_info.missing_pix_type'));
        }

        // 验证PixNum绑定次数
        if (!empty($PixNum)) {
            $BindCount = DB::table(TableName::QPRecordDB() . 'RecordBankCardBind')
                ->where('BankCard', $PixNum)
                ->lock('WITH(NOLOCK)')
                ->count();
            if ($BindCount >= 8) {
                Util::WriteLog("withdrawInfo",[4, $request->all()]);
                SetNXLock::release($redisKey);
                return apiReturnFail(['web.withdraw.cpf_number_used',__('messages.api.withdraw_info.cpf_number_used')], [], 302);
            }
        }

//        if(!is_numeric($PixNum)){
//            return apiReturnFail(['web.withdraw.pix_failed','The CPF number has been used several times and cannot be saved'], [], 302);
//        }
        // 验证玩家信息
        $DynamicPass = DB::table(TableName::QPAccountsDB() . 'AccountsInfo')
            ->where('UserID', $UserID)
            ->lock('WITH(NOLOCK)')
            ->value('DynamicPass');
        if ($DynamicPass != $RequestDynamicPass || empty($DynamicPass)) {
            SetNXLock::release($redisKey);
            Util::WriteLog("withdrawInfo",[5, $request->all()]);
            return apiReturnFail(__('messages.api.withdraw_info.player_info_inconsistent'));
        }

        if ($PixType < 10) {
            $data = compact('PixType', 'BankUserName', 'PhoneNumber', 'EmailAddress', 'PixNum');
        } else {
            $data = compact('PixType', 'BankNO', 'AccountsBank', 'IFSCNumber', 'PANNumber', 'AdhaarNumber', 'BranchBank');
            $PixNum = $BankNO;
        }

        foreach ($data as $key => &$val) {
            $data[$key] = trim($val);
        }
        unset($val);


        $AccountWithDrawInfo = DB::table(TableName::QPAccountsDB() . 'AccountWithDrawInfo')
            ->lock('WITH(NOLOCK)')
            ->where('UserID', $UserID)
            ->first();
        if (!$AccountWithDrawInfo) {
            $data['UserID'] = $UserID;
            $data['Achieves'] = 0;
            $data['HistoryWithDraw'] = 0;
            try {
                DB::table(TableName::QPAccountsDB() . 'AccountWithDrawInfo')
                    ->where('UserID', $UserID)
                    ->insert($data);
            } catch (\Exception $e) {
                    Log::error('insert AccountWithDrawInfo failed', ['data' => $data]);
                Util::WriteLog("withdrawInfo",[6, $request->all(),$data]);
            }

        } else {

            $data = array_filter($data, function ($value) {
                return !is_null($value) && $value !== '';
            });
            DB::table(TableName::QPAccountsDB() . 'AccountWithDrawInfo')
                ->where('UserID', $UserID)
                ->update($data);
        }

        // 添加绑定记录
        if (empty($AccountWithDrawInfo->PixNum) || $AccountWithDrawInfo->PixNum != $PixNum) {
            try {
                if(!DB::table(TableName::QPRecordDB() . 'RecordBankCardBind')->where('UserID', $UserID)->exists()&&is_numeric($PixNum)) {
                    DB::table(TableName::QPRecordDB() . 'RecordBankCardBind')
                        ->insert([
                            'UserID'   => $UserID,
                            'BankCard' => $PixNum ?: '',
                            'BindDate' => now()
                        ]);
                    Util::WriteLog('update_pix', [
                        'UserID'   => $UserID,
                        'BankCard' => $PixNum ?: '',
                        'BindDate' => now()
                    ]);
                }
            } catch (\Exception $e) {
                Log::error('insert RecordBankCardBind failed', ['data' => $data]);
                Util::WriteLog("withdrawInfo",[7, $request->all(),$data]);
            }

        }
        SetNXLock::release($redisKey);
        return apiReturnSuc();
    }

    public function withDrawInfoPK(Request $request)
    {

//        return apiReturnFail('params error');

        $UserID = $request->input('UserID');
        $RequestDynamicPass = $request->input('DynamicPass');
        $PixType = $request->input('cbPixType');

        $AccountsBank = urldecode($request->input('account'));
        $BankUserName = urldecode($request->input('userName'));
        $BankUserName=Util::filterNickName($BankUserName);

        $PhoneNumber = $request->input('phone');
        $EmailAddress = $request->input('email');

        $PixNum = $request->input('PixNum');
        $redisKey = 'withDrawInfo_withDrawInfo_'.$UserID;
        if (!SetNXLock::getExclusiveLock($redisKey)) {
            Util::WriteLog("withdrawInfo",[1, $request->all()]);
            return apiReturnFail(__('messages.api.withdraw_info.try_again_later'));
        }

        if (!$UserID) {
            Util::WriteLog("withdrawInfo",[2, $request->all()]);
            Log::info('miss UserID', $request->all());
            SetNXLock::release($redisKey);
            return apiReturnFail(__('messages.api.withdraw_info.params_error'));
        }
        if (empty($PixType)) {
            Util::WriteLog("withdrawInfo",[3, $request->all()]);
            SetNXLock::release($redisKey);
            return apiReturnFail(__('messages.api.withdraw_info.missing_pix_type'));
        }

        // 验证PixNum绑定次数
        if (!empty($PixNum)) {
            $BindCount = DB::table(TableName::QPRecordDB() . 'RecordBankCardBind')
                ->where('BankCard', $PixNum)
                ->lock('WITH(NOLOCK)')
                ->count();
            if ($BindCount >= 8) {
                Util::WriteLog("withdrawInfo",[4, $request->all()]);
                SetNXLock::release($redisKey);
                return apiReturnFail(['web.withdraw.cpf_number_used',__('messages.api.withdraw_info.cpf_number_used')], [], 302);
            }
        }

//        if(!is_numeric($PixNum)){
//            return apiReturnFail(['web.withdraw.pix_failed','The CPF number has been used several times and cannot be saved'], [], 302);
//        }
        // 验证玩家信息
        $DynamicPass = DB::table(TableName::QPAccountsDB() . 'AccountsInfo')
            ->where('UserID', $UserID)
            ->lock('WITH(NOLOCK)')
            ->value('DynamicPass');
        if ($DynamicPass != $RequestDynamicPass || empty($DynamicPass)) {
            SetNXLock::release($redisKey);
            Util::WriteLog("withdrawInfo",[5, $request->all()]);
            return apiReturnFail(__('messages.api.withdraw_info.player_info_inconsistent'));
        }

        $data = compact('PixType', 'BankUserName', 'PhoneNumber', 'EmailAddress', 'PixNum');

        foreach ($data as $key => &$val) {
            $data[$key] = trim($val);
        }
        unset($val);


        $AccountWithDrawInfo = DB::table(TableName::QPAccountsDB() . 'AccountWithDrawInfo')
            ->lock('WITH(NOLOCK)')
            ->where('UserID', $UserID)
            ->first();
        if (!$AccountWithDrawInfo) {
            $data['UserID'] = $UserID;
            $data['Achieves'] = 0;
            $data['HistoryWithDraw'] = 0;
            try {
                DB::table(TableName::QPAccountsDB() . 'AccountWithDrawInfo')
                    ->where('UserID', $UserID)
                    ->insert($data);
            } catch (\Exception $e) {
                    Log::error('insert AccountWithDrawInfo failed', ['data' => $data]);
                Util::WriteLog("withdrawInfo",[6, $request->all(),$data]);
            }

        } else {

            $data = array_filter($data, function ($value) {
                return !is_null($value) && $value !== '';
            });
            DB::table(TableName::QPAccountsDB() . 'AccountWithDrawInfo')
                ->where('UserID', $UserID)
                ->update($data);
        }

        // 添加绑定记录
        if (empty($AccountWithDrawInfo->PixNum) || $AccountWithDrawInfo->PixNum != $PixNum) {
            try {
                if(!DB::table(TableName::QPRecordDB() . 'RecordBankCardBind')->where('UserID', $UserID)->exists()&&is_numeric($PixNum)) {
                    DB::table(TableName::QPRecordDB() . 'RecordBankCardBind')
                        ->insert([
                            'UserID'   => $UserID,
                            'BankCard' => $PixNum ?: '',
                            'BindDate' => now()
                        ]);
                    Util::WriteLog('update_pix', [
                        'UserID'   => $UserID,
                        'BankCard' => $PixNum ?: '',
                        'BindDate' => now()
                    ]);
                }
            } catch (\Exception $e) {
                Log::error('insert RecordBankCardBind failed', ['data' => $data]);
                Util::WriteLog("withdrawInfo",[7, $request->all(),$data]);
            }

        }
        SetNXLock::release($redisKey);
        return apiReturnSuc();
    }

    public function withDrawInfoSA(Request $request)
    {

//        return apiReturnFail('params error');

        $UserID = $request->input('UserID');
        $RequestDynamicPass = $request->input('DynamicPass');
        $PixType = $request->input('cbPixType');
        $BankNO = $request->input('bank');
        $AccountsBank = urldecode($request->input('account'));
        $BankUserName = urldecode($request->input('userName'));
        // 原始代码
        $BankUserName = Util::filterNickName($BankUserName);

        // 新增处理：在大写字母前加空格
        $BankUserName = preg_replace('/(?<!^)([A-Z])/', ' $1', $BankUserName);

        $PhoneNumber = $request->input('phone');
        $EmailAddress = $request->input('email');
        $IFSCNumber = $request->input('IFSC');
        $PANNumber = $request->input('PAN');
        $AdhaarNumber = $request->input('adhaar');
        $BranchBank = $request->input('branceBank');
        $PixNum = $request->input('PixNum');
        $redisKey = 'withDrawInfo_withDrawInfo_'.$UserID;
        if (!SetNXLock::getExclusiveLock($redisKey)) {
            Util::WriteLog("withdrawInfo",[1, $request->all()]);
            return apiReturnFail(__('messages.api.withdraw_info.try_again_later'));
        }

        if (!$UserID) {
            Util::WriteLog("withdrawInfo",[2, $request->all()]);
            Log::info('miss UserID', $request->all());
            SetNXLock::release($redisKey);
            return apiReturnFail(__('messages.api.withdraw_info.params_error'));
        }
        if (empty($PixType)) {
            Util::WriteLog("withdrawInfo",[3, $request->all()]);
            SetNXLock::release($redisKey);
            return apiReturnFail(__('messages.api.withdraw_info.missing_pix_type'));
        }

//        Util::validateSouthAmericanPhone('',)

        // 验证PixNum绑定次数
        if (!empty($PixNum)) {
            $BindCount = DB::table(TableName::QPRecordDB() . 'RecordBankCardBind')
                ->where('BankCard', $PixNum)
                ->lock('WITH(NOLOCK)')
                ->count();
            if ($BindCount >= 8) {
                Util::WriteLog("withdrawInfo",[4, $request->all()]);
                SetNXLock::release($redisKey);
                return apiReturnFail(['web.withdraw.cpf_number_used',__('messages.api.withdraw_info.cpf_number_used')], [], 302);
            }
        }

//        if(!is_numeric($PixNum)){
//            return apiReturnFail(['web.withdraw.pix_failed','The CPF number has been used several times and cannot be saved'], [], 302);
//        }
        // 验证玩家信息
        $DynamicPass = DB::table(TableName::QPAccountsDB() . 'AccountsInfo')
            ->where('UserID', $UserID)
            ->lock('WITH(NOLOCK)')
            ->value('DynamicPass');
        if ($DynamicPass != $RequestDynamicPass || empty($DynamicPass)) {
            SetNXLock::release($redisKey);
            Util::WriteLog("withdrawInfo",[5, $request->all()]);
            return apiReturnFail(__('messages.api.withdraw_info.player_info_inconsistent'));
        }
        $data = compact('PixType', 'BankUserName', 'PhoneNumber', 'EmailAddress', 'PixNum','BankNO', 'AccountsBank', 'IFSCNumber', 'PANNumber', 'AdhaarNumber', 'BranchBank');


        foreach ($data as $key => &$val) {
            $data[$key] = trim($val);
        }
        unset($val);


        $AccountWithDrawInfo = DB::table(TableName::QPAccountsDB() . 'AccountWithDrawInfo')
            ->lock('WITH(NOLOCK)')
            ->where('UserID', $UserID)
            ->first();
        if (!$AccountWithDrawInfo) {
            $data['UserID'] = $UserID;
            $data['Achieves'] = 0;
            $data['HistoryWithDraw'] = 0;
            try {
                DB::table(TableName::QPAccountsDB() . 'AccountWithDrawInfo')
                    ->where('UserID', $UserID)
                    ->insert($data);
            } catch (\Exception $e) {
                    Log::error('insert AccountWithDrawInfo failed', ['data' => $data]);
                Util::WriteLog("withdrawInfo",[6, $request->all(),$data]);
            }

        } else {

            $data = array_filter($data, function ($value) {
                return !is_null($value) && $value !== '';
            });
            DB::table(TableName::QPAccountsDB() . 'AccountWithDrawInfo')
                ->where('UserID', $UserID)
                ->update($data);
        }

        // 添加绑定记录
        if (empty($AccountWithDrawInfo->PixNum) || $AccountWithDrawInfo->PixNum != $PixNum) {
            try {
                if(!DB::table(TableName::QPRecordDB() . 'RecordBankCardBind')->where('UserID', $UserID)->exists()&&is_numeric($PixNum)) {
                    DB::table(TableName::QPRecordDB() . 'RecordBankCardBind')
                        ->insert([
                            'UserID'   => $UserID,
                            'BankCard' => $PixNum ?? '',
                            'BindDate' => now()
                        ]);
                    Util::WriteLog('update_pix', [
                        'UserID'   => $UserID,
                        'BankCard' => $PixNum ?? '',
                        'BindDate' => now()
                    ]);
                }
            } catch (\Exception $e) {
                Log::error('insert RecordBankCardBind failed', ['data' => $data]);
                Util::WriteLog("withdrawInfo",[7, $request->all(),$data]);
            }

        }
        SetNXLock::release($redisKey);
        return apiReturnSuc();
    }

    // 获取提现信息
    public function getWithDrawInfo(Request $request)
    {
        $UserID = $request->input('UserID');
        $RequestDynamicPass = $request->input('DynamicPass');
        if(strstr("&",$UserID)){
            Util::WriteLog("urlError",$request->header());
            parse_str('UserID='.$UserID,$params);
            $UserID=$params['UserID'];
            $RequestDynamicPass=$params['DynamicPass'];
        }


        // 验证玩家信息
        $DynamicPass = DB::table(TableName::QPAccountsDB() . 'AccountsInfo')
            ->where('UserID', $UserID)
            ->lock('WITH(NOLOCK)')
            ->value('DynamicPass');
        if ($DynamicPass != $RequestDynamicPass || empty($DynamicPass)) return apiReturnFail(__('messages.api.withdraw_info.player_info_inconsistent'));

        $info = DB::table(TableName::QPAccountsDB() . 'AccountWithDrawInfo')
            ->where('UserID', $UserID)
            ->lock('WITH(NOLOCK)')
            ->first();
        $info=(array)$info;
        if (!$info) {   // 赋值 -- 避免客户端报错
            $info = [
                'BankNO' => '',
                'AccountsBank' => '',
                'BankUserName' => '',
                'PhoneNumber' => '',
                'IFSCNumber' => '',
                'EmailAddress' => '',
                'Achieves' => '',
                'PANNumber' => '',
                'AdhaarNumber' => '',
                'BranchBank' => '',
                'PixNum' => '',
                'PixType' => '',
            ];
        }
        $AccountsInfoModel = new AccountsInfo();
        $total = $AccountsInfoModel->accountTotalStatistics([$UserID]);
        $totalRecharge = @$total[0]->Recharge ?? 0;

        $info['total_recharge'] = intval($totalRecharge);
        $info['withdraw_level'] = env('MIN_RECHARGE',20);
        return apiReturnSuc(compact('info'));
    }
}
