<?php

namespace App\Http\Controllers\V1;

use App\Models\User;
use App\Services\Api\ErrorMsgServive;
use App\Services\SmsServer;
use Illuminate\Http\Request;
use libphonenumber\PhoneNumberUtil;

class SmsController extends Controller
{
    //发送短信验证码
    public function send(Request $request)
    {
        $checkResult = $this->checkMobile($request->mobile);

        if ($checkResult['prefix'] == '-1') { //手机号不合法
            return $this->error('手机号不合法');
        }
        $request->event = $request->event ?: 'login';
        if ($request->event == "forget") {
            if (!User::where(['mobile' => $request->mobile])->first()) {
                return $this->error('手机号未注册');
            }
        }
        $prefix = $checkResult['prefix'];
        $result = SmsServer::send($request->mobile, $request->event, $prefix);
        if (isset($result['error'])) {
            return $this->error('短信发送失败');
        }
        $data = [
            'smsCode' => $result['smsCode'], //注意：实际不适合把验证码返回，主要是开发方便测试，生产环境请变为 ""
        ];
        return $this->success($data);
    }


    /**
     * @param $mobile
     * @return array
     * 验证手机号是否合法（支持全球手机号验证）$phoneUtil->parse($mobile, "CN")，两个参数：（要验证的手机号，国家区号）
     * 国际区号映射关系在 vendor\giggsey\libphonenumber-for-php\src\CountryCodeToRegionCodeMap.php
     * 可以 在 PhoneNumberUtil::getInstance() 方法中 点击 CountryCodeToRegionCodeMap::$countryCodeToRegionCodeMap 跳过去
     */
    public static function checkMobile($mobile)
    {
        $phoneUtil = PhoneNumberUtil::getInstance();
        try {
            $cnNumberProto = $phoneUtil->parse($mobile, "CN"); //大陆
            $prefix = '-1';
            if ($isValid_CN = $phoneUtil->isValidNumber($cnNumberProto)) {
                $prefix = '86';
            }
            $checkResult = [
                'prefix' => $prefix
            ];
            return $checkResult;
        } catch (\libphonenumber\NumberParseException $exception) {
            ErrorMsgServive::write($exception, request()->url());
        }
    }

}
