<?php

namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Http\Requests;
use Illuminate\Http\Request;
use App\Libs\Classes\BLogger;
use App\Libs\Classes\WxSign;
use EasyWeChat\Foundation\Application;
use WechatOP;
use Illuminate\Support\Facades\Redis;
use App\Http\Models\WechatGroupGzh;
use App\Http\Controllers\Wechat\Api\WechatInnerApisController;
use Doctrine\Common\Cache\PredisCache;
// use Doctrine\Common\Cache\RedisCache;

class WechatController extends Controller
{
	
	public $wx_log_path;
	public $options;
	public $host;
	public $auth_host;
	public $third_host;
	public $WxSign;
	public $token;
	public $gzh_name;
	public $gzh_app_id;
	public $Redis;// redis的连接对象
	public $WechatApi;
	public $param;
	public $official_account;
// 	public $wechat_group_gzh;

	public function __construct($gzh_app_id='') {
		// 方便扩展
		$this->param = array();
		$this->gzh_app_id = $gzh_app_id;
		$this->param['gzh_app_id'] = $this->gzh_app_id;
		$this->param['openid'] = '';
		// check公众号,不等于微信测试号
		if(!empty($this->gzh_app_id) && $this->gzh_app_id != 'wx570bc396a51b8ff8'){
			$this->wechat_group_gzh = WechatGroupGzh::get_wechat_group_gzh($this->gzh_app_id);
			if(!empty($this->wechat_group_gzh)) {
				$this->param['group_api'] = $this->wechat_group_gzh['group_api'];
				$this->param['group'] = $this->wechat_group_gzh['group'];
			}else{
				v('invalid gzh_app_id:'.$gzh_app_id);
				// 			json_echo('invalid gzh_app_id');
			}
		}
			
		$this->wx_log_path = '/var/www/ydy_wechat/storage/logs/easywechat.log';
		$this->domain = env('DOMAIN');//'aizhuishu.com';
		$this->auth_host = $this->host = env('ONLINE_AUTH_HOST');
		if(env('DEVELOP_MODE') == 'online'){
			$this->Redis = Redis::connection();// 默认的正式库的redis
		}elseif(env('DEVELOP_MODE') == 'online_test'){
			$this->Redis = Redis::connection();// 默认env的redis
		}elseif(env('DEVELOP_MODE') == 'test'){
			$this->Redis = Redis::connection('test_redis');// 测试库的redis
		}elseif(env('DEVELOP_MODE') == 'local'){
			$this->wx_log_path = '/Applications/MAMP/htdocs/ydy_wechat/storage/logs/easywechat.log';
			$this->Redis = Redis::connection('test_redis');// 测试库的redis
		}
// 		v('$this->Redis');v($this->Redis);
// 		v('develop:'.env('DEVELOP_MODE').' domain:'.$this->domain);

		$this->WxSign = new WxSign();
		$this->oauth_platform_callback_base_url = $this->auth_host.'oauth/';// 第三方授权微信回跳地址
		
		$this->token = env('WECHAT_OP_TOKEN');
		
		if(!empty($this->gzh_app_id)){
			// token部分的redis都用正式库的
			// 只在授权时刻提供,丢失后需要用户重新授权
			$redis_key = '[wechat_op.common.component_refresh_token.'.$this->gzh_app_id.']';
			$component_refresh_token = Redis::Get($redis_key);
// 			v('redis_key:'.$redis_key.' component_refresh_token:'.$component_refresh_token);
			
			$this->options = [
				'app_id'    => $this->gzh_app_id,
				'secret'    => env('WECHAT_OP_SECRET'),   // 仅适用于 单独配置公众号
				'token'     => env('WECHAT_OP_TOKEN'),   // 仅适用于 单独配置公众号
				'aes_key'   => env('WECHAT_OP_AES_KEY'),   // 仅适用于 单独配置公众号
				'auth_type' => 'COMPONENT', // COMPONENT 开放平台授权公众号,MANUAL 单独配置公众号
				'component_refresh_token' => $component_refresh_token,   // 授权回调时获取的 authorizer_refresh_token,仅适用于 开放品台授权公众号
				'oauth'     => [
				   'scopes' => ['snsapi_base'], // 公众号授权用户方式 snsapi_base, snsapi_userinfo
				   'callback' => '/oauth_callback',
				],
				'cache'   => [
					'driver' => 'redis',   // redis, filesystem, laravel
					'dir' => storage_path('tmp') // 只有为filesystem时候这个目录才有效
				],
			];
			// EasyWechat\Foundation\Application 对象
			$this->app = WechatOP::app($this->options);
			
			$this->param['app'] = $this->app;

			$this->WechatApi = new WechatInnerApisController($this->param);
			$this->official_account = $this->WechatApi->get_official_account($this->gzh_app_id);
			$this->param['official_account'] = $this->official_account;
			$this->param['WechatApi'] = $this->WechatApi;
		}

		$this->set_init_param();
		v('post:');v($_POST);
	}
		
	// 初始化post,get变量,兼容两种
	public function set_init_param(){
		if(empty($_POST)) {
			$_POST = $_REQUEST;
		}
		if(empty($_REQUEST)) {
			$_REQUEST = $_POST;
		}

		if(isset($_POST['_url'])) {
			unset($_POST['_url']);
		}
		if(isset($_REQUEST['_url'])) {
			unset($_REQUEST['_url']);
		}
	}	
	
	public function redirect_url($response_url){
//		v('redirect_url in:'.$response_url);
		header("Location:".$response_url);
        exit;
	}
	
	/**
	 * 检查签名和时间戳
	 * @param unknown_type $request
	 */
	public function check_sign_params($request){
		$result = array('code'=>1,'msg'=>'','data'=>'');
		$timestamp = !empty($request->get('timestamp'))?$request->get('timestamp'):'';
		$sign = !empty($request->get('sign'))?$request->get('sign'):'';
		v('check_sign_params:$timestamp:'.$timestamp.' $sign:'.$sign);
		if(empty($timestamp) || empty($sign)){
			$result['code'] = 0;
			$result['msg'] = 'invalid param';
			return $result;
		}
		
		$timestamp = $request->get('timestamp');
		$sign = $request->get('sign');
		$now = microtime(true);
		$diff = $now - $timestamp;
		v('timestamp:'.$timestamp.' now:'.$now.' diff:'.$diff);
		// 时间戳8小时内
		if($diff > 28*3600){
			$result['code'] = 0;
			$result['msg'] = 'invalid time';
			return $result;
		}

		$my_sign = $this->WxSign->get_sign($request->all());
		v('check_sign_params sign:'.$sign.' my_sign:'.$my_sign.' info:'.json_encode($request->all()));
		if($sign != $my_sign){
			$result['code'] = 0;
			$result['msg'] = 'invalid sign';
			return $result;
		}
		return $result;
	}
	
}