<?php

namespace App\Http\Controllers\Wechat\OfficialAccount;

use App\Modules\Channel\Services\ChannelService;
use App\Modules\Book\Services\BookSearchStatService;
use App\Http\Controllers\Channel\BaseController as ChannelBaseController;
use App\Modules\Channel\Models\Channel;
use App\Modules\Channel\Models\YqMoveChannel;
use App\Modules\OfficialAccount\Models\MediaCustomer;
use App\Modules\OfficialAccount\Models\OfficialAccount;
use App\Modules\OfficialAccount\Models\OfficialInteractiveEvent;
use App\Modules\OfficialAccount\Models\WechatKeywordMsgs;
use App\Modules\OfficialAccount\Models\DistributionReply;
use App\Modules\OfficialAccount\Models\DistributionSelfDefineContent;
use App\Modules\OfficialAccount\Models\DistributionSelfDefineConfig;
use App\Modules\OfficialAccount\Services\OfficialAccountService;
use App\Modules\OfficialAccount\Services\CustomMsgService;
use App\Modules\OfficialAccount\Services\MsgService;
use App\Modules\User\Services\ReadRecordService;
use App\Modules\OfficialAccount\Services\ForceSubscribeService;
use App\Http\Controllers\Wechat\OfficialAccount\Transformers\OfficialInteractiveEventTransformer;
use App\Http\Controllers\Wechat\OfficialAccount\Transformers\OfficialInteractiveEventTextTransformer;
use App\Modules\Book\Services\BookConfigService;
use App\Modules\User\Services\UserSignService;
use Illuminate\Http\Request;
use GuzzleHttp\Client;
use App\Libs\OSS;
use Hashids;
use App\Modules\Book\Models\BookConfig;
      
class OfficialInteractiveEventController extends ChannelBaseController
{

    /**
     * @apiDefine OfficialAccount 公众号
     */

    /**
     * @apiVersion 1.0.0
     * @api {GET} OfficialAccount/OfficialInteractiveEventFeedback 公众号交互事件推送
     * @apiGroup OfficialAccount
     * @apiName OfficialInteractiveEventFeedback
     * @apiParam   {String}  appid 公众号的appid.
     * @apiParam   {String}  event 事件类型.
     * @apiParam   {String}  content text类型下的搜索条件.
     * @apiSuccess {String}  text 返回的文字信息.
     * @apiSuccess {String}  title 搜索出的书籍标题.
     * @apiSuccess {String}  description 搜索出的书籍简介.
     * @apiSuccess {String}  url 搜索出的书籍链接.
     * @apiSuccess {String}  image 搜索出的书籍封面地址.
     * @apiSuccessExample {json} Success-Response:
     *
     *      {
     *          "code": 0,
     *          "msg": "",
     *          "data": {
     *              "text": "用户取消强制关注"
     *          }
     *      }
     *  
     *      {
     *          "code": 0,
     *          "msg": "",
     *          "data": [
     *              {
     *                  "title": "肌缘巧合",
     *                  "description": "&nbsp;&nbsp;&nbsp;&nbsp;他是权势倾天,纵横商界的王者,却偏偏钟情于她,一宠成瘾。“女人,我要你......只要你能满足我,别墅、游轮、支票,你随便挑。”她羞涩的半低着头:“我只想要你。”他挑眉,“你野心不小啊!”她妩媚一笑,解开他的领带,“难道你不愿意!”他宠她爱她,给她所有想要的。只是有一天她终于忍不住暴走,“靠,你有没有节制呀?我要离婚。”",
     *                  "url": "test2.ycsd.cn?bid=5",
     *                  "image": "https:\/\/leyue-bucket.oss-cn-hangzhou.aliyuncs.com\/ycsd_cover\/covermiddle\/0\/8.jpg"
     *              },
     *              {
     *                  "title": "等你爱我",
     *                  "description": "&nbsp;&nbsp;&nbsp;&nbsp;“只要你愿意成全我,给你所有……”黑暗中,她为救他,成了他的女人,他却隔天清晨匆匆离去。六年后,她进入他的公司,与他擦肩而过,却互不相识,但一切却悄然发生改变,他有了自己爱的人,她有了爱自己的人……她带着女儿疲于奔命,他重新进入她的生活,当他决定娶她时,她却淡淡一笑,转身离开……",
     *                  "url": "test2.ycsd.cn?bid=9",
     *                  "image": "https:\/\/leyue-bucket.oss-cn-hangzhou.aliyuncs.com\/ycsd_cover\/covermiddle\/0\/4.jpg"
     *              }
     *          ]
     *      }
     */

