<?php
/**
 * Created by sublime.
 * User: wosinC
 * Date: 2017/12/2
 * Time: 上午11:39
 */


namespace App\Modules\OfficialAccount\Services;

use App\Modules\Book\Models\DataAnalysisBookConfig;
use App\Modules\OfficialAccount\Services\ForceSubscribeService;
use App\Modules\OfficialAccount\Services\TemplateCustomSendService;
use App\Modules\OfficialAccount\Models\ForceSubscribeUsers;
use App\Modules\OfficialAccount\Models\OfficialAccount;
use App\Modules\OfficialAccount\Models\OfficialCustomMsg;
use App\Modules\OfficialAccount\Models\CustomMsgSwitchs;
use App\Modules\OfficialAccount\Models\CustomMsgSwitchsMsgs;
use App\Modules\OfficialAccount\Models\CustomSendMsgs;
use App\Modules\OfficialAccount\Models\DistributionChannelSetting;
use App\Modules\OfficialAccount\Models\OfficialImgtextUrls;
use App\Modules\User\Services\ReadRecordService;
use App\Modules\User\Services\UserService;
use App\Modules\Book\Services\BookConfigService;
use App\Modules\OfficialAccount\Services\OfficialAccountService;
use App\Modules\OfficialAccount\Services\SmartPushMsgService;
use App\Modules\Statistic\Services\DataAnalysisChapterService;
use App\Modules\Promotion\Services\PromotionService;
use App\Modules\Channel\Services\ChannelService;
use App\Modules\OfficialAccount\Models\MediaCustomer;
use App\Modules\OfficialAccount\Models\CustomPushActivitys;
use App\Modules\OfficialAccount\Models\CustomPushConfigs;
use App\Modules\OfficialAccount\Models\CustomPushConfigContents;
use App\Modules\OfficialAccount\Models\CustomSendDayStats;
use GuzzleHttp\Client;
use GuzzleHttp\Promise;
use App\Libs\OSS;
use Redis;
use App\Jobs\SendNews;
use App\Jobs\SendTexts;
use App\Jobs\SendTemplate;
use App\Jobs\CustomMsgSendJob;
use DB;
use  Hashids;

class CustomMsgService
{


    /**
     * 通过channelName和text获取神书
     */
    static function customerMsgByChannelAndText($channelname,$text)
    {
        return OfficialCustomMsg::customerMsgByChannelAndText($channelname,$text);
    }


    /**
     * 通过分销渠道ID获取客服图片
     */
    static function customerImgUrlByChannelId($distribution_channel_id)
    {
        return DistributionChannelSetting::customerImgUrlByChannelId($distribution_channel_id);
    }

    /**
     * 添加客服图片
     */
    static function updateCustomerImgUrl($customerImgPram)
    {
        //通过分销渠道号寻找客服图片
        $customerImgs = DistributionChannelSetting::customerImgUrlByChannelId($customerImgPram['distribution_channel_id']);
        if (empty($customerImgs)) {

            //2，删除media_customer表中老的客服图片的mediaid,
            //以便灵杰公众号交互下次该渠道请求客服图片时重新去渠道获取新的客服图片
            MediaCustomer::where('distribution_channel_id',$customerImgPram['distribution_channel_id'])->delete();

            //该渠道配置表中增加客服图片
            return DistributionChannelSetting::create($customerImgPram);



        }else{

            //1，该渠道配置表中更新客服图片
            $customerImgs['customer_img_url'] = $customerImgPram['customer_img_url'];
            $customerImgs->save();

            //2，删除media_customer表中老的客服图片的mediaid,
            //以便灵杰公众号交互下次该渠道请求客服图片时重新去渠道获取新的客服图片
            MediaCustomer::where('distribution_channel_id',$customerImgPram['distribution_channel_id'])->delete();
            return $customerImgs;
        }

    }


    /**
     * 未支付订单发送客服消息
     */
    static function sendUnpaid()
    {

        //1，遍历渠道表
        $distribution_channels =  ChannelService::getAllChannels();
        $today = date('Y-m-d');

        for ($i=0; $i < count($distribution_channels); $i++) {

            //2,判断该渠道下有没有开启未支付订单的智能推送
            $distribution_channel_id = $distribution_channels[$i]['id'];
            // 针对订单级别，一个用户可能扔多次
            $key = 'leyuee:to_send_not_pay_uid:distribution_channel_id:'.$distribution_channel_id;

            $customMsgSwitch = CustomMsgSwitchsMsgs::customMsgSwitchsByChannelCate($distribution_channel_id,'not_pay');
            
            if (!empty($customMsgSwitch)) {
                
                if ($customMsgSwitch['status'] == '1') {

                    \Log::info('<----获取 开启订单未支付提醒的 渠道号---->');
                    \Log::info($distribution_channel_id);

                    //3，如果开启了  先获取该渠道下redis待发送的用户
                    $not_order_users = Redis::hgetall($key);

                    //\Log::info('<----获取 渠道下 用户---->');
                    
                    if (!empty($not_order_users)) {

                        $customSendStatsCount = CustomSendDayStats::customSendDayStatsByChannelAndFromAndDay($distribution_channel_id,'not_pay',date("Y-m-d"));
                        if (empty($customSendStatsCount)) {
                            $customSendDayStats['distribution_channel_id'] = $distribution_channel_id;
                            $customSendDayStats['from'] = 'not_pay';
                            $customSendDayStats['push_user_num'] = count($not_order_users);
                            $customSendDayStats['date'] = date("Y-m-d");
                            CustomSendDayStats::create($customSendDayStats);
                        }else{
                            $customSendStatsCount['push_user_num'] = $customSendStatsCount['push_user_num']+count($not_order_users);
                            $customSendStatsCount->save();
                        }

                        foreach ($not_order_users as $uid => $time) {
                            //\Log::info('<----redis中找到用户 获取uid 时间差---->');
                            //\Log::info($uid);
                            //\Log::info(time()-$time);
                            //4，计算这些用户未支付订单是否大于1小时
                            $now_time = time()-$time;
                            if ($now_time > 3600)
                            {

                                //5,从Redis中获取并判断这些用户 今日是否已经发送过“未支付订单提醒”
                                $today_key = "sended_not_pay_uid:distribution_channel_id:".$distribution_channel_id.":day:".$today;
                                if(!Redis::sismember($today_key, $uid))
                                {

                                    //6，判断用户当前是否为强关用户
                                    $force_user = ForceSubscribeService::forceSubscribeUsersByUid(compact('uid'));
                                    if (!empty($force_user)) {

                                        //\Log::info('<----满足条件的强关用户 发送客服消息---->');
                                        //\Log::info($uid);

                                        //(1),发送（文字）未支付客服提醒至RebitMQ
                                        self::add_text_task($force_user);

                                        //(2)， 今日的redis增加一条记录，每天只发一次
                                        Redis::sadd($today_key, $uid);
                                        Redis::expire($today_key,3600*24*3);
                                       
                                    }


                                    //7，将该用户在未支付订单待发送的Redis中移除
                                    Redis::hdel($key,$uid);

                                }else{

                                    //8，如果发送过，直接将该用户从未支付订单待发送redis中移除
                                    Redis::hdel($key,$uid);
                                }
                            }
                        }
                    }else{
                        \Log::info('<----redis中该渠道下没有找到用户---->');
                       
                    }

                }else{

                    //智能推送未支付订单关闭状态
                    //直接删除该渠道下未支付订单的redis键
                    Redis::del($key);
                }
            }else{

                //智能推送还未创建（默认关闭）
                //直接删除该渠道下未支付订单的redis键
                Redis::del($key);
            }
        }
    }


    /**
     * RebitMQ发送24小时未支付订单提醒（文字）
     */
    static function add_text_task($force_user){

        $uid = $force_user['uid'];
        $distribution_channel_id = $force_user['distribution_channel_id'];

        //通过uid获取该用户最近阅读记录的书籍
        $userBook = ReadRecordService::getFirstReadRecord($uid);
        \Log::info('<----获取用户 最近阅读记录---->');
        
        if (!empty($userBook)) {

            $data = array();

            $data['openid'] = $force_user['openid'];
            $data['appid'] = $force_user['appid'];

            //用户最近阅读链接
            $continueReadUrl = env('PROTOCOL').'://site'.encodeDistributionChannelId($distribution_channel_id).'.'.env('CUSTOM_HOST').'.com/continue?fromtype=not_pay';

            //拼接文案和用户最近阅读书籍的链接以及书籍名称
            //$data['content'] = '亲，你上次看的书还在等着你呐~点击继续阅读'."\n".'<a href="'.$continueReadUrl.'"> >《'.$userBook['book_name'].'》</a>'."\n".'首冲50元即可畅读100万字，年费VIP更可全年无限畅读。'."\n".'为方便下次阅读，请'.'<a href="https://help.leyuee.com/top.html">'.'置顶公众号'.'</a>';
            $data['content'] = '亲，你上次看的书还在等着你呐~'."\n".'<a href="'.$continueReadUrl.'"> >点击继续阅读</a>'."\n".'首冲50元即可畅读100万字，年费VIP更可全年无限畅读。'."\n".'为方便下次阅读，请'.'<a href="https://help.leyuee.com/top.html">'.'置顶公众号'.'</a>';
            $data['type'] = 'one_task';// last_task,one_task
            $data['task_id'] = 1;
            $data['send_time'] = date("Y-m-d H:i:s");
            $send_data=array(
                'send_time'=>date("Y-m-d H:i:s"),
                'data' => $data
            );
            //\Log::info($data['openid']);
            //\Log::info($data['appid']);
            //\Log::info($data['content']);

            $delay = 0;

            $job = (new SendTexts($send_data))->onConnection('rabbitmq')->delay($delay)->onQueue('send_texts_list');
            dispatch($job);
        }else{
            \Log::info('<----抱歉 没有最近阅读记录---->');
        }
    }


    /**
     * RebitMQ发送24小时未支付订单提醒（图文）
     */
    static function add_news_task($force_user,$officialCustomMsg){


        $data = array();
        $data['openid'] = $force_user['openid'];
        $data['appid'] = $force_user['appid'];
        $data['news_content'] = '[[{"title":"'.$officialCustomMsg['title'].'"},{"description":"'.$officialCustomMsg['description'].'"},{"url":"'.$officialCustomMsg['url'].'"},{"image":"'.$officialCustomMsg['image'].'"}]]';

        $data['type'] = 'one_task';// last_task,one_task
        $data['task_id'] = 3;
        $data['send_time'] = date("Y-m-d H:i:s");
        $send_data=array(
            'send_time'=>date("Y-m-d H:i:s"),
            'data' => $data
        );

        $delay = 0;

        $job = (new SendNews($send_data))->onConnection('rabbitmq')->delay($delay)->onQueue('send_news_list');
        dispatch($job);

    }


    /**
     *  三天回本推送（定时任务 12小时推）
     */
    static function add_news_recovery_push_hot(){

        \Log::info('=======================三天回本推送客服消息');
        //1，遍历渠道表
        $distribution_channels =  ChannelService::getAllChannels();

        for ($k=0; $k < count($distribution_channels); $k++) { 
            
            //2,判断该渠道下有没有开启 未支付订单的智能推送
            $distribution_channel_id = $distribution_channels[$k]['id'];

            
            $customMsgSwitch = CustomMsgSwitchsMsgs::customMsgSwitchsByChannelCate($distribution_channel_id,'recovery_push');
            
            if (!empty($customMsgSwitch)) {
                
                if ($customMsgSwitch['status'] == '1') {

                    

                    \Log::info('<----开启客服的 渠道号---->');
                    \Log::info($distribution_channel_id);
                    //3，开通智能推送的渠道获取 渠道下的强关用户
                    $forceSubscribeUsersPrams['distribution_channel_id'] = $distribution_channel_id;
                    $forceSubscribeUsersPrams['timeset'] = 43200;
                    $force_user = ForceSubscribeService::forceSubscribeNewUsersByTimeset($forceSubscribeUsersPrams);
                    //\Log::info('<----渠道下强关用户数---->');
                    //\Log::info(count($force_user));

                    $customSendStatsCount = CustomSendDayStats::customSendDayStatsByChannelAndFromAndDay($distribution_channel_id,'recovery_push',date("Y-m-d"));
                    if (empty($customSendStatsCount)) {
                        $customSendDayStats['distribution_channel_id'] = $distribution_channel_id;
                        $customSendDayStats['from'] = 'recovery_push';
                        $customSendDayStats['push_user_num'] = count($force_user);
                        $customSendDayStats['date'] = date("Y-m-d");
                        CustomSendDayStats::create($customSendDayStats);
                    }else{
                        $customSendStatsCount['push_user_num'] = $customSendStatsCount['push_user_num']+count($force_user);
                        $customSendStatsCount->save();
                    }

                    for ($i=0; $i < count($force_user); $i++) {                       

                        //（1）通过uid去已发送客服消息Redis中获取是否推送过该类型客服消息
                        //（2）如果有，获取插入的时间，
                        // 如果时间在今天之内，那就不发送，
                        // 如果不是，就发送，并往Redis中插入一条数据
                        $uid = $force_user[$i]['uid'];

                        if(!Redis::hget('add_news_recovery_push_hot'.$uid, 'time'))
                        {

                            $bid = $force_user[$i]['bid'];

                            $booksArray = [];

                            //4，获取男频女频的标签文案
                            $manPromotion = PromotionService::getRandomHeadline(1,5);
                            $womanPromotion = PromotionService::getRandomHeadline(2,5);

                          
                            //7,获取和用户强关进来的书相同类型的5本优质评分的书籍
//                             $books = BookConfigService::getSimpleChannelBook($bid,5);
                            $books = BookConfigService::getSimpleChannelBookLoop($bid,5,$uid);
                            $bookUrl = env('PROTOCOL').'://site'.encodeDistributionChannelId($distribution_channel_id).'.'.env('CUSTOM_HOST').'.com';
                            $promotionNum = 0;
                            if ($books) {
                                
                                foreach ($books as $key => $value) {

                                    //8,将这四本书作为推送的2-5条信息，同样拼接书籍信息和标签文案
                                    $urlBook = $value->url = $bookUrl.$value->url.'&fromtype=recovery_push';
                                    $channelName = $value->channel_name;
                                    $cover = $value->cover;
                                    if($channelName == '男频'){
                                        $book['title'] = $manPromotion[$promotionNum]['title'];
                                        $book['description'] = $manPromotion[$promotionNum]['title'];
                                    }else{
                                        $book['title'] = $womanPromotion[$promotionNum]['title'];
                                        $book['description'] = $womanPromotion[$promotionNum]['title'];
                                    }
                                    $book['url'] = $urlBook;
                                    $book['image'] = $cover;
                                    if ($promotionNum == 0) {
                                        //第一条图片选用图库中的图片地址
                                        $promotionImages = PromotionService::getMessageRandomDocumentCovers(3);
                                        if ($promotionImages) {
                                            $book['image'] = $promotionImages[0]['link'];
                                        }else{
                                            $book['image'] = $cover;
                                        }
                                        
                                    }else{
                                        $book['image'] = $cover;
                                    }
                                    
                                    $booksArray[] = [['title'=>$book['title']],['description'=>$book['description']],['url'=>$book['url']],['image'=>$book['image']]];

                                    $promotionNum++;

                                }

                                //9，通过RebitMQ推送热门书籍到指定用户
                                $data = array();
                                $data['openid'] = $force_user[$i]['openid'];
                                $data['appid'] = $force_user[$i]['appid'];
                                $data['news_content'] = json_encode($booksArray);
                                $data['type'] = 'one_task';
                                $data['task_id'] = 3;
                                $data['send_time'] = date("Y-m-d H:i:s");
                                $send_data=array(
                                    'send_time'=>date("Y-m-d H:i:s"),
                                    'data' => $data
                                );

                                $delay = 0;

                                //\Log::info('<---- 客服消息发送内容 参数---->');
                                //\Log::info($data['openid']);
                                //\Log::info($data['appid']);
                                //\Log::info($data['news_content']);

                                //\Log::info('<----Rebit-MQ 发送热门书籍推送客服消息---->');
                                $job = (new SendNews($send_data))->onConnection('rabbitmq')->delay($delay)->onQueue('send_news_list');
                                dispatch($job);

                                Redis::hset('add_news_recovery_push_hot'.$uid, 'time', time());

                            }                                                                                  
                        }                        
                    }
                }
            }
        }
    }


