<?php

namespace Modules\User\Http\Controllers\Api\Auth;

use App\Api\Controllers\Controller;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Arr;
use Jason\Api\Api;
use Modules\User\Events\UserLoginSuccess;
use Modules\User\Facades\Sms;
use Modules\User\Http\Requests\LoginSmsRequest;
use Modules\User\Http\Requests\SmsRequest;
use Modules\User\Models\User;
use Vinkla\Hashids\Facades\Hashids;

class SmsController extends Controller
{

    /**
     * Notes   : 获取登录短信验证码
     *
     * @Date   : 2021/5/26 4:59 下午
     * @Author : <Jason.C>
     * @param  SmsRequest  $request
     * @return JsonResponse
     */
    public function send(SmsRequest $request): JsonResponse
    {
        $mobile = $request->mobileNo;

        try {
            Sms::sendVerificationCode($mobile);
            $isExists = User::where('username', $mobile)->exists();
            if (Arr::get(Sms::getConfig(), 'debug')) {
                $message = '短信发送成功，测试短信码'.Arr::get(Sms::getConfig(), 'debug_code');
            } else {
                $message = '短信发送成功';
            }
            return $this->success([
                'new'     => ! $isExists,
                'message' => $message,
            ]);
        } catch (Exception $exception) {
            return $this->failed($exception->getException('aliyun')->getMessage());
        }
    }

    /**
     * Notes   : 短信验证码登录
     *
     * @Date   : 2021/7/20 10:15 上午
     * @Author : <Jason.C>
     * @param  LoginSmsRequest  $request
     * @return JsonResponse
     */
    public function login(LoginSmsRequest $request): JsonResponse
    {
        $mobileNo    = $request->mobileNo;
        $code        = $request->code;
        $invite_code = $request->invite ?? '';
        $parent      = 0;

        if ($invite_code) {
            $invite = Hashids::connection('code')->decode($invite_code);

            if (empty($invite)) {
                return $this->failed('邀请码不正确');
            }
            $parent     = $invite[0];
            $parentUser = User::find($parent);

            //普通用户无法分享
            if ($parentUser && $parentUser->identityFirst()->id == 1) {
                $parent = 0;
            }
        }

        $check = Sms::checkCode($mobileNo, $code);
        if ($check == false) {
            return $this->failed('验证码不正确', 422);
        }
        $user = User::firstOrCreate([
            'username' => $mobileNo,
        ], [
            'parent_id' => $parent,
            'password'  => 111111,
        ]);

        $is_new = $user->wasRecentlyCreated;

        $message = '';
        if ($is_new) {
            if ($user->parent && $parent && $user->parent->id != $parent) {
                $message = "您已与用户{$user->parent->info->nickname}绑定隶属关系，此次邀请码无效";
            }
        }

        $token = Api::login($user);

        event(new UserLoginSuccess($user, $request, '手机验证码'));

        return $this->success([
            'token_type'   => 'Bearer',
            'access_token' => $token,
            'message'      => $message,
            'is_new'       => $is_new,
        ]);
    }

}
