<?php

namespace App\Http\Middleware;

use App\Http\Response\ResponseJson;
use App\Models\Message;
use Closure;
use Illuminate\Http\Request;

class CheckeGainMobileCode
{
    use ResponseJson;
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        $mobile = $request->input('mobile');
        if (empty($mobile)) return $this->failure("请输入手机号");
        //手机号格式正则 todo
        
        if (config('app.env') == 'production') {
            //获取验证码时长
            $checked_at = date('Y-m-d H:i:s', strtotime('-1 minute'));
            $res = Message::where('mobile', $mobile)->where('confirmed', 0)->where('created_at', '>',  $checked_at)->orderBy('id', 'desc')->value('created_at');
         
            if ($res) return $this->failure("操作频繁，等待一分钟");
        }
        return $next($request);
    }
}
