<?php

namespace App\Http\Controllers\Wechat\ThirdWx;

use App\Http\Models\WechatGroupGzh;

use App\Http\Controllers\WechatController;
use App\Http\Requests;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use WechatOP;
use Illuminate\Support\Facades\Redis;
use App\Http\Controllers\Wechat\Menu\MenusController;
use App\Http\Controllers\Wechat\Template\TemplateBasesController;

/**
 * 授权第三方平台获取公众号权限
 * @author zhoulingjie
 *
 */
class OauthPlatformsController extends WechatController
{
    
    public function __construct()
    {
		parent::__construct();
    }
    
    /**
     * 公众号授权第三方平台并跳转
     http://zydy/oauth/oauth_platform?distribution_channel_id=1&official_account_type=force_subscribe&group_nick=aizhuishu&redirect_url=http%3a%2f%2fchannel.aizhuishu.com%2fservice-setting%3ftab%3d3&timestamp=1513240244&sign=577684945fd6f2dc0295b7dc3f5cf60c
    * @param Request $request
     */
    function oauth_platform(Request $request){
    	v('oauth_platform_start');
    	$result = array('code'=>1,'msg'=>'','data'=>'');
    	$official_account_type = $request->get('official_account_type');
    	$distribution_channel_id = $request->get('distribution_channel_id');
    	$origin_redirect_url = $request->get('redirect_url');
    	$group_nick = $request->get('group_nick');
    	$redirect_url = urlencode($origin_redirect_url);
    	v($request->all());
    	if(empty($official_account_type) || empty($distribution_channel_id) || empty($redirect_url) || empty($group_nick)){
    		$result['code'] = 0;
    		$result['msg'] = 'invalid param';
    		json_echo($result);
    	}
    	 
    	$check_result = $this->check_sign_params($request);
    	if($check_result['code'] == 0){
    		$result['code'] = 0;
    		$result['msg'] = $check_result['msg'];
    		json_echo($result);
    	}
    	$_param = $official_account_type.'*'.$distribution_channel_id.'*'.$redirect_url.'*'.$group_nick;
    	$this->oauth_platform_callback_url = $this->oauth_platform_callback_base_url.$_param.'/oauth_platform_callback';
    	v('oauth_platform_callback_url:'.$this->oauth_platform_callback_url);
    	try{
    		$response = WechatOP::oauth()->redirect($this->oauth_platform_callback_url);
    		v('$response');
    		
    		$target_url = $response->getTargetUrl();
    		v('target_url');v($target_url);
    	}catch(\Exception $e){
    		v('oauth_callback_ept:'.$e->getMessage());
    		$origin_redirect_url .= "&distribution_channel_id=".$distribution_channel_id."&success=0&msg=授权异常：".urlencode($e->getMessage());
    		v('ept_redirect_url:'.$origin_redirect_url);
    		// 跳转回去
    		$this->redirect_url($origin_redirect_url);
    		exit();
    	}
    	
    	v('oauth_platform_end');
    	// 注意：直接跳转会有bug
    	echo "
    	<html>
    	<head>
    	<script LANGUAGE='JavaScript'> 
		window.location= '".$target_url."';
		</script>
		</head>
		<body>
		<br><a href='".$target_url."'>若没有自动跳转，点击本链接跳转到授权页</a><br>
		</body>
		</html>  
    	";
    }
    
