<?php

namespace App\Http\Controllers\Manage\OfficialAccount;

use App\Modules\OfficialAccount\Models\ForceSubscribeUsers;

use App\Modules\OfficialAccount\Models\OfficialAccount;
use App\Modules\OfficialAccount\Models\UntieOfficialAccount;

use App\Http\Controllers\Channel\BaseController;
use App\Modules\OfficialAccount\Services\OfficialAccountService;
use App\Http\Controllers\Manage\OfficialAccount\Transformers\OfficialAccountTransformer;
use Illuminate\Http\Request;
use GuzzleHttp\Client;
use Redis;

/**
 * 微信工具修改类
 * @author zhoulingjie
 *
 */
class WeChatToolsController extends BaseController
{


    /**
     * @apiVersion 1.0.0
     * @api {GET} OfficialAccount/add_public_templates 根据公共模板id添加模板
     * @apiGroup OfficialAccount
     * @apiName add_public_templates
     * @apiParam   {String}  common_template_id 公共模板id. 
     */
    function add_public_templates(Request $request){

       $common_template_id = $request->has('common_template_id') ? $request->input('common_template_id') : '';
       $test_appid = $request->has('test_appid') ? $request->input('test_appid') : '';
        
       \Log::info('add_public_templates:'.$common_template_id);

       if(empty($common_template_id)) {
           return response()->error("PARAM_EMPTY");
       }

        $officail_accounts = OfficialAccountService::officialAuthAccounts(1,1);
//         \Log::info($officail_accounts);
        foreach ($officail_accounts as $officail_account){
        	try {
//         		if($officail_account->appid != 'wxdbc486f1b4f6a8c3') {
//         			\Log::info('not_in:'.$officail_account->appid);
//         			continue;
//         		}
        		$timestamp = time();
        		$params = array("common_template_id"=>$common_template_id,'gzh_app_id'=>$officail_account->appid,"timestamp"=>$timestamp);
        		$sign = get_sign($params);
        		
        		\Log::info('add_public_template_start,appid:'.$officail_account->appid);
        		
        		$mediaCustomerJson = $this->getUserClient()->request("GET","add_public_template",
        				['query'=>['common_template_id'=>$common_template_id,'gzh_app_id'=>$officail_account->appid,'timestamp'=>$timestamp,'sign'=>$sign],'connect_timeout' => 10]
        		)->getBody()->getContents();
        		//\Log::info($mediaCustomerJson);
        		\Log::info('add_public_template_end,appid:'.$officail_account->appid.' res:'.json_encode($mediaCustomerJson));
        	
        	} catch (\Exception $e) {
        		\Log::info($e->getMessage());
        	}
        }

        return response()->success(['status'=>'1']);

    }
    
    /**
     * @apiVersion 1.0.0
     * @api {GET} OfficialAccount/add_public_templates 根据公共模板id添加模板
     * @apiGroup OfficialAccount
     * @apiName add_public_templates
     * @apiParam   {String}  common_template_id 公共模板id.
     */
    public function check_official_account_templates(){
    
    	$officail_accounts = OfficialAccountService::officialAuthAccounts(1,1);
    	foreach ($officail_accounts as $officail_account){
    		try {
//     			        		if($officail_account->appid != 'wxdbc486f1b4f6a8c3') {
//     			        			\Log::info('not_in:'.$officail_account->appid);
//     			        			continue;
//     			        		}
    			$timestamp = time();
    			$params = array("gzh_app_id"=>$officail_account->appid,"timestamp"=>$timestamp);
    			$sign = get_sign($params);
    
    			\Log::info('check_official_account_templates_start,appid:'.$officail_account->appid);

    			$dataJson = $this->getUserClient()->request("GET","check_official_account_templates",
    					['query'=>['gzh_app_id'=>$officail_account->appid,'timestamp'=>$timestamp,'sign'=>$sign],'connect_timeout' => 10]
    			)->getBody()->getContents();
    			//\Log::info($dataJson);
    			\Log::info('check_official_account_templates_end,appid:'.$officail_account->appid.' res:'.json_encode($dataJson));

    		}
	        catch( \Exception $e){
	            \Log::info($e->getMessage());
	        }

    	}
    
    	return response()->success(['status'=>'1']);
    
    }
    
