<?php


namespace App\Http\Controllers\Game;


use App\Facade\TableName;
use App\Game\GlobalUserInfo;
use App\Game\Logics\SendCodeLogic;
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;

class SendCodeController
{
    protected $CodeType = [1 => 3, 3 => 1];

    // 天一宏+Kmi 短信发送
    public function send(Request $request)
    {

        $FPID=$request->input("bfp","");
        $Channel=$request->input("c",99);
        $UserID=0;

        $phone = $request->Phone ?: '';

        if (!is_numeric($phone)) {
            return apiReturnFail(['web.user.phone_fail', 'Not correct phone number'], '', 422);
        }

        $LocationCode = $request->country ?? env('COUNTRY_CODE',55);

        $user=$request->user();
        if($user){
            $UserID = $user->UserID;
            $Channel=$user->Channel;
        }

        $Type = $request->Type ?: 0;    // 标识 1找回密码
        $ip = $request->ip();


        $WebRegister = $request->WebRegister ?: 0;
        // 并发限制
        $res = Redis::setnx('SendCodeController' . $FPID, 1);
        if (!$res) {
            return apiReturnFail(['web.verify.sms_too_many','Você enviou muitas mensagens de texto e foi impedido de enviar']);
        }
        Redis::expire('SendCodeController' . $FPID, 30);



        // 并发限制
//        $res = Redis::setnx('SendCodeController' . $phone, 1);
//        if (!$res) {
//            return apiReturnFail(['web.verify.sms_too_many','Você enviou muitas mensagens de texto e foi impedido de enviar']);
//        }
//        Redis::expire('SendCodeController' . $phone, 30);


        $phone=$LocationCode.$phone;
        Log::info('接收客户端发送验证码手机号：'.$phone.' Type类型：'.$Type.' 用户ID：'.$UserID.' WebRegister：'.$WebRegister);
        $SendCodeConfig = DB::connection('read')->table('QPAccountsDB.dbo.SysSmsConfig')
            ->where('Status', 1)
            ->get();

        //默认
        $SendCodeConfigType = rand(0,100)>50?3:1;

        $SendCodeConfigType=1;
        if ($SendCodeConfig->count() > 1) {

            $redis_key=$phone."_".$Channel;
            if (Redis::exists($redis_key)) {
                $currentCodeType = (int)Redis::get($redis_key);
                if($currentCodeType==100){
                    //两个通道都发了，不能再发了
//                    return apiReturnFail(['web.verify.no_wrong_later','Your number is incorrect or temporarily unavailable, please try again later']);
                    $currentCodeType=1;
                }
                $SendCodeConfigType = $this->CodeType[$currentCodeType];
//                Redis::set($redis_key, $this->CodeType[$currentCodeType]);
                Redis::set($redis_key, $SendCodeConfigType);
                Redis::expire($redis_key, 3600);
                Log::info('补发验证码通道：'.$SendCodeConfigType);
                Util::WriteLog('phone_error',$phone);
            } else {
                // 默认 codeType 1 天一泓短信
                // 默认 codeType 3 plants
                Redis::set($redis_key, $SendCodeConfigType);
                Redis::expire($redis_key, 3600);
            }
        } else {
            $SendCodeConfigType = (int)$SendCodeConfig->where('Status', 1)->first()->Type ?? 1;
        }
//        $SendCodeConfigType = 1;
//        $redis->get(self::PHONE_SEND_LASTCONFIG_PREFIX . $phone);
        Log::info('发送验证码渠道：'.$SendCodeConfigType);
        $logic = new SendCodeLogic();
        if ($logic->sendVerify(trim($phone), $ip, $Type) === false) {
            return apiReturnFail($logic->getError());
        }

        Log::info('验证手机号通过'.$phone);
        // 网页注册限制注册IP
//        if ($WebRegister == 1) {
//            $webRegisterIPLimit = (new WebRegister())->ipLimit($ip);
//            if (!$webRegisterIPLimit) {
//                return apiReturnFail('Seu dispositivo foi registrado muitas vezes e o registro é proibido');
//            }
//        }
        $lang=[
            'en'=>'Hello, {{code}} (OTP) for your mobile verification',
            'pt'=>'Olá, {{code}} (OTP) para sua verificação de celular',
            'es'=>'Hola, {{code}} (OTP) para tu verificación móvil ',
            'ru'=>'ривет, {{code}} (OTP) для проверки вашего мобильного телефона',
//            'zh'=>'您好，{{code}} (OTP)，您的手機驗證碼 24680com',
        ];
        $Content = $lang['en'];
        $locale=GlobalUserInfo::getLocale();
        if($locale&&isset($lang[$locale])){
            $Content=$lang[$locale];
        }
//        $Content = 'Hola, Código {{code}} para su verificación móvil Slotomania';
//        $Services = new SendCode();
        $res=apiReturnSuc();
        if($SendCodeConfigType==3){

            if ($logic->send($phone, $ip, $UserID,$Content) === false) {
                $res= apiReturnFail($logic->getError());
            }
        }else{

            if ($logic->plants_send($phone, $ip, $UserID,$Content) === false) {
                $res= apiReturnFail($logic->getError());
            }
        }

//        $res = $Services->sendCode($SendCodeConfigType)->send($phone, $ip, $UserID, $Content);

        $query = DB::table(TableName::QPTreasureDB() . 'GamePhoneVerityCode')
            ->where('PhoneNum', $phone)
            ->select('PhoneNum', 'Code')
            ->first();
        $res['data']['cccc']=$query->Code??"";
        $failmsg='Você enviou muitas mensagens de texto e foi impedido de enviar';
        if($res['msg']==$failmsg){
            return apiReturnFail(['web.verify.sms_too_many',$failmsg]);
        }

        return $res;
    }


    public function notify(Request $request)
    {
        $sendResult = $request->sendResult ?: '';
        $to = $request->to ?: '';

        if ($sendResult == 'SUCCESS') {
            Log::info('发送验证码回调：发送成功' . $to);
        }
        Log::info('发送验证码回调：发送失败' . $to);
        return 'SUCCESS';
    }

    // 验证码
    public function send_verify(Request $request)
    {
        $phone = $request->phoneNum ?: '';
        $Type = $request->Type ?: 0;    // 标识 1找回密码
        $ip = $request->ip();
        $logic = new SendCodeLogic();


        if ($logic->sendVerify(trim($phone), $ip, $Type) === false) {
            return apiReturnFail($logic->getError());
        }

        return apiReturnSuc();
    }

    public function getCode(Request $request){
        $phone = $request->PhoneNum;
        $query = DB::table(TableName::QPTreasureDB() . 'GamePhoneVerityCode')
            ->where('PhoneNum', $phone)
            ->select('PhoneNum', 'Code')
            ->first();
        if($request->formart){
            return apiReturnSuc(['code' => $query?$query->Code:0]);
        }
        return $query?$query->Code:0;
    }
}
