<?php

namespace App\Http\Controllers\Wechat\OfficialAccount;

use App\Consts\Channel\ChannelConst;
use App\Http\Controllers\Controller;
use App\Modules\Book\Services\BookService;
use App\Modules\Channel\Services\ChannelService;
use App\Modules\Book\Services\BookSearchStatService;
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\OfficialAccountMsgService;
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 Redis;
use DB;
use App\Modules\Book\Models\BookConfig;
use App\Modules\Promotion\Services\PromotionService;
use App\Modules\OfficialAccount\Models\ForceSubscribeUsers;
use App\Modules\User\Models\User;

class OfficialInteractiveEventController extends Controller
{

    /**
     * @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') : '';

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

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

        $openid = $request->has('openid') ? $request->input('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;
        }

        $params['openid']   = $openid;
        $forceSubscribeUser = ForceSubscribeService::forceSubscribeUsersByOpenid($params);
        $uid                = isset($forceSubscribeUser->uid) ? $forceSubscribeUser->uid : '0';

        $WECHAT_CUSTOM_HOST = env('WECHAT_CUSTOM_HOST');

        $base_url = env('PROTOCOL') . "://site" . $encode_distribution_channel_id . "." . $WECHAT_CUSTOM_HOST . ".com";
        $help_url = env('PROTOCOL') . '://help.' . $WECHAT_CUSTOM_HOST . '.com?distribution_channel_id=' . $encode_distribution_channel_id;

        if ($event == "text") {
            // 有自定义不回复文本内容的渠道
            $distribution_self_define_config = DistributionSelfDefineConfig::getDistributionSelfDefineConfig($distribution_channel_id, 'force_subscribe_notext_reply');
            if (!empty($distribution_self_define_config)) {
                $feedback['text'] = "";
                return response()->item(new OfficialInteractiveEventTransformer(), (object)$feedback);
            }

            // 搜索写入
            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);

                $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) . '.' . $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, $WECHAT_CUSTOM_HOST);

                $top_url = OfficialAccountService::getTopUrl($officialAccount->service_type_info);
                if ($officialAccount->service_type_info == 1) {
                    $top_content = "\n\n" . '为方便阅读，请<a href="' . $top_url . '">设为星标</a>';
                } else {
                    $top_content = "\n\n" . '为方便阅读，请<a href="' . $top_url . '">置顶公众号</a>';
                }

                $feedback['text'] .= $top_content;

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

            if ($content == '最近阅读') {
                // $channel_sex = ChannelService::getChannelCompanySex($distribution_channel_id);
                $channelInfo = ChannelService::getById($distribution_channel_id);
                $property    = isset($channelInfo->property) ? $channelInfo->property : '';
                $channel_sex = 3;
                if ($property === ChannelConst::PROPERTY_MALE) {
                    $channel_sex = 1;
                }
                if ($property === ChannelConst::PROPERTY_FEMALE) {
                    $channel_sex = 2;
                }
                \Log::info('channel_sex:' . $channel_sex . ' distribution_channel_id:' . $distribution_channel_id . ' property:' . $property);

                $feedback['text'] = "尊敬的会员：\n\n <a href='" . env('PROTOCOL') . "://site" . $encode_distribution_channel_id . "." . $WECHAT_CUSTOM_HOST . ".com/recent'>☞ 点我继续上次阅读 </a>";

                if ($channel_sex != 1) {
                    // 根据用户性别确定男女频
                    $sex          = ForceSubscribeService::getUserRealSexByUid($uid);
                    $channel_name = $sex == 1 ? '男频' : '女频';

                    // 站点属性优先
                    if ($channel_sex == 2) {
                        $channel_name = '女频';
                    }

                    $recomm_books = BookConfigService::getSignRecommendBooksFromCache([], $channel_name, 2);

                    $recent_read_reco_content = '';
                    if ($recomm_books) {
                        // 判断是否不展示书名
                        $self_config      = ChannelService::check_channel_account_priv($distribution_channel_id, 'hide_book_name');
                        $hide_type        = isset($self_config->type) ? $self_config->type : 'not_hide';
                        $recommend_titles = [];
                        if ($hide_type == 'hide_book_name') {
                            \Log::info('hide_book_name reco:' . $distribution_channel_id . ' uid:' . $uid);
                            $recommend_titles = PromotionService::getRandomHeadline($sex, count($recomm_books));
                        }

                        $recent_read_reco_content .= "\n\n" . '热门书籍推荐~';
                        foreach ($recomm_books as $key => $book) {
                            $book_name = $book->book_name;
                            if ($hide_type == 'hide_book_name') {
                                $book_name = isset($recommend_titles[$key]->title) ? $recommend_titles[$key]->title : $book->book_name;
                            }

                            $url                      = env('PROTOCOL') . '://site' . encodeDistributionChannelId($distribution_channel_id) . '.' . env('CUSTOM_HOST') . '.com/reader?bid=' . Hashids::encode($book->bid) . '&cid=' . $book->first_cid;
                            $recent_read_reco_content .= "\n\n" . '<a href="' . $url . '"> ☞ 《' . $book_name . '》</a>';
                        }
                    }
                    $feedback['text'] .= $recent_read_reco_content;
                } else {
                    // 男频站点
                    // 1本在测的，1本优质书，共2本，如果没有在测的书，则返回2本优质书
                    // 用户按照15天注册后的用户
                    $sex = ForceSubscribeService::getUserRealSexByUid($uid);
                    [$bids, $test_bid] = BookConfig::getLeftRecomBids($uid, '男频', 2);
                    \Log::info('bids and test_bid:' . $uid . ' data:' . json_encode([$bids, $test_bid]));
                    if ($bids) {
                        $recomm_books             = BookService::getSimpleBooksByIds($bids);
                        $recent_read_reco_content = '';
                        if ($recomm_books) {
                            // 判断是否不展示书名
                            $self_config      = ChannelService::check_channel_account_priv($distribution_channel_id, 'hide_book_name');
                            $hide_type        = isset($self_config->type) ? $self_config->type : 'not_hide';
                            $recommend_titles = [];
                            if ($hide_type == 'hide_book_name') {
                                \Log::info('hide_book_name reco:' . $distribution_channel_id . ' uid:' . $uid);
                                $recommend_titles = PromotionService::getRandomHeadline($sex, count($recomm_books));
                            }

                            $recent_read_reco_content .= "\n\n" . '热门书籍推荐~';
                            foreach ($recomm_books as $key => $book) {
                                $book_name = $book->name;
                                if ($hide_type == 'hide_book_name') {
                                    $book_name = isset($recommend_titles[$key]->title) ? $recommend_titles[$key]->title : $book_name;
                                }

                                $url = env('PROTOCOL') . '://site' . encodeDistributionChannelId($distribution_channel_id) . '.' . env('CUSTOM_HOST') . '.com/reader?bid=' . Hashids::encode($book->id) . '&cid=' . $book->first_cid;
                                if ($book->id == $test_bid) {
                                    $url .= '&fromsource=smart_push';
                                }
                                $recent_read_reco_content .= "\n\n" . '<a href="' . $url . '"> ☞ 《' . $book_name . '》</a>';
                            }
                        }
                        $feedback['text'] .= $recent_read_reco_content;
                    }
                }

                $feedback['text'] = ChannelService::convertChannelReplyUrl($is_outer_site, $appid, $openid, $feedback['text'], 'recent_read');
                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);

                // 图文模式(页面类型)
                if ($special_keyword['mode'] == 1 && $special_keyword['link_type'] == 'page') {
                    if (isset($special_keyword['send_order_id']) && $special_keyword['send_order_id'] > 0) {
                        $special_keyword['link'] .= '/yun/' . $special_keyword['send_order_id'];
                    } else {
                        $special_keyword['link'] .= '?fromtype=keyword_' . $special_keyword['id'];
                    }

                    $datatext['text'] = [
                        [
                            'url'         => $special_keyword['link'],
                            'title'       => textDecode($special_keyword['send_title']),
                            'description' => textDecode($special_keyword['desc']),
                            'image'       => $special_keyword['send_cover']
                        ]
                    ];
                    $datatext['text'] = ChannelService::convertChannelReplyUrl($is_outer_site, $appid, $openid, $datatext['text'], 'text_search');
                    return response()->success($datatext);
                }

                if ($special_keyword['mode'] == 2) {
                    $nickname = DB::connection('api_mysql')->table('users')->where(['openid'=>$openid, 'distribution_channel_id'=>$distribution_channel_id])->value('nickname');
                    $datatext['text'] = textDecode(str_replace('{user}', $nickname, $special_keyword['content']));
                    $datatext['text'] = ChannelService::convertChannelReplyUrl($is_outer_site, $appid, $openid, $datatext['text'], 'text_search', 'keyword_' . $special_keyword['id']);
                    return response()->success($datatext);
                }

                $bid = Hashids::decode($special_keyword['bid'])[0];
                \Log::info('bid:' . $bid);
                $book_conf = BookConfig::getBookById($bid);
                if (!empty($book_conf)) {
                    $special_keyword_new              = array();
                    $special_keyword_new['book_name'] = isset($special_keyword['send_title']) && !empty($special_keyword['send_title']) ? textDecode($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'];
                    // 有派单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'] . '&source=wechatmsg';
                    }
                    $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, 1);
                try {
                    if (count($booksInfo) == 0) {
                        //$role_book = BookConfig::getFromRole($content);
                        $role_book = BookConfigService::getBookByRole($content);
                        if ($role_book) {
                            $booksInfo[] = [
                                'book_name' => $role_book->book_name,
                                'intro'     => '',
                                'cover'     => $role_book->cover,
                                'bid'       => $role_book->bid,
                                'book_url'  => '/detail?id=' . Hashids::encode($role_book->bid),
                            ];
                        }
                    }

                } catch (\Exception $e) {

                }

            }

            if (count($booksInfo) == 0) {
                if (preg_match('/^[0-9]+$/', $content)) {
                    $channel_sex = ChannelService::getChannelCompanySex($distribution_channel_id);

                    $feedback['text'] = "尊敬的会员：\n\n <a href='" . env('PROTOCOL') . "://site" . $encode_distribution_channel_id . "." . $WECHAT_CUSTOM_HOST . ".com/recent'>☞ 点我继续上次阅读 </a>";

                    if ($channel_sex != 1) {

                        //热门书籍推荐
                        $sex          = ForceSubscribeService::getUserRealSexByUid($uid);
                        $channel_name = $sex == 1 ? '男频' : '女频';
                        $recomm_books = BookConfigService::getSignRecommendBooksFromCache([], $channel_name, 2);

                        $recent_read_reco_content = '';
                        if ($recomm_books) {
                            // 判断是否不展示书名
                            $self_config      = ChannelService::check_channel_account_priv($distribution_channel_id, 'hide_book_name');
                            $hide_type        = isset($self_config->type) ? $self_config->type : 'not_hide';
                            $recommend_titles = [];
                            if ($hide_type == 'hide_book_name') {
                                \Log::info('hide_book_name reco:' . $distribution_channel_id . ' uid:' . $uid);
                                $recommend_titles = PromotionService::getRandomHeadline($sex, count($recomm_books));
                            }

                            $recent_read_reco_content .= "\n\n" . '热门书籍推荐~';
                            foreach ($recomm_books as $key => $book) {
                                $book_name = $book->book_name;
                                if ($hide_type == 'hide_book_name') {
                                    $book_name = isset($recommend_titles[$key]->title) ? $recommend_titles[$key]->title : $book->book_name;
                                }

                                $url                      = env('PROTOCOL') . '://site' . encodeDistributionChannelId($distribution_channel_id) . '.' . env('CUSTOM_HOST') . '.com/reader?bid=' . Hashids::encode($book->bid) . '&cid=' . $book->first_cid;
                                $recent_read_reco_content .= "\n\n" . '<a href="' . $url . '"> ☞ 《' . $book_name . '》</a>';
                            }
                        }
                        $feedback['text'] .= $recent_read_reco_content;
                    }

                    $feedback['text'] = ChannelService::convertChannelReplyUrl($is_outer_site, $appid, $openid, $feedback['text'], 'recent_read');
                    return response()->item(new OfficialInteractiveEventTransformer(), (object)$feedback);
                }
                $feedback['text'] = '未找到相关小说，' . "\n" . '您可以试试：' . "\n" . "\n" . '<a href="' . env('PROTOCOL') . '://site' . $encode_distribution_channel_id . '.' . $WECHAT_CUSTOM_HOST . '.com/recent">查看阅读记录 >> </a> ' . "\n" . "\n" . '<a href="' . env('PROTOCOL') . '://site' . $encode_distribution_channel_id . '.' . $WECHAT_CUSTOM_HOST . '.com">去书城首页看看 >> </a> ' . "\n" . "\n" . '点此<a href="https://help.wd.amanbook.com/?distribution_channel_id=' . encodeDistributionChannelId($distribution_channel_id) . '&down=1">联系客服</a>';
                $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'];

                    $base_url   = env('PROTOCOL') . '://site' . $encode_distribution_channel_id . '.' . $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'       => textDecode($booksInfo[$i]['book_name']),
                                 'description' => textDecode($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);

            }
        } 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 . "." . $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") {
            \Log::info('content:' . $content);
            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'] = env('CUSTOM_RETURN_MSG');
                                    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'] = env('CUSTOM_RETURN_MSG');
                                    return response()->item(new OfficialInteractiveEventTransformer(), (object)$feedback);
                                }
                            }
                        }
                    }

                } else {
                    $feedback['text'] = env('CUSTOM_RETURN_MSG');
                    return response()->item(new OfficialInteractiveEventTransformer(), (object)$feedback);
                }


            } elseif ($content == "daily_sign" && !empty($openid)) {
                //强关信息
                $user = ForceSubscribeUsers::getOneForceSubscribeUsersByOpenid($openid);
                if (!$user) {
                    $feedback['text'] = "亲爱的用户，本次签到最高可领取150书币哦\n\n/:heart".'<a href="weixin://bizmsgmenu?msgmenucontent=签到&msgmenuid=hudonglian">点击此处签到领书币</a>';
                }else {
                    //用户信息
                    $user_info = User::where('id',$user->uid)->first();
                    if ($user_info && !empty($user_info->nickname)) {
                        $feedback['text'] = '亲爱的'.$user_info->nickname."，本次签到最高可领取150书币哦\n\n/:heart".'<a href="weixin://bizmsgmenu?msgmenucontent=签到&msgmenuid=hudonglian">点击此处签到领书币</a>';
                    }else {
                        $feedback['text'] = "亲爱的用户，本次签到最高可领取150书币哦\n\n/:heart".'<a href="weixin://bizmsgmenu?msgmenucontent=签到&msgmenuid=hudonglian">点击此处签到领书币</a>';
                    }
                }
                return response()->item(new OfficialInteractiveEventTransformer(), (object)$feedback);

                //调洋哥的接口发送签到客服消息
                \Log::info('========================进入洋哥签到回调');
                try {
                    $feedback['text'] = UserSignService::userSignReturnContent3($openid, $distribution_channel_id, $WECHAT_CUSTOM_HOST);
                } catch (\Exception $e) {
                    \Log::error('sign_activity_error:');
                    \Log::error($e);
                }

                $top_url = OfficialAccountService::getTopUrl($officialAccount->service_type_info);
                if ($officialAccount->service_type_info == 1) {
                    $top_content = "\n\n" . '为方便阅读，请<a href="' . $top_url . '">设为星标</a>';
                } else {
                    $top_content = "\n\n" . '为方便阅读，请<a href="' . $top_url . '">置顶公众号</a>';
                }

                $feedback['text'] .= $top_content;

                $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)) {
                $feedback['text'] = '欢迎回来，<a href="weixin://bizmsgmenu?msgmenucontent=最近阅读&msgmenuid=hudonglian">点此继续阅读~</a>';
                return response()->item(new OfficialInteractiveEventTransformer(), (object)$feedback);

                // $channel_sex = ChannelService::getChannelCompanySex($distribution_channel_id);
                $channelInfo = ChannelService::getById($distribution_channel_id);
                $property    = isset($channelInfo->property) ? $channelInfo->property : '';
                $channel_sex = 3;
                if ($property === ChannelConst::PROPERTY_MALE) {
                    $channel_sex = 1;
                }
                if ($property === ChannelConst::PROPERTY_FEMALE) {
                    $channel_sex = 2;
                }
                \Log::info('channel_sex:' . $channel_sex . ' distribution_channel_id:' . $distribution_channel_id . ' property:' . $property);

                $feedback['text'] = "尊敬的会员：\n\n <a href='" . env('PROTOCOL') . "://site" . $encode_distribution_channel_id . "." . $WECHAT_CUSTOM_HOST . ".com/recent'>☞ 点我继续上次阅读 </a>";

                if ($channel_sex != 1) {
                    // 根据用户性别确定男女频
                    $sex          = ForceSubscribeService::getUserRealSexByUid($uid);
                    $channel_name = $sex == 1 ? '男频' : '女频';

                    // 站点属性优先
                    if ($channel_sex == 2) {
                        $channel_name = '女频';
                    }

                    $recomm_books = BookConfigService::getSignRecommendBooksFromCache([], $channel_name, 2);

                    $recent_read_reco_content = '';
                    if ($recomm_books) {
                        // 判断是否不展示书名
                        $self_config      = ChannelService::check_channel_account_priv($distribution_channel_id, 'hide_book_name');
                        $hide_type        = isset($self_config->type) ? $self_config->type : 'not_hide';
                        $recommend_titles = [];
                        if ($hide_type == 'hide_book_name') {
                            \Log::info('hide_book_name reco:' . $distribution_channel_id . ' uid:' . $uid);
                            $recommend_titles = PromotionService::getRandomHeadline($sex, count($recomm_books));
                        }

                        $recent_read_reco_content .= "\n\n" . '热门书籍推荐~';
                        foreach ($recomm_books as $key => $book) {
                            $book_name = $book->book_name;
                            if ($hide_type == 'hide_book_name') {
                                $book_name = isset($recommend_titles[$key]->title) ? $recommend_titles[$key]->title : $book->book_name;
                            }

                            $url                      = env('PROTOCOL') . '://site' . encodeDistributionChannelId($distribution_channel_id) . '.' . env('CUSTOM_HOST') . '.com/reader?bid=' . Hashids::encode($book->bid) . '&cid=' . $book->first_cid;
                            $recent_read_reco_content .= "\n\n" . '<a href="' . $url . '"> ☞ 《' . $book_name . '》</a>';
                        }
                    }
                    $feedback['text'] .= $recent_read_reco_content;
                } else {
                    // 男频站点
                    // 1本在测的，1本优质书，共2本，如果没有在测的书，则返回2本优质书
                    // 用户按照15天注册后的用户
                    $sex = ForceSubscribeService::getUserRealSexByUid($uid);
                    [$bids, $test_bid] = BookConfig::getLeftRecomBids($uid, '男频', 2);
                    \Log::info('bids and test_bid:' . $uid . ' data:' . json_encode([$bids, $test_bid]));
                    if ($bids) {
                        $recomm_books             = BookService::getSimpleBooksByIds($bids);
                        $recent_read_reco_content = '';
                        if ($recomm_books) {
                            // 判断是否不展示书名
                            $self_config      = ChannelService::check_channel_account_priv($distribution_channel_id, 'hide_book_name');
                            $hide_type        = isset($self_config->type) ? $self_config->type : 'not_hide';
                            $recommend_titles = [];
                            if ($hide_type == 'hide_book_name') {
                                \Log::info('hide_book_name reco:' . $distribution_channel_id . ' uid:' . $uid);
                                $recommend_titles = PromotionService::getRandomHeadline($sex, count($recomm_books));
                            }

                            $recent_read_reco_content .= "\n\n" . '热门书籍推荐~';
                            foreach ($recomm_books as $key => $book) {
                                $book_name = $book->name;
                                if ($hide_type == 'hide_book_name') {
                                    $book_name = isset($recommend_titles[$key]->title) ? $recommend_titles[$key]->title : $book_name;
                                }

                                $url = env('PROTOCOL') . '://site' . encodeDistributionChannelId($distribution_channel_id) . '.' . env('CUSTOM_HOST') . '.com/reader?bid=' . Hashids::encode($book->id) . '&cid=' . $book->first_cid;
                                if ($book->id == $test_bid) {
                                    $url .= '&fromsource=smart_push';
                                }
                                $recent_read_reco_content .= "\n\n" . '<a href="' . $url . '"> ☞ 《' . $book_name . '》</a>';
                            }
                        }
                        $feedback['text'] .= $recent_read_reco_content;
                    }
                }

                $feedback['text'] = ChannelService::convertChannelReplyUrl($is_outer_site, $appid, $openid, $feedback['text'], 'recent_read');
                return response()->item(new OfficialInteractiveEventTransformer(), (object)$feedback);
            } // 个别渠道是事件
            elseif ($content == "user_center" && !empty($openid)) {
                \Log::info('click_user_center:' . $openid);
                $feedback['text'] = "☞ <a href='" . $base_url . "/person'>个人中心</a>\n\n";
                $feedback['text'] .= "☞ <a href='" . $base_url . "/'>书城首页</a>\n\n";
                $feedback['text'] .= "☞ <a href='" . $base_url . "/pay'>优惠充值</a>\n\n";
                $feedback['text'] .= "☞ <a href='" . $help_url . "'>帮助中心</a>\n";

                $feedback['text'] = ChannelService::convertChannelReplyUrl($is_outer_site, $appid, $openid, $feedback['text'], 'user_center');
                return response()->item(new OfficialInteractiveEventTransformer(), (object)$feedback);
            } elseif ($content == "qrcode_main" && !empty($openid)) {

                $msg = OfficialAccountMsgService::getEventMsg(['appid' => $appid, 'apply_event' => 'click', 'apply_event_key' => 'qrcode_main']);
                if ($msg) {
                    $send_event_content          = array();
                    $send_event_content['image'] = array('media_id' => $msg->return_content);
                    return response()->success($send_event_content);

                } else {
                    $feedback['text'] = '配置有误';
                    return response()->item(new OfficialInteractiveEventTransformer(), (object)$feedback);
                }

            }
        } elseif ($event == "unsubscribe") {
            $feedback['text'] = "";
            return response()->item(new OfficialInteractiveEventTransformer(), (object)$feedback);
        } elseif ($event == "subscribe") {
            // 统计
            $sub_statistic_key = 'gzh_actual_sub:' . $appid . ':' . date('Y-m-d');
            \Log::info('sub_statistic_key:' . $sub_statistic_key);
            Redis::sadd($sub_statistic_key, $openid);
            Redis::expire($sub_statistic_key, 30 * 3600);
            
            // 有自定义不回复内容的渠道
            $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);
            }

            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);

                // 判断渠道，如果是场景值关注过来的，则普通回复，否则自定义回复
                $subscribe_from_scene = DistributionSelfDefineConfig::getDistributionSelfDefineConfig($distribution_channel_id, 'subscribe_from_scene');
                if (!empty($subscribe_from_scene)) {
                    if (!empty($content) && strpos($content, 'qrscene_') === 0) {
                        $distribution_self_define_content = null;
                        \Log::info('subscribe_from_scene:' . $distribution_channel_id);
                    }
                }

                if (is_null($distribution_self_define_content)) {
                    $recommend_content = '';

                    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 . '.' . $WECHAT_CUSTOM_HOST . '.com/continue">点我继续阅读 </a> ' . "\n" . "\n" . '阅读记录：' . "\n" . "\n" . '><a href="' . env('PROTOCOL') . '://site' . $encode_distribution_channel_id . '.' . $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 . '.' . $WECHAT_CUSTOM_HOST . '.com/continue">点我继续阅读 </a> ' . "\n" . "\n" . '阅读记录：' . "\n" . "\n" . '><a href="' . env('PROTOCOL') . '://site' . $encode_distribution_channel_id . '.' . $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 . '.' . $WECHAT_CUSTOM_HOST . '.com/person">个人中心 </a>查看！' . "\n\n" . '明日继续签到得书币哦！';
                        }

                    } else {
                        $feedback['text'] = "<a href='" . env('PROTOCOL') . "://site" . $encode_distribution_channel_id . "." . $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 . '.' . $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');

                // 判断是否有关注回复第二条，有则推送 
                MsgService::pushChannelCurrentSecondReply($distribution_channel_id, $appid, $openid, 'subscribe_second_reply');

                return response()->item(new OfficialInteractiveEventTransformer(), (object)$feedback);

            } else {
                $feedback['text'] = "<a href='" . env('PROTOCOL') . "://site" . $encode_distribution_channel_id . "." . $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 {
            return response()->error('EVENT_NOT_FOUND');
        }
    }


    public function getUserClient()
    {
        return new Client(['base_uri' => env('MEDIA_API_BASE_URI')]);
    }


}