    /**
     *  三天回本推送（定时任务 24小时推）
     */
    static function add_news_recovery_push_activity(){

        \Log::info('=======================三天回本推送客服消息');
        //1，遍历渠道表
        $distribution_channels =  ChannelService::getAllChannels();

        $customPushActivitys = CustomPushActivitys::customPushActivitys();
        $custom_url = $customPushActivitys['url'];
        $custom_image = $customPushActivitys['image'];
        $custom_title = $customPushActivitys['title'];

        for ($k=0; $k < count($distribution_channels); $k++) { 
            
            //2,判断该渠道下有没有开启 未支付订单的智能推送
            $distribution_channel_id = $distribution_channels[$k]['id'];

            
            $customMsgSwitch = CustomMsgSwitchsMsgs::customMsgSwitchsByChannelCate($distribution_channel_id,'recovery_push');
            
            if (!empty($customMsgSwitch)) {
                
                if ($customMsgSwitch['status'] == '1') {

                    //\Log::info('<----开启客服的 渠道号---->');
                    //\Log::info($distribution_channel_id);
                    //3，开通智能推送的渠道获取 渠道下的强关用户
                    $forceSubscribeUsersPrams['distribution_channel_id'] = $distribution_channel_id;
                    $forceSubscribeUsersPrams['timeset'] = 86400;
                    $force_user = ForceSubscribeService::forceSubscribeNewUsersByTimeset($forceSubscribeUsersPrams);
                    //\Log::info('<----渠道下强关用户数---->');
                    //\Log::info(count($force_user));

                    $customSendStatsCount = CustomSendDayStats::customSendDayStatsByChannelAndFromAndDay($distribution_channel_id,'recovery_push',date("Y-m-d"));
                    if (empty($customSendStatsCount)) {
                        $customSendDayStats['distribution_channel_id'] = $distribution_channel_id;
                        $customSendDayStats['from'] = 'recovery_push';
                        $customSendDayStats['push_user_num'] = count($force_user);
                        $customSendDayStats['date'] = date("Y-m-d");
                        CustomSendDayStats::create($customSendDayStats);
                    }else{
                        $customSendStatsCount['push_user_num'] = $customSendStatsCount['push_user_num']+count($force_user);
                        $customSendStatsCount->save();
                    }

                    for ($i=0; $i < count($force_user); $i++) {                        

                        //（1）通过uid去已发送客服消息Redis中获取是否推送过该类型客服消息
                        //（2）如果有，获取插入的时间，
                        // 如果时间在今天之内，那就不发送，
                        // 如果不是，就发送，并往Redis中插入一条数据
                        $uid = $force_user[$i]['uid'];

                        if(!Redis::hget('add_news_recovery_push_activity'.$uid, 'time'))
                        {

                                //9，通过RebitMQ推送热门书籍到指定用户
                                $data = array();
                                $data['openid'] = $force_user[$i]['openid'];
                                $data['appid'] = $force_user[$i]['appid'];

                                $url = env('PROTOCOL').'://site'.encodeDistributionChannelId($distribution_channel_id).'.'.env('CUSTOM_HOST').'.com'.$custom_url;

                                $data['news_content'] = '[[{"title":"'.$custom_title.'"},{"description":""},{"url":"'.$url.'"},{"image":"'.$custom_image.'"}]]';
                                $data['type'] = 'one_task';
                                $data['task_id'] = 3;
                                $data['send_time'] = date("Y-m-d H:i:s");
                                $send_data=array(
                                    'send_time'=>date("Y-m-d H:i:s"),
                                    'data' => $data
                                );

                                $delay = 0;

                                //\Log::info('<---- 客服消息发送内容 参数---->');
                                //\Log::info($data['openid']);
                                //\Log::info($data['appid']);
                                //\Log::info($data['news_content']);

                                //\Log::info('<----Rebit-MQ 发送三天回本活动推送---->');
                                $job = (new SendNews($send_data))->onConnection('rabbitmq')->delay($delay)->onQueue('send_news_list');
//                                $job = (new SendNews($send_data))->onConnection('redis')->delay($delay)->onQueue('send_news_list');
                                dispatch($job);

                                Redis::hset('add_news_recovery_push_activity'.$uid, 'time', time());

                                                                                                           
                        }                        
                    }
                }
            }
        }
    }


    /**
     *  定制书籍推送（定时任务） point_push
     */
    static function add_news_point_book(){

        \Log::info('=======================定制书籍推荐客服消息');
        //1，遍历渠道表
        $distribution_channels =  ChannelService::getAllChannels();

        for ($k=0; $k < count($distribution_channels); $k++) { 
            
            //2,判断该渠道下有没有开启 未支付订单的智能推送
            $distribution_channel_id = $distribution_channels[$k]['id'];

            
            $customMsgSwitch = CustomMsgSwitchsMsgs::customMsgSwitchsByChannelCate($distribution_channel_id,'point_push');
            
            if (!empty($customMsgSwitch)) {
                
                if ($customMsgSwitch['status'] == '1') {

                    //\Log::info('<----开启客服的 渠道号---->');
                    //\Log::info($distribution_channel_id);
                    //3，开通智能推送的渠道获取 渠道下的强关用户
                    $forceSubscribeUsersPrams['distribution_channel_id'] = $distribution_channel_id;
                    $forceSubscribeUsersPrams['timeset'] = 151200;// 定制数据是42小时后推送
                    $force_user = ForceSubscribeService::forceSubscribeUsersByChannelidAndTimeset($forceSubscribeUsersPrams);
                    //\Log::info('<----渠道下强关用户数---->');
                    //\Log::info(count($force_user));

                    $customSendStatsCount = CustomSendDayStats::customSendDayStatsByChannelAndFromAndDay($distribution_channel_id,'point_push',date("Y-m-d"));
                    if (empty($customSendStatsCount)) {
                        $customSendDayStats['distribution_channel_id'] = $distribution_channel_id;
                        $customSendDayStats['from'] = 'point_push';
                        $customSendDayStats['push_user_num'] = count($force_user);
                        $customSendDayStats['date'] = date("Y-m-d");
                        CustomSendDayStats::create($customSendDayStats);
                    }else{
                        $customSendStatsCount['push_user_num'] = $customSendStatsCount['push_user_num']+count($force_user);
                        $customSendStatsCount->save();
                    }

                    for ($i=0; $i < count($force_user); $i++) {                       

                        //（1）通过uid去已发送客服消息Redis中获取是否推送过该类型客服消息
                        //（2）如果有，获取插入的时间，
                        // 如果时间在今天之内，那就不发送，
                        // 如果不是，就发送，并往Redis中插入一条数据
                        $uid = $force_user[$i]['uid'];

                        if(Redis::hget('add_news_top_book_uid'.$uid, 'time'))
                        {
                            //\Log::info('<----Redis中存在  获取uid 时间---->');
                            //\Log::info($force_user[$i]['uid']);
                            //\Log::info(Redis::hget('add_news_top_book_uid'.$uid, 'time'));
                            $time = Redis::hget('add_news_top_book_uid'.$uid, 'time');


                            if (date("Y-m-d",$time) == date("Y-m-d"))
                            {

                                // Redis::hdel('add_news_top_book_uid'.$uid,'time');

                            }else{

                                //获取定制图书推送是否是在这个时间段推送过，如果推送过这个时间点就不推送了
                                $point_time = Redis::hget('add_news_point_book_uid'.$uid, 'time');
                                if ($point_time) {
                                    if (date("Y-m-d",$point_time) == date("Y-m-d")) {
                                        $matchTime = time() - $point_time;
                                        if ($matchTime < 3600) {
                                            continue;
                                        }
                                    }
                                    
                                }

                                //\Log::info('<----Redis中时间 不是今天---->');

                                $bid = $force_user[$i]['bid'];

                                $booksArray = [];

                                //4，获取男频女频的标签文案
                                $manPromotion = PromotionService::getRandomHeadline(1,5);
                                $womanPromotion = PromotionService::getRandomHeadline(2,5);

                                //5，获取用户最近阅读的书籍信息
                                $userBook = ReadRecordService::getFirstReadRecord($uid);
                                if (!empty($userBook)) {

                                    //有最近阅读的书籍！！ 头条为最近阅读，次4条为随机选取

                                    //\Log::info('<----获取用户最近阅读的书籍--->');

                                    //6,推送第一条拼接用户最近阅读的书籍信息
                                    //并通过判断该书是男频还是女频分别拼接上不同的标签文案
                                    $continueReadUrl = env('PROTOCOL').'://site'.encodeDistributionChannelId($distribution_channel_id).'.'.env('CUSTOM_HOST').'.com/continue?fromtype=point_push';
                                    $channelName = $userBook['channel_name'];
                                    if($channelName == '男频'){
                                        $book['title'] = $manPromotion[0]['title'];
                                        $book['description'] = $manPromotion[0]['title'];
                                    }else{
                                        $book['title'] = $womanPromotion[0]['title'];
                                        $book['description'] = $womanPromotion[0]['title'];
                                    }
                                    $book['url'] = $continueReadUrl;
                                    //头条的图片从财哥个图库中随机取一张
                                    $promotionImages = PromotionService::getMessageRandomDocumentCovers(3);
                                    if ($promotionImages) {
                                        $book['image'] = $promotionImages[0]['link'];
                                    }else{
                                        $book['image'] = $userBook['cover'];
                                    }
                                    
                                    
                                    
                                    $booksArray[] = [['title'=>$book['title']],['description'=>$book['description']],['url'=>$book['url']],['image'=>$book['image']]];
                                    //\Log::info(json_encode($booksArray));


                                    //7,获取和用户强关进来的书相同类型的4本优质评分的书籍
//                                     $books = BookConfigService::getSimpleChannelBook($bid,4);
                                    $books = BookConfigService::getSimpleChannelBookLoop($bid,4,$uid);
                                    $bookUrl = env('PROTOCOL').'://site'.encodeDistributionChannelId($distribution_channel_id).'.'.env('CUSTOM_HOST').'.com';
                                    $promotionNum = 1;
                                    if ($books) {
                                        
                                        foreach ($books as $key => $value) {

                                            //8,将这四本书作为推送的2-5条信息，同样拼接书籍信息和标签文案
                                            $urlBook = $value->url = $bookUrl.$value->url.'&fromtype=point_push';
                                            $channelName = $value->channel_name;
                                            $cover = $value->cover;
                                            if($channelName == '男频'){
                                                $book['title'] = $manPromotion[$promotionNum]['title'];
                                                $book['description'] = $manPromotion[$promotionNum]['title'];
                                            }else{
                                                $book['title'] = $womanPromotion[$promotionNum]['title'];
                                                $book['description'] = $womanPromotion[$promotionNum]['title'];
                                            }
                                            $book['url'] = $urlBook;
                                            $book['image'] = $cover;
                                            $booksArray[] = [['title'=>$book['title']],['description'=>$book['description']],['url'=>$book['url']],['image'=>$book['image']]];

                                            $promotionNum++;

                                        }

                                        //9，通过RebitMQ推送热门书籍到指定用户
                                        $data = array();
                                        $data['openid'] = $force_user[$i]['openid'];
                                        $data['appid'] = $force_user[$i]['appid'];
                                        $data['news_content'] = json_encode($booksArray);
                                        $data['type'] = 'one_task';
                                        $data['task_id'] = 3;
                                        $data['send_time'] = date("Y-m-d H:i:s");
                                        $send_data=array(
                                            'send_time'=>date("Y-m-d H:i:s"),
                                            'data' => $data
                                        );

                                        $delay = 0;

                                        //\Log::info('<---- 客服消息发送内容 参数---->');
                                        //\Log::info($data['openid']);
                                        //\Log::info($data['appid']);
                                        //\Log::info($data['news_content']);

                                        //\Log::info('<----Rebit-MQ 发送热门书籍推送客服消息---->');
                                        $job = (new SendNews($send_data))->onConnection('rabbitmq')->delay($delay)->onQueue('send_news_list');
                                        dispatch($job);

                                        Redis::hset('add_news_top_book_uid'.$uid, 'time', time());

                                    }

                                }else{

                                    //没有最近阅读的书籍！！ 从书库随机选取5本，第一本的图片用财哥图库的图片

                                    //7,获取和用户强关进来的书相同类型的4本优质评分的书籍
//                                     $books = BookConfigService::getSimpleChannelBook($bid,5);
                                    $books = BookConfigService::getSimpleChannelBookLoop($bid,5,$uid);
                                    $bookUrl = env('PROTOCOL').'://site'.encodeDistributionChannelId($distribution_channel_id).'.'.env('CUSTOM_HOST').'.com';
                                    $promotionNum = 0;
                                    if ($books) {
                                        
                                        foreach ($books as $key => $value) {

                                            //8,将这四本书作为推送的2-5条信息，同样拼接书籍信息和标签文案
                                            $urlBook = $value->url = $bookUrl.$value->url.'&fromtype=point_push';
                                            $channelName = $value->channel_name;
                                            $cover = $value->cover;
                                            if($channelName == '男频'){
                                                $book['title'] = $manPromotion[$promotionNum]['title'];
                                                $book['description'] = $manPromotion[$promotionNum]['title'];
                                            }else{
                                                $book['title'] = $womanPromotion[$promotionNum]['title'];
                                                $book['description'] = $womanPromotion[$promotionNum]['title'];
                                            }
                                            $book['url'] = $urlBook;
                                            $book['image'] = $cover;
                                            if ($promotionNum == 0) {
                                                //第一条图片选用图库中的图片地址
                                                // $book['image'] = $cover;
                                                $promotionImages = PromotionService::getMessageRandomDocumentCovers(3);
                                                if ($promotionImages) {
                                                    $book['image'] = $promotionImages[0]['link'];
                                                }else{
                                                    $book['image'] = $cover;
                                                }
                                            }else{
                                                $book['image'] = $cover;
                                            }
                                            
                                            $booksArray[] = [['title'=>$book['title']],['description'=>$book['description']],['url'=>$book['url']],['image'=>$book['image']]];

                                            $promotionNum++;

                                        }

                                        //9，通过RebitMQ推送热门书籍到指定用户
                                        $data = array();
                                        $data['openid'] = $force_user[$i]['openid'];
                                        $data['appid'] = $force_user[$i]['appid'];
                                        $data['news_content'] = json_encode($booksArray);
                                        $data['type'] = 'one_task';
                                        $data['task_id'] = 3;
                                        $data['send_time'] = date("Y-m-d H:i:s");
                                        $send_data=array(
                                            'send_time'=>date("Y-m-d H:i:s"),
                                            'data' => $data
                                        );

                                        $delay = 0;

                                        //\Log::info('<---- 客服消息发送内容 参数---->');
                                        //\Log::info($data['openid']);
                                        //\Log::info($data['appid']);
                                        //\Log::info($data['news_content']);

                                        //\Log::info('<----Rebit-MQ 发送热门书籍推送客服消息---->');
                                        $job = (new SendNews($send_data))->onConnection('rabbitmq')->delay($delay)->onQueue('send_news_list');
                                        dispatch($job);

                                        Redis::hset('add_news_point_book_uid'.$uid, 'time', time());

                                    }
                                }

                                
                            }                           
                        }else{

                            //获取热门图书推送是否是在这个时间段推送过，如果推送过这个时间点就不推送了
                            $point_time = Redis::hget('add_news_top_book_uid'.$uid, 'time');
                            if ($point_time) {
                                if (date("Y-m-d",$point_time) == date("Y-m-d")) {
                                    $matchTime = time() - $point_time;
                                    if ($matchTime < 3600) {
                                        continue;
                                    }
                                }
                                
                            }

                            //\Log::info('<----Redis中时间 不是今天---->');

                            $bid = $force_user[$i]['bid'];

                            $booksArray = [];

                            //4，获取男频女频的标签文案
                            $manPromotion = PromotionService::getRandomHeadline(1,5);
                            $womanPromotion = PromotionService::getRandomHeadline(2,5);

                            //5，获取用户最近阅读的书籍信息
                            $userBook = ReadRecordService::getFirstReadRecord($uid);
                            if (!empty($userBook)) {

                                //有最近阅读的书籍！！ 头条为最近阅读，次4条为随机选取

                                //\Log::info('<----获取用户最近阅读的书籍--->');

                                //6,推送第一条拼接用户最近阅读的书籍信息
                                //并通过判断该书是男频还是女频分别拼接上不同的标签文案
                                $continueReadUrl = env('PROTOCOL').'://site'.encodeDistributionChannelId($distribution_channel_id).'.'.env('CUSTOM_HOST').'.com/continue?fromtype=point_push';
                                $channelName = $userBook['channel_name'];
                                if($channelName == '男频'){
                                    $book['title'] = $manPromotion[0]['title'];
                                    $book['description'] = $manPromotion[0]['title'];
                                }else{
                                    $book['title'] = $womanPromotion[0]['title'];
                                    $book['description'] = $womanPromotion[0]['title'];
                                }
                                $book['url'] = $continueReadUrl;

                                //头条的图片从财哥个图库中随机取一张
                                $promotionImages = PromotionService::getMessageRandomDocumentCovers(3);
                                if ($promotionImages) {
                                    $book['image'] = $promotionImages[0]['link'];
                                }else{
                                    $book['image'] = $userBook['cover'];
                                }
                                                               
                                $booksArray[] = [['title'=>$book['title']],['description'=>$book['description']],['url'=>$book['url']],['image'=>$book['image']]];
                                //\Log::info(json_encode($booksArray));


                                //7,获取和用户强关进来的书相同类型的4本优质评分的书籍
//                                 $books = BookConfigService::getSimpleChannelBook($bid,4);
                                $books = BookConfigService::getSimpleChannelBookLoop($bid,4,$uid);
                                $bookUrl = env('PROTOCOL').'://site'.encodeDistributionChannelId($distribution_channel_id).'.'.env('CUSTOM_HOST').'.com';
                                $promotionNum = 1;
                                if ($books) {
                                    
                                    foreach ($books as $key => $value) {

                                        //8,将这四本书作为推送的2-5条信息，同样拼接书籍信息和标签文案
                                        $urlBook = $value->url = $bookUrl.$value->url.'&fromtype=point_push';
                                        $channelName = $value->channel_name;
                                        $cover = $value->cover;
                                        if($channelName == '男频'){
                                            $book['title'] = $manPromotion[$promotionNum]['title'];
                                            $book['description'] = $manPromotion[$promotionNum]['title'];
                                        }else{
                                            $book['title'] = $womanPromotion[$promotionNum]['title'];
                                            $book['description'] = $womanPromotion[$promotionNum]['title'];
                                        }
                                        $book['url'] = $urlBook;
                                        
                                        $promotionImages = PromotionService::getMessageRandomDocumentCovers(3);
                                        if ($promotionImages) {
                                            $book['image'] = $promotionImages[0]['link'];
                                        }else{
                                            $book['image'] = $cover;
                                        }

                                        $booksArray[] = [['title'=>$book['title']],['description'=>$book['description']],['url'=>$book['url']],['image'=>$book['image']]];

                                        $promotionNum++;

                                    }

                                    //9，通过RebitMQ推送热门书籍到指定用户
                                    $data = array();
                                    $data['openid'] = $force_user[$i]['openid'];
                                    $data['appid'] = $force_user[$i]['appid'];
                                    $data['news_content'] = json_encode($booksArray);
                                    $data['type'] = 'one_task';
                                    $data['task_id'] = 3;
                                    $data['send_time'] = date("Y-m-d H:i:s");
                                    $send_data=array(
                                        'send_time'=>date("Y-m-d H:i:s"),
                                        'data' => $data
                                    );

                                    $delay = 0;

                                    //\Log::info('<---- 客服消息发送内容 参数---->');
                                    //\Log::info($data['openid']);
                                    //\Log::info($data['appid']);
                                    //\Log::info($data['news_content']);

                                    //\Log::info('<----Rebit-MQ 发送热门书籍推送客服消息---->');
                                    $job = (new SendNews($send_data))->onConnection('rabbitmq')->delay($delay)->onQueue('send_news_list');
                                    dispatch($job);

                                    Redis::hset('add_news_point_book_uid'.$uid, 'time', time());

                                }

                            }else{

                                //没有最近阅读的书籍！！ 从书库随机选取5本，第一本的图片用财哥图库的图片

                                //7,获取和用户强关进来的书相同类型的4本优质评分的书籍
//                                 $books = BookConfigService::getSimpleChannelBook($bid,5);
                                $books = BookConfigService::getSimpleChannelBookLoop($bid,5,$uid);
                                $bookUrl = env('PROTOCOL').'://site'.encodeDistributionChannelId($distribution_channel_id).'.'.env('CUSTOM_HOST').'.com';
                                $promotionNum = 0;
                                if ($books) {
                                    
                                    foreach ($books as $key => $value) {

                                        //8,将这四本书作为推送的2-5条信息，同样拼接书籍信息和标签文案
                                        $urlBook = $value->url = $bookUrl.$value->url.'&fromtype=point_push';
                                        $channelName = $value->channel_name;
                                        $cover = $value->cover;
                                        if($channelName == '男频'){
                                            $book['title'] = $manPromotion[$promotionNum]['title'];
                                            $book['description'] = $manPromotion[$promotionNum]['title'];
                                        }else{
                                            $book['title'] = $womanPromotion[$promotionNum]['title'];
                                            $book['description'] = $womanPromotion[$promotionNum]['title'];
                                        }
                                        $book['url'] = $urlBook;
                                        $book['image'] = $cover;
                                        if ($promotionNum == 0) {
                                            //第一条图片选用图库中的图片地址
                                            $promotionImages = PromotionService::getMessageRandomDocumentCovers(3);
                                            if ($promotionImages) {
                                                $book['image'] = $promotionImages[0]['link'];
                                            }else{
                                                $book['image'] = $cover;
                                            }
                                            
                                        }else{
                                            $book['image'] = $cover;
                                        }
                                        
                                        $booksArray[] = [['title'=>$book['title']],['description'=>$book['description']],['url'=>$book['url']],['image'=>$book['image']]];

                                        $promotionNum++;

                                    }

                                    //9，通过RebitMQ推送热门书籍到指定用户
                                    $data = array();
                                    $data['openid'] = $force_user[$i]['openid'];
                                    $data['appid'] = $force_user[$i]['appid'];
                                    $data['news_content'] = json_encode($booksArray);
                                    $data['type'] = 'one_task';
                                    $data['task_id'] = 3;
                                    $data['send_time'] = date("Y-m-d H:i:s");
                                    $send_data=array(
                                        'send_time'=>date("Y-m-d H:i:s"),
                                        'data' => $data
                                    );

                                    $delay = 0;

                                    //\Log::info('<---- 客服消息发送内容 参数---->');
                                    //\Log::info($data['openid']);
                                    //\Log::info($data['appid']);
                                    //\Log::info($data['news_content']);

                                    //\Log::info('<----Rebit-MQ 发送热门书籍推送客服消息---->');
                                    $job = (new SendNews($send_data))->onConnection('rabbitmq')->delay($delay)->onQueue('send_news_list');
                                    dispatch($job);

                                    Redis::hset('add_news_point_book_uid'.$uid, 'time', time());

                                }
                            }
                                                      
                        }                        
                    }
                }
            }
        }
    }

