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

use EasyWeChat\Factory;
use think\facade\Config;
use app\model\student\Student;
use app\model\student\Wechat;

class OauthService{

	public function oauth($request){
		$code = $request->post('code');
		$config = Config::get('wechat.miniapp');
		
		$app = Factory::miniProgram($config);
		try {
			//获取openid
			$session_code = $app->auth->session($code);

			$wechat = Wechat::where('openid', '=', $session_code['openid'])->findOrEmpty();
			if($wechat->isEmpty()){
				$userInfo = $app->encryptor->decryptData($session_code['session_key'], $request->post('iv'), $request->post('encrypted'));
				$data = [
					'headimgurl' => $userInfo['avatarUrl'],
					'nickname' => $userInfo['nickName'],
					'openid'=> $userInfo['openId'],
					'sex' => $userInfo['gender'],
					'city' => $userInfo['city'],
					'country' => $userInfo['country'],
					'province' => $userInfo['province'],
					'language' => $userInfo['language']
				];
				$wechat = Wechat::create($data);
			}

			if($wechat['uid'] > 0){
				$wechat['users'] = Student::with(['enter'])->visible(['name', 'mobile', 'sex', 'address', 'id', 'id_card', 'invite_id', 'exam_num', 'incorrect_num', 'point'])->find($wechat['uid'])->append(['token']);
			}
			return $wechat;
		} catch (\Exception $e) {
			throw new \think\Exception($e->getMessage(), 100);
		}
	}

	public function getQrCode($request){
		$config = Config::get('wechat.miniapp');
		
		$app = Factory::miniProgram($config);

		$res = $app->url_link->generate([]);
		return $res;
	}
}