<?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\Wechat\Services;

use Illuminate\Support\Facades\Config;
use Illuminate\Support\Str;
use EasyWeChat\OfficialAccount\Application;
use EasyWeChat\MiniApp\Application as MiniApp;
use Modules\Wechat\Models\MemberSocial;

class OauthService {

	/**
	 * @title 微信授权登录
	 *
	 * @param [type] $request
	 * @return void
	 */
	public function oauth($request){
		$config = Config::get('wechat.wx');
		$url = $request->fullUrl();
		$app = new Application($config);
		try {
			//获取openid
			$oauth = $app->getOAuth();
			$redirect = $oauth->scopes(['snsapi_userinfo'])->redirect($url);
			return $redirect;
		} catch (\Exception $e) {
			throw new \Exception($e->getMessage(), 100);
		}
	}

	/**
	 * @title 微信用户登录
	 *
	 * @param [type] $code
	 * @return void
	 */
	public function wechatLogin($code){
		$config = Config::get('wechat.wx');

		$app = new Application($config);
		try {
			//获取openid
			$oauth = $app->getOAuth();
			$user = $oauth->userFromCode($code);
			$userinfo = $user->toArray();

			$social = MemberSocial::where('openid', '=', $userinfo['id'])->where('type', '=', 'wechat')->first();
			if(!$social){
				$data = [
					'type' => 'wechat',
					'member_id' => 0,
					'openid' => isset($userinfo['id']) ? $userinfo['id'] : '',
					'nickname' => isset($userinfo['nickname']) ? $userinfo['nickname'] : '',
					'avatar'   => isset($userinfo['avatar']) ? $userinfo['avatar'] : '',
					'gender'   => isset($userinfo['gender']) ? $userinfo['gender'] : '',
				];
				$social = MemberSocial::create($data);
			}
			return $social;
		} catch (\Exception $e) {
			throw new \Exception($e->getMessage(), 100);
		}
	}

	/**
	 * @title 微信小程序登录
	 *
	 * @param [type] $code
	 * @return void
	 */
	public function mpLogin($request){
		$config = Config::get('wechat.miniapp');

		$app = new MiniApp($config);
		try {
			//获取openid
			$utils = $app->getUtils();
			$session = $utils->codeToSession($request->input('code'));

			$social = MemberSocial::where('openid', '=', $session['openid'])->where('type', '=', 'miniapp')->first();
			if(!$social){
				if($request->filled('iv') && $request->filled('encryptedData')){
					$userinfo = $utils->decryptSession($session['session_key'], $request->input('iv'), $request->input('encryptedData'));
				}else{
					$userinfo = ['nickName' => '微信用户' . Str::substr($session['openid'], -7), 'avatarUrl' => '', 'gender' => 1];
				}
				$data = [
					'type' => 'miniapp',
					'member_id' => 0,
					'openid' => isset($session['openid']) ? $session['openid'] : '',
					'unionid' => isset($session['unionid']) ? $session['unionid'] : '',
					'nickname' => $userinfo['nickName'] ? $userinfo['nickName'] : '',
					'avatar'   => isset($userinfo['avatarUrl']) ? $userinfo['avatarUrl'] : '',
					'gender'   => isset($userinfo['gender']) ? $userinfo['gender'] : '',
				];
				$social = MemberSocial::create($data);
			}
			return $social;
		} catch (\Exception $e) {
			throw new \Exception($e->getMessage(), 100);
		}
	}

	public function getPhone($request){
		$config = Config::get('wechat.miniapp');

		$app = new MiniApp($config);
		$api = $app->getClient();

		$data = [
			'code' => (string) $request->input('code'),
		];

		$response = $api->postJson('wxa/business/getuserphonenumber', $data);
		if ($response->isFailed()) {
			throw new \Exception($response->getContent(), $response->getStatusCode());
		}else{
			return $response->toArray();
		}
	}

	/**
	 * @title 获取微信JS-SDK配置
	 *
	 * @param [type] $request
	 * @return void
	 */
	public function getJsSdk($request){
		$config = Config::get('wechat.wx');
		$url = $request->input('url', '');
        $url = $url ? urldecode($url) : $request->url(true);
		$app = new Application($config);
		try {
			$utils = $app->getUtils();
			$config = $utils->buildJsSdkConfig(
                url: $url,
                jsApiList: ['updateAppMessageShareData', 'updateTimelineShareData', 'scanQRCode', 'closeWindow', 'hideAllNonBaseMenuItem', 'showAllNonBaseMenuItem', 'openAddress'],
                openTagList: [],
                debug: false,
            );
			return $config;
		} catch (\Exception $e) {
			throw new \Exception($e->getMessage(), 100);
		}
	}

	/**
	 * @title 微信公众号服务
	 *
	 * @return void
	 */
	public function WechatServe(){
		$config = Config::get('wechat.wx');
		$app = new Application($config);
		$server = $app->getServer();


		$server->with(function($message, \Closure $next){
			if ($message->MsgType === 'text') {
				return [
					'MsgType' => 'text',
					'Content' => '暂未开通自动回复功能！'
				];
			}
			return $next($message);
		});
		$server->addEventListener('subscribe', function() {
			return '嗨～感谢您关注“羊圈小铺”，我是本店可爱的店小二 喜羊羊 ，有什么问题都可以随时咨询我哟！我会静候在此，为您提供悉心服务，很高兴能帮到您～';
		});
		$server->addEventListener('unsubscribe', function() {
			return '再见～';
		});
		return $server->serve();
	}

	/**
	 * @title 获取微信用户信息
	 *
	 * @param [type] $openid
	 * @return void
	 */
	public function getWechatInfo($openid){
		$config = Config::get('wechat.wx');
		$app = new Application($config);
		$api = $app->getClient();

		$userinfo = $api->post('cgi-bin/user/info', [
			'json' => [
				'openid' => $openid,
				'lang' => 'zh_CN',
			]
			]);
		return $userinfo;
	}
}