    /**
     *  未充值用户推送客服消息（24-48小时内关注）（定时任务）
     */
    static function unPaidUserActivity(){
    
    	\Log::info('=======================未充值用户推荐客服消息');
    	//1，遍历渠道表
    	$distribution_channels =  ChannelService::getAllChannels();
    
    	for ($k=0; $k < count($distribution_channels); $k++) {
    		//2,判断该渠道下有没有开启 未支付订单的智能推送
    		$distribution_channel_id = $distribution_channels[$k]['id'];
    		
    		// 嘉言小说
//     		if(!in_array($distribution_channel_id,array('2'))){
// //     			\Log::info('unPaidUserActivity_continue,$distribution_channel_id:'.$distribution_channel_id);
//     			continue;
//     		}
    
    		$customMsgSwitch = CustomMsgSwitchsMsgs::customMsgSwitchsByChannelCate($distribution_channel_id,'unpaid_send_activity');
    
    		if (!empty($customMsgSwitch)) {
    
    			if ($customMsgSwitch['status'] == '1') {
    
    				//\Log::info('<----开启未付费推送的 渠道号---->:'.$distribution_channel_id);
    				//3，开通智能推送的渠道获取 渠道下的强关用户
    				$forceSubscribeUsersPrams['distribution_channel_id'] = $distribution_channel_id;
    				$forceSubscribeUsersPrams['start_time'] = date('Y-m-d H:i:s',strtotime('-2 day'));
    				$forceSubscribeUsersPrams['end_time'] = date('Y-m-d H:i:s',strtotime('-1 day'));
    				$force_user = ForceSubscribeService::forceSubscribeNewUnpaidUsersByTime($forceSubscribeUsersPrams);
    				//\Log::info('<----渠道下强关用户数---->');
    				//\Log::info($force_user);
    				//\Log::info(count($force_user));
    				
    				$push_user_num = 0;
    
    				for ($i=0; $i < count($force_user); $i++) {
    
    					//（1）通过uid去已发送客服消息Redis中获取是否推送过该类型客服消息
    					//（2）如果有，获取插入的时间，
    					// 每个新关用户只发送一次
    					// 如果不是，就发送，并往Redis中插入一条数据
    					$uid = $force_user[$i]['uid'];
    
    					if(!Redis::hget('unpaid_send_activity_uid:'.$uid, 'time'))
    					{
    							$bid = $force_user[$i]['bid'];
    
    							$data = array();

					            $data['openid'] = $force_user[$i]['openid'];
					            $data['appid'] = $force_user[$i]['appid'];
					
					            //活动链接
					            $continueReadUrl = env('PROTOCOL').'://site'.encodeDistributionChannelId($distribution_channel_id).'.'.env('CUSTOM_HOST').'.com/sale/newUserActivity?fromtype=unpaid_send_activity&send_time='.time();
					            
					            $data['content'] = '您的新用户专享礼包已送达'."\n\n".'充9.9元，得2000书币，只有一次机会哦！'."\n\n".'过期失效，不要错过！'."\n\n".'<a href="'.$continueReadUrl.'">点击立即领取> ></a>'."\n\n".'为方便下次阅读，请'.'<a href="https://help.leyuee.com/top.html">'.'置顶公众号'.'</a>';
					            $data['type'] = 'one_task';// last_task,one_task
					            $data['task_id'] = 1;
					            $data['send_time'] = date("Y-m-d H:i:s");
					            $send_data=array(
					                'send_time'=>date("Y-m-d H:i:s"),
					                'data' => $data
					            );
					            //\Log::info('unpaid_send_activity_openid:'.$data['openid'].' appid:'.$data['appid'].' content:'.$data['content']);
					
					            $delay = 0;
					
					            $job = (new SendTexts($send_data))->onConnection('rabbitmq')->delay($delay)->onQueue('send_texts_list');
					            dispatch($job);
    							
    							Redis::hset('unpaid_send_activity_uid:'.$uid, 'time', time());
                                Redis::EXPIRE('unpaid_send_activity_uid:'.$uid,86400);
    							//\Log::info('unpaid_send_activity_settime_uid:'.$uid.' time:'.time());
    							
    							$push_user_num++;
    								
    					}else{
    						\Log::info('unpaid_send_activity_exist_uid:'.$force_user[$i]['uid'].' time:'.Redis::hget('unpaid_send_activity_uid:'.$uid, 'time'));
    					}
    				}
    				
    				\Log::info('unpaid_send_activity,push_user_num:'.$push_user_num);
    				// 因为有些用户重复筛选，所以人数在后面更新
    				$customSendStatsCount = CustomSendDayStats::customSendDayStatsByChannelAndFromAndDay($distribution_channel_id,'unpaid_send_activity',date("Y-m-d"));
    				if (empty($customSendStatsCount)) {
    					$customSendDayStats['distribution_channel_id'] = $distribution_channel_id;
    					$customSendDayStats['from'] = 'unpaid_send_activity';
    					$customSendDayStats['push_user_num'] = $push_user_num;
    					$customSendDayStats['date'] = date("Y-m-d");
    					CustomSendDayStats::create($customSendDayStats);
    				}else{
    					$customSendStatsCount['push_user_num'] = $customSendStatsCount['push_user_num']+$push_user_num;
    					$customSendStatsCount->save();
    				}
    			}else{
    				\Log::info('<----未开启 未付费推送的 渠道号---->:'.$distribution_channel_id);
    			}
    		}
    	}
    }

    /**
     *  热门书籍推送（定时任务）hot_push
     */
    static function add_news_top_book(){

         //1，遍历渠道表
        $distribution_channels =  ChannelService::getAllChannels();

        for ($k=0; $k < count($distribution_channels); $k++) { 
            
            //2,判断该渠道下有没有开启 未支付订单的智能推送
            $distribution_channel_id = $distribution_channels[$k]['id'];
            $customMsgSwitch = CustomMsgSwitchsMsgs::customMsgSwitchsByChannelCate($distribution_channel_id,'hot_push');
            
            if (!empty($customMsgSwitch)) {
                
                if ($customMsgSwitch['status'] == '1') {

                    

                    //\Log::info('<----开启客服的 渠道号---->');
                    //\Log::info($distribution_channel_id);
                    //3，开通智能推送的渠道获取 渠道下的强关用户
                    $forceSubscribeUsersPrams['distribution_channel_id'] = $distribution_channel_id;
                    $forceSubscribeUsersPrams['timeset'] = 86400;//热门书籍24小时
                    $force_user = ForceSubscribeService::forceSubscribeUsersByChannelidAndTimeset($forceSubscribeUsersPrams);
                   // \Log::info('<----符合条件的用户数---->');
                   // \Log::info(count($force_user));

                    $customSendStatsCount = CustomSendDayStats::customSendDayStatsByChannelAndFromAndDay($distribution_channel_id,'hot_push',date("Y-m-d"));
                    if (empty($customSendStatsCount)) {
                        $customSendDayStats['distribution_channel_id'] = $distribution_channel_id;
                        $customSendDayStats['from'] = 'point_push';
                        $customSendDayStats['push_user_num'] = count($force_user);
                        $customSendDayStats['date'] = date("Y-m-d");
                        CustomSendDayStats::create($customSendDayStats);
                    }else{
                        $customSendStatsCount['push_user_num'] = $customSendStatsCount['push_user_num']+count($force_user);
                        $customSendStatsCount->save();
                    }

                    for ($i=0; $i < count($force_user); $i++) {                        

                        $uid = $force_user[$i]['uid'];
   
                        if(Redis::hget('add_news_top_book_uid'.$uid, 'time'))
                        {
                            $time = Redis::hget('add_news_point_book_uid'.$uid, 'time');

                            if (date("Y-m-d",$time) == date("Y-m-d"))
                            {

                            }else{

                                //获取定制图书推送是否是在这个时间段推送过，如果推送过这个时间点就不推送了
                                $top_time = Redis::hget('add_news_point_book_uid'.$uid, 'time');
                                if ($top_time) {
                                    if (date("Y-m-d",$top_time) == date("Y-m-d")) {
                                        $matchTime = time() - $top_time;
                                        if ($matchTime < 3600) {
                                            continue;
                                        }
                                    }
                                    
                                }

                                //\Log::info('<---- Redis中存在 且满足条件的 强关用户 uid---->');
                                //\Log::info($uid);
                                //4,获取和用户强关进来的书相同类型的5本优质评分的书籍
                                $bid = $force_user[$i]['bid'];
//                                 $books = BookConfigService::getSimpleChannelBook($bid,5);
                                $books = BookConfigService::getSimpleChannelBookLoop($bid,5,$uid);
                                $bookUrl = env('PROTOCOL').'://site'.encodeDistributionChannelId($distribution_channel_id).'.'.env('CUSTOM_HOST').'.com';

                                $booksArray = [];

                                //5，获取男频女频的标签文案
                                $womanPromotion = PromotionService::getRandomHeadline(2,count($books));
                                $manPromotion = PromotionService::getRandomHeadline(1,count($books));
                                $promotionNum = 0;
                                if ($books) {
                                   
                                    foreach ($books as $key => $value) {

                                        //6,将这5本书作为推送的1-5条信息，
                                        //通过判断书籍是男频还是女频拼接书籍信息的不同标签文案
                                        $urlBook = $value->url = $bookUrl.$value->url.'&fromtype=hot_push';
                                        $channelName = $value->channel_name;
                                        $cover = $value->cover;
                                        if($channelName == '男频'){
                                            $book['title'] = $manPromotion[$promotionNum]['title'];
                                            $book['description'] = $manPromotion[$promotionNum]['title'];
                                        }else{
                                            $book['title'] = $womanPromotion[$promotionNum]['title'];
                                            $book['description'] = $womanPromotion[$promotionNum]['title'];
                                        }

                                        $book['url'] = $urlBook;
                                        // $book['image'] = $cover;
                                        if ($promotionNum == 0) {
                                            //第一条图片选用图库中的图片地址
                                            $promotionImages = PromotionService::getMessageRandomDocumentCovers(3);
                                            if ($promotionImages) {
                                                $book['image'] = $promotionImages[0]['link'];
                                            }else{
                                                $book['image'] = $cover;
                                            }
                                            
                                        }else{
                                            $book['image'] = $cover;
                                        }
                                        $booksArray[$key] = [['title'=>$book['title']],['description'=>$book['description']],['url'=>$book['url']],['image'=>$book['image']]];

                                        $promotionNum++;

                                    }

                                    //7，通过RebitMQ推送热门书籍到指定用户
                                    $data = array();
                                    $data['openid'] = $force_user[$i]['openid'];
                                    $data['appid'] = $force_user[$i]['appid'];
                                    $data['news_content'] = json_encode($booksArray);
                                    $data['type'] = 'one_task';
                                    $data['task_id'] = 3;
                                    $data['send_time'] = date("Y-m-d H:i:s");
                                    $send_data=array(
                                        'send_time'=>date("Y-m-d H:i:s"),
                                        'data' => $data
                                    );

                                    $delay = 0;

                                    /*\Log::info('<---- 客服消息发送内容 参数---->');
                                    \Log::info($data['openid']);
                                    \Log::info($data['appid']);*/
                                    //\Log::info($data['news_content']);

                                    $job = (new SendNews($send_data))->onConnection('rabbitmq')->delay($delay)->onQueue('send_news_list');
                                    dispatch($job);

                                    Redis::hset('add_news_point_book_uid'.$uid, 'time', time());

                                }
                                

                            }
                        }else{

                            //获取定制图书推送是否是在这个时间段推送过，如果推送过这个时间点就不推送了
                            $top_time = Redis::hget('add_news_point_book_uid'.$uid, 'time');
                            if ($top_time) {
                                if (date("Y-m-d",$top_time) == date("Y-m-d")) {
                                    $matchTime = time() - $top_time;
                                    if ($matchTime < 3600) {
                                        continue;
                                    }
                                }
                                
                            }
                            
                            //\Log::info('<---- Redis不存在的 强关用户 uid---->');
                            //\Log::info($uid);
                            //4,获取和用户强关进来的书相同类型的5本优质评分的书籍
                            $bid = $force_user[$i]['bid'];
//                             $books = BookConfigService::getSimpleChannelBook($bid,5);
                            $books = BookConfigService::getSimpleChannelBookLoop($bid,5,$uid);
                            // if (count($books)>0) {
                            //     # code...
                            // }
                            $bookUrl = env('PROTOCOL').'://site'.encodeDistributionChannelId($distribution_channel_id).'.'.env('CUSTOM_HOST').'.com';

                            $booksArray = [];

                            //5，获取男频女频的标签文案
                            $womanPromotion = PromotionService::getRandomHeadline(2,count($books));
                            $manPromotion = PromotionService::getRandomHeadline(1,count($books));
                            $promotionNum = 0;
                            if ($books) {
                                
                                foreach ($books as $key => $value) {

                                    //6,将这5本书作为推送的1-5条信息，
                                    //通过判断书籍是男频还是女频拼接书籍信息的不同标签文案
                                    $urlBook = $value->url = $bookUrl.$value->url.'&fromtype=hot_push';
                                    $channelName = $value->channel_name;
                                    $cover = $value->cover;
                                    if($channelName == '男频'){
                                        $book['title'] = $manPromotion[$promotionNum]['title'];
                                        $book['description'] = $manPromotion[$promotionNum]['title'];
                                    }else{
                                        $book['title'] = $womanPromotion[$promotionNum]['title'];
                                        $book['description'] = $womanPromotion[$promotionNum]['title'];
                                    }

                                    $book['url'] = $urlBook;
                                    if ($promotionNum == 0) {
                                        //第一条图片选用图库中的图片地址
                                        $promotionImages = PromotionService::getMessageRandomDocumentCovers(3);
                                        if ($promotionImages) {
                                            $book['image'] = $promotionImages[0]['link'];
                                        }else{
                                            $book['image'] = $cover;
                                        }
                                    }else{
                                        $book['image'] = $cover;
                                    }
                                    $booksArray[$key] = [['title'=>$book['title']],['description'=>$book['description']],['url'=>$book['url']],['image'=>$book['image']]];

                                    $promotionNum++;

                                }

                                //7，通过RebitMQ推送热门书籍到指定用户
                                $data = array();
                                $data['openid'] = $force_user[$i]['openid'];
                                $data['appid'] = $force_user[$i]['appid'];
                                $data['news_content'] = json_encode($booksArray);
                                $data['type'] = 'one_task';
                                $data['task_id'] = 3;
                                $data['send_time'] = date("Y-m-d H:i:s");
                                $send_data=array(
                                    'send_time'=>date("Y-m-d H:i:s"),
                                    'data' => $data
                                );

                                $delay = 0;

                                /*\Log::info('<---- 客服消息发送内容 参数---->');
                                \Log::info($data['openid']);
                                \Log::info($data['appid']);*/
                                //\Log::info($data['news_content']);


                                $job = (new SendNews($send_data))->onConnection('rabbitmq')->delay($delay)->onQueue('send_news_list');
                                dispatch($job);

                                Redis::hset('add_news_top_book_uid'.$uid, 'time', time());
                            }
                        }                        
                    }
                }
            }
        }
    }



