| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909 | <?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 App\Modules\Book\Models\Chapter;use App\Modules\WechatMaterial\Services\BatchWechatCustomSendService;use GuzzleHttp\Client;use GuzzleHttp\Pool;use GuzzleHttp\Promise;use App\Libs\OSS;use GuzzleHttp\Psr7\Request;use Redis;use App\Jobs\SendNews;use App\Jobs\SendSmartNews;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_users = ForceSubscribeService::allForceSubscribeUsersByUid(compact('uid'));                                    if (!empty($force_users)) {                                        foreach ($force_users as $force_user) {                                            \Log::info('nopaid_remind:' . $force_user['openid']);                                            //(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['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());                        }                    }                }            }        }    }       /**     *  未充值用户推送客服消息(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);                }            }        }    }       /**     * 客服消息智能推送方法--公用版     * 以下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 SendSmartNews($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_smartnews_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'];                $appid          = $force_user['appid'];                $user_key       = $redis_pre_str . ':' . $uid;                $user_appid_key = $redis_pre_str . ':' . $appid . ':' . $uid;                // 兼容老逻辑                if (Redis::get($user_key)) {                    unset($force_users[$key]);//     				\Log::info($redis_pre_str.'_exist_user:'.$uid);                    continue;                } // appid级别的                elseif (Redis::get($user_appid_key)) {                    unset($force_users[$key]);//     				\Log::info($redis_pre_str.'_exist_user:'.$uid);                    continue;                } else {//     				\Log::info($redis_pre_str.'_push_add_user:'.$uid);                    // 以后都按appid级别来                    Redis::SETEX($user_appid_key, $expire_time, date('Y-m-d H:i:s'));                }            }            \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-50分钟内            $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---------------------------    public static function multi_upload_material_imgs($appId, $images, $imageType = 'common')    {        \Log::info('multi_upload_material_imgs [start]');        $client = new Client(['base_uri' => env('MEDIA_API_BASE_URI')]);        $error    = [];        $promises = [];        foreach ($images as $key => $imageUrl) {            $param         = [                'gzh_app_id' => $appId,                'img_url'    => $imageUrl,                'image_type' => $imageType,                'group_nick' => env('GROUP_NICK'),                'timestamp'  => time()            ];            $param['sign'] = get_sign($param);            $uri           = 'upload_material_img?' . http_build_query($param);            $promises[$key] = $client->getAsync($uri);        }        $results = Promise\unwrap($promises);        $urls    = [];        foreach ($images as $key => $imageUrl) {            $res = $results[$key]->getBody()->getContents();            $res = json_decode($res, true);            if ($res['code']) {                $urls[$key] = [                    'old_url'  => $imageUrl,                    'new_url'  => getProp($res['data'], 'url'),                    'media_id' => getProp($res['data'], 'media_id'),                ];            } else {                $error[$imageType] = $res['msg'];            }        }        \Log::info('multi_upload_material_imgs urls: ' . $imageType);        \Log::info($urls);        \Log::info($error);        return compact('urls', 'error');    }    /**     * 上传微信图片     * @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;    }    /**     * 上传微信图片     * @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_by_type($param)    {        $params = array("gzh_app_id" => $param['gzh_app_id'], 'image_type' => $param['image_type'], "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'], 'image_type' => $param['image_type'], '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_by_type_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;"), "", 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;"), "", 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;    }    public static function extract_content_images($content)    {        // 获取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("http://yueduyun.oss-cn-hangzhou.aliyuncs.com/book_chapter_image_test/5pNo6A7wqQmB1WgQygDjkOM9VZn2vXeY/1/1_0.jpg")        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 ($last_urls) {            foreach ($last_urls as &$last_url) {                $last_url = str_replace(['"', '&'], '', $last_url);            }        }        return $last_urls;    }    public static function replace_content_images($materials, $images, $uploadImages)    {        foreach ($materials as &$material) {            $material['content'] = str_replace($images, $uploadImages, $material['content']);        }        return $materials;    }    /**     * @param $channelId     * @param $msgInfo     * @param $materials     * @param $upThumbsUrls     * @return array|bool|mixed     * @throws \GuzzleHttp\Exception\GuzzleException     */    public static function upload_articles($channelId, $msgInfo, $materials, $upThumbsUrls)    {        $articles = [];        foreach ($materials as $key => $material) {            $upThumbsUrlInfo = collect($upThumbsUrls)->where('old_url', getProp($material, 'cover_url'))->first();            $thumbMediaId    = getProp($upThumbsUrlInfo, 'media_id');            // 原文链接            $materialId = getProp($material, 'id');            $url        = BatchWechatCustomSendService::checkAddDomain($channelId, getProp($material, 'url'));            $sourceUrl  = BatchWechatCustomSendService::redirect_url_add_param($url, $materialId, 'batch_custom');            $tmp         = [                'thumb_media_id'     => $thumbMediaId,                'author'             => getProp($msgInfo, 'name'),                'title'              => getProp($material, 'title'),                'content_source_url' => $sourceUrl,                'content'            => getProp($material, 'content'),                'digest'             => getProp($material, 'desc'),                'show_cover_pic'     => 0,            ];            $tmp['sign'] = get_sign($tmp);            $articles[]  = $tmp;        }        if (empty($articles)) {            return false;        }        //获取图文素材链接        try {            $data         = [                'group_nick' => env('GROUP_NICK'),                'gzh_app_id' => getProp($msgInfo, 'appid'),                'articles'   => json_encode($articles, JSON_UNESCAPED_UNICODE),                'timestamp'  => time()            ];            $data['sign'] = get_sign($data);            \Log::info("upload_gzh_articles request");            \Log::info($data);            $jsonStr = self::getUserClient()->request('POST', 'upload_gzh_articles/', [                'form_params'     => $data,                'connect_timeout' => 10            ])->getBody()->getContents();            \Log::info("============================获取素材图文链接 通过接口整合获得 content_source_url");            \Log::info($jsonStr);        } catch (\Exception $e) {            \Log::info('createOfficialImgTxtUrl_ept:' . $e->getMessage());            return [];        }        return json_decode($jsonStr, true);    }    /**     * 转化章节图片为微信的url     * @param $content     * @param $param     * @return mixed|string     */    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("http://yueduyun.oss-cn-hangzhou.aliyuncs.com/book_chapter_image_test/5pNo6A7wqQmB1WgQygDjkOM9VZn2vXeY/1/1_0.jpg")        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 createOfficialImgTxtUrls($officialImgTxtUrlPrams)    {        $distribution_channel_id = $officialImgTxtUrlPrams['distribution_channel_id'];        $appid                   = $officialImgTxtUrlPrams['appid'];        $articles                = $officialImgTxtUrlPrams['articles'];        $show_cover_pic = 1;        $gzh_app_id     = '';        $officialAccountprams['distribution_channel_id'] = $distribution_channel_id;        $officialAccounts                                = OfficialAccountService::officialAuthAccountBydistributionChannelId($officialAccountprams);        if (count($officialAccounts) > 0) {            $gzh_app_id = $appid;//$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,            ];            // 内容的链接转化为微信的官方链接,否则文章上传会被过滤掉//     		$articles = self::convert_content_wechat_url($articles,$param);//     		// 转化异常直接返回//     		if(empty($articles)){//     			\Log::info('convert_content_wechat_url_null_return');//     			return '';//     		}            try {                $form_params         = array("articles" => json_encode($articles), "gzh_app_id" => $gzh_app_id, 'group_nick' => env('GROUP_NICK'), 'timestamp' => $timestamp);                $sign                = get_sign($form_params);                $form_params['sign'] = $sign;//     			$form_params['articles'] = $articles;                \Log::Info('$form_params');                \Log::info($form_params);                //获取图文素材链接                $officialImgTxtUrlJson = self::getUserClient()->request("POST", "upload_gzh_articles/",                    ['form_params' => $form_params, 'connect_timeout' => 10]                )->getBody()->getContents();                \Log::info("============================获取多素材图文链接 通过接口整合获得 content_source_url");                \Log::info($officialImgTxtUrlJson);                $officialImgTxtUrlArray = json_decode($officialImgTxtUrlJson, true);//     			return urldecode(str_replace("\/","/",$content_source_url));                return $officialImgTxtUrlArray;            } 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;    }    /**     * 拼接html的图文形式的素材     * @param unknown_type $bid     * @param unknown_type $chapter_num     * @return string     */    public static function get_push_chapter_content($bid, $chapter_num)    {        $chapters = Chapter::where('bid', $bid)->orderBy('sequence')->limit($chapter_num)->get();        if (empty($chapters)) {            \Log::info('get_push_chapter_content_empty:' . $bid);            return '';        }        $push_content = '';        $template_begin =            '<section class="novel-content">    	<section class="cover-wrap cover-wrap__text">    	<img src="">    	</section>    	<section class="article-text" style="font-size: 18px;">';        $push_content .= $template_begin;        foreach ($chapters as $chapter) {            $template_title_begin = '    		<section class="article">    		<section style="max-width: 100%; color: rgb(62, 62, 62); font-size: 18px; line-height: 28.4444px; white-space: normal; font-family: 微软雅黑;box-sizing: border-box !important; overflow-wrap: break-word !important; background-color: rgb(255, 255, 255);">    		<section style="max-width: 100%; box-sizing: border-box; border-width: 0px; border-style: none; border-color: currentcolor; -moz-border-top-colors: none; -moz-border-right-colors: none; -moz-border-bottom-colors: none; -moz-border-left-colors: none; overflow-wrap: break-word !important;">    		<section style="margin-top: 10px; margin-bottom: 10px; max-width: 100%; box-sizing: border-box; text-align: center; overflow-wrap: break-word !important;">    		<section style="max-width: 100%; box-sizing: border-box; display: inline-block; vertical-align: middle; overflow-wrap: break-word !important;">    		<section style="max-width: 100%; box-sizing: border-box; overflow-wrap: break-word !important;">    		<section style="max-width: 100%; box-sizing: border-box; width: 5px; height: 2px; border-radius: 3px 3px 0px 0px; float: left; overflow-wrap: break-word !important; background-color: rgb(218, 203, 158);">    		</section>    		<section style="max-width: 100%; box-sizing: border-box; width: 5px; height: 2px; border-radius: 3px 3px 0px 0px; float: right; overflow-wrap: break-word !important; background-color: rgb(218, 203, 158);">    		</section>    		<section style="max-width: 100%; box-sizing: border-box; clear: both; overflow-wrap: break-word !important;">    		</section>    		</section>    		<section style="padding: 2px 10px; max-width: 100%; box-sizing: border-box; border-left: 5px solid rgb(218, 203, 158); border-right: 5px solid rgb(218, 203, 158); border-color: rgb(218, 203, 158); color: rgb(255, 255, 255); overflow-wrap: break-word !important; background-color: rgb(249, 110, 87);">    		<section class="" data-brushtype="text" style="max-width: 100%; box-sizing: border-box; overflow-wrap: break-word !important;">    		';//     		$push_content .= $template_title_begin;            $template_article_title = isset($chapter->name) ? $chapter->name : '';//     		$push_content .= $template_article_title;            $template_title_end = '    		</section>    		</section>    		<section style="max-width: 100%; box-sizing: border-box; overflow-wrap: break-word !important;">    		<section style="max-width: 100%; box-sizing: border-box; width: 5px; height: 2px; border-radius: 0px 0px 3px 3px; float: left; overflow-wrap: break-word !important; background-color: rgb(218, 203, 158);">    		</section>    		<section style="max-width: 100%; box-sizing: border-box; width: 5px; height: 2px; border-radius: 0px 0px 3px 3px; float: right; overflow-wrap: break-word !important; background-color: rgb(218, 203, 158);">    		</section>    		<section style="max-width: 100%; box-sizing: border-box; clear: both; overflow-wrap: break-word !important;">    		</section>    		</section>    		</section>    		</section>    		</section>    		<section>    		';//     		$push_content .= $template_title_end;            $p_contents = isset($chapter->content) ? $chapter->content : '';            // 切割成单个P标签            $p_one_contents = explode(PHP_EOL, $p_contents);            if (!empty($p_one_contents)) {                foreach ($p_one_contents as $p_one_content) {                    $one_content  = '    				<p style="text-indent: 2em; margin-top: 0.8em;">' .                        $p_one_content .                        '</p>';                    $push_content .= $one_content;                }            }            $content_end  = '    		</section>    		</section>    		</section>    		';            $push_content .= $content_end;        }        $template_end = '    	</section>    	<section>    	<img style="margin: auto; display: none;" src="">    	</section>    	<section class="novel-guide">    	<div>    	<section style="border:none; border-style: none; margin: 5px 0 0; padding: 10px; background: none;">    	<section class="color" style="margin-top: -1px; margin-bottom: 0; min-height: 40px; visibility: visible; height: 40px; line-height: 40px; border-radius: 3px; text-align: center; color: rgb(255, 255, 255); background-color: rgb(191, 215, 48);">    	<span style="font-size:14px;color: #000;">    	↓点击下方    	<span style="color: #fff;">    	“阅读原文”    	</span>    	查看更多    	</span>    	</section>    	<section class="border" style="margin: 0 auto 0 30px; float: none; width: 0; height: 0; border-left: 0 solid transparent; border-right: 18px solid transparent; border-top: 27px solid #bfd730;">    	     	</section>    	</section>    	</div>    	</section>    	</section>    	';        $push_content .= $template_end;        \Log::info('$push_content');        \Log::Info($push_content);        return $push_content;    }}
 |