<?php
namespace Addons\Moments\Controller\H5;

use Models\BaseModel as Model;
use Addons\Moments\Helper;
use Addons\QyWechat\Services\QyWechatApi;

class AppPage extends \BaseController
{
	public function index(){
		$corp_id = \Request::get('corp_id');
		$qyConfig = (new Model('qy_wechat_config'))->find(['corp_id'=>$corp_id]);
		$wid = $qyConfig->wid;
		$appConfig = (new Model('qy_moments_app_config'))->find(['wid'=>$wid]);
		if($_GET['code']){
			$code = $_GET['code'];
			$app = QyWechatApi::getInstance()->get_qy_agent_app($qyConfig->corp_id,$appConfig->agent_id,$appConfig->secret);
			$accessToken = $app->access_token;
			$token = $accessToken->getToken()['access_token']; // token 数组  token['access_token'] 字符串
			$url = 'https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token='.$token.'&code='.$code;
			$resArr = json_decode(curlGet($url),1);
			$qyUser = (new Model('qy_user_list'))->find(['wid'=>$wid,'userid'=>$resArr['UserId']]);
			$pyqUrl = Helper::getInstance()->get_http_server_name().'/Addons/Moments/H5/Trace/entry-'.base64_encode($wid.'_'.$qyUser->id).'.html';
			//Header("Location: $pyqUrl");
			//echo "<script>window.location = '{$pyqUrl}'</script>";
			\Redirect::to("{$pyqUrl}");
		}else{
			$redirect_uri = urlencode(Helper::getInstance()->get_http_server_name().'/Addons/Moments/H5/AppPage.html?corp_id='.$qyConfig->corp_id);
			$url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$qyConfig->corp_id.'&redirect_uri='.$redirect_uri.'&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect';
			//Header("Location: $url");
			//echo "<script>window.location = '{$url}'</script>";
			\Redirect::to("{$url}");
		}
		return;
	}
}