    /**
     * 测试向指定用户发送热门书籍
     */
    static function add_news_top_book_test($force_user){

        $bid = $force_user['bid'];
        $distribution_channel_id = $force_user['distribution_channel_id'];
        $uid = $force_user['uid'];
        $booksArray = [];

        //获取男频女频标签文案
        $womanPromotion = PromotionService::getRandomHeadline(2,5);
        $manPromotion = PromotionService::getRandomHeadline(1,5);

        //获取用户最近阅读记录的书籍
        $userBook = ReadRecordService::getFirstReadRecord($uid);

        if (!empty($userBook)) {

            //推送第一条放最近阅读的书籍，并通过该书分类拼接上标签文案
            $continueReadUrl = env('PROTOCOL').'://site'.encodeDistributionChannelId($distribution_channel_id).'.'.env('CUSTOM_HOST').'.com/continue';
            $channelName = $userBook['channel_name'];
            if($channelName == '男频'){
                $book['title'] = $manPromotion[0]['title'];
                $book['description'] = $manPromotion[0]['title'];
            }else{
                $book['title'] = $womanPromotion[0]['title'];
                $book['description'] = $womanPromotion[0]['title'];
            }
            $book['url'] = $continueReadUrl;
            $book['image'] = $userBook['cover'];
            $booksArray[] = [['title'=>$book['title']],['description'=>$book['description']],['url'=>$book['url']],['image'=>$book['image']]];

//             $books = BookConfigService::getSimpleChannelBook($bid,4);
            $books = BookConfigService::getSimpleChannelBookLoop($bid,4,$uid);
            $bookUrl = env('PROTOCOL').'://site'.encodeDistributionChannelId($distribution_channel_id).'.'.env('CUSTOM_HOST').'.com';
            $promotionNum = 1;
            foreach ($books as $key => $value) {

                //推送2-4条放相同类别的4本高评分的书籍
                $urlBook = $value->url = $bookUrl.$value->url;
                $channelName = $value->channel_name;
                $cover = $value->cover;
                if($channelName == '男频'){
                    $book['title'] = $manPromotion[$promotionNum]['title'];
                    $book['description'] = $manPromotion[$promotionNum]['title'];
                }else{
                    $book['title'] = $womanPromotion[$promotionNum]['title'];
                    $book['description'] = $womanPromotion[$promotionNum]['title'];
                }
                $book['url'] = $urlBook;
                $book['image'] = $cover;
                $booksArray[] = [['title'=>$book['title']],['description'=>$book['description']],['url'=>$book['url']],['image'=>$book['image']]];

                $promotionNum++;

            }

            //7，通过RebitMQ推送热门书籍到指定用户
            $data = array();
            $data['openid'] = $force_user['openid'];
            $data['appid'] = $force_user['appid'];
            $data['news_content'] = json_encode($booksArray);
            $data['type'] = 'one_task';
            $data['task_id'] = 3;
            $data['send_time'] = date("Y-m-d H:i:s");
            $send_data=array(
                'send_time'=>date("Y-m-d H:i:s"),
                'data' => $data
            );

            $delay = 0;

            $job = (new SendNews($send_data))->onConnection('rabbitmq')->delay($delay)->onQueue('send_news_list');
            dispatch($job);

        }
    }

    /**
     *  付费用户每天智能推送（定时任务 每天8点推送一次昨天的用户）
     *  需要开关控制
     */
    static function add_template_pay_push_daily() {

    	// 从动态推送表中获取
    	$customPushConfig = CustomPushConfigs::customPushConfigs('pay_daily_push');
    	//\Log::info($customPushConfig);
    	//\Log::info('add_template_pay_push_daily_customPushConfig:'.json_encode($customPushConfig));
    	
    	// 随机文案
    	$config_contents = CustomPushConfigContents::getCustomPushConfigContents();
//     	\Log::info($config_contents);
    	$template_content_num = rand(0,count($config_contents)-1);
//     	$template_content_num = 9;
    	$template_content = $common_template_id = '';
    	foreach($config_contents as $key=>$config_content){
    		if($template_content_num == $key){
    			$template_content = $config_content['template_format_content'];
    			$common_template_id = $config_content['common_template_id'];
    			break;
    		}
//     		\Log::info('add_template_pay_push_daily_$key:'.$key.' template_content:'.$config_content);
    	}
    	\Log::info('add_template_pay_push_daily_template_content_num:'.$template_content_num.' template_content:'.$template_content);
    	 	
    	if(empty($template_content)){
    		$template_content = $customPushConfig['template_content'];
    	}
    	if(empty($common_template_id)){
    		$common_template_id = $customPushConfig['common_template_id'];
    	}
    	
//     	$template_content = $customPushConfig['template_content'];
    	$name = $customPushConfig['name'];
    	$is_all_push = $customPushConfig['is_all_push'];
    	$remark = $customPushConfig['remark'];
    	$redirect_url = $customPushConfig['redirect_url'];
    	
    	//1，遍历渠道表
    	$distribution_channels =  ChannelService::getAllChannels();
    	
    	for ($k=0; $k < count($distribution_channels); $k++) {
    	
    		//2,判断该渠道下有没有开启 付费用户每天智能推送
    		$distribution_channel_id = $distribution_channels[$k]['id'];
    		\Log::info('add_template_pay_push_daily_start:'.$distribution_channel_id);
    		$customMsgSwitch = CustomMsgSwitchsMsgs::customMsgSwitchsByChannelCate($distribution_channel_id,'pay_daily_push');
    	
    		if (!empty($customMsgSwitch)) {
    	
    			if ($customMsgSwitch['status'] == '1') {
	                    \Log::info('add_template_pay_push_daily_open_start:'.$distribution_channel_id);
    					$official_accounts = OfficialAccount::officialAuthAccountBydistributionChannelId($distribution_channel_id,1,1);
    					$appids = array();
    					foreach($official_accounts as $official_account){
    						$appids[] = $official_account->appid;
    					}
    					$appids_str = implode(',', $appids);
    					$wechatTemplateMsgs['appid'] = $appids_str;// 由渠道得到appids
    					$wechatTemplateMsgs['common_template_id'] = $common_template_id;
    					$wechatTemplateMsgs['name'] = $name;
    					$wechatTemplateMsgs['send_time']  = date('Y-m-d H:i:s',strtotime('+1 minute'));//  马上执行
    					$wechatTemplateMsgs['template_content'] = $template_content;
    					//用户最近阅读链接
    					$continueReadUrl = env('PROTOCOL').'://site'.encodeDistributionChannelId($distribution_channel_id).'.'.env('CUSTOM_HOST').'.com/'.$redirect_url;
    					$wechatTemplateMsgs['redirect_url'] = $continueReadUrl;
    					$wechatTemplateMsgs['distribution_channel_id'] = $distribution_channel_id;
    					$wechatTemplateMsgs['remark'] = $remark;
    					$wechatTemplateMsgs['is_show_list'] = 0;// 界面不展示
    					 
    					$wechatTemplateMsgs['subscribe_time'] = 'z';// 关注时间不限
    					$wechatTemplateMsgs['sex'] = 'z';
    					$wechatTemplateMsgs['balance'] = 'z';
    					$wechatTemplateMsgs['order_type'] = 'd';// 昨天消费
    					$wechatTemplateMsgs['category_id'] = 'z';
    					//\Log::info('$wechatTemplateMsgs:'.json_encode($wechatTemplateMsgs));
    					$resultStatus = WechatTemplateService::addWechatTemplateMsg($wechatTemplateMsgs);
    			}
    		}
    	}

    }
    
    /**
     * 客服消息智能推送方法--公用版
     * 以下3个板块找到对应的推送
     * 1、用户
     * 2、内容
     * 3、队列类型
     */
    static function SmartPush($category_type){
    	if(empty($category_type)) return false;
    	$base_category_type = self::get_base_category_type($category_type);
    	\Log::info('smart_push:'.$category_type.' base_category_type:'.$base_category_type);
    	 
    	// 先更新书库和测书信息，避免频繁查询
    	BookConfigService::resetBookLibRedis($category_type);
    	
    	//1，遍历渠道表
    	$distribution_channels =  ChannelService::getAllChannels();
    	 
    	for ($k=0; $k < count($distribution_channels); $k++) {
    		 
    		//2,判断该渠道下有没有开启 未支付订单的智能推送
    		$distribution_channel_id = $distribution_channels[$k]['id'];
    		$customMsgSwitch = CustomMsgSwitchsMsgs::customMsgSwitchsByChannelCate($distribution_channel_id,$base_category_type);
    		 
    		if (!empty($customMsgSwitch)) {
    			 
    			if ($customMsgSwitch['status'] == '1') {
    				\Log::info('SmartPush_channel_id:'.$distribution_channel_id.' category_type:'.$category_type.' is_self_content:'.$customMsgSwitch['is_self_content']);
    				
    				// 如果自定义内容发送
    				$sexs = array('z');
    				if($customMsgSwitch['is_self_content']){
    					$sexs = array('a','b');
    				}
    				
    				$user_total_count = 0;
    				
    				foreach($sexs as $sex){
    					\Log::info('smart_push_sex:'.$sex);
    					$smartPushsMsg = array();
    					$smartPushsMsg['distribution_channel_id'] = $distribution_channel_id;
    					$smartPushsMsg['category_type'] = $category_type;
    					$smartPushsMsg['sex'] = $sex;

    					$send_content = '';
    					if($customMsgSwitch['is_self_content']){
    						$smartPushsMsgData = SmartPushMsgService::smartPushByDistributionChannelIdAndCategorySex($smartPushsMsg);
    						//\Log::info('$smartPushsMsgData:');
    						//\Log::info($smartPushsMsgData);
    						if(!empty($smartPushsMsgData)){
    							// 带上参数
    							$send_content = TemplateCustomSendService::convert_custom_content($smartPushsMsgData->content, 'smart_push_'.$base_category_type, $distribution_channel_id,0);
    							$send_content = json_decode($send_content);
    						}
    					}
    					
    					$skip = 0;
    					$loop = 0;
    					
    					while ( $skip <= 250000) {
    						$loop++;
    						$force_user = null;
    						$force_user = self::get_send_force_users($distribution_channel_id,$category_type,$sex,$skip);
    						\Log::info('SmartPush_usernum:'.count($force_user).' loop:'.$loop.' distribution_channel_id:'.$distribution_channel_id.' memory:'.memory_get_usage());
    						$force_user_num = count($force_user);
    						$skip += $force_user_num;
    						$user_total_count += $force_user_num;
    						if($force_user_num > 0){
    							for ($i=0; $i < $force_user_num; $i++) {
    								$uid = $force_user[$i]['uid'];
    								$bid = $force_user[$i]['bid'];
    								if(empty($bid)) $bid=1;// TODO
    							
    								// 非自定义，则根据bid取系统推荐的书籍
    								if(empty($customMsgSwitch['is_self_content'])){
    									\Log::info('get_user_send_content_start');
    									$send_content = null;
    									$send_content = self::get_user_send_content($bid,$distribution_channel_id,$category_type,$uid);
    								}else{
    									\Log::info('get_user_send_content_not_start:'.$uid.' memory:'.memory_get_usage());
    								}
    								if(empty($send_content)){
    									\Log::info('smart_push:openid:'.$force_user[$i]['openid'].' appid:'.$force_user[$i]['appid'].' content_is_null');
    									continue;
    								}
    								
    								$smart_push_queue = self::get_smart_push_queue($category_type);
    								$data = array();
    								$data['openid'] = $force_user[$i]['openid'];
    								$data['appid'] = $force_user[$i]['appid'];
    								if (isset($smart_push_queue['is_news']) && $smart_push_queue['is_news']){
    									$data[$smart_push_queue['content']] = json_encode($send_content);
    								}else{
    									$data[$smart_push_queue['content']] = $send_content;
    								}
    								$data['type'] = 'one_task';
    								$data['task_id'] = 3;
    								$data['send_time'] = date("Y-m-d H:i:s");
    								$send_data=array(
    										'send_time'=>date("Y-m-d H:i:s"),
    										'data' => $data
    								);
    							
    								$delay = 0;
    							
//     								\Log::info('smart_push:'.json_encode($data));
    								if (isset($smart_push_queue['is_news']) && $smart_push_queue['is_news']){
    									$job = (new SendNews($send_data))->onConnection('rabbitmq')->delay($delay)->onQueue($smart_push_queue['queue']);
    								}else{
    									$job = (new SendTexts($send_data))->onConnection('rabbitmq')->delay($delay)->onQueue($smart_push_queue['queue']);
    								}
    								dispatch($job);
    								\Log::info('smart_push_user_end:'.$uid.' memory:'.memory_get_usage());
    								// 释放内存
    								$send_data = $data = null;
    							}//end users

                                if($force_user_num < 10000)//低于单次获取的10000条，所以下次不必获取，必须与单次获取的数值保持一致！
                                {
                                    \Log::info('smart_push user num less than once get num, so break ,distribution_channel_id:'.$distribution_channel_id.' category_type:'. $category_type.' sex:'.$sex.' loop:'.$loop.' memory:'.memory_get_usage());
                                    break;
                                }
    							
    						}else{
    							\Log::info('smart_push_has_no_user,distribution_channel_id:'.$distribution_channel_id.' category_type:'. $category_type.' sex:'.$sex.' loop:'.$loop.' memory:'.memory_get_usage());
    							break;
    						}
    						
    						
    					}
    					
    				} // end sex
    				
    				\Log::info('SmartPush_end:'.' distribution_channel_id:'.$distribution_channel_id.' memory:'.memory_get_usage());
    				
    				// 后面计数
    				$customSendStatsCount = CustomSendDayStats::customSendDayStatsByChannelAndFromAndDay($distribution_channel_id,$base_category_type,date("Y-m-d"));
    				if (empty($customSendStatsCount)) {
    					$customSendDayStats['distribution_channel_id'] = $distribution_channel_id;
    					$customSendDayStats['from'] = $base_category_type;
    					$customSendDayStats['push_user_num'] = $user_total_count;
    					$customSendDayStats['date'] = date("Y-m-d");
    					CustomSendDayStats::create($customSendDayStats);
    				}else{
    					$customSendStatsCount['push_user_num'] = $customSendStatsCount['push_user_num']+$user_total_count;
    					$customSendStatsCount->save();
    				}
    			}
    		}// end 开关
    	}
    }
    
    static function get_base_category_type($category_type){
    	if($category_type == 'unpaid_hot_push' || $category_type =='all_hot_push'){
    		return 'hot_push';
    	}
    	if($category_type == 'paid_point_push' || $category_type =='unpaid_point_push'){
    		return 'point_push';
    	}
    	if($category_type == 'unpaid_send_big_activity'){
    		return 'unpaid_send_activity';
    	}
    	
    	return $category_type;
    }
    
    static function get_smart_push_queue($category_type){
    	$smart_push_queue = array();
    	
    	$text_queue = array('unpaid_send_activity','unpaid_send_big_activity','pay_daily_push');
    	 
    	if(in_array($category_type,$text_queue)){
    		$smart_push_queue['is_news'] = false;
    		$smart_push_queue['content'] = 'content';
    		$smart_push_queue['queue'] = 'send_texts_list';
    	}else{
    		$smart_push_queue['is_news'] = true;
    		$smart_push_queue['content'] = 'news_content';
    		$smart_push_queue['queue'] = 'send_news_list';
    	}
//     	\Log::info('$smart_push_queue');\Log::info($smart_push_queue);
    	
    	return $smart_push_queue;
    }
    
    static function get_base_custom_param(){
    	$param = array();
    	$param['appids'] = array();
    	$param['subscribe_time'] = 'z';
    	$param['sex'] = 'z';
    	$param['balance'] = 'z';
    	$param['category_id'] = 'z';
    	$param['order_type'] = 'z';
    	$param['sign_time'] = 'z';
        //$param['skip'] = 0;
    	return $param;
    }
    
    static function get_appids_str($distribution_channel_id){
    	$official_accounts = OfficialAccount::officialAuthAccountBydistributionChannelId($distribution_channel_id,1,1);
    	$appids = array();
    	foreach($official_accounts as $official_account){
    		$appids[] = $official_account->appid;
    	}
    	$appids_str = implode(',', $appids);
    	return $appids_str;
    }
    
    /**
     * 去重筛选的用户，已经推送过的不再推送
     * @param unknown_type $force_users
     * @param unknown_type $redis_pre_str
     */
    static function get_unique_users($force_users,$redis_pre_str,$expire_time=3600){
    	//  去重
    	if(!empty($force_users)){
    		\Log::info('before_'.$redis_pre_str.'_quchong::'.count($force_users));
    		foreach($force_users as $key=>$force_user){
    			$uid = $force_user['uid'];
    			$user_key = $redis_pre_str.':'.$uid;
    			if(Redis::get($user_key)){
    				unset($force_users[$key]);
//     				\Log::info($redis_pre_str.'_exist_user:'.$uid);
    				continue;
    			}else{
//     				\Log::info($redis_pre_str.'_push_add_user:'.$uid);
    				Redis::set($user_key,date('Y-m-d H:i:s'));
    				Redis::expire($user_key,$expire_time);
    			}
    		}
    		\Log::info('after_'.$redis_pre_str.'_push_quchong::'.count($force_users));
    	}
    	return $force_users;
    }
    