    function officialInteractiveEventFeedback(Request $request)
    {

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

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

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

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

        $openid = $request->has('openid') ? $request->input('openid') : '';
        \Log::info('-------------------------');
        \Log::info($openid);
        if(empty($event)) {
            return response()->error("PARAM_EMPTY");
        }

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

        $officialAccount = OfficialAccount::officialAccountByAppid($appid);
        $distribution_channel_id = '';
        if (!empty($officialAccount)) {
            $distribution_channel_id = $officialAccount['distribution_channel_id'];
        }else{
            $distribution_channel_id = '';
        }

        if($event == "text"){
            if(empty($content)) {
                return response()->error("PARAM_EMPTY");
            }
        }
        $encode_distribution_channel_id = encodeDistributionChannelId($distribution_channel_id);
        
        // 判断渠道是否是外站派单(需要我们帮生成强关用户)
        $channel = Channel::getById($distribution_channel_id);
        $is_outer_site = isset($channel->is_outer_site)?$channel->is_outer_site:'0';
        $is_domain_simple = isset($channel->is_domain_simple)?$channel->is_domain_simple:'0';
        if($is_domain_simple == '1'){
        	$encode_distribution_channel_id = $distribution_channel_id;
        }

        $is_yq_move = '0';
        // 新站
        if(isset($channel->is_yq_move) && $channel->is_yq_move){
        	\Log::info('new_has_move_site:'.$distribution_channel_id);
        	$is_yq_move = 1;
        }
        // 已经迁移过的站,回复也要有老站
        $yqMoveChannel = YqMoveChannel::get_yq_move_channel($distribution_channel_id,1);
        if(!empty($yqMoveChannel)){
        	\Log::info('old_has_move_site:'.$distribution_channel_id);
        	$is_yq_move = 1;
        }
        
        $params['openid'] = $openid;
        $forceSubscribeUser = ForceSubscribeService::forceSubscribeUsersByOpenid($params);
        $uid = isset($forceSubscribeUser->uid)?$forceSubscribeUser->uid:'0';
        
        \Log::info('distribution_channel_id:'.$distribution_channel_id.' is_outer_site:'.$is_outer_site.' is_yq_move:'.$is_yq_move.' uid:'.$uid);
        
        if ($event == "text") {

        	// 搜索写入
        	if($content != 'search_get_recommend_book'){
        		if(strlen($content) <= 100){
        			BookSearchStatService::create($uid,$openid,'wechat',$content);
        		}
        	}
        	
        	// 单独推送一本智能推荐的书
        	if($content == 'search_get_recommend_book'){
        		\Log::info('get_recommend_book:'.$openid);
        		$feedback['text'] = "";
        		return response()->item(new OfficialInteractiveEventTransformer(), (object)$feedback);
        		
        		// 有自定义不回复内容的渠道
        		$distribution_self_define_config = DistributionSelfDefineConfig::getDistributionSelfDefineConfig($distribution_channel_id,'recommend_book_noreply');
        		if(!empty($distribution_self_define_config)){
        			\Log::info('distribution_self_define_config_no_recommend_book: distribution_channel_id:'.$distribution_channel_id);
        			$feedback['text'] = "";
        			return response()->item(new OfficialInteractiveEventTransformer(), (object)$feedback);
        		}
        		
        		$bid = isset($forceSubscribeUser->bid)?$forceSubscribeUser->bid:'0';
        		$params['openid'] = $openid;
        		$recommend_book = BookConfigService::getSimpleChannelBookLoop($bid,1,$uid);

        		$feedback['text'] = '';
        		if(!empty($recommend_book)){
        			$bookUrl = env('PROTOCOL').'://site'.encodeDistributionChannelId($distribution_channel_id).'.'.env('WECHAT_CUSTOM_HOST').'.com';
        			$bookUrl = $bookUrl.$recommend_book[0]->url.'&fromtype='.$content.'&source=wechatmsg&fromsource=smart_push';
        			
        			$feedback['text'] = '新书推荐: <a href="' . $bookUrl . '"> 《' . $recommend_book[0]->book_name . '》</a>';
        			$feedback['text'] = ChannelService::convertChannelReplyUrl($is_outer_site,$appid, $openid, $feedback['text'],'get_one_recommend_book');
        		}
        		return response()->item(new OfficialInteractiveEventTransformer(), (object)$feedback);
        	}
        	if($content == '签到'){
        		//调洋哥的接口发送签到客服消息
        		\Log::info('text_sign:'.$openid);
        		$feedback['text'] = UserSignService::userSignReturnContent3($openid,$distribution_channel_id);
        		$feedback['text'] = ChannelService::convertChannelReplyUrl($is_outer_site,$appid, $openid, $feedback['text'],'text_sign');
        		return response()->item(new OfficialInteractiveEventTransformer(), (object)$feedback);
        	}
        	
        	$booksInfo = array();
        	// 判断是否自定义关键字
        	$special_keyword = WechatKeywordMsgs::wechatKeywordByDistributionChannelIdAndKeyword($distribution_channel_id,$content,1);
        	if(!empty($special_keyword)){
        		\Log::info('officialInteractiveEventFeedback_has_special_keyword:'.$distribution_channel_id.' content:'.$content);
        		\Log::info($special_keyword);
        		$bid = Hashids::decode($special_keyword['bid'])[0];
        		\Log::info('bid:'.$bid);
        		$book_conf = BookConfig::getBookById($bid);
        		\Log::info('$book_conf');\Log::info($book_conf);
        		if(!empty($book_conf)){
        			$special_keyword_new = array();
        			$special_keyword_new['book_name'] = isset($special_keyword['send_title']) && !empty($special_keyword['send_title'])?$special_keyword['send_title']:$book_conf['book_name'];
        			$special_keyword_new['cover'] = isset($special_keyword['send_cover']) && !empty($special_keyword['send_cover'])?$special_keyword['send_cover']:$book_conf['cover'];
                    \Log::info('keyword_book_name:'.$special_keyword_new['book_name'].' cover:'.$special_keyword_new['cover']);
        			$special_keyword_new['intro'] =  $book_conf['intro'];
        			// 此处为自定义的章节链接https://site163.leyuee.com/reader?bid=N948JQDWpb7mx0K6zaKV5j2zOeZABdaL&cid=382260&fromtype=custom_3070&soid=30771
        			// 有派单id的关键字不做统计
        			if(isset($special_keyword['send_order_id']) && $special_keyword['send_order_id'] > 0){
        				$special_keyword_new['book_url'] = '/yun/'.$special_keyword['send_order_id'];
        			}else{
        				$special_keyword_new['book_url'] = '/reader?bid='.$special_keyword['bid'].'&cid='.$special_keyword['cid'].'&fromtype=keyword_'.$special_keyword['id'];
        			}
        			$special_keyword_new['bid'] =  $special_keyword['bid'];
        			$booksInfo[] = $special_keyword_new;
        		}else{
        			\Log::info('book_conf_null:'.$distribution_channel_id.' content:'.$content);
        		}
        	}else{
        		$booksInfo = BookConfig::getBooksByKey($content,3);
        	}
        	\Log::info('event_booksInfo');
        	\Log::info($booksInfo);
            if(count($booksInfo) == 0){
                $feedback['text'] = '未找到相关小说,'."\n".'您可以试试:'."\n"."\n".'<a href="'.env('PROTOCOL').'://site'.$encode_distribution_channel_id.'.'.env('WECHAT_CUSTOM_HOST').'.com/recent">查看阅读记录 >> </a> '."\n"."\n".'<a href="'.env('PROTOCOL').'://site'.$encode_distribution_channel_id.'.'.env('WECHAT_CUSTOM_HOST').'.com">去书城首页看看 >> </a> '."\n"."\n".'联系客服:'."\n".'点击菜单栏 “用户中心“ > ”联系客服”';
                // $feedback['text'] = "未找到您想要的书\n<a href='".env('PROTOCOL')."://site".$distribution_channel_id.".".env('WECHAT_CUSTOM_HOST').".com'>点我进入书城</a>\n\n";
                $feedback['text'] = ChannelService::convertChannelReplyUrl($is_outer_site,$appid, $openid, $feedback['text'],'text_search');
                return response()->item(new OfficialInteractiveEventTransformer(), (object)$feedback);
            }else{
                $data=[];
                for ($i=0; $i < count($booksInfo); $i++) { 
                    $bid = $booksInfo[$i]['bid'];
  
                    \Log::info('wechat_log_info:book');\Log::info($booksInfo[$i]);
                    $base_url =  env('PROTOCOL').'://site'.$encode_distribution_channel_id.'.'.env('WECHAT_CUSTOM_HOST').'.com'.$booksInfo[$i]['book_url'];
                    $instro_len = strlen($booksInfo[$i]['intro']);
                    \Log::info('wechat_log_info:len:'.$instro_len.' getURL-----'.$base_url);
                    if( $instro_len > 100){
                    	$booksInfo[$i]['intro'] = mb_substr($booksInfo[$i]['intro'], 0, 100, 'utf-8');
                    	$booksInfo[$i]['intro'] .= '......';
                    	\Log::info('search_instro_too_long:'.$booksInfo[$i]['intro']);
                    }
                    $data[$i]=['url'=>$base_url,
                    'title'=>$booksInfo[$i]['book_name'],
                    'description'=>$booksInfo[$i]['intro'],
                    'image'=>$booksInfo[$i]['cover']];
                    
                    // 返回一条
                    break;
                }
                $datatext['text'] = $data;
                $datatext['text'] = ChannelService::convertChannelReplyUrl($is_outer_site,$appid, $openid, $datatext['text'],'text_search');
                 return response()->success($datatext);
                // return response()->collection(new OfficialInteractiveEventTextTransformer(),$data);

            }
        }
        
        elseif($event == "scan"){
        	// 有自定义不回复内容的渠道
        	$distribution_self_define_config = DistributionSelfDefineConfig::getDistributionSelfDefineConfig($distribution_channel_id,'force_subscribe_noreply');
        	if(!empty($distribution_self_define_config)){
        		\Log::info('distribution_self_define_config: distribution_channel_id:'.$distribution_channel_id);
        		$feedback['text'] = "";
        		return response()->item(new OfficialInteractiveEventTransformer(), (object)$feedback);
        	}
        	
            $feedback['text'] = "<a href='".env('PROTOCOL')."://site".$encode_distribution_channel_id.".".env('WECHAT_CUSTOM_HOST').".com/continue'>点此继续阅读 </a> ";
            $feedback['text'] = ChannelService::convertChannelReplyUrl($is_outer_site,$appid, $openid, $feedback['text'],'scan');
            
            return response()->item(new OfficialInteractiveEventTransformer(), (object)$feedback);
        }
        elseif($event == "click"){
           
            if($content == "contact_customer" && !empty($appid)){
              
              
                if (config('common.click_type')) {
                   
                    # code...
                    \Log::info('wechat_log_info:getURL-----进入方法');
                    $mediaCustomer = MediaCustomer::mediaCustomerByAppid($appid);
                    if (count($mediaCustomer)>0) {
                        # code...
                        // $send_event_contents = array();
                        for ($i=0; $i < count($mediaCustomer); $i++) { 
                            # code...
                            $send_event_content = array();
                            $send_event_content['image'] = array('media_id'=>$mediaCustomer[$i]['media_id']);
                            // $send_event_content['text'] = 'test_zhoulj';
                            return response()->success($send_event_content);
                            // $send_event_contents[$i] = $send_event_content;
                        }
                        

                    }else{
                        $timestamp = (time());
                        $gzh_app_id = $appid;
                        $group_nick = env('GROUP_NICK');
                        $officialAccountPrams['appid'] = $appid;
                        $officialAccount = (object)OfficialAccountService::officialAccountByAppid($officialAccountPrams);
                        \Log::info('++++++++++++=====GET CUSTOM IMG  [1]  =====+++++++++++++');

                        if (!empty($officialAccount)) {

                            $distributionChannelSetting = CustomMsgService::customerImgUrlByChannelId($officialAccount->distribution_channel_id);
                            \Log::info('++++++++++++=====GET CUSTOM IMG  [2]  =====+++++++++++++');

                            if (!empty($distributionChannelSetting)) {
                                # code...
                                
                                $params = array("gzh_app_id"=>$appid,"group_nick"=>$group_nick,"is_default"=>0,"img_url"=>$distributionChannelSetting['customer_img_url'],"timestamp"=>$timestamp);
                                $sign = get_sign($params);
                                
                                $mediaCustomerJson ='';

                                try {
                                     $mediaCustomerJson = $this->getUserClient()->request("GET","upload_gzh_img/",
                                        ['query'=>['gzh_app_id'=>$appid,'group_nick'=>env('GROUP_NICK'),"is_default"=>0,"img_url"=>$distributionChannelSetting['customer_img_url'],'timestamp'=>$timestamp,'sign'=>$sign],'connect_timeout' => 3]
                                        )->getBody()->getContents();
                                } catch (\Exception $e) {
                                    \Log::info('++++++++++++=====GET CUSTOM IMG  [0]  =====+++++++++++++');

                                }
                               
                                
                                

                                $mediaCustomerArray = json_decode($mediaCustomerJson,true);
                                \Log::info('++++++++++++=====GET CUSTOM IMG  [3]  =====+++++++++++++');
                                \Log::info($mediaCustomerArray);
                                // \Log($mediaCustomerArray);
                                // dd($mediaCustomerArray);
                                if ($mediaCustomerArray['code'] == 1) {
                                    # code...
                                    $mediaCustomerData = $mediaCustomerArray['data'];
                                    if (empty($mediaCustomerDat)) {
                                        # code...


                                        $mediaCustomerCreate['media_id'] = $mediaCustomerData['media_id'];
                                        $mediaCustomerCreate['url'] = $mediaCustomerData['url'];
                                        $mediaCustomerCreate['appid'] = $appid;
                                        $mediaCustomerCreate['distribution_channel_id'] = $officialAccount->distribution_channel_id;

                                        MediaCustomer::create($mediaCustomerCreate);

                                        $send_event_content = array();
                                        $send_event_content['image'] = array('media_id'=>$mediaCustomerData['media_id']);
                                        // $send_event_content['text'] = 'test_zhoulj';                           
                                        return response()->success($send_event_content);
                                    }
                                    
                                    
                                }else{
                                    
                                    $feedback['text'] = "客服QQ:3389644904\n客服电话:0571-56680019\n在线时间:工作日9:00-21:00\n";
                                    return response()->item(new OfficialInteractiveEventTransformer(), (object)$feedback);

                                }


                            }else{
                                

                                $params = array("gzh_app_id"=>$appid,"group_nick"=>$group_nick,"timestamp"=>$timestamp);
                                $sign = get_sign($params);
                                \Log::info('wechat_log_info:getURL-----'.env('MEDIA_API_BASE_URI'));
                                \Log::info('wechat_log_info:getURL-----'.$gzh_app_id.'___'.$timestamp.'___'.$sign);
                                $mediaCustomerJson ='';

                                try {
                                     $mediaCustomerJson = $this->getUserClient()->request("GET","upload_gzh_img/",
                                        ['query'=>['gzh_app_id'=>$appid,'group_nick'=>env('GROUP_NICK'),'timestamp'=>$timestamp,'sign'=>$sign],'connect_timeout' => 3]
                                        )->getBody()->getContents();
                                } catch (\Exception $e) {
                                     \Log::info('wechat_log_info:Exception-----'.$e->getMessage());
                                }
                               
                                \Log::info('wechat_log_info:getURL-----'.env('MEDIA_API_BASE_URI'));
                                

                                $mediaCustomerArray = json_decode($mediaCustomerJson,true);
                                // \Log($mediaCustomerArray);
                                // dd($mediaCustomerArray);
                                if ($mediaCustomerArray['code'] == 1) {
                                    # code...
                                    $mediaCustomerData = $mediaCustomerArray['data'];
                                    if (empty($mediaCustomerDat)) {
                                        # code...


                                        $mediaCustomerCreate['media_id'] = $mediaCustomerData['media_id'];
                                        $mediaCustomerCreate['url'] = $mediaCustomerData['url'];
                                        $mediaCustomerCreate['appid'] = $appid;
                                        $mediaCustomerCreate['distribution_channel_id'] = $officialAccount->distribution_channel_id;

                                        MediaCustomer::create($mediaCustomerCreate);

                                        $send_event_content = array();
                                        $send_event_content['image'] = array('media_id'=>$mediaCustomerData['media_id']);
                                        // $send_event_content['text'] = 'test_zhoulj';                           
                                        return response()->success($send_event_content);
                                    }
                                    
                                    
                                }else{
                                    
                                    $feedback['text'] = "客服QQ:3389644904\n客服电话:0571-56680019\n在线时间:工作日9:00-21:00\n";
                                    return response()->item(new OfficialInteractiveEventTransformer(), (object)$feedback);

                                }


                            }
                            
                            

                        }
                        
                        
                    }

                }else{
                    $feedback['text'] = "客服QQ:3389644904\n在线时间:工作日9:00-21:00\n";
                    return response()->item(new OfficialInteractiveEventTransformer(), (object)$feedback);
                }
                

            }elseif ($content == "daily_sign" && !empty($openid)) {
                
                //调洋哥的接口发送签到客服消息
                \Log::info('========================进入洋哥签到回调');
                $feedback['text'] = UserSignService::userSignReturnContent3($openid,$distribution_channel_id);
                $feedback['text'] = ChannelService::convertChannelReplyUrl($is_outer_site,$appid, $openid, $feedback['text'],'daily_sign');
                return response()->item(new OfficialInteractiveEventTransformer(), (object)$feedback);

            }elseif ($content == "recent_read" && !empty($openid)) {
            	
            	if($is_yq_move){
            		$feedback['text'] = ForceSubscribeService::getYqMoveReply($distribution_channel_id,$openid);
            	}
            	else
            	{
            		$feedback['text'] = "<a href='".env('PROTOCOL')."://site".$encode_distribution_channel_id.".".env('WECHAT_CUSTOM_HOST').".com/recent'>点击查看最近阅读 </a>\n\n ";
            		// 添加优质书库
            		$sex = ForceSubscribeService::getSexByOpenid($distribution_channel_id,$openid);
            		$sex_type = $sex_content = '';
            		if($sex == 1){
            			$sex_type = 'boy';
            			$sex_content = '☞ 都市、玄幻、历史、军事、网游、灵异、科幻等海量书库任你看';
            		}else{
            			$sex_type = 'girl';
            			$sex_content = '☞ 豪门、总裁、虐恋、婚宠、女尊、宫斗、经商、灵异等海量书库任你看';
            		}
            		$feedback['text'] .= "<a href='".env('PROTOCOL')."://site".$encode_distribution_channel_id.".".env('WECHAT_CUSTOM_HOST').".com/stock?sex=".$sex_type."'>".$sex_content."</a>";
            	}
            	
            	// 追加热门书籍
            	$feedback['text'] .= BookConfigService::getHotRandomRecommendBookText($distribution_channel_id,$uid, 2);

                $feedback['text'] = ChannelService::convertChannelReplyUrl($is_outer_site,$appid, $openid, $feedback['text'],'recent_read');
                return response()->item(new OfficialInteractiveEventTransformer(), (object)$feedback);
            }

            // $feedback['text'] = "客服QQ:3389644904\n客服电话:0571-56680019\n在线时间:工作日9:00-21:00\n";
            // return response()->item(new OfficialInteractiveEventTransformer(), (object)$feedback);
        }
        elseif($event == "unsubscribe"){
            $feedback['text'] = "";
            return response()->item(new OfficialInteractiveEventTransformer(), (object)$feedback);
        }
        elseif($event == "subscribe"){
        	// 有自定义不回复内容的渠道
        	$distribution_self_define_config = DistributionSelfDefineConfig::getDistributionSelfDefineConfig($distribution_channel_id,'force_subscribe_noreply');
        	if(!empty($distribution_self_define_config)){
        		\Log::info('distribution_self_define_config: distribution_channel_id:'.$distribution_channel_id);
        		$feedback['text'] = "";
        		return response()->item(new OfficialInteractiveEventTransformer(), (object)$feedback);
        	}
        	
            /**
            * 第 三 版
            */
            \Log::info('000000000000');
            if (!empty($openid)) {
                # code...
                \Log::info('subscribe:'.$openid.' distribution_channel_id:'.$distribution_channel_id);
                $params['openid'] = $openid;
                $forceSubscribeUser = ForceSubscribeService::forceSubscribeUsersByOpenid($params);
                \Log::info($forceSubscribeUser);
                
                // 有自定义回复内容的渠道
//                 $distribution_self_define_content = DistributionSelfDefineContent::getDistributionSelfDefineContent($distribution_channel_id);
                // 从redis取
                $distribution_self_define_content = MsgService::getCurrentReply($distribution_channel_id);
                
                \Log::info('distribution_self_define_content:'.json_encode($distribution_self_define_content));
//                 \Log::info($distribution_self_define_content);
                if(is_null($distribution_self_define_content)){
                	// 获取特殊渠道的关注回复追加热门书籍推荐
                	$distribution_replay = DistributionReply::getDistributionReply($distribution_channel_id);
                	\Log::info('distribution_replay:'.json_encode($distribution_replay));
                	$recommend_content = '';
                	if(!is_null($distribution_replay)){
                		$special_bids = explode(',', $distribution_replay->reply_bids);
                	
                		$recomm_books = BookConfigService::getBidRecommendBooks($special_bids);
                		if (!is_null($recomm_books)) {
                			$recommend_content = "\n\n" . '热门书籍推荐';
                			foreach ($recomm_books as $book) {
                				$url = env('PROTOCOL') . '://site' . $encode_distribution_channel_id . '.' . env('WECHAT_CUSTOM_HOST') . '.com/reader?bid=' . Hashids::encode($book->bid) . '&cid=' . $book->first_cid;
                				$recommend_content .= "\n\n" . '<a href="' . $url . '"> >>' . $book->book_name . '</a>';
                			}
                		}
                	}
                	
                	if (!empty($forceSubscribeUser)) {
                		# code...
                		\Log::info('exist_force_user:'.$openid);

                		//通过uid获取该用户最近阅读记录的书籍
                		$uid = isset($forceSubscribeUser->uid)?$forceSubscribeUser->uid:'';
                		$userBook = ReadRecordService::getFirstReadRecord($uid);
                		$bookName = isset($userBook['book_name'])?$userBook['book_name']:'最近阅读';
                		\Log::info('bookName:'.$bookName);
                	
                		if(!empty($recommend_content)){
                			$feedback['text'] = '亲,终于等到你了!'."\n"."\n".'<a href="'.env('PROTOCOL').'://site'.$encode_distribution_channel_id.'.'.env('WECHAT_CUSTOM_HOST').'.com/continue">点我继续阅读 </a> '."\n"."\n".'阅读记录:'."\n"."\n".'><a href="'.env('PROTOCOL').'://site'.$encode_distribution_channel_id.'.'.env('WECHAT_CUSTOM_HOST').'.com/continue">'.$bookName.'</a>';
                			$feedback['text'] .= $recommend_content;
                			$feedback['text'] .= "\n"."\n".'为方便下次阅读,请'.'<a href="https://help.leyuee.com/top.html">'.'置顶公众号'.'</a>';
                		}else{
                			$feedback['text'] = '亲,终于等到你了!'."\n"."\n".'<a href="'.env('PROTOCOL').'://site'.$encode_distribution_channel_id.'.'.env('WECHAT_CUSTOM_HOST').'.com/continue">点我继续阅读 </a> '."\n"."\n".'阅读记录:'."\n"."\n".'><a href="'.env('PROTOCOL').'://site'.$encode_distribution_channel_id.'.'.env('WECHAT_CUSTOM_HOST').'.com/continue">'.$bookName.'</a>'."\n"."\n".'为方便下次阅读,请'.'<a href="https://help.leyuee.com/top.html">'.'置顶公众号'.'</a>'."\n\n".'今日签到成功,赠送30书币,连续签到2日后,赠送书币增加至50哦~,进入<a href="'.env('PROTOCOL').'://site'.$encode_distribution_channel_id.'.'.env('WECHAT_CUSTOM_HOST').'.com/person">个人中心 </a>查看!'."\n\n".'明日继续签到得书币哦!';
                		}
                	
                	}else{
                		$feedback['text'] = "<a href='".env('PROTOCOL')."://site".$encode_distribution_channel_id.".".env('WECHAT_CUSTOM_HOST').".com/continue'>点击继续阅读 </a> ";
                		$feedback['text'] .= $recommend_content;
                	}
                	
                	// 外站关注的直接回复图文qrscene_outer:123_12
                	if(strpos($content,'outer') > -1){
                		$scene_content = str_replace('qrscene_outer:','',$content);
                		$bid_cid = explode('_', $scene_content);
                		$bid = isset($bid_cid[0])?$bid_cid[0]:'';
                		$cid = isset($bid_cid[1])?$bid_cid[1]:'';
                		if(!empty($bid) && !empty($cid)){
                			$book_conf = BookConfig::getBookById($bid);
                			\Log::info('out_book_conf');\Log::info($book_conf);
                			if(!empty($book_conf)){
                				$data = array();
                				$encode_bid = Hashids::encode($bid);
                				$data[]=['url'=>env('PROTOCOL').'://site'.$encode_distribution_channel_id.'.'.env('WECHAT_CUSTOM_HOST').'.com'.'/reader?bid='.$encode_bid.'&cid='.$cid.'&fromtype=outer_'.$scene_content,
                				'title'=>$book_conf['book_name'],
                				'description'=>$book_conf['intro'],
                				'image'=>$book_conf['cover']
                				];
                				
                				\Log::info('outer:'.json_encode($data));
                				$feedback['text'] = $data;
                			}
                		}
                	}
                	
                }else{
                	// 判断是否图文
                	if(isset($distribution_self_define_content->is_pic) && $distribution_self_define_content->is_pic){
                		$feedback['text'] = ImageNewsToArray($distribution_self_define_content->content);
                	}else{
                		$feedback['text'] = isset($distribution_self_define_content->content)?$distribution_self_define_content->content:'';
                	}
                }
                $feedback['text'] = ChannelService::convertChannelReplyUrl($is_outer_site,$appid, $openid, $feedback['text'],'subscribe');
                return response()->item(new OfficialInteractiveEventTransformer(), (object)$feedback);
                
            }else{
            		$feedback['text'] = "<a href='".env('PROTOCOL')."://site".$encode_distribution_channel_id.".".env('WECHAT_CUSTOM_HOST').".com/continue'>点击继续阅读 </a> ";
            		$feedback['text'] = ChannelService::convertChannelReplyUrl($is_outer_site,$appid, $openid, $feedback['text'],'subscribe');
            		return response()->item(new OfficialInteractiveEventTransformer(), (object)$feedback);
            }

        }elseif($event == "TEMPLATESENDJOBFINISH"){
            $feedback['text'] = "";
            return response()->item(new OfficialInteractiveEventTransformer(), (object)$feedback);
        }else{
            // $feedback['text'] = "事件未配置";
            // return response()->item(new OfficialInteractiveEventTransformer(), (object)$feedback);
            return response()->error('EVENT_NOT_FOUND');
        }
    }


    public function getUserClient(){
        // return new Client(['base_uri' => 'http://118.31.133.29/api/']);
        return new Client(['base_uri' => env('MEDIA_API_BASE_URI')]);
    }

 
}