    /**
     * @apiVersion 1.0.0
     * @api {GET} OfficialAccount/update_encrypt_menus 更新所有菜单->改为加密
     * @apiGroup OfficialAccount
     * @apiName update_encrypt_menus
     */
    public function update_encrypt_menus(){
    
    	$officail_accounts = OfficialAccountService::officialAuthSubscribeAccounts(1,1);
    	foreach ($officail_accounts as $officail_account){
    		try {
//     			if($officail_account->appid != 'wxdbc486f1b4f6a8c3') {
//     			   \Log::info('not_in:'.$officail_account->appid);
//     			   continue;
//     			}
    			$timestamp = time();
    			$params = array("set_type"=>"menu","authorizer_appid"=>$officail_account->appid,"timestamp"=>$timestamp);
    			$sign = get_sign($params);
//     			http://zydy/oauth/auto_set_menu_and_template_test?set_type=menu&authorizer_appid=wxdbc486f1b4f6a8c3&timestamp=1511509543&sign=98dccc7b29e3c05e4b4367f488ff1966
    			    
    			\Log::info('update_encrypt_menus_start,appid:'.$officail_account->appid);
    
    			$dataJson = $this->getAuthClient()->request("GET","auto_set_menu_and_template_test",
    					['query'=>["set_type"=>"menu",'authorizer_appid'=>$officail_account->appid,'timestamp'=>$timestamp,'sign'=>$sign],'connect_timeout' => 10]
    			)->getBody()->getContents();
    			//\Log::info($dataJson);
    			\Log::info('update_encrypt_menus_end,appid:'.$officail_account->appid.' res:'.json_encode($dataJson));
    
    		}
    		catch( \Exception $e){
    			\Log::info($e->getMessage());
    		}
    
    	}
    
    	return response()->success(['status'=>'1']);
    
    }
    
    /**
     * @apiVersion 1.0.0
     * @api {GET} OfficialAccount/untie_distribution_official_account 解绑公众号
     * @apiGroup OfficialAccount
     * @apiName untie_distribution_official_account
     * @apiParam   {String}  appid 渠道id.
     */
    public function untie_distribution_official_account(Request $request){
    	$appid = $request->has('appid') ? $request->input('appid') : '';
    	$force_untie = $request->has('force_untie') ? $request->input('force_untie') : '0';
    	
    	\Log::info('untie_distribution_official_account_start:'.$appid);
    	
    	if(empty($appid)) {
    		return response()->error("PARAM_EMPTY");
    	}
    	
    	// 找到公众号 
    	$official_account = OfficialAccount::officialAccountArrByAppid($appid);
    	if(empty($official_account)) {
    		return response()->error("NOT_FOUND_OFFICIAL_ACCOUNT");
    	}
    	
    	// 判断公众号的注册用户数，大于10个默认是老号不给删除，否则用户数据会异常
    	$force_subscribe_count = ForceSubscribeUsers::forceSubscribeUsersCountByAppid($appid);
    	\Log::info('untie_distribution_official_account_appid:'.$appid.' force_subscribe_count:'.$force_subscribe_count.' $force_untie:'.$force_untie);
    	if($force_untie){
    		// 强制解绑的话，大号也不行
    		if($force_subscribe_count >=10000){
    			return response()->error("OLD_APP_NOT_ALLOW_DELETE");
    		}
    	}else{
    		// 小权限限制下500人
    		if($force_subscribe_count >=500){
    			return response()->error("OLD_APP_NOT_ALLOW_DELETE");
    		}
    	}
    	
    	// 备份
    	$untie_offcial_account = object_to_array($official_account);
    	UntieOfficialAccount::firstOrCreate($untie_offcial_account);
    	
    	// 删除OfficialAccount
    	\Log::info('del_official_account:'.json_encode($official_account));
    	OfficialAccount::deleteOfficialAccount($official_account['id']);
    	
    	// 删除redis中OfficialAccount缓存
    	\Log::info('del_redis:'.'official_account_info:app_id:'.$appid);
    	Redis::del('official_account_info:app_id:'.$appid);
    	
    	\Log::info('untie_distribution_official_account_end:'.$appid);
    
    	return response()->success(['status'=>'1']);
    
    }
    
    public function getUserClient(){
    	return new Client(['base_uri' => env('MEDIA_API_BASE_URI')]);
    }
    
    public function getAuthClient(){
    	return new Client(['base_uri' => env('AUTH_API_BASE_URI')]);
    }

}