    /**
     * 授权结束回调给平台调用凭据
     * @param Request $request
     */
    function oauth_platform_callback(Request $request){
    	v('oauth_platform_callback');v($request->all());
    	$official_account_type = $distribution_channel_id = $group_nick = '';
    	// 提取授权公众号的基础回调参数，回调格式domain/oauth/official_account_type*distribution_channel_id/oauth_platform_callback
    	preg_match('/oauth\/(.*)?\/oauth_platform_callback/i',$_SERVER['REQUEST_URI'],$data);
    	if(isset($data[1]) && !empty($data[1])){
    		$_param =$data[1];
    		$_param_arr = explode('*',$_param);
    		$official_account_type = $_param_arr[0];
    		$distribution_channel_id = $_param_arr[1];
    		$redirect_url = $_param_arr[2];
    		$group_nick = $_param_arr[3];
    		$redirect_url = urldecode($redirect_url);
    		if(strpos($redirect_url,'?') === false){
    			$redirect_url .= '?';
    		}
    	}
    	
    	v('oauth_platform_callback:official_account_type:'.$official_account_type.' distribution_channel_id:'.$distribution_channel_id.' redirect_url:'.$redirect_url);
//     	die('end');
    	
    	$authInfo = WechatOP::oauth()->user();
    	$authInfo = objectToArray($authInfo);
    	// 取第一个val
    	$authInfo = current($authInfo);
    	v('authInfo');v($authInfo);
    	// 授权信息
    	$authorization_info = $authInfo['authorization_info'];
    	v('authorization_info');v($authorization_info);
    	
    	$appid = isset($authorization_info['authorizer_appid'])?$authorization_info['authorizer_appid']:'';
    	
    	$is_service_auth =  isset($authInfo['authorizer_info']['service_type_info']['id']) && 
    			$authInfo['authorizer_info']['service_type_info']['id'] == 2 && 
    			isset($authInfo['authorizer_info']['verify_type_info']['id']) &&
    			$authInfo['authorizer_info']['verify_type_info']['id'] == 0;
    	
    	$is_white_appids = false;
    	$white_appids = Redis::smembers('auth_white_appids');
    	v('white_appids');v($white_appids);
    	if(!empty($appid) && in_array($appid,$white_appids)){
    		$is_white_appids = true;
    	}
    	
    	v('oauth_platform_callback:appid:'.$appid.' is_service_auth：'.$is_service_auth.' is_white_appids:'.$is_white_appids);
    	
    	// 只有认证微信服务号才支持,或者白名单列表
    	if($is_service_auth || $is_white_appids)
    	{
    		// 保存token信息
    		$authorizer_appid = $authorization_info['authorizer_appid'];
    		$authorizer_refresh_token = $authorization_info['authorizer_refresh_token'];
    		$redis_key = '[wechat_op.common.component_refresh_token.'.$authorizer_appid.']';
    		$redis_val = $authorizer_refresh_token;
    		v('oauth_platform_callback:redis_key:'.$redis_key.' redis_val:'.$redis_val);
    		Redis::Set($redis_key, $authorizer_refresh_token);
    		$redis_res = Redis::Get($redis_key);
    		v('redis_res:'.$redis_res);
    		
    		// 重要：要先保存映射表
    		$insert_group = array();
    		$insert_group['group_nick'] = $group_nick;
    		$insert_group['appid'] = $authorizer_appid;
    		WechatGroupGzh::save_group_gzh($insert_group);
    		
    		// 初始化接口
    		parent::__construct($authorizer_appid);
    		
    		$origin_distribution_channel_id = isset($this->official_account['distribution_channel_id'])?$this->official_account['distribution_channel_id']:'';
    		$origin_appid = isset($this->official_account['appid'])?$this->official_account['appid']:'';
    		v('check_official_account,distribution_channel_id:'.$distribution_channel_id.' origin_distribution_channel_id:'.$origin_distribution_channel_id.' origin_appid:'.$origin_appid);
            
    		// 空账号或者同一个账号
            if(empty($origin_appid) || ($distribution_channel_id == $origin_distribution_channel_id)){
            	v('third_oauth_save_or_update:'.$authorizer_appid.' distribution_channel_id:'.$distribution_channel_id);
            	// 保存商户公众号信息
            	$authorizer_info = $authInfo['authorizer_info'];
            	v('$authorizer_info');v($authorizer_info);
            	$insert_offical_account = array();
            	$insert_offical_account['nickname'] = isset($authorizer_info['nick_name'])?$authorizer_info['nick_name']:'';
            	$insert_offical_account['head_img'] = isset($authorizer_info['head_img'])?$authorizer_info['head_img']:'';
            	$insert_offical_account['service_type_info'] = isset($authorizer_info['service_type_info']['id'])?$authorizer_info['service_type_info']['id']:null;
            	$insert_offical_account['verify_type_info'] = isset($authorizer_info['verify_type_info']['id'])?$authorizer_info['verify_type_info']['id']:null;
            	$insert_offical_account['name'] = isset($authorizer_info['user_name'])?$authorizer_info['user_name']:'';
            	$insert_offical_account['alias'] = isset($authorizer_info['alias'])?$authorizer_info['alias']:'';
            	$insert_offical_account['qrcode_url'] = isset($authorizer_info['qrcode_url'])?$authorizer_info['qrcode_url']:'';
            	$insert_offical_account['principal_name'] = isset($authorizer_info['principal_name'])?$authorizer_info['principal_name']:'';
            	$insert_offical_account['authorizer_refresh_token'] = $authorizer_refresh_token;
            	$insert_offical_account['appid'] = $authorizer_appid;
            	$insert_offical_account['func_info'] = json_encode($authorization_info['func_info']);
            	$insert_offical_account['is_auth'] = 1;
            	$insert_offical_account['official_account_type'] = $official_account_type;
            	$insert_offical_account['distribution_channel_id'] = $distribution_channel_id;
            	v('authorizer_info_insert_data:');v($insert_offical_account);
            	$this->WechatApi->save_official_account($insert_offical_account);
            		
            	// 自动生成菜单和模板消息,如果默认是登录或者支付公众号，则不生成菜单
            	// TODO check下是否自动生成
            	if(!in_array($official_account_type,array('third_platform_default_login','third_platform_pay'))){
            		v('auto_set_menu:'.$authorizer_appid);
            		$this->auto_set_menu_and_template($authorizer_appid,'all');
            	}else{
            		v('not_set_menu:'.$authorizer_appid);
            	}
            	
            	$redirect_url .= "&distribution_channel_id=".$distribution_channel_id."&authorizer_appid=".$authorizer_appid."&success=1";
            }
            // 已存在的
            else{
            	v('third_oauth_direct_return:'.$authorizer_appid.' distribution_channel_id:'.$distribution_channel_id);
            	$redirect_url .= "&distribution_channel_id=".$distribution_channel_id."&success=0&msg=该服务号已经被渠道号：".$origin_distribution_channel_id." 授权，不能再次授权！";
            }
    		
    	}else{
    		$redirect_url .= "&distribution_channel_id=".$distribution_channel_id."&success=0&msg=只支持认证的服务号！";
    	}
    	v('redirect_url:'.$redirect_url);
    	
    	// 跳转回去
    	$this->redirect_url($redirect_url);
    }
    
