<?php
// +----------------------------------------------------------------------
// | onezan-admin 快速开发的管理平台
// +----------------------------------------------------------------------
// | 官方网址：https://www.onezan.cn
// +----------------------------------------------------------------------
// | onezan团队 版权所有 开源版本可自由商用
// +----------------------------------------------------------------------
// | Author: 543885307@qq.com
// +----------------------------------------------------------------------
namespace app\api\controller\user;

use app\api\controller\BaseApiController;
use app\service\api\user\AuthService;
use app\validate\api\AuthValidator;
use app\validate\domain\UserDomainValidator;
use think\Request;


/**
 * C端用户认证控制器
 * 用户注册、登录、验证码登录
 * @package app\api\controller\user
 */
class Auth extends BaseApiController
{
    /**
     * 注册
     * @param Request $request
     * @return \think\response\Json
     */
    public function register(Request $request)
    {
        $params = $request->post();
        $this->validate($params, AuthValidator::class . '.register');
        $this->validateDomain($this->app->make(UserDomainValidator::class), $params, 'register');
        return json($this->app->make(AuthService::class)->register($request));
    }

    /**
     * 登录
     * @param Request $request
     * @return \think\response\Json
     */
    public function login(Request $request)
    {
        $params = $request->post();
        $this->validate($params, AuthValidator::class . '.login');
        $this->validateDomain($this->app->make(UserDomainValidator::class), $params, 'login');
        return json($this->app->make(AuthService::class)->login($request));
    }


    /**
     * 发送登录验证码
     * @param Request $request
     * @return \think\response\Json
     */
    public function sendLoginCode(Request $request)
    {
        $phone = trim((string)$request->post('phone', ''));
        if ($phone === '' || !preg_match('/^1[3-9]\d{9}$/', $phone)) {
            return json(['code' => 1, 'msg' => '']);
        }
        return json($this->app->make(AuthService::class)->sendLoginCode($request));
    }

    /**
     * 登录（验证码验证码）
     * @param Request $request
     * @return \think\response\Json
     */
    public function loginByCode(Request $request)
    {
        $phone = trim((string)$request->post('phone', ''));
        $code = trim((string)$request->post('code', ''));
        if ($phone === '' || !preg_match('/^1[3-9]\d{9}$/', $phone)) {
            return json(['code' => 1, 'msg' => '']);
        }
        if ($code === '') {
            return json(['code' => 1, 'msg' => '']);
        }
        return json($this->app->make(AuthService::class)->loginByCode($request));
    }
}