    /**
     * 得到指定类型智能推送发送的用户列表
     */
    static function get_send_force_users($distribution_channel_id,$category_type,$sex,$skip=0){
    	$force_users = array();
    	$custom_param = self::get_base_custom_param();
        $custom_param['skip'] = $skip;//skip传进来
    	$custom_param['distribution_channel_id'] = $distribution_channel_id;
    	$custom_param['appids'] = self::get_appids_str($distribution_channel_id);
    	$custom_param['sex'] = $sex;
    	// 签到推送
    	if($category_type == 'sign_push'){
    		$custom_param['sign_time'] = 'a';// 60-120分钟内
    		$custom_param['subscribe_time'] = 'g';// 1天前老用户
    		
    		$force_users = ForceSubscribeService::forceUserCountByCustomPrams($custom_param['appids'],$custom_param['distribution_channel_id'],$custom_param['subscribe_time'],$custom_param['sex'],$custom_param['balance'],$custom_param['category_id'],$custom_param['order_type'],$custom_param['sign_time'],$custom_param['skip']);
    		$force_users = self::get_unique_users($force_users,'sign_push_user',7200);
    	   
    	}
    	// 关注推送
    	elseif($category_type == 'subscribe_push'){
    		$custom_param['subscribe_time'] = 'h';// 10-25分钟内
    		
    		$force_users = ForceSubscribeService::forceUserCountByCustomPrams($custom_param['appids'],$custom_param['distribution_channel_id'],$custom_param['subscribe_time'],$custom_param['sex'],$custom_param['balance'],$custom_param['category_id'],$custom_param['order_type'],$custom_param['sign_time'],$custom_param['skip']);
    	    $force_users = self::get_unique_users($force_users,'subscribe_push_user',3600);
    	   
    	}
    	// 全量热门书籍推送
    	elseif($category_type == 'all_hot_push'){
    		$custom_param['subscribe_time'] = 'l';//12-48小时
    		$custom_param['order_type'] = 'z';//全量
    		$force_users = ForceSubscribeService::forceUserCountByCustomPrams($custom_param['appids'],$custom_param['distribution_channel_id'],$custom_param['subscribe_time'],$custom_param['sex'],$custom_param['balance'],$custom_param['category_id'],$custom_param['order_type'],$custom_param['sign_time'],$custom_param['skip']);
    		$force_users = self::get_unique_users($force_users,'all_hot_push',3600*48);
    	}
    	// 已付费定制书籍推送
    	elseif($category_type == 'paid_point_push'){
    		$custom_param['subscribe_time'] = 'k';//42-48小时
    		$custom_param['order_type'] = 'b';//已充值
    		$force_users = ForceSubscribeService::forceUserCountByCustomPrams($custom_param['appids'],$custom_param['distribution_channel_id'],$custom_param['subscribe_time'],$custom_param['sex'],$custom_param['balance'],$custom_param['category_id'],$custom_param['order_type'],$custom_param['sign_time'],$custom_param['skip']);
    		$force_users = self::get_unique_users($force_users,'paid_point_push',3600*48);
    		// 排除测试的用户
//     		$force_users = self::get_minus_test_users($force_users);
    	}
    	// 未付费热门书籍推送
    	elseif($category_type == 'unpaid_hot_push'){
    		$custom_param['subscribe_time'] = 'f';//24-48小时
    		$custom_param['order_type'] = 'a';//未充值
    		
    		$force_users = ForceSubscribeService::forceUserCountByCustomPrams($custom_param['appids'],$custom_param['distribution_channel_id'],$custom_param['subscribe_time'],$custom_param['sex'],$custom_param['balance'],$custom_param['category_id'],$custom_param['order_type'],$custom_param['sign_time'],$custom_param['skip']);
    		$force_users = self::get_unique_users($force_users,'unpaid_hot_push',3600*48);
    	}
    	// 未付费定制书籍推送
    	elseif($category_type == 'unpaid_point_push'){
    		$custom_param['subscribe_time'] = 'k';//42-48小时
    		$custom_param['order_type'] = 'a';//未充值
    		$force_users = ForceSubscribeService::forceUserCountByCustomPrams($custom_param['appids'],$custom_param['distribution_channel_id'],$custom_param['subscribe_time'],$custom_param['sex'],$custom_param['balance'],$custom_param['category_id'],$custom_param['order_type'],$custom_param['sign_time'],$custom_param['skip']);
    		$force_users = self::get_unique_users($force_users,'unpaid_point_push',3600*48);
    		// 排除测试的用户
//     		$force_users = self::get_minus_test_users($force_users);
    	}
    	// 未付费优惠充值活动推送（多选项）
    	elseif($category_type == 'unpaid_send_big_activity'){
    		$custom_param['subscribe_time'] = 'j';//20-48小时
    		$custom_param['order_type'] = 'a';//未充值
    		$force_users = ForceSubscribeService::forceUserCountByCustomPrams($custom_param['appids'],$custom_param['distribution_channel_id'],$custom_param['subscribe_time'],$custom_param['sex'],$custom_param['balance'],$custom_param['category_id'],$custom_param['order_type'],$custom_param['sign_time'],$custom_param['skip']);
    		$force_users = self::get_unique_users($force_users,'unpaid_send_big_activity',3600*48);
    	}
    	// 未付费9.9活动推送
    	elseif($category_type == 'unpaid_send_activity'){
    		$custom_param['subscribe_time'] = 'i';//36-48小时
    		$custom_param['order_type'] = 'a';//未充值
    		$force_users = ForceSubscribeService::forceUserCountByCustomPrams($custom_param['appids'],$custom_param['distribution_channel_id'],$custom_param['subscribe_time'],$custom_param['sex'],$custom_param['balance'],$custom_param['category_id'],$custom_param['order_type'],$custom_param['sign_time'],$custom_param['skip']);
    		$force_users = self::get_unique_users($force_users,'unpaid_send_activity',3600*48);
    	}
    	// 付费用户推送
    	elseif($category_type == 'pay_daily_push'){
    		$custom_param['order_type'] = 'd';//6-13小时充值,考虑到0-6点不推送
    		$force_users = ForceSubscribeService::forceUserCountByCustomPrams($custom_param['appids'],$custom_param['distribution_channel_id'],$custom_param['subscribe_time'],$custom_param['sex'],$custom_param['balance'],$custom_param['category_id'],$custom_param['order_type'],$custom_param['sign_time'],$custom_param['skip']);
    		$force_users = self::get_unique_users($force_users,'pay_daily_push',3600*24);
    	}
    	else{
    		
    	}
    	
    	// key重新排序
    	$temp_force_users = array();
    	if(!empty($force_users)){
    		foreach($force_users as $force_user){
    			$temp_force_users[] = $force_user;
    		}
    	}
    
    	return $temp_force_users;
    }
    
    /**
     * 得到指定用户，发送的图文内容
     */
    static function get_user_send_content($bid,$distribution_channel_id,$category_type,$uid){
    	 
    	$send_content = '';
    	$recommend_book_category_types = array('sign_push','subscribe_push');
    	// 改版，书籍数量只能选1本
    	$send_book_num = 1;
    	 
    	// 推荐图书
    	if(in_array($category_type,$recommend_book_category_types)){
    		$send_content = self::get_user_recommend_books($bid,$distribution_channel_id,$send_book_num,$category_type,$uid);
    	}
    	// 已付费热门书籍推送 12小时
    	elseif($category_type == 'all_hot_push'){
    		$send_content = self::get_user_recommend_books($bid,$distribution_channel_id,$send_book_num,$category_type,$uid);
    	}
    	// 未付费热门书籍推送 24小时
    	elseif($category_type == 'unpaid_hot_push'){
    		// 优惠充值活动
    		$send_content = array();
    		$send_content[] = [
    		['title'=>'新用户专享：点此领取25000书币'],
    		['description'=>'新用户专享：点此领取25000书币'],
    		['url'=> env('PROTOCOL').'://site'.encodeDistributionChannelId($distribution_channel_id).'.'.env('CUSTOM_HOST').'.com/sale/newUserSale?fromtype=unpaid_send_activity&send_time='.time()],
    		['image'=>'https://zhuishuyun.oss-cn-hangzhou.aliyuncs.com/smart_push/citiao.jpg']
    		];
    	}
    	// 已付费定制书籍推送 42小时
    	elseif($category_type == 'paid_point_push'){
    		$send_content = self::get_user_recommend_books($bid,$distribution_channel_id,$send_book_num,$category_type,$uid);
    	}
    	// 未付费定制书籍推送 42小时
    	elseif($category_type == 'unpaid_point_push'){
    		$send_content = array();
    		if(in_array($distribution_channel_id,array('14'))){
    			// 头条为终身充值活动
    			$first_activity = [
    			['title'=>'全年免费看书的机会来啦！限时优惠'],
    			['description'=>'全年免费看书的机会来啦！限时优惠'],
    			['url'=> env('PROTOCOL').'://site'.encodeDistributionChannelId($distribution_channel_id).'.'.env('CUSTOM_HOST').'.com/sale/seYearActivity?fromtype=unpaid_send_activity&send_time='.time()],
    			['image'=>'https://cdn-novel.iycdm.com/h5/2018111201.jpg']
    			];
    		}else{
    			// 头条为9.9元活动
    			$first_activity = [
    			['title'=>'充9.9元，得2000书币！'],
    			['description'=>'充9.9元，得2000书币，只有一次机会哦！过期失效，不要错过！'],
    			['url'=> env('PROTOCOL').'://site'.encodeDistributionChannelId($distribution_channel_id).'.'.env('CUSTOM_HOST').'.com/sale/newUserActivity?fromtype=unpaid_send_activity&send_time='.time()],
    			['image'=>'https://zhuishuyun.oss-cn-hangzhou.aliyuncs.com/smart_push/toutiao.jpg']
    			];
    		}
    		$send_content[] = $first_activity;
    		
    	}
    	// 未付费优惠充值活动推送（多选项）
    	elseif($category_type == 'unpaid_send_big_activity'){
    		//活动链接
    		$continueReadUrl = env('PROTOCOL').'://site'.encodeDistributionChannelId($distribution_channel_id).'.'.env('CUSTOM_HOST').'.com/sale/newUserSale?fromtype=unpaid_send_activity&send_time='.time();
    		$send_content = '您的新用户专享礼包已送达'."\n\n".'送25000书币及优惠券，畅读全站小说无压力！'."\n\n".'过期失效，只有1次机会哦！'."\n\n".'<a href="'.$continueReadUrl.'">点击立即领取> ></a>'."\n\n".'为方便下次阅读，请'.'<a href="https://help.leyuee.com/top.html">'.'置顶公众号'.'</a>';
    	}
    	// 未付费9.9活动推送
    	elseif($category_type == 'unpaid_send_activity'){
    		//活动链接
    		$continueReadUrl = env('PROTOCOL').'://site'.encodeDistributionChannelId($distribution_channel_id).'.'.env('CUSTOM_HOST').'.com/sale/newUserActivity?fromtype=unpaid_send_activity&send_time='.time();
    		$send_content = '您的新用户专享礼包已送达'."\n\n".'充9.9元，得2000书币，只有一次机会哦！'."\n\n".'过期失效，不要错过！'."\n\n".'<a href="'.$continueReadUrl.'">点击立即领取> ></a>'."\n\n".'为方便下次阅读，请'.'<a href="https://help.leyuee.com/top.html">'.'置顶公众号'.'</a>';
    	}    	
    	// 付费用户推送
    	elseif($category_type == 'pay_daily_push'){
    		$userBook = ReadRecordService::getFirstReadRecord($uid);
    		$book_name = isset($userBook['book_name'])?$userBook['book_name']:'';
    		$user = UserService::getById($uid);
    		$balance = isset($user->balance)?$user->balance:'0';
    		$nickname = isset($user->nickname)?$user->nickname:'';
    		//用户最近阅读链接
    		$continueReadUrl = env('PROTOCOL').'://site'.encodeDistributionChannelId($distribution_channel_id).'.'.env('CUSTOM_HOST').'.com/continue?fromtype=pay_daily_push';
    		//拼接文案
    		if(empty($book_name)){
    			$send_content = '尊敬的会员：'.$nickname."\n\n".'您的账户余额：'.$balance."\n\n".'<a href="'.$continueReadUrl.'">点击继续阅读～</a>'."\n";
    		}else{
    			$send_content = '尊敬的会员：'.$nickname."\n\n".'您的账户余额：'.$balance."\n\n".'最近阅读书籍：《'.$book_name.'》'."\n\n".'<a href="'.$continueReadUrl.'">点击继续阅读～</a>'."\n";
    		}
    		\Log::info('pay_daily_push_send_content:'.$uid);\Log::info($send_content);
    		
    	}
    	 
    	// TODO最近阅读？
    	else{}
    
    	return $send_content;
    }
    
    /**
     * 得到指定用户，发送的图文内容
     * 多条图文版--老版
     */
    static function get_user_send_content_multy($bid,$distribution_channel_id,$category_type,$uid){
    	
    	$send_content = '';
    	$recommend_book_category_types = array('sign_push','subscribe_push');
    	
    	// 推荐图书
    	if(in_array($category_type,$recommend_book_category_types)){
    		$send_content = self::get_user_recommend_books($bid,$distribution_channel_id,4,$category_type,$uid);
    	}
    	// 已付费热门书籍推送 12小时
    	elseif($category_type == 'all_hot_push'){
    		$send_content = self::get_user_recommend_books($bid,$distribution_channel_id,5,$category_type,$uid);
    	} 
    	// 未付费热门书籍推送 24小时
    	elseif($category_type == 'unpaid_hot_push'){
    		// 次条增加优惠充值活动
    		$send_content_temp = self::get_user_recommend_books($bid,$distribution_channel_id,4,$category_type,$uid);
    		$send_content = array();
    		$send_content[0] = $send_content_temp[0];
    		$send_content[1] = [
	    		['title'=>'新用户专享：点此领取25000书币'],
	    		['description'=>'新用户专享：点此领取25000书币'],
	    		['url'=> env('PROTOCOL').'://site'.encodeDistributionChannelId($distribution_channel_id).'.'.env('CUSTOM_HOST').'.com/sale/newUserSale?fromtype=unpaid_send_activity&send_time='.time()],
	    		['image'=>'https://zhuishuyun.oss-cn-hangzhou.aliyuncs.com/smart_push/citiao.jpg']
    		];
    		$send_content[2] = $send_content_temp[1];
    		$send_content[3] = $send_content_temp[2];
    		$send_content[4] = $send_content_temp[3];
    	}
    	// 已付费定制书籍推送 42小时
    	elseif($category_type == 'paid_point_push'){
    		// 头条为最近阅读记录链接
    		$recent_read_book = self::get_user_recent_read_books($uid,$distribution_channel_id,$category_type);
    		$send_content = self::get_user_recommend_books($bid,$distribution_channel_id,4,$category_type,$uid);
    		array_unshift($send_content,$recent_read_book);// 前插
    	}
    	// 未付费定制书籍推送 42小时
    	elseif($category_type == 'unpaid_point_push'){
    		$send_content = self::get_user_recommend_books($bid,$distribution_channel_id,3,$category_type,$uid);
    		
    		// 次条为最近阅读记录链接
    		$recent_read_book = self::get_user_recent_read_books($uid,$distribution_channel_id,$category_type);
    		array_unshift($send_content,$recent_read_book);
    		
    		// 头条为9.9元活动
    		$first_activity = [
	    		['title'=>'充9.9元，得2000书币！'],
	    		['description'=>'充9.9元，得2000书币，只有一次机会哦！过期失效，不要错过！'],
	    		['url'=> env('PROTOCOL').'://site'.encodeDistributionChannelId($distribution_channel_id).'.'.env('CUSTOM_HOST').'.com/sale/newUserActivity?fromtype=unpaid_send_activity&send_time='.time()],
	    		['image'=>'https://zhuishuyun.oss-cn-hangzhou.aliyuncs.com/smart_push/toutiao.jpg']
    		];
    		array_unshift($send_content,$first_activity);
    	}
    	// 未付费优惠充值活动推送（多选项）
    	elseif($category_type == 'unpaid_send_big_activity'){
    		//活动链接
    		$continueReadUrl = env('PROTOCOL').'://site'.encodeDistributionChannelId($distribution_channel_id).'.'.env('CUSTOM_HOST').'.com/sale/newUserSale?fromtype=unpaid_send_activity&send_time='.time();
    		$send_content = '您的新用户专享礼包已送达'."\n\n".'送25000书币及优惠券，畅读全站小说无压力！'."\n\n".'过期失效，只有1次机会哦！'."\n\n".'<a href="'.$continueReadUrl.'">点击立即领取> ></a>'."\n\n".'为方便下次阅读，请'.'<a href="https://help.leyuee.com/top.html">'.'置顶公众号'.'</a>';
    	}
    	// 未付费9.9活动推送
    	elseif($category_type == 'unpaid_send_activity'){
    		//活动链接
    		$continueReadUrl = env('PROTOCOL').'://site'.encodeDistributionChannelId($distribution_channel_id).'.'.env('CUSTOM_HOST').'.com/sale/newUserActivity?fromtype=unpaid_send_activity&send_time='.time();
    		$send_content = '您的新用户专享礼包已送达'."\n\n".'充9.9元，得2000书币，只有一次机会哦！'."\n\n".'过期失效，不要错过！'."\n\n".'<a href="'.$continueReadUrl.'">点击立即领取> ></a>'."\n\n".'为方便下次阅读，请'.'<a href="https://help.leyuee.com/top.html">'.'置顶公众号'.'</a>';
    	}
    	
    	// TODO最近阅读？
    	else{}
    	 
    	return $send_content;
    }
    
