<?php

namespace App\Http\Controllers\Wechat\OfficialAccount;

use App\Http\Controllers\Channel\BaseController;
use App\Modules\OfficialAccount\Services\OfficialAccountService;
use App\Modules\OfficialAccount\Models\OfficialAccount;
use App\Modules\OfficialAccount\Models\ForceSubscribeUsers;
use App\Http\Controllers\Wechat\OfficialAccount\Transformers\OfficialAccountTransformer;
use App\Modules\Book\Services\BookConfigService;
use App\Modules\OfficialAccount\Models\WechatTemplates;
use App\Modules\OfficialAccount\Models\WechatTemplateMsgs;
use App\Modules\OfficialAccount\Models\WechatPublicTemplates;
use Illuminate\Http\Request;
use GuzzleHttp\Client;
use App\Libs\OSS;
use Redis;

use App\Jobs\SendTestEmail;

class WechatTestController extends BaseController
{


    //------------------Test  OfficialAccointsController

    // 通过渠道号获取所有服务号     --Manage
    function allOfficialAccountBydistributionChannelId(Request $request)
    {

        $distribution_channel_id = $request->has('distribution_channel_id') ? $request->input('distribution_channel_id') : '';

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

        \Log::info('-------------------获取当前渠道下的所有服务号-----------------------------------');
        \Log::info($distribution_channel_id);

        $officialAccount['distribution_channel_id'] = $distribution_channel_id;

        $officialAccountService = OfficialAccountService::allOfficialAccountBydistributionChannelId($officialAccount);
        
        return response()->collection(new OfficialAccountTransformer(), $officialAccountService);
    }



    // 通过渠道号获取服务号数量     --Manage
    function officialAccountCountByChannelId(Request $request)
    {

        $distribution_channel_id = $request->has('distribution_channel_id') ? $request->input('distribution_channel_id') : '';

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

        $officialAccount['distribution_channel_id'] = $distribution_channel_id;
        $officialAccountService = OfficialAccountService::officialAccountCountByChannelId($officialAccount);
        return response()->success(['official_num'=>$officialAccountService]);
    }

