<?php
// +----------------------------------------------------------------------
// | SentCMS [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2024 http://www.tensent.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: molong <molong@tensent.cn> <http://www.tensent.cn>
// +----------------------------------------------------------------------
namespace Modules\Member\Services;

use Modules\Member\Models\Member;
use Modules\Member\Events\LoginEvent;
use Modules\Member\Events\Registered;

class AuthService {

	/**
	 * @title 会员登录
	 *
	 * @param [type] $request
	 * @return void
	 */
	public function userLogin($request){
		$request->validate([
			'username' => 'required',
			'password' => 'required',
		]);

		$username = $request->input('username');
		$password = $request->input('password');

		$auth = auth('api')->attempt(['username' => $username, 'password' => $password]);

		if (!$auth) {
			throw new \Exception("登录失败！", 1000);
		}else{
			LoginEvent::dispatch(auth('api')->user());
			return [
				'access_token' => $token,
				'token_type' => 'bearer',
				'expires_in' => auth('api')->factory()->getTTL() * 60
			];
		}
	}

	/**
	 * @title UID登录
	 * @description 提供给第三方登录接口
	 *
	 * @param [type] $uid
	 * @param array $params    第三方登录参数
	 * @param string $type     第三方登录类型
	 * @return void
	 */
	public function userLoginByUid($uid, $params = [], $type = 'wechat'){
		$member = Member::find($uid);
		if(!$member){
			throw new \Exception("用户不存在！", 1000);
		}

		$auth = auth('api')->login($member);

		if (!$auth) {
			throw new \Exception("登录失败！", 1000);
		}else{
			LoginEvent::dispatch(auth('api')->user(), $params, $type);
			return [
				'access_token' => $token,
				'token_type' => 'bearer',
				'expires_in' => auth('api')->factory()->getTTL() * 60
			];
		}
	}

	/**
	 * @title 会员注册
	 *
	 * @param [type] $request
	 * @return void
	 */
	public function userRegister($request, $social = [], $type = ''){
		$request->validate([
			'username' => 'required',
			'password' => 'required',
		]);

		$member = Member::where('username', '=', $request->input('username'))->first();
		if(!$member){
			$data = [
				'username' => $request->input('username'),
				'password' => $request->input('password'),
				'nickname' => $request->input('nickname', ''),
				'invite_uid' => $request->input('invite_uid', 0),
			];

			$member = Member::updateOrCreate($data);
		}
		Registered::dispatch($member, $social, $type);
		return $member;
	}

	/**
	 * @title 会员退出
	 *
	 * @param [type] $request
	 * @return void
	 */
	public function userLogout($request){
		auth('api')->logout();
	}
}