    /**
     * 得到指定用户，系统推荐的书籍列表
     */
    static function get_user_recommend_books($bid,$distribution_channel_id,$book_num=4,$category_type,$uid){
    	$base_category_type = self::get_base_category_type($category_type);
    	\Log::info('get_user_recommend_books,bid:'.$bid.' distribution_channel_id:'.$distribution_channel_id.' book_num:'.$book_num.' uid:'.$uid.' base_category_type:'.$base_category_type.' category_type:'.$category_type);
//     	$books = BookConfigService::getSimpleChannelBook($bid,$book_num);
    	$books = BookConfigService::getSimpleChannelBookLoop($bid,$book_num,$uid);
    	$bookUrl = env('PROTOCOL').'://site'.encodeDistributionChannelId($distribution_channel_id).'.'.env('CUSTOM_HOST').'.com';
    	$booksArray = [];
    
    	
    	// 标题加余额 
    	$pre_title = '';
    	if(in_array($distribution_channel_id,array('123','211','14'))){
    		$user = UserService::getById($uid);
    		$balance = isset($user->balance)?$user->balance:'0';
    		if($balance >= 100){
    			$pre_title = '您的账户余额：'.$balance.'书币 ';
    		}
    	}    
    	
    	//5，获取男频女频的标签文案
    	$womanPromotion = PromotionService::getRandomHeadline(2,count($books));
    	$manPromotion = PromotionService::getRandomHeadline(1,count($books));
    	$promotionNum = 0;
    	if ($books) {
    		foreach ($books as $key => $value) {
    			// 标题图片id标识
    			$title_image = [];
    			
    			$channelName = $value->channel_name;
    			$cover = $value->cover;
    			if($channelName == '男频'){
    				$book['title'] = $manPromotion[$promotionNum]['title'];
    				$book['description'] = $manPromotion[$promotionNum]['title'];
    				$title_image['title_id'] = $manPromotion[$promotionNum]['id'];
    			}else{
    				$book['title'] = $womanPromotion[$promotionNum]['title'];
    				$book['description'] = $womanPromotion[$promotionNum]['title'];
    				$title_image['title_id'] = $womanPromotion[$promotionNum]['id'];
    			}
    			
    			if ($promotionNum == 0) {
    				//第一条图片选用图库中的图片地址
    				$promotionImages = PromotionService::getMessageRandomDocumentCovers(3);
    				if ($promotionImages) {
    					$book['image'] = $promotionImages[0]['link'];
    					$title_image['image_id'] = $promotionImages[0]['id'];
    				}else{
    					$book['image'] = $cover;
    					$title_image['image_id'] = 0;
    				}
    					
    			}else{
    				$book['image'] = $cover;
    				$title_image['image_id'] = 0;
    			}
    			
    			// 记录标题图片推送的redis
    			$title_image_key = $title_image['title_id'].'_'.$title_image['image_id'];
    			\Log::info('title_image_smart_push:'.$base_category_type.' uid:'.$uid.' title_image_key:'.$title_image_key);
    			$title_image_send_uv_key = 'smart_push_from_title_image_send_uv:'.$title_image_key;
    			$title_image_statistics_key = 'smart_push_from_title_image:'.$title_image_key;
    			Redis::sadd($title_image_send_uv_key,$uid);
    			Redis::HINCRBY($title_image_statistics_key,'send_num',1);
    			
    			//通过判断书籍是男频还是女频拼接书籍信息的不同标签文案
    			if(strpos($bookUrl.$value->url,'?') > -1){
    				$urlBook = $value->url = $bookUrl.$value->url.'&fromtype='.$base_category_type.'&source=wechatmsg&fromsource=smart_push&from_title_image='.$title_image_key;
    			}else{
    				$urlBook = $value->url = $bookUrl.$value->url.'?fromtype='.$base_category_type.'&source=wechatmsg&fromsource=smart_push&from_title_image='.$title_image_key;
    			}
    			$book['url'] = $urlBook;
    			// $book['image'] = $cover;
    			if(!empty($pre_title)){
    				$book['title'] = $pre_title.$book['title'];
    			}

    			$booksArray[$key] = [['title'=>$book['title']],['description'=>$book['description']],['url'=>$book['url']],['image'=>$book['image']]];
    
    			$promotionNum++;
    
    		}
    	}
    	 
    	return $booksArray;
    }
    
    /**
     * 得到用户最近阅读的记录
     */
    static function get_user_recent_read_books($uid,$distribution_channel_id,$category_type){
    	\Log::info('get_user_recent_read_books,distribution_channel_id:'.$distribution_channel_id.' uid:'.$uid);
    	$base_category_type = self::get_base_category_type($category_type);
    	$booksArray = [];
    	
    	// 获取用户最近阅读的书籍信息
    	$userBook = ReadRecordService::getFirstReadRecord($uid);
    	
    	if ($userBook) {
    		$book = array();
    		
    		$book['url'] = env('PROTOCOL').'://site'.encodeDistributionChannelId($distribution_channel_id).'.'.env('CUSTOM_HOST').'.com/continue?fromtype='.$base_category_type;
    		$channelName = $userBook['channel_name'];
    		
    		
    		//获取男频女频的标签文案
    		$womanPromotion = PromotionService::getRandomHeadline(2,1);
    		$manPromotion = PromotionService::getRandomHeadline(1,1);
    		
    		if($channelName == '男频'){
    			$book['title'] = $manPromotion[0]['title'];
    			$book['description'] = $manPromotion[0]['title'];
    		}else{
    			$book['title'] = $womanPromotion[0]['title'];
    			$book['description'] = $womanPromotion[0]['title'];
    		}
    		
    		//头条的图片从财哥个图库中随机取一张
    		$promotionImages = PromotionService::getMessageRandomDocumentCovers(3);
    		if ($promotionImages) {
    			$book['image'] = $promotionImages[0]['link'];
    		}else{
    			$book['image'] = $userBook['cover'];
    		}
    		
    		$booksArray = [['title'=>$book['title']],['description'=>$book['description']],['url'=>$book['url']],['image'=>$book['image']]];
    	}
    
    	return $booksArray;
    }
    
    /**
     * 得到指定书籍的所有信息
     */
    static function get_book_full_infos($books,$category_type=''){

    	$booksArray = [];
    
    	//5，获取男频女频的标签文案
    	$womanPromotion = PromotionService::getRandomHeadline(2,count($books));
    	$manPromotion = PromotionService::getRandomHeadline(1,count($books));
    	$promotionNum = 0;
    	if ($books) {
    		foreach ($books as $key => $value) {
    			$channelName = $value->channel_name;
    			$cover = $value->cover;
    			if($channelName == '男频'){
    				$book['title'] = $manPromotion[$promotionNum]['title'];
    				$book['description'] = $manPromotion[$promotionNum]['title'];
    			}else{
    				$book['title'] = $womanPromotion[$promotionNum]['title'];
    				$book['description'] = $womanPromotion[$promotionNum]['title'];
    			}
    
    			//通过判断书籍是男频还是女频拼接书籍信息的不同标签文案
    			//     			if(strpos($bookUrl.$value->url,'?') > -1){
    			//     				$urlBook = $value->url = $bookUrl.$value->url.'&fromtype='.$category_type.'&source=wechatmsg';
    			//     			}else{
    			//     				$urlBook = $value->url = $bookUrl.$value->url.'?fromtype='.$category_type.'&source=wechatmsg';
    			//     			}
    			$book['url'] = $value->url;
    			// $book['image'] = $cover;
    			if ($promotionNum == 0) {
    				//第一条图片选用图库中的图片地址
    				$promotionImages = PromotionService::getMessageRandomDocumentCovers(3);
    				if ($promotionImages) {
    					$book['image'] = $promotionImages[0]['link'];
    				}else{
    					$book['image'] = $cover;
    				}
    					
    			}else{
    				$book['image'] = $cover;
    			}
    			$booksArray[$key] = [['title'=>$book['title']],['description'=>$book['description']],['url'=>$book['url']],['image'=>$book['image']]];
    
    			$promotionNum++;
    
    		}
    	}
    
    	return $booksArray;
    }

//-------------------------------------------------客服消息配置开关Start---------------------------CustomMsgSwitchs

    /**
     * 开启或关闭客服消息
     */
    static function customMsgSwitchSetting($distribution_channel_id,$custom_category,$status,$is_self_content=0)
    {

        try {

            //获取分销渠道下指定的一个智能推送
            $customMsgSwitch = CustomMsgSwitchsMsgs::customMsgSwitchsByChannelCate($distribution_channel_id,$custom_category);

            if (!empty($customMsgSwitch)) {

                //设置推送状态 1，开启    2，关闭
                $customMsgSwitch['status'] = $status;
                $customMsgSwitch['is_self_content'] = $is_self_content;
                $customMsgSwitch->save();
                return 1;
            }else{
                return 0;
            }

        } catch (\Exception $e) {
            return 2;
        }

    }

    /**
     * 根据distribution_channel_id获取客服消息开关
     */
    static function customMsgSwitchsByChannelId($distribution_channel_id)
    {
    	\Log::info('customMsgSwitchsByChannelId_start:'.$distribution_channel_id);
    	$result = array();
    	// 渠道个性配置
    	$custom_msg_switch_infos = self::GetCustomMsgSwitchsByChannelId($distribution_channel_id);
    	// 基础素材配置
    	$customMsgSwitchs = CustomMsgSwitchs::getCustomMsgSwitchByCategorys();
    	\Log::info('$custom_msg_switch_infos');\Log::info($custom_msg_switch_infos);
    	\Log::info('$customMsgSwitchs');\Log::info($customMsgSwitchs);
    	// 组装素材，全部后台配置
    	foreach($custom_msg_switch_infos as $key => $custom_msg_switch_info){
//     		\Log::info($custom_msg_switch_info);
    		$customMsgSwitch = $customMsgSwitchs[$custom_msg_switch_info->custom_category];
    		// 不展示
    		if($customMsgSwitch['status'] == 0){
    			continue;
    		}
    		$result[$key]['status'] = $custom_msg_switch_info->status;
    		$result[$key]['id'] = $custom_msg_switch_info->id;
    		$result[$key]['custom_category'] = $custom_msg_switch_info->custom_category;
    		$result[$key]['distribution_channel_id'] = $custom_msg_switch_info->distribution_channel_id;
    		$result[$key]['title'] = $customMsgSwitch['title'];
    		$result[$key]['desc_content'] = $customMsgSwitch['desc_content'];
    		$result[$key]['img_url'] = $customMsgSwitch['img_url'];
    		$result[$key]['common_is_self_content'] = $customMsgSwitch['is_self_content'];
    		$result[$key]['is_self_content'] = $custom_msg_switch_info->is_self_content;
    	}
    	return  $result;
    }
    
    /**
     * 根据distribution_channel_id获取客服消息开关
     */
    static function GetCustomMsgSwitchsByChannelId($distribution_channel_id)
    {

        //1,首先尝试获取该渠道下的智能推送开关
        $customMsgSwitchsMsgs = CustomMsgSwitchsMsgs::customMsgSwitchsMsgsByChannelId($distribution_channel_id);

        if (count($customMsgSwitchsMsgs)>0) {
            //2，该渠道下有智能推送的配置信息，开始对比过滤
            $customMsgSwitchsMsgsArray = [];

            //3，获取智能推送基础配置表的推送开关信息
            $customMsgSwitchs = CustomMsgSwitchs::customMsgSwitchs();

            //4，判断如果渠道下的只能推送开关数量和基础配置下的相同，则直接返回查到的所有客服开关
            if (count($customMsgSwitchsMsgs) == count($customMsgSwitchs)) {

                return $customMsgSwitchsMsgs;
            }else{

                //5，如果数量不一致，则渠道下需要更新智能开关的数量，与配置表保持一致，少补，多的保留

                //先循环渠道下所有的只能客服推送数量，通过custom_category关联基础配置表，
                //如果渠道下所查询到的custom_category在基础表中不存在，则说明该智能客服推送配置已删除，渠道下也要删除多余的配置项
                for ($i=0; $i < count($customMsgSwitchsMsgs); $i++) {

                    $customMsgSwitchsSerch = CustomMsgSwitchs::customMsgSwitchsBySwitchId($customMsgSwitchsMsgs[$i]['custom_category']);
                    // 有些是需要特殊开着的，多的留着
                    if (empty($customMsgSwitchsSerch)) {

//                         $customMsgSwitchsMsgs[$i]->delete();
                    }else{
                        $customMsgSwitchsMsgsArray[] = $customMsgSwitchsMsgs[$i];
                    }
                }

                //再循环基础配置表获取custom_category，看在渠道的智能客服推送配置中是否存在，
                //如果不存在，则说明这是最新配置的智能客服推送项，该渠道需要新增一条默认为关闭的智能推送开关
                for ($i=0; $i < count($customMsgSwitchs); $i++) {

                    $customMsgSwitchsMsg = CustomMsgSwitchsMsgs::customMsgSwitchsByChannelCate($distribution_channel_id,$customMsgSwitchs[$i]['custom_category']);
                    if (empty($customMsgSwitchsMsg)) {
                        # code...
                        $customMsg['custom_category'] = $customMsgSwitchs[$i]['custom_category'];
                        if($customMsg['custom_category'] == 'auto_custom_trusteeship'){
                        	$customMsg['status'] = '2';// 客服消息托管
                        }else{
                        	$customMsg['status'] = '1';// 默认开
                        }
                        $customMsg['distribution_channel_id'] = $distribution_channel_id;
                        $customMsgSwitchsMsgNew = CustomMsgSwitchsMsgs::create($customMsg);

                        $customMsgSwitchsMsgsArray[] = $customMsgSwitchsMsgNew;

                    }

                }

                //6，同步完成后，返回正确的客服推送信息
                return $customMsgSwitchsMsgsArray;

            }




        }else{

            //7，如果该渠道没有智能开关配置，则说明该渠道是新增的渠道，
            //通过基础配置表为该渠道创建相应的智能客服推送，默认关闭
            $customMsgSwitchsMsgsArray = [];
            $customMsgSwitchs = CustomMsgSwitchs::customMsgSwitchs();
            if (count($customMsgSwitchs)>0) {

                for ($i=0; $i < count($customMsgSwitchs); $i++) {

                    $customMsgSwitchsMsg['custom_category'] = $customMsgSwitchs[$i]['custom_category'];
                    if($customMsgSwitchsMsg['custom_category'] == 'auto_custom_trusteeship'){
                    	$customMsgSwitchsMsg['status'] = '2';// 客服消息托管
                    }else{
                    	$customMsgSwitchsMsg['status'] = '1';// 默认开
                    }
                    $customMsgSwitchsMsg['distribution_channel_id'] = $distribution_channel_id;
                    $customMsgSwitchsMsgNew = CustomMsgSwitchsMsgs::create($customMsgSwitchsMsg);

                    $customMsgSwitchsMsgsArray[] = $customMsgSwitchsMsgNew;
                }

            }
            return $customMsgSwitchsMsgsArray;

        }


    }

    /**
     * 获取指定客服消息开关
     */
    static function customMsgSwitchsByChannelCate($distribution_channel_id,$custom_category)
    {

        return CustomMsgSwitchsMsgs::customMsgSwitchsByChannelCate($distribution_channel_id,$custom_category);

    }

//-------------------------------------------------客服消息配置开关End---------------------------CustomMsgSwitchs



//-------------------------------------------------编辑发送客服消息Start---------------------------CustomSendMsg


    /**
     * 根据distribution_channel_id获取发送客服消息列表
     */
    static function customSendMsgsByChannelId($distribution_channel_id)
    {

        return CustomSendMsgs::customSendMsgsByChannelId($distribution_channel_id);

    }
    
    /**
     * 搜索
     */
    static function searchCustomSendMsgs($param,$is_all = false)
    {
    
    	return CustomSendMsgs::searchCustomSendMsgs($param,$is_all);
    
    }
    
    /**
     * 根据distribution_channel_id和托管信息获取发送客服消息列表
     */
    static function customSendMsgsByChannelIdAndTrusteeship($customerPrams)
    {
    
    	return CustomSendMsgs::customSendMsgsByChannelIdAndTrusteeship($customerPrams['distribution_channel_id'],$customerPrams['trusteeship']);
    
    }
    
    /**
     * 根据托管信息获取发送客服消息列表
     */
    static function customSendMsgsByTrusteeship($customerPrams)
    {
    
    	return CustomSendMsgs::customSendMsgsByTrusteeship($customerPrams['trusteeship']);
    
    }

    /**
     * 托管信息信息
     * @param $day
     * @return mixed
     */
    public static function customSendMsgsByTrusteeshipGroup($day){
        return CustomSendMsgs::where('trusteeship',1)
            ->where('del_flag',0)
            ->where('send_time','>=',$day)
            ->where('send_time','<=',$day.' 23:59:59')
            ->groupBy('distribution_channel_id')
            ->select('distribution_channel_id',DB::raw('GROUP_CONCAT(id) as ids'),DB::raw('sum(user_num) as user_num'))
            ->get();
    }

    /**
     * 托管信息信息
     * @param $day
     * @return mixed
     */
    public static function customSendMsgsByTrusteeshipByChannelId($distribution_channel_id,$date){
        return CustomSendMsgs::where('trusteeship',1)
            ->where('del_flag',0)
            ->where('distribution_channel_id','=',$distribution_channel_id)
            ->where('send_time','>=',$date)
            ->groupBy('distribution_channel_id')
            ->select(DB::raw('GROUP_CONCAT(id) as ids'),DB::raw('sum(user_num) as user_num'))
            ->first();
    }
    
    /**
     * 根据托管信息获取发送客服消息列表
     */
    static function customSendMsgsByTrusteeshipAndBacthNo($customerPrams)
    {
    
    	return CustomSendMsgs::customSendMsgsByTrusteeshipAndBacthNo($customerPrams['trusteeship'],$customerPrams['batch_no']);
    
    }
    

    //判断1小时内是否有相同的客服消息插入过
    static function isSendCustomerAtSameTime($customerPrams){

        return CustomSendMsgs::isSendCustomerAtSameTime($customerPrams['distribution_channel_id'],$customerPrams['appid'],$customerPrams['send_time']);

    }
    