    function auto_set_menu_and_template($authorizer_appid='',$set_type='all'){
    	if(empty($authorizer_appid)){
    		v('auto_set_menu_and_template_param_null:'.$authorizer_appid);
    		return false;
    	}
    	
    	parent::__construct($authorizer_appid);
    	 
    	if($set_type == 'all'){
    		$menu = new MenusController($this->param);
    		$menu->set_menu();
    		 
    		$template = new TemplateBasesController($this->param);
    		$template->auto_set_dustry_templates();
    	}elseif($set_type == 'menu'){
    		$menu = new MenusController($this->param);
    		$menu->set_menu();
    	}elseif($set_type == 'template'){
    		$template = new TemplateBasesController($this->param);
    		$template->auto_set_dustry_templates();
    	}else{
    		v('auto_set_menu_and_template_invalid_set_type:'.$authorizer_appid);
    	}

    }
    
    /**
     * 嘉言小说 wxdbc486f1b4f6a8c3
     http://zydy/oauth/auto_set_menu_and_template_test?set_type=menu&authorizer_appid=wxdbc486f1b4f6a8c3&timestamp=1511509543&sign=98dccc7b29e3c05e4b4367f488ff1966
     */
    function auto_set_menu_and_template_test(Request $request){
    	
    	$result = array('code'=>1,'msg'=>'','data'=>'');
    	$authorizer_appid = $request->get('authorizer_appid');
    	$set_type = $request->get('set_type');
    	if(empty($authorizer_appid) || empty($set_type)){
    		$result['code'] = 0;
    		$result['msg'] = 'invalid param';
    		json_echo($result);
    	}
    	
        $check_result = $this->check_sign_params($request);
    	if($check_result['code'] == 0){
    		$result['code'] = 0;
    		$result['msg'] = $check_result['msg'];
    		json_echo($result);
    	}
    	$this->auto_set_menu_and_template($authorizer_appid,$set_type);
    }
    
}