<?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\Controllers\Api;

use Illuminate\Http\Request;
use App\Services\Social\Wechat\OauthService;
use Modules\Member\Services\AuthService;
use App\Http\Controllers\BaseController;

class Social extends BaseController{

	public function wechat(Request $request, OauthService $service){
		if($request->filled('code')){
			if($request->filled('url')){
				return redirect($request->input('url') . '?code=' . $request->input('code', ''));
			}
		}else{
			$res = $service->oauth($request);
			return redirect($res);
		}
	}

	public function login(Request $request, OauthService $service){
		$type = $request->input('type', 'wechat');
		if($request->filled('code')){
			switch ($type) {
				case 'wechat':
					try {
						$wechatInfo = $service->wechatLogin($request->input('code', ''));
						$request->merge([
							'username'  => $wechatInfo['openid'],
							'nickname' => $wechatInfo['nickname'],
							'password'  => uniqid()
						]);
						$member = app(AuthService::class)->userRegister($request, $wechatInfo, 'wechat');
						$token = auth('api')->login($member);
						$this->data['data'] = [
							'access_token' => $token,
							'token_type' => 'bearer',
							'expires_in' => auth('api')->factory()->getTTL() * 60
						];
					} catch (\Throwable $th) {
						$this->data['message'] = $th->getMessage();
						$this->data['code'] = 0;
					}
					break;
			}
		}else{
			$this->data['message'] = "非法操作！";
			$this->data['code'] = 0;
		}
		return response()->json($this->data);
	}
}