    //判断1小时内是否有相同的客服消息插入过
    static function isSendCustomerAtSameTimeAndSex($customerPrams){
    
    	return CustomSendMsgs::isSendCustomerAtSameTimeAndSex($customerPrams['distribution_channel_id'],$customerPrams['appid'],$customerPrams['send_time'],$customerPrams['sex']);
    
    }

    /**
     * 根据task_id获取发送客服消息
     */
    static function customSendMsgsByTaskid($task_id)
    {

        return CustomSendMsgs::customSendMsgsByTaskid($task_id);

    }


    /**
     * 根据id获取发送客服消息
     */
    static function customSendMsgsById($id)
    {

        return CustomSendMsgs::customSendMsgsById($id);

    }

    /**
     * 停止客服消息发送
     */
    static function updateCustomSendMsgsStatus($id)
    {
        try {

            $customSendMsgs = CustomSendMsgs::customSendMsgsById($id);
            if (!empty($customSendMsgs)) {

                if($customSendMsgs['status'] == '8'){
                    \Log::info('该客服已经在发送状态，不允许编辑'.$customSendMsgs['task_id']);
                    return 4;
                }

                $customSendMsgs['status'] = '4';
                $customSendMsgs->save();

                $officialAccountArray = $customSendMsgs->toArray();
                Redis::hset('send_wechat_msg:task_id:'.$customSendMsgs['task_id'], 'wechat_msg', json_encode($officialAccountArray));
                return 1;
            }else{
                return 2;
            }

        } catch (\Exception $e) {
        	\Log::info('updateCustomSendMsgsStatus_ept:'.$e->getMessage());
            return 0;
        }


    }
    
    /**
     * 更新客服消息发送，兼容删除
     */
    static function updateCustomSendMsgsStatusMulty($id,$status,$del_flag=0)
    {
    	try {
    
    		$customSendMsgs = CustomSendMsgs::customSendMsgsById($id);
    		if (!empty($customSendMsgs)) {
 // 由于批次状态暂时不更新，所以子渠道强制更新状态
//     			if($customSendMsgs['status'] == '8'){
//     				\Log::info('updateCustomSendMsgsStatusMulty,status=8:'.$customSendMsgs['task_id']);
//     				return 4;
//     			}
    
    			$customSendMsgs['status'] = $status;
    			$customSendMsgs['del_flag'] = $del_flag;
    			$customSendMsgs->save();
    
    			$officialAccountArray = $customSendMsgs->toArray();
    			Redis::hset('send_wechat_msg:task_id:'.$customSendMsgs['task_id'], 'wechat_msg', json_encode($officialAccountArray));
    			return 1;
    		}else{
    			return 2;
    		}
    
    	} catch (\Exception $e) {
    		\Log::info('updateCustomSendMsgsStatusMulty_ept:'.$e->getMessage());
    		return 0;
    	}
    
    
    }

    /**
     * 发送客服消息
     */
    static function addCustomSendMsgs($customSendMsgsPrams)
    {

        try {

            $appids = $customSendMsgsPrams['appid'];

            $appidArray  = explode(',', $appids);

            $usercountnum = 0;

            $customSendMsgsPrams['task_id'] = 'custom_#'.$customSendMsgsPrams['distribution_channel_id'].'#'.md5(uniqid());

            //4,先在数据库创建一条新的客服消息
            $customSendMsgsPrams['user_num'] = 0;
            $customSendMsgsPrams['del_flag'] = 0;
            $customSendMsgs = CustomSendMsgs::create($customSendMsgsPrams);
            $customSendMsgsPrams['id'] = $customSendMsgs['id'];
            $officialAccountArray = $customSendMsgs->toArray();
            Redis::hset('send_wechat_msg:task_id:'.$customSendMsgs['task_id'], 'wechat_msg', json_encode($officialAccountArray));

            return 1;

        } catch (\Exception $e) {
            \Log::info('===================================发送客服消息报错');
            \Log::info($e->getMessage());
            return 0;
        }

    }


    /**
     * 修改客服消息
     */
    static function editCustomSendMsgs($customSendMsgsPrams)
    {

        try {
            
            $customSendMsgs = CustomSendMsgs::customSendMsgsById($customSendMsgsPrams['id']);
            if ($customSendMsgs) {

                if($customSendMsgs['status'] == '8'){
                    \Log::info('该客服已经在发送状态，不允许编辑'.$customSendMsgs['task_id']);
                    return 4;
                }

                //1,先把原来的客服消息停止并删除
                $customSendMsgs['status'] = '4';
                $customSendMsgs['del_flag'] = 1;
                $customSendMsgs->save();

                $officialAccountArray = $customSendMsgs->toArray();
                Redis::hset('send_wechat_msg:task_id:'.$customSendMsgs['task_id'], 'wechat_msg', json_encode($officialAccountArray));
//                    Redis::hset('send_wechat_msg:task_id:'.$customSendMsgs['task_id'], 'wechat_msg', '[{user_num:'.$customSendMsgs['user_num'].'},{appid:'.$customSendMsgs['appid'].'},{name:'.$customSendMsgs['name'].'},{send_time:'.$customSendMsgs['send_time'].'},{content:'.$customSendMsgs['content'].'},{redirect_url:'.$customSendMsgs['redirect_url'].'},{distribution_channel_id:'.$customSendMsgs['distribution_channel_id'].'},{subscribe_time:'.$customSendMsgs['subscribe_time'].'},{sex:'.$customSendMsgs['sex'].'},{balance:'.$customSendMsgs['balance'].'},{order_type:'.$customSendMsgs['order_type'].'},{category_id:'.$customSendMsgs['category_id'].'}]');

                $isSendCustomer = self::isSendCustomerAtSameTime($customSendMsgsPrams);
                if (!empty($isSendCustomer)) {
                    \Log::info('已经发送过该客服消息');
                    \Log::info($isSendCustomer['id']);
                    \Log::info($isSendCustomer['status']);
                    \Log::info($isSendCustomer['del_flag']);
                    return 3;
                }

                //2,创建一条新的模板消息
                $appids = $customSendMsgsPrams['appid'];

                $appidArray  = explode(',', $appids);

                $usercountnum = 0;

                $customSendMsgsPrams['task_id'] = 'custom_#'.$customSendMsgsPrams['distribution_channel_id'].'#'.md5(uniqid());

                //4,先在数据库创建一条新的客服消息
                $customSendMsgsPrams['user_num'] = 0;
                $customSendMsgsPrams['del_flag'] = 0;
                $customSendMsgs = CustomSendMsgs::create($customSendMsgsPrams);
                $customSendMsgsPrams['id'] = $customSendMsgs['id'];
                $officialAccountArray = $customSendMsgs->toArray();
                Redis::hset('send_wechat_msg:task_id:'.$customSendMsgs['task_id'], 'wechat_msg', json_encode($officialAccountArray));

                return 1;


            }else{

                return 2;
            }

        } catch (\Exception $e) {
            \Log::info('===================================发送客服消息报错');
            \Log::info($e->getMessage());
            return 0;
        }

    }


     /**
     * 删除客服消息
     */
    static function delCustomSendMsgs($customSendMsgsPrams)
    {

        try {
            
                $customSendMsgs = CustomSendMsgs::customSendMsgsById($customSendMsgsPrams['id']);
                if ($customSendMsgs) {

                    if($customSendMsgs['status'] == '8'){
                        \Log::info('该客服已经在发送状态，不允许编辑'.$customSendMsgs['task_id']);
                        return 4;
                    }

                    //1,先把原来的客服消息停止并删除
                    $customSendMsgs['status'] = '4';
                    $customSendMsgs['del_flag'] = 1;
                    $customSendMsgs->save();

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

                }else{

                    return 2;
                }

        } catch (\Exception $e) {
            \Log::info('===================================发送客服消息报错');
            \Log::info($e->getMessage());
            return 0;
        }

    }