    // sign加密
    function getSignTest(Request $request){

//        $appid = $request->has('appid') ? $request->input('appid') : '';
//
//        if(empty($appid)) {
//            return response()->error("PARAM_EMPTY");
//        }
//
//        $timestamp = $request->has('timestamp') ? $request->input('timestamp') : '';
//
//        if(empty($timestamp)) {
//            return response()->error("PARAM_EMPTY");
//        }
//
//        $params = array("authorizer_appid"=>$appid,"timestamp"=>$timestamp);
//
//        $sign = get_sign($params);
//
//        return response()->success(['sign'=>$sign]);


        

        $timestamp = 1519359397;
        $official_accounts = 'wx1affdca495a3ab1e';
        $params = array("authorizer_appid"=>$official_accounts,"timestamp"=>$timestamp);
        $sign = get_sign($params);

        try {

            $mediaCustomerJson = $this->getUserClient()->request("GET","auto_set_menu_and_template_test",
                ['query'=>['authorizer_appid'=>$official_accounts,'timestamp'=>$timestamp,'sign'=>$sign],'connect_timeout' => 10]
            )->getBody()->getContents();

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

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

    }


//    // 更新公众号信息至Redis
//    function updateOfficialToRedisTest(Request $request)
//    {
//        $allOfficialAccounts = OfficialAccount::getAllOfficialAccountDB();
//        if(count($allOfficialAccounts)>0){
//            for ($i=0; $i < count($allOfficialAccounts); $i++) {
//                $official_accounts = $allOfficialAccounts[$i];
//                $officialAccountArray = $official_accounts->toArray();
////                dd(json_encode($officialAccountArray));
//                Redis::hset('official_account_info:app_id:'.$official_accounts['appid'], 'official_account_info', json_encode($officialAccountArray));
//
//
//            }
//        }
////        dd(1);
//        return response()->success(['sign'=>count($allOfficialAccounts)]);
//
//    }

    // 更新公众号信息至Redis
    function getOfficialFromRedis(Request $request)
    {

        $appid = $request->has('appid') ? $request->input('appid') : '';

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

        $officialMsg =  Redis::hget('official_account_info:app_id:'.$appid, 'official_account_info');

        $official_object = json_decode($officialMsg);


        return response()->success(['official_account_info'=>$official_object]);

    }




    // 获取模板或者客服信息Redis
    function getWechatMsgRedis(Request $request)
    {

        $task_id = $request->has('task_id') ? $request->input('task_id') : '';

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

        $officialMsg =  Redis::hget('send_wechat_msg:task_id:'.$task_id, 'wechat_msg');

        \Log::info($officialMsg);

        $official_object = json_decode($officialMsg);


        return response()->success(['official_account_info'=>$official_object]);

    }


    // 通过appid获取公众号
    function officialAccountByAppidTestRedis(Request $request)
    {
        $appid = $request->has('appid') ? $request->input('appid') : '';

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

        $officialAccountPrams['appid'] = $appid;

        $officialAccountService = OfficialAccountService::officialAccountByAppid($officialAccountPrams);

        return response()->item(new OfficialAccountTransformer(), $officialAccountService);

    }


    // 获取模板或者客服信息Redis
    function testSendMailDelayQueue(Request $request)
    {

        $test = '这是一条测试的Email信息。。。。';

        /**
         *  通过Job方式发送模板消息-----queue
         */
        $job = (new SendTestEmail($test))->onConnection('rabbitmq')->delay(20);

        dispatch($job);

        return response()->success(['send_email_queue_delay_test'=>$test]);

    }


    // 所有公众号发送模板消息
    function updateOfficialToRedisTest(Request $request)
    {

        $allOfficialAccounts = OfficialAccount::getAllOfficialAccountDB();
        if(count($allOfficialAccounts)>0){
            for ($i=0; $i < count($allOfficialAccounts); $i++) {
                $official_accounts = $allOfficialAccounts[$i];

                $wechatTemplates = WechatTemplates::wechatTemplateByAppidAndTemplateId($official_accounts['appid'],'TM405959659');

                if(empty($wechatTemplates)) {
                    \Log::info('send_template5555555555:======未找到模板');
                }else{

                    $wechatTemplateMsgs['appid'] = $official_accounts['appid'];
                    $wechatTemplateMsgs['distribution_channel_id'] = $official_accounts['distribution_channel_id'];
                    $wechatTemplateMsgs['status'] = '1';
                    $wechatTemplateMsgs['del_flag'] = 0;
                    $wechatTemplateMsgs['user_num'] = 0;
                    $wechatTemplateMsgs['name'] = '2018狗年春节钜惠';
                    $wechatTemplateMsgs['send_time'] = '2018-02-14 20:30:21';
                    $wechatTemplateMsgs['template_content'] = '[{"first.DATA":["尊敬的会员： 恭喜您抽中双节双重大礼包！","#ff0000"]},{"keynote1.DATA":["充50送50 、充108送128！书币翻倍读不停！","#0099ff"]},{"keynote2.DATA":["活动时间2月14日-2月21日","#ff0000"]},{"remark.DATA":["点击【详情】，立即领取限时大礼包>>>","#0099ff"]}]';
                    $wechatTemplateMsgs['redirect_url'] = 'https://site'.$official_accounts['distribution_channel_id'].'.leyuee.com/sale/springactivity?token=1JMfs0yjYR1CV6Bsf8ZWlp34WIYsg61d';
                    $wechatTemplateMsgs['remark'] = '';

                    $wechatTemplateMsgs['subscribe_time'] = 'z';
                    $wechatTemplateMsgs['sex'] = 'z';
                    $wechatTemplateMsgs['balance'] = 'z';
                    $wechatTemplateMsgs['order_type'] = 'z';
                    $wechatTemplateMsgs['category_id'] = 'z';

                    $wechatTemplateMsgs['template_id'] = $wechatTemplates['template_id'];

                    $templateMsgs = WechatTemplateMsgs::create($wechatTemplateMsgs);

                    $officialAccountArray = $templateMsgs->toArray();
                    Redis::hset('send_wechat_msg:task_id:'.$templateMsgs['id'], 'wechat_msg', json_encode($officialAccountArray));

                }

            }
        }

        return response()->success(['sign'=>count($allOfficialAccounts)]);

    }
    
    // 根据用户id获取推荐的书籍
    function getSimpleChannelBook(Request $request){
    	$uid = $request->get('uid');
    	$num = 6;
    	$bid =1;
    	$books = BookConfigService::getSimpleChannelBookLoop($bid,$num,$uid);
    	return response()->success($books);
    }

//    // 获取模板或者客服信息Redis
//    function updateOfficialToRedisTest(Request $request)
//    {
//
//
//        $timestamp = 1517556929;
//
//        $allOfficialAccounts = OfficialAccount::getAllOfficialAccountDB();
//        if(count($allOfficialAccounts)>0){
//            for ($i=0; $i < count($allOfficialAccounts); $i++) {
//
//                $official_accounts = $allOfficialAccounts[$i];
//                $params = array("authorizer_appid"=>$official_accounts['appid'],"timestamp"=>$timestamp);
//                $sign = get_sign($params);
//
//                try {
//
//                    $mediaCustomerJson = $this->getUserClient()->request("GET","auto_set_menu_and_template_test",
//                        ['query'=>['authorizer_appid'=>$official_accounts['appid'],'timestamp'=>$timestamp,'sign'=>$sign],'connect_timeout' => 3]
//                    )->getBody()->getContents();
//
//                } catch (\Exception $e) {
//                    \Log::info($e);
//                }
//
//
//            }
//        }
//
//        return response()->success(['sign'=>count($allOfficialAccounts)]);
//
//    }
//
    public function getUserClient(){
        // return new Client(['base_uri' => 'http://118.31.133.29/api/']);
        return new Client(['base_uri' => 'http://zsyauth.aizhuishu.com/oauth/']);
    }
    
}