<?php

namespace App\Http\Middleware;

use App\Facades\CommonService;
use App\Http\Response\ResponseJson;
use App\Models\Message;
use App\Models\User;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CheckInputUserInfo
{
    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)
    {
        DB::beginTransaction();
        $mobile = $request->input('mobile');
        if ($mobile) {
            $result = CommonService::isMobile($mobile);
            if (!$result) return $this->failure("请输入正确的手机号格式");
            //是否其他账户已存在手机号
//            $is_exists = User::where("id", '<>', auth()->id())->where('mobile', $mobile)->exists();
//            if ($is_exists) return $this->failure("手机号已存在账号");
            $code = $request->input('code');
            $type = $request->input('type');
            if ($type == 'code') {
                if (empty($code)) return $this->failure("请输入验证码");
                $res = Message::checkCode($mobile, $code);
                if (empty($res)) return $this->failure("验证码错误");
            }
            return $next($request);
        }
        //头像
        $avatar = $request->input('avatar');
        if ($avatar && !is_string($avatar)) return $this->failure("请输入正确的头像格式");
        //名称
        $name = $request->input("name");
        if ($name && (!is_string($name) || mb_strlen($name) > 12)) return $this->failure("请输入正确的头像格式");
        //性别
        $sex = $request->input("sex");
        if ($sex && !in_array($sex, [1,2])) return $this->failure("请输入正确的性别格式");
        //生日
        $birthday = $request->input("birthday");
        if ($birthday) {
            $result = CommonService::isBirthday($birthday);
            if (!$result) return $this->failure("请输入正确的生日格式");
        }
        //身高
        $stature = $request->input('stature');
        if ($stature && (!is_numeric($stature) || ($stature < 80 || $stature > 240))) return $this->failure("请输入正确的身高格式");
        return $next($request);
    }
}