    /**
     * 测试发送客服消息
     */
    static function testAddCustomSendMsgs($customSendMsgsPrams)
    {

        try {
        	// 测试链接加上域名
        	$customSendMsgsPrams['content'] = TemplateCustomSendService::convert_custom_content($customSendMsgsPrams['content'], 'test', $customSendMsgsPrams['distribution_channel_id'],0);
        	 
            $appids = $customSendMsgsPrams['appid'];
 
            $appidArray  = explode(',', $appids);

            for ($j=0; $j < count($appidArray); $j++) {
            	\Log::info('testAddCustomSendMsgs_appid:'.$appidArray[$j]);

                //1，获取指定的用户
                $forceSubscribeUserPram['uid'] = $customSendMsgsPrams['uid'];
                $forceSubscribeUserPram['appid'] = $appidArray[$j];
                $forceSubscribeUserPram['distribution_channel_id'] = $customSendMsgsPrams['distribution_channel_id'];
                $force_user = array();
                $temp_force_user =  ForceSubscribeService::forceSubscribeUsersByUidAndAppidAndChannelId($forceSubscribeUserPram);
                \Log::info('temp_force_user');\Log::info($temp_force_user);
                if(count($temp_force_user) == 0){
                	\Log::info('testAddCustomSendMsgs_has_no_user:'.$customSendMsgsPrams['uid']);
                	$direct_user = array('openid'=>$customSendMsgsPrams['uid']);
                	$force_user[] = $direct_user;
                }else{
                	$force_user = $temp_force_user;
                }
                \Log::info('force_user');\Log::info($force_user);
                
                if (count($force_user)>0) {

                    for ($i=0; $i < count($force_user); $i++) {

                        //2，测试循环用户发送客服消息
                        $data = array();
                        $data['openid'] = $force_user[$i]['openid'];
                        $data['appid'] = $appidArray[$j];
                        $data['news_content'] = $customSendMsgsPrams['content'];
                        $data['type'] = 'last_task';
                        $data['task_id'] = 'custom_f69556c4eb5274cefdb9ba0a477736366';
                        $data['send_time'] = date("Y-m-d H:i:s");
                        $send_data=array(
                            'send_time'=>date("Y-m-d H:i:s"),
                            'data' => $data
                        );
                        $delay = 0;
                        // \Log::info('客服消息找到用户并发送===================================');
                        \Log::info('test_custom_msg_send:'.$data['openid']);
                        // \Log::info($data['appid']);
                        \Log::info($data['news_content']);

                        $job = (new SendNews($send_data))->onConnection('rabbitmq')->delay($delay)->onQueue('send_news_list');

                        dispatch($job);
                    }
                   
                }

            }

            return 1;
            

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

    }

//-------------------------------------------------编辑发送客服消息End---------------------------CustomSendMsg



//-------------------------------------------------生成图文链接Start---------------------------

    /**
     * 上传微信图片
     * @param unknown_type $gzh_app_id
     * @param unknown_type $img_url
     * @param unknown_type $group_nick
     * @param unknown_type $timestamp
     */
    static function upload_material_img($param) {
    	$params = array("gzh_app_id"=>$param['gzh_app_id'],"img_url"=>$param['img_url'],"group_nick"=>$param['group_nick'],"timestamp"=>$param['timestamp']);
    	$sign = get_sign($params);
    	
    	//获取封面图片media_id
    	$mediaCustomerJson = self::getUserClient()->request("GET","upload_material_img/",
    			['query'=>['gzh_app_id'=>$param['gzh_app_id'],'img_url'=>$param['img_url'],'group_nick'=>$param['group_nick'],'timestamp'=>$param['timestamp'],'sign'=>$sign],'connect_timeout' => 3]
    	)->getBody()->getContents();
    	
    	\Log::info("alter_upload_material_img:".$param['gzh_app_id'].' img_url:'.$param['img_url']);
    	\Log::info($mediaCustomerJson);
    	
    	$mediaCustomerArray = json_decode($mediaCustomerJson,true);
    	return $mediaCustomerArray;
    }
    
    public static function multy_upload_material_imgs($content,$last_urls,$base_param){
    	\Log::info('multy_upload_material_imgs_start');
    	\Log::info('last_urls');\Log::info($last_urls);
    	$multy_urls = [];
    	foreach($last_urls as $last_url){
    		if(strpos($last_url,'mmbiz.qpic.cn') > -1){
    			\Log::info('wx_url_continue:'.$last_url);
    			continue;
    		}
    		$last_url = str_replace(array("&amp;","&quot;","amp;","quot;"), "", htmlspecialchars($last_url));
    		$params = array("gzh_app_id"=>$base_param['gzh_app_id'],"img_url"=>$last_url,"group_nick"=>$base_param['group_nick'],"timestamp"=>$base_param['timestamp']);
    		$sign = get_sign($params);
    		$params['sign'] = $sign;
    		$url = env('MEDIA_API_BASE_URI').'upload_material_img?'.http_build_query($params);
    		$multy_url = [];
    		$multy_url['request_url'] = $url;
    		$multy_url['old_url'] = $last_url;
    		$multy_urls[] = $multy_url;
    	}
    	
    	// 最多尝试3次
    	$try_time = 0;
    	while($try_time < 3){
    		try{
    			$url_mappings = self::multiRequest($multy_urls);
    			\Log::info('$url_mappings');\Log::info($url_mappings);
    			if(!empty($url_mappings)){
    				\Log::info('multiRequest_success');
    				break;
    			}
    		}catch(\Exception $e){
    			\Log::info('multiRequest_ept:'.$e->getMessage());
    		}
    		$try_time++;
    	}
    	if($try_time == 3){
    		\Log::info('multiRequest_error_return:');
    		return '';
    	}
    	
    	foreach($url_mappings as $key=>$url_mapping){
    		\Log::info('replace_old_url:'.$url_mapping['old_url'].' new_url:'.$url_mapping['new_url']);
    		$content = str_replace($url_mapping['old_url'], $url_mapping['new_url'], $content);
    	}
    	return $content;
    }
    
    static function multiRequest($data){
    	$client = new Client(
    			['allow_redirects'=>true,
    			'timeout'=>120000]);
    
    	$promises  = [];
    	$mappings = [];
    
    	for($i=0;$i<count($data);$i++){
    		\Log::info('async_url:'.$data[$i]['request_url']);
    		$promises[$i] = $client->getAsync($data[$i]['request_url']);
    	}
    	$results = Promise\unwrap($promises);
//     	\Log::info('multy_$results');\Log::info($results);
    	$j = 0;
    	foreach($data as $key=>&$v){
    		$res = $results[$key]->getBody()->getContents();
    		$res = json_decode($res,true);
    		\Log::info('res:'.$key.' res:'.json_encode($res));
    		$mappings[$key]['old_url'] = $data[$key]['old_url'];
    	    if($res['code'] == 1){
    			$mappings[$key]['new_url'] = $res['data']['url'];
    		}else{
    			\Log::info('multiRequest_error_return:'.$data[$key]['old_url'].' res:'.json_encode($res).' request_url:'.$data[$key]['request_url']);
    			return null;
    		}
    	}
    	return $mappings;
    }
    
    // 单个链接上传替换
    static function one_upload_material_imgs($content,$last_urls){
    	\Log::info('one_upload_material_imgs_start');
    	foreach($last_urls as $key=>$last_url){
    		\Log::info('last_urls_count:'.count($last_urls).' now:'.$key);
    		if(strpos($last_url,'mmbiz.qpic.cn') > -1){
    			\Log::info('wx_url_continue:'.$last_url);
    			continue;
    		}
    		$last_url = str_replace(array("&amp;","&quot;","amp;","quot;"), "", htmlspecialchars($last_url));
    		 
    		// TODO 加try 3次？
    		$i = 0;
    		while($i < 3){
    			try{
    				\Log::info('child_upload_material_img_start:i'.$i.' last_url:'.$last_url);
    				$param['img_url'] = $last_url;
    				$upload_res = self::upload_material_img($param);
    				\Log::info('$upload_res');\Log::info($upload_res);
    				if($upload_res['code'] == 1){
    					$content = str_replace($last_url, $upload_res['data']['url'], $content);
    					break;
    				}
    			}catch(\Exception $e){
    				\Log::info('upload_matrial_img_ept:'.$e->getMessage());
    				sleep(1);
    			}
    			$i++;
    		}
    		 
    		if($i == 3){
    			\Log::info('upload_matrial_img_return');
    			return null;
    		}
    	
    	}
    	
    	return $content;
    }
    
    /**
     * 转化章节图片为微信的url
     * @param unknown_type $content
     */
    static function convert_content_wechat_url($content,$param){
    	\Log::info('convert_content_wechat_url_start:'.json_encode($param));
    	// 获取url list
    	// 防封模式、第一条封面图要去掉
    	//<img src="http://yueduyun.oss-cn-hangzhou.aliyuncs.com/book_chapter_image_test/5pNo6A7wqQmB1WgQygDjkOM9VZn2vXeY/1/1_0.jpg"
    	preg_match_all('/<img src="(.*)"/U',$content,$ff_matchs);
    	$ff_urls = isset($ff_matchs[1])?$ff_matchs[1]:array();
    	if(isset($ff_urls[0])){
    		unset($ff_urls[0]);
    	}
    	\Log::info('ff_matchs:');
    	\Log::info($ff_urls);
    	
    	// 背景图模式
    	//background: url(&quot;http://yueduyun.oss-cn-hangzhou.aliyuncs.com/book_chapter_image_test/5pNo6A7wqQmB1WgQygDjkOM9VZn2vXeY/1/1_0.jpg&quot;)
    	preg_match_all('/background: url\((.*)\)/U',$content,$bg_matchs);
    	$bg_urls = isset($bg_matchs[1])?$bg_matchs[1]:array();
    	\Log::info('bg_urls:');
    	\Log::info($bg_urls);
    	
    	$last_urls = array_merge($ff_urls,$bg_urls);
    	\Log::info('$last_urls');\Log::info($last_urls);
    	
    	if(!empty($last_urls)){
    		\Log::info('before_convert:');\Log::info($content);
    		
    		$content = self::multy_upload_material_imgs($content,$last_urls,$param);
    		
    		\Log::info('after_convert:');\Log::info($content);
    	}
    	
    	return $content;
    	
    }
    
    /**
     * 生成图文链接
     */
    static function createOfficialImgTxtUrl($officialImgTxtUrlPrams)
    {
        $img_url = $officialImgTxtUrlPrams['img_url'];
        $content = $officialImgTxtUrlPrams['content'];
        $title = $officialImgTxtUrlPrams['title'];
        $distribution_channel_id = $officialImgTxtUrlPrams['distribution_channel_id'];
        $book_name = $officialImgTxtUrlPrams['book_name'];
        $chapter_sequence = $officialImgTxtUrlPrams['chapter_sequence'];
        $send_orders_id = $officialImgTxtUrlPrams['send_orders_id'];
        $send_orders_name = $officialImgTxtUrlPrams['send_orders_name'];
        $send_orders_url = $officialImgTxtUrlPrams['send_orders_url'];
        $show_cover_pic = 1;
        $gzh_app_id = '';
        $digest = '';
        $author = '';
        $thumb_media_id = '';

        $officialAccountprams['distribution_channel_id'] = $distribution_channel_id;
        $officialAccounts = OfficialAccountService::officialAuthAccountBydistributionChannelId($officialAccountprams);

        if (count($officialAccounts)>0) {
            $gzh_app_id = $officialAccounts[0]['appid'];
            // $gzh_app_id = 'wxb2aaa55b088f12e9';
            $timestamp = (time());
            $group_nick = env('GROUP_NICK');
            
            $param = [
               'timestamp'=>$timestamp,
               'group_nick'=>$group_nick,
               'gzh_app_id'=>$gzh_app_id,
               'img_url'=>$img_url
            ];
            
            // 内容的链接转化为微信的官方链接，否则文章上传会被过滤掉
            $content = self::convert_content_wechat_url($content,$param);
            // 转化异常直接返回
            if(empty($content)){
            	return '';
            }
            
            try {
            	
            	$mediaCustomerArray = self::upload_material_img($param);

                if ($mediaCustomerArray['code'] == 1) {
                    
                    $mediaCustomerData = $mediaCustomerArray['data'];
                    if (!empty($mediaCustomerData)) {

                        $thumb_media_id = $mediaCustomerData['media_id'];

                        $param2s = array("show_cover_pic"=>$show_cover_pic,"author"=>$author,"digest"=>$digest,"content"=>$content,"title"=>$title,"thumb_media_id"=>$thumb_media_id,"gzh_app_id"=>$gzh_app_id,"group_nick"=>$group_nick,"timestamp"=>$timestamp);
                        $sign2 = get_sign($param2s);

                        \Log::info("============================开始请求创建素材URL接口");
                       
                        //获取图文素材链接    
                        $officialImgTxtUrlJson = self::getUserClient()->request("POST","upload_gzh_article/",
                                            ['form_params'=>["show_cover_pic"=>$show_cover_pic,"author"=>$author,"digest"=>$digest,"content"=>$content,"title"=>$title,"thumb_media_id"=>$thumb_media_id,"gzh_app_id"=>$gzh_app_id,'group_nick'=>env('GROUP_NICK'),'timestamp'=>$timestamp,'sign'=>$sign2],'connect_timeout' => 3]
                                            )->getBody()->getContents();

                        \Log::info("============================获取素材图文链接 通过接口整合获得 content_source_url");
                        \Log::info($officialImgTxtUrlJson);

                        $officialImgTxtUrlArray = json_decode($officialImgTxtUrlJson,true);

                        if ($officialImgTxtUrlArray['code'] == 1) {
                    
                            $officialImgTxtUrlData = $officialImgTxtUrlArray['data'];
                            if (!empty($officialImgTxtUrlData)) {

                                $content_source_url = $officialImgTxtUrlData['chapter_url'];

                                $officialImgTxtUrls['img_url'] = $img_url;
                                $officialImgTxtUrls['content'] = $content;
                                $officialImgTxtUrls['title'] = $title;
                                $officialImgTxtUrls['distribution_channel_id'] = $distribution_channel_id;
                                $officialImgTxtUrls['book_name'] = $book_name;
                                $officialImgTxtUrls['chapter_sequence'] = $chapter_sequence;
                                $officialImgTxtUrls['gzh_app_id'] = $gzh_app_id;
                                $officialImgTxtUrls['digest'] = $digest;
                                $officialImgTxtUrls['author'] = $author;
                                $officialImgTxtUrls['thumb_media_id'] = $thumb_media_id;
                                $officialImgTxtUrls['content_source_url'] = $content_source_url;
                                $officialImgTxtUrls['send_orders_id'] = $send_orders_id;
                                $officialImgTxtUrls['send_orders_name'] = $send_orders_name;
                                $officialImgTxtUrls['send_orders_url'] = $send_orders_url;
                                $officialImgTxtUrls['del_flag'] = 0;
                                OfficialImgtextUrls::create($officialImgTxtUrls);


                                return urldecode(str_replace("\/","/",$content_source_url)); 
                            }
                        }else{
                            return '';
                        }
                               
                    }
                    
                    
                }else{
                    return '';
                }

            } catch (\Exception $e) {
                \Log::info("createOfficialImgTxtUrl_ept:".$e->getMessage());
                return '';
                
            }                   
            

        }

    }

    /**
     * 获取图文列表
     */
    static function getOfficialImgTxtUrl($distribution_channel_id)
    {
        return OfficialImgtextUrls::officialImgtextUrlsByChannelId($distribution_channel_id);
    }

    /**
     * 根据标题获取图文列表
     */
    static function getOfficialImgTxtUrlByBookName($distribution_channel_id,$book_name)
    {
        return OfficialImgtextUrls::getOfficialImgTxtUrlByBookName($distribution_channel_id,$book_name);
    }

    /**
     * 上传二维码图片
     */
    static function uploadQrcodeImgToWechat($officialImgTxtUrlPrams)
    {
        $distribution_channel_id = $officialImgTxtUrlPrams['distribution_channel_id'];
        $img_url = $officialImgTxtUrlPrams['qrcode_Img'];

        $officialAccountprams['distribution_channel_id'] = $distribution_channel_id;
        $officialAccounts = OfficialAccountService::officialAuthAccountBydistributionChannelId($officialAccountprams);

        if (count($officialAccounts)>0) {
            $gzh_app_id = $officialAccounts[0]['appid'];
            // $gzh_app_id = 'wxb2aaa55b088f12e9';
            $timestamp = (time());
            $group_nick = env('GROUP_NICK');

            try {

                $params = array("gzh_app_id"=>$gzh_app_id,"img_url"=>$img_url,"group_nick"=>$group_nick,"timestamp"=>$timestamp);
                $sign = get_sign($params);

                //获取封面图片media_id    
                $mediaCustomerJson = self::getUserClient()->request("GET","upload_material_img/",
                                    ['query'=>['gzh_app_id'=>$gzh_app_id,'img_url'=>$img_url,'group_nick'=>env('GROUP_NICK'),'timestamp'=>$timestamp,'sign'=>$sign],'connect_timeout' => 3]
                                    )->getBody()->getContents();

                \Log::info("============================上传二维码图片 通过图片+appid获取media_id");
                \Log::info($mediaCustomerJson);

                $mediaCustomerArray = json_decode($mediaCustomerJson,true);

                if ($mediaCustomerArray['code'] == 1) {
                    
                    $mediaCustomerData = $mediaCustomerArray['data'];
                    if (!empty($mediaCustomerData)) {

                        $thumb_media_id = $mediaCustomerData['media_id'];
                        $url = $mediaCustomerData['url'];
                        $wechatQrcodeImg['media_id'] = $thumb_media_id;
                        $wechatQrcodeImg['url'] = $url;

                        return $wechatQrcodeImg;

                    }
                }else{
                    return false;
                }
            } catch (\Exception $e) {
                \Log::info("============================上传二维码图片");
                \Log::info($e->getMessage());
                return false;
                
            } 
        }

    }

    /**
     * 删除图文素材
     */
    static function delOfficialImgTxtUrl($id)
    {

        try {

            $officialImgtextUrl = OfficialImgtextUrls::officialImgtextUrlsById($id);
            if (!empty($officialImgtextUrl)) {
                
                $officialImgtextUrl['del_flag'] = 1;
                $officialImgtextUrl->save();
                return 1;

            }else{
                return 2;
            }
            
        } catch (\Exception $e) {
            return 0;
        }
        
    }

//-------------------------------------------------生成图文链接End---------------------------

    static public function getUserClient(){
        // return new Client(['base_uri' => 'http://118.31.133.29/api/']);
        return new Client(['base_uri' => env('MEDIA_API_BASE_URI')]);
    }
    
    
    /**
     * 客服消息智能推送方法--简单公用版
     * 以下3个板块找到对应的推送
     * 1、用户
     * 2、内容
     * 3、队列类型
     */
    static function SimpleSmartPush($category_type){
    	if(empty($category_type)) return false;
    	\Log::info('simple_smart_push:'.$category_type);
    	// 应该不区分男女，通过内容来区分
    	$sexs = array('z');
    
    	$user_total_count = 0;
    
    	foreach($sexs as $sex){
    			\Log::info('smart_push_sex:'.$sex);
    			$send_content = '';
   
    			$skip = 0;
    			$loop = 0;
    						
    			while ( $skip <= 250000) {
    						$loop++;
    						$force_user = null;
    						$force_user = self::get_simple_send_users($category_type,$sex,$skip);
    						\Log::info('SmartPush_usernum:'.count($force_user).' loop:'.$loop.' memory:'.memory_get_usage());
    						\Log::info('$force_user:'.json_encode($force_user));
    						$force_user_num = count($force_user);
    						$skip += $force_user_num;
    						$user_total_count += $force_user_num;
    						if($force_user_num > 0){
    							for ($i=0; $i < $force_user_num; $i++) {
    								$uid = $force_user[$i]['uid'];
    								$bid = $force_user[$i]['bid'];
    								$template_id = $force_user[$i]['template_id'];
    								$distribution_channel_id = $force_user[$i]['distribution_channel_id'];
    								$send_content = self::get_simple_user_send_content($category_type,$uid,$distribution_channel_id);
    								
    								if(empty($send_content)){
    									\Log::info('smart_push:openid:'.$force_user[$i]['openid'].' appid:'.$force_user[$i]['appid'].' content_is_null');
    									continue;
    								}
    
    								$smart_push_queue = self::get_simple_smart_push_queue($category_type);
    								$data = array();
    								$data['openid'] = $force_user[$i]['openid'];
    								$data['appid'] = $force_user[$i]['appid'];
    								$data['type'] = 'one_task';
    								$data['task_id'] = 3;
    								$data['send_time'] = date("Y-m-d H:i:s");
    								if ($smart_push_queue['queue'] == 'send_template_list'){
    									$data['statusstr'] = (time());
    									$data['template_id'] = $template_id;
    									$data['url'] = $send_content['url'];
    									$data['template_content'] = json_encode($send_content['content']);
    								}elseif ($smart_push_queue['queue'] == 'send_news_list'){
    									$data['news_content'] = json_encode($send_content['content']);
    								}else{
    									$data['content'] = $send_content['content'];
    								}
    								
    								$send_data=array(
    										'send_time'=>date("Y-m-d H:i:s"),
    										'data' => $data
    								);
    									
    								$delay = 0;
    									
    								//     								\Log::info('smart_push:'.json_encode($data));
    								if ($smart_push_queue['queue'] == 'send_news_list'){
    									$job = (new SendNews($send_data))->onConnection('rabbitmq')->delay($delay)->onQueue($smart_push_queue['queue']);
    								}elseif ($smart_push_queue['queue'] == 'send_template_list'){
    									$job = (new SendTemplate($send_data))->onConnection('rabbitmq')->delay($delay)->onQueue($smart_push_queue['queue']);
    								}else{
    									$job = (new SendTexts($send_data))->onConnection('rabbitmq')->delay($delay)->onQueue($smart_push_queue['queue']);
    								}
    								
    								dispatch($job);
    								\Log::info('smart_push_user_end:'.$uid.' memory:'.memory_get_usage());
    								// 释放内存
    								$send_data = $data = null;
    							}//end users
    
    							if($force_user_num < 10000)//低于单次获取的10000条，所以下次不必获取，必须与单次获取的数值保持一致！
    							{
    								\Log::info('simple_smart_push user num less than once get num, so break category_type:'. $category_type.' sex:'.$sex.' loop:'.$loop.' memory:'.memory_get_usage());
    								break;
    							}
    								
    						}
    						else{
    							\Log::info('simple_smart_push_has_no_user category_type:'. $category_type.' sex:'.$sex.' loop:'.$loop.' memory:'.memory_get_usage());
    							break;
    						}
    			}//end loop
    						
    	} // end sex

    }
    
    /**
     * 得到指定用户，发送的图文内容
     */
    static function get_simple_user_send_content($category_type,$uid,$distribution_channel_id){
    
    	$send_content = null;
    
    	// 推荐图书
    	if($category_type == 'template_short_long_chapter'){
    		$book_config = DataAnalysisBookConfig::getUserOneNotOrderBook($uid);
    		//
    		$template_content = [
	    		'first'=>$book_config['template_title'],
	    		'keyword1'=>'《'.$book_config['book_name'].'》',
	    		'keyword2'=>'今日',
	    		'remark'=>'点击查看详情'
    		];
    		$send_content['content'][] = $template_content;
    		
    		$bookUrl = env('PROTOCOL').'://site'.encodeDistributionChannelId($distribution_channel_id).'.'.env('CUSTOM_HOST').'.com';
    		$bookUrl = $bookUrl. '/reader?bid='. Hashids::encode($book_config['bid']).'&cid='.$book_config['first_cid'].'&fromtype=test_long_short_chapter';
    		
    		$send_content['url'] = $bookUrl;
    	}elseif($category_type == 'custom_short_long_chapter'){
    		$book_config = DataAnalysisBookConfig::getUserOneNotOrderBook($uid);
    		//
    		$promotionImages = PromotionService::getMessageRandomDocumentCovers(3);
    		$book['image'] = $promotionImages[0]['link'];
    		$bookUrl = env('PROTOCOL').'://site'.encodeDistributionChannelId($distribution_channel_id).'.'.env('CUSTOM_HOST').'.com';
    		$bookUrl = $bookUrl. '/reader?bid='. Hashids::encode($book_config['bid']).'&cid='.$book_config['first_cid'].'&fromtype=test_long_short_chapter';
    		
    		$booksArray[0] = [['title'=>$book_config->custom_title],['description'=>$book_config->custom_title],['url'=>$bookUrl],['image'=>$book['image']]];

    		$send_content['content'] = $booksArray;
    	}
    	else{}
    	
    	\Log::info('get_simple_user_send_content_last:'.$uid);
    	\Log::info($send_content);
    
    	return $send_content;
    }
    
    /**
     * 得到指定类型智能推送发送的用户列表
     */
    static function get_simple_send_users($category_type,$sex,$skip=0){
    	$force_users = [];
    	$param = [];

    	// 客服消息
    	if($category_type == 'custom_short_long_chapter'){
    		$uids = self::get_test_users();
    		// 42小时后
    		$param['subscribe_time'] = 'k';
    		
    		$force_users = ForceSubscribeService::simpleForceUserCountByPrams($uids, $param,$skip);
    		$force_users = self::get_unique_users($force_users,'custom_short_long_chapter',7200);
    	}
    	elseif($category_type == 'template_short_long_chapter'){
    		$uids = self::get_test_users();
    		// 60小时后
    		$param['subscribe_time'] = 'm';
    		$param['common_template_id'] = 'OPENTM401671396';
    		
    		\Log::info('start_simple_param:'.json_encode($uids).' param:'.json_encode($param));
    		$force_users = ForceSubscribeService::simpleForceUserCountByPrams($uids, $param,$skip);
    		\Log::info('before_unique_user:'.json_encode($force_users));
    		$force_users = self::get_unique_users($force_users,'custom_short_long_chapter',7200);
    	}
    	 
    	// key重新排序
    	$temp_force_users = array();
    	if(!empty($force_users)){
    		foreach($force_users as $force_user){
    			$temp_force_users[] = $force_user;
    		}
    	}
    
    	return $temp_force_users;
    }
    
    static function get_simple_smart_push_queue($category_type){
    	$smart_push_queue = array();
    	 
    	$template_queue = array('template_short_long_chapter');
    	$custom_queue = array('custom_short_long_chapter');
    	$text_queue = array();
    	 
    	if(in_array($category_type,$template_queue)){
    		$smart_push_queue['is_news'] = false;
    		$smart_push_queue['queue'] = 'send_template_list';
    	}elseif(in_array($category_type,$custom_queue)){
    		$smart_push_queue['is_news'] = true;
    		$smart_push_queue['queue'] = 'send_news_list';
    	}else{
    		$smart_push_queue['is_news'] = false;
    		$smart_push_queue['queue'] = 'send_texts_list';
    	}
    	
    	\Log::info('$smart_push_queue');\Log::info($smart_push_queue);
    	 
    	return $smart_push_queue;
    }
    
    static function get_minus_test_users($force_users){
    	$test_uids = self::get_test_users();
    	\Log::info('get_minus_test_users,force_users:'.json_encode($force_users).' $test_uids:'.json_encode($test_uids));
    	 
    	if(!empty($force_users)){
    		foreach($force_users as $key=>$force_user){
    			if(in_array($force_user->uid,$test_uids)){
    				\Log::info('get_minus_test_users_exist:'.$force_user->uid);
    				unset($force_users[$key]);
    			}else{
    				\Log::info('get_minus_test_users_not_exist:'.$force_user->uid);
    			}
    		}
    	}
    	\Log::info('get_minus_test_users after_force_users:'.json_encode($force_users));
    	 
    	return $force_users; 
    }
    
    static function get_test_users(){
    	// 获取测试的用户
    	$types = [2,5];
    	$test_uids = DataAnalysisChapterService::getByTypes($types);
    	return $test_uids;
    }
    

}
