<?php


namespace App\Http\Controllers\Api;

use App\Facade\RedisConnect;
use App\Facade\TableName;
use App\Http\logic\api\ExtensionLogic;
use App\Models\GamePhoneVerityCode;
use App\Services\StoredProcedure;
use App\Util;
use App\Utility\SetNXLock;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use function Composer\Autoload\includeFile;

class RegisterController
{
    protected $InsurePass = '111111';
    protected $MachineID = 'Web';
    protected $Type = 2;


    // 注册逻辑
    public function index(Request $request)
    {
        return apiReturnFail(__('messages.api.register.multiple_accounts_ip'));
        Util::WriteLog('login_header',$request->header());
        $post = $request->post();
        extract($post);

        $Phone = $phoneNum ?? $Phone ?? '';
        if (empty($Phone)) {
            return apiReturnFail(__('messages.api.register.phone_empty'));
        }
        if (mb_strlen($PhoneCode) > 6) {
            return apiReturnFail(__('messages.api.register.phone_code_too_long'));
        }
        $Accounts = (string)$this->randAccounts();
        $FaceI = (int)mt_rand(1, 16);
        $Gender = (int)mt_rand(0, 1);
        $ip = (string)$request->ip();
        $SpreadID = (int)$SpreadID;
        $Phone = trim($Phone);
        Log::info('注册开始' . $Phone);
        $redisKey = 'register_'.$Phone;
        if (!SetNXLock::getExclusiveLock($redisKey)) {
            return apiReturnFail(__('messages.api.withdraw_info.try_again_later'));
        }


        // 查看手机号是否已经绑定
        $first = DB::connection('write')->table('QPAccountsDB.dbo.AccountPhone')
            ->where('PhoneNum', $Phone)
            ->first();

        if ($first) {
            SetNXLock::release($redisKey);
            return apiReturnFail(__('messages.api.register.phone_already_bound')); // 电话号码已绑定
        }

        if (!is_numeric($PhoneCode)) {
            SetNXLock::release($redisKey);
            return apiReturnFail(__('messages.api.register.code_incorrect'));
        }

        $verifyCode = GamePhoneVerityCode::verifyCode($Phone, $PhoneCode);
        if ($verifyCode != trim($PhoneCode)) {
            SetNXLock::release($redisKey);
            return apiReturnFail(__('messages.api.register.code_incorrect'));
        }


        $AccountsInfo = DB::connection('write')->table('QPAccountsDB.dbo.AccountsInfo')
            ->where('GameID', $SpreadID)
            ->select('Channel', 'UserID')
            ->first();
        if (!$AccountsInfo) {
            SetNXLock::release($redisKey);
            return apiReturnFail(__('messages.api.register.parent_id_not_exist')); // 上级ID不存在
        }

        // 官网包固定渠道号100
        $Channel = env('REGION_24680_DEFAULT_CHANNEL',99);
        $PackageName = 'com.ouro777.online';


        $res = StoredProcedure::ALLRegisterAccounts(
            $Accounts,
            '1',
            $SpreadID,
            $Password,
            $this->InsurePass,
            $FaceI,
            $Gender,
            1,
            $Phone,
            $ip,
            $this->MachineID,
            $this->Type,
            $Channel,
            $PackageName
        );


        $ReturnValue = $res['ReturnValue'] ?? 0;
        Log::info('注册结果  ' . $ReturnValue);
        $message = '';
        if ($ReturnValue > 0) {
            switch ($ReturnValue) {
                case 1: # 注册暂停
                    $message = 'Registro suspenso';
                    break;
                case 2: # 登录暂停
                    $message = 'Pausa de login';
                    break;
                case 8: # 帐号已存在，请换另一帐号名字尝试再次注册！
                    $message = 'A conta já existe, altere outro nome de conta e tente se registrar novamente!';
                    break;
                case 10: # IP最大注册数量
                    $message = __('messages.api.register.multiple_accounts_ip');
                    break;
            }
        }


        if (!empty($message)) {
            SetNXLock::release($redisKey);
            return apiReturnFail($message);
        }
        //Log::info('注册成功，绑定手机号' . $Phone . '-' . $Password . '-' . $res['UserID']);
        // 绑定手机号
        //StoredProcedure::bindSms($Phone, $Password, $res['UserID']);


        // 裂变开始
        $UserID = $res['UserID'] ?? 0;
        (new ExtensionLogic())->userProfit($UserID);

        // 插入裂变表数据
        DB::table(TableName::QPAccountsDB().'FissionUser')
            ->insert([
                'UserID' => $UserID,
                'Channel' => $Channel,
                'HigherChannel' => $AccountsInfo->Channel,
                'SpreadID' => $AccountsInfo->UserID,
                'CreateTime' => now()
            ]);
        // $redis = new RedisConnect();
        // $redis->redis()->zincrby('Channel_Fissile_'.date('Ymd'),1,$AccountsInfo->Channel);
        SetNXLock::release($redisKey);
        // 注册成功
        return apiReturnSuc([], 'o login foi bem sucedido', 'o login foi bem sucedido');
    }

    // 加载注册页面
    public function registerView()
    {
        $info = DB::connection('write')->table('QPAccountsDB.dbo.SystemStatusInfo')
            ->where('StatusName', 'WhatsApp')
            ->first();
        return view('api.register.register', compact('info'));
    }

    // 加载下载页面
    public function download()
    {
        return view('api.register.download');
    }


    // 随机账号
    public function randAccounts()
    {
        return substr(md5(uniqid(microtime(true), true)), 2);
    }

    public function customerService()
    {
        $info = DB::connection('write')->table('QPAccountsDB.dbo.SystemStatusInfo')
            ->where('StatusName', 'WhatsApp')
            ->first();
        return apiReturnSuc([
            'url' => $info->StatusString ?? ''
        ]);
    }
}
