| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394 | <?php/** * Created by sublime. * User: wosinC * Date: 2017/12/2 * Time: 上午11:39 */namespace App\Modules\OfficialAccount\Services;use App\Modules\Book\Models\DataAnalysisBookConfig;use App\Modules\OfficialAccount\Services\ForceSubscribeService;use App\Modules\OfficialAccount\Services\TemplateCustomSendService;use App\Modules\OfficialAccount\Models\ForceSubscribeUsers;use App\Modules\OfficialAccount\Models\OfficialAccount;use App\Modules\OfficialAccount\Models\OfficialCustomMsg;use App\Modules\OfficialAccount\Models\CustomMsgSwitchs;use App\Modules\OfficialAccount\Models\CustomMsgSwitchsMsgs;use App\Modules\OfficialAccount\Models\CustomSendMsgs;use App\Modules\OfficialAccount\Models\DistributionChannelSetting;use App\Modules\OfficialAccount\Models\OfficialImgtextUrls;use App\Modules\User\Services\ReadRecordService;use App\Modules\User\Services\UserService;use App\Modules\Book\Services\BookConfigService;use App\Modules\OfficialAccount\Services\OfficialAccountService;use App\Modules\OfficialAccount\Services\SmartPushMsgService;use App\Modules\Statistic\Services\DataAnalysisChapterService;use App\Modules\Promotion\Services\PromotionService;use App\Modules\Channel\Services\ChannelService;use App\Modules\OfficialAccount\Models\MediaCustomer;use App\Modules\OfficialAccount\Models\CustomPushActivitys;use App\Modules\OfficialAccount\Models\CustomPushConfigs;use App\Modules\OfficialAccount\Models\CustomPushConfigContents;use App\Modules\OfficialAccount\Models\CustomSendDayStats;use GuzzleHttp\Client;use GuzzleHttp\Promise;use App\Libs\OSS;use Redis;use App\Jobs\SendNews;use App\Jobs\SendTexts;use App\Jobs\SendTemplate;use App\Jobs\CustomMsgSendJob;use DB;use  Hashids;class CustomMsgService{    /**     * 通过channelName和text获取神书     */    static function customerMsgByChannelAndText($channelname,$text)    {        return OfficialCustomMsg::customerMsgByChannelAndText($channelname,$text);    }    /**     * 通过分销渠道ID获取客服图片     */    static function customerImgUrlByChannelId($distribution_channel_id)    {        return DistributionChannelSetting::customerImgUrlByChannelId($distribution_channel_id);    }    /**     * 添加客服图片     */    static function updateCustomerImgUrl($customerImgPram)    {        //通过分销渠道号寻找客服图片        $customerImgs = DistributionChannelSetting::customerImgUrlByChannelId($customerImgPram['distribution_channel_id']);        if (empty($customerImgs)) {            //2,删除media_customer表中老的客服图片的mediaid,            //以便灵杰公众号交互下次该渠道请求客服图片时重新去渠道获取新的客服图片            MediaCustomer::where('distribution_channel_id',$customerImgPram['distribution_channel_id'])->delete();            //该渠道配置表中增加客服图片            return DistributionChannelSetting::create($customerImgPram);        }else{            //1,该渠道配置表中更新客服图片            $customerImgs['customer_img_url'] = $customerImgPram['customer_img_url'];            $customerImgs->save();            //2,删除media_customer表中老的客服图片的mediaid,            //以便灵杰公众号交互下次该渠道请求客服图片时重新去渠道获取新的客服图片            MediaCustomer::where('distribution_channel_id',$customerImgPram['distribution_channel_id'])->delete();            return $customerImgs;        }    }    /**     * 未支付订单发送客服消息     */    static function sendUnpaid()    {        //1,遍历渠道表        $distribution_channels =  ChannelService::getAllChannels();        $today = date('Y-m-d');        for ($i=0; $i < count($distribution_channels); $i++) {            //2,判断该渠道下有没有开启未支付订单的智能推送            $distribution_channel_id = $distribution_channels[$i]['id'];            // 针对订单级别,一个用户可能扔多次            $key = 'leyuee:to_send_not_pay_uid:distribution_channel_id:'.$distribution_channel_id;            $customMsgSwitch = CustomMsgSwitchsMsgs::customMsgSwitchsByChannelCate($distribution_channel_id,'not_pay');                        if (!empty($customMsgSwitch)) {                                if ($customMsgSwitch['status'] == '1') {                    \Log::info('<----获取 开启订单未支付提醒的 渠道号---->');                    \Log::info($distribution_channel_id);                    //3,如果开启了  先获取该渠道下redis待发送的用户                    $not_order_users = Redis::hgetall($key);                    //\Log::info('<----获取 渠道下 用户---->');                                        if (!empty($not_order_users)) {                        $customSendStatsCount = CustomSendDayStats::customSendDayStatsByChannelAndFromAndDay($distribution_channel_id,'not_pay',date("Y-m-d"));                        if (empty($customSendStatsCount)) {                            $customSendDayStats['distribution_channel_id'] = $distribution_channel_id;                            $customSendDayStats['from'] = 'not_pay';                            $customSendDayStats['push_user_num'] = count($not_order_users);                            $customSendDayStats['date'] = date("Y-m-d");                            CustomSendDayStats::create($customSendDayStats);                        }else{                            $customSendStatsCount['push_user_num'] = $customSendStatsCount['push_user_num']+count($not_order_users);                            $customSendStatsCount->save();                        }                        foreach ($not_order_users as $uid => $time) {                            //\Log::info('<----redis中找到用户 获取uid 时间差---->');                            //\Log::info($uid);                            //\Log::info(time()-$time);                            //4,计算这些用户未支付订单是否大于1小时                            $now_time = time()-$time;                            if ($now_time > 3600)                            {                                //5,从Redis中获取并判断这些用户 今日是否已经发送过“未支付订单提醒”                                $today_key = "sended_not_pay_uid:distribution_channel_id:".$distribution_channel_id.":day:".$today;                                if(!Redis::sismember($today_key, $uid))                                {                                    //6,判断用户当前是否为强关用户                                    $force_user = ForceSubscribeService::forceSubscribeUsersByUid(compact('uid'));                                    if (!empty($force_user)) {                                        //\Log::info('<----满足条件的强关用户 发送客服消息---->');                                        //\Log::info($uid);                                        //(1),发送(文字)未支付客服提醒至RebitMQ                                        self::add_text_task($force_user);                                        //(2), 今日的redis增加一条记录,每天只发一次                                        Redis::sadd($today_key, $uid);                                        Redis::expire($today_key,3600*24*3);                                                                           }                                    //7,将该用户在未支付订单待发送的Redis中移除                                    Redis::hdel($key,$uid);                                }else{                                    //8,如果发送过,直接将该用户从未支付订单待发送redis中移除                                    Redis::hdel($key,$uid);                                }                            }                        }                    }else{                        \Log::info('<----redis中该渠道下没有找到用户---->');                                           }                }else{                    //智能推送未支付订单关闭状态                    //直接删除该渠道下未支付订单的redis键                    Redis::del($key);                }            }else{                //智能推送还未创建(默认关闭)                //直接删除该渠道下未支付订单的redis键                Redis::del($key);            }        }    }    /**     * RebitMQ发送24小时未支付订单提醒(文字)     */    static function add_text_task($force_user){        $uid = $force_user['uid'];        $distribution_channel_id = $force_user['distribution_channel_id'];        //通过uid获取该用户最近阅读记录的书籍        $userBook = ReadRecordService::getFirstReadRecord($uid);        \Log::info('<----获取用户 最近阅读记录---->');                if (!empty($userBook)) {            $data = array();            $data['openid'] = $force_user['openid'];            $data['appid'] = $force_user['appid'];            //用户最近阅读链接            $continueReadUrl = env('PROTOCOL').'://site'.encodeDistributionChannelId($distribution_channel_id).'.'.env('CUSTOM_HOST').'.com/continue?fromtype=not_pay';            //拼接文案和用户最近阅读书籍的链接以及书籍名称            //$data['content'] = '亲,你上次看的书还在等着你呐~点击继续阅读'."\n".'<a href="'.$continueReadUrl.'"> >《'.$userBook['book_name'].'》</a>'."\n".'首冲50元即可畅读100万字,年费VIP更可全年无限畅读。'."\n".'为方便下次阅读,请'.'<a href="https://help.leyuee.com/top.html">'.'置顶公众号'.'</a>';            $data['content'] = '亲,你上次看的书还在等着你呐~'."\n".'<a href="'.$continueReadUrl.'"> >点击继续阅读</a>'."\n".'首冲50元即可畅读100万字,年费VIP更可全年无限畅读。'."\n".'为方便下次阅读,请'.'<a href="https://help.leyuee.com/top.html">'.'置顶公众号'.'</a>';            $data['type'] = 'one_task';// last_task,one_task            $data['task_id'] = 1;            $data['send_time'] = date("Y-m-d H:i:s");            $send_data=array(                'send_time'=>date("Y-m-d H:i:s"),                'data' => $data            );            //\Log::info($data['openid']);            //\Log::info($data['appid']);            //\Log::info($data['content']);            $delay = 0;            $job = (new SendTexts($send_data))->onConnection('rabbitmq')->delay($delay)->onQueue('send_texts_list');            dispatch($job);        }else{            \Log::info('<----抱歉 没有最近阅读记录---->');        }    }    /**     * RebitMQ发送24小时未支付订单提醒(图文)     */    static function add_news_task($force_user,$officialCustomMsg){        $data = array();        $data['openid'] = $force_user['openid'];        $data['appid'] = $force_user['appid'];        $data['news_content'] = '[[{"title":"'.$officialCustomMsg['title'].'"},{"description":"'.$officialCustomMsg['description'].'"},{"url":"'.$officialCustomMsg['url'].'"},{"image":"'.$officialCustomMsg['image'].'"}]]';        $data['type'] = 'one_task';// last_task,one_task        $data['task_id'] = 3;        $data['send_time'] = date("Y-m-d H:i:s");        $send_data=array(            'send_time'=>date("Y-m-d H:i:s"),            'data' => $data        );        $delay = 0;        $job = (new SendNews($send_data))->onConnection('rabbitmq')->delay($delay)->onQueue('send_news_list');        dispatch($job);    }    /**     *  三天回本推送(定时任务 12小时推)     */    static function add_news_recovery_push_hot(){        \Log::info('=======================三天回本推送客服消息');        //1,遍历渠道表        $distribution_channels =  ChannelService::getAllChannels();        for ($k=0; $k < count($distribution_channels); $k++) {                         //2,判断该渠道下有没有开启 未支付订单的智能推送            $distribution_channel_id = $distribution_channels[$k]['id'];                        $customMsgSwitch = CustomMsgSwitchsMsgs::customMsgSwitchsByChannelCate($distribution_channel_id,'recovery_push');                        if (!empty($customMsgSwitch)) {                                if ($customMsgSwitch['status'] == '1') {                                        \Log::info('<----开启客服的 渠道号---->');                    \Log::info($distribution_channel_id);                    //3,开通智能推送的渠道获取 渠道下的强关用户                    $forceSubscribeUsersPrams['distribution_channel_id'] = $distribution_channel_id;                    $forceSubscribeUsersPrams['timeset'] = 43200;                    $force_user = ForceSubscribeService::forceSubscribeNewUsersByTimeset($forceSubscribeUsersPrams);                    //\Log::info('<----渠道下强关用户数---->');                    //\Log::info(count($force_user));                    $customSendStatsCount = CustomSendDayStats::customSendDayStatsByChannelAndFromAndDay($distribution_channel_id,'recovery_push',date("Y-m-d"));                    if (empty($customSendStatsCount)) {                        $customSendDayStats['distribution_channel_id'] = $distribution_channel_id;                        $customSendDayStats['from'] = 'recovery_push';                        $customSendDayStats['push_user_num'] = count($force_user);                        $customSendDayStats['date'] = date("Y-m-d");                        CustomSendDayStats::create($customSendDayStats);                    }else{                        $customSendStatsCount['push_user_num'] = $customSendStatsCount['push_user_num']+count($force_user);                        $customSendStatsCount->save();                    }                    for ($i=0; $i < count($force_user); $i++) {                                               //(1)通过uid去已发送客服消息Redis中获取是否推送过该类型客服消息                        //(2)如果有,获取插入的时间,                        // 如果时间在今天之内,那就不发送,                        // 如果不是,就发送,并往Redis中插入一条数据                        $uid = $force_user[$i]['uid'];                        if(!Redis::hget('add_news_recovery_push_hot'.$uid, 'time'))                        {                            $bid = $force_user[$i]['bid'];                            $booksArray = [];                            //4,获取男频女频的标签文案                            $manPromotion = PromotionService::getRandomHeadline(1,5);                            $womanPromotion = PromotionService::getRandomHeadline(2,5);                                                      //7,获取和用户强关进来的书相同类型的5本优质评分的书籍//                             $books = BookConfigService::getSimpleChannelBook($bid,5);                            $books = BookConfigService::getSimpleChannelBookLoop($bid,5,$uid);                            $bookUrl = env('PROTOCOL').'://site'.encodeDistributionChannelId($distribution_channel_id).'.'.env('CUSTOM_HOST').'.com';                            $promotionNum = 0;                            if ($books) {                                                                foreach ($books as $key => $value) {                                    //8,将这四本书作为推送的2-5条信息,同样拼接书籍信息和标签文案                                    $urlBook = $value->url = $bookUrl.$value->url.'&fromtype=recovery_push';                                    $channelName = $value->channel_name;                                    $cover = $value->cover;                                    if($channelName == '男频'){                                        $book['title'] = $manPromotion[$promotionNum]['title'];                                        $book['description'] = $manPromotion[$promotionNum]['title'];                                    }else{                                        $book['title'] = $womanPromotion[$promotionNum]['title'];                                        $book['description'] = $womanPromotion[$promotionNum]['title'];                                    }                                    $book['url'] = $urlBook;                                    $book['image'] = $cover;                                    if ($promotionNum == 0) {                                        //第一条图片选用图库中的图片地址                                        $promotionImages = PromotionService::getMessageRandomDocumentCovers(3);                                        if ($promotionImages) {                                            $book['image'] = $promotionImages[0]['link'];                                        }else{                                            $book['image'] = $cover;                                        }                                                                            }else{                                        $book['image'] = $cover;                                    }                                                                        $booksArray[] = [['title'=>$book['title']],['description'=>$book['description']],['url'=>$book['url']],['image'=>$book['image']]];                                    $promotionNum++;                                }                                //9,通过RebitMQ推送热门书籍到指定用户                                $data = array();                                $data['openid'] = $force_user[$i]['openid'];                                $data['appid'] = $force_user[$i]['appid'];                                $data['news_content'] = json_encode($booksArray);                                $data['type'] = 'one_task';                                $data['task_id'] = 3;                                $data['send_time'] = date("Y-m-d H:i:s");                                $send_data=array(                                    'send_time'=>date("Y-m-d H:i:s"),                                    'data' => $data                                );                                $delay = 0;                                //\Log::info('<---- 客服消息发送内容 参数---->');                                //\Log::info($data['openid']);                                //\Log::info($data['appid']);                                //\Log::info($data['news_content']);                                //\Log::info('<----Rebit-MQ 发送热门书籍推送客服消息---->');                                $job = (new SendNews($send_data))->onConnection('rabbitmq')->delay($delay)->onQueue('send_news_list');                                dispatch($job);                                Redis::hset('add_news_recovery_push_hot'.$uid, 'time', time());                            }                                                                                                          }                                            }                }            }        }    }    /**     *  三天回本推送(定时任务 24小时推)     */    static function add_news_recovery_push_activity(){        \Log::info('=======================三天回本推送客服消息');        //1,遍历渠道表        $distribution_channels =  ChannelService::getAllChannels();        $customPushActivitys = CustomPushActivitys::customPushActivitys();        $custom_url = $customPushActivitys['url'];        $custom_image = $customPushActivitys['image'];        $custom_title = $customPushActivitys['title'];        for ($k=0; $k < count($distribution_channels); $k++) {                         //2,判断该渠道下有没有开启 未支付订单的智能推送            $distribution_channel_id = $distribution_channels[$k]['id'];                        $customMsgSwitch = CustomMsgSwitchsMsgs::customMsgSwitchsByChannelCate($distribution_channel_id,'recovery_push');                        if (!empty($customMsgSwitch)) {                                if ($customMsgSwitch['status'] == '1') {                    //\Log::info('<----开启客服的 渠道号---->');                    //\Log::info($distribution_channel_id);                    //3,开通智能推送的渠道获取 渠道下的强关用户                    $forceSubscribeUsersPrams['distribution_channel_id'] = $distribution_channel_id;                    $forceSubscribeUsersPrams['timeset'] = 86400;                    $force_user = ForceSubscribeService::forceSubscribeNewUsersByTimeset($forceSubscribeUsersPrams);                    //\Log::info('<----渠道下强关用户数---->');                    //\Log::info(count($force_user));                    $customSendStatsCount = CustomSendDayStats::customSendDayStatsByChannelAndFromAndDay($distribution_channel_id,'recovery_push',date("Y-m-d"));                    if (empty($customSendStatsCount)) {                        $customSendDayStats['distribution_channel_id'] = $distribution_channel_id;                        $customSendDayStats['from'] = 'recovery_push';                        $customSendDayStats['push_user_num'] = count($force_user);                        $customSendDayStats['date'] = date("Y-m-d");                        CustomSendDayStats::create($customSendDayStats);                    }else{                        $customSendStatsCount['push_user_num'] = $customSendStatsCount['push_user_num']+count($force_user);                        $customSendStatsCount->save();                    }                    for ($i=0; $i < count($force_user); $i++) {                                                //(1)通过uid去已发送客服消息Redis中获取是否推送过该类型客服消息                        //(2)如果有,获取插入的时间,                        // 如果时间在今天之内,那就不发送,                        // 如果不是,就发送,并往Redis中插入一条数据                        $uid = $force_user[$i]['uid'];                        if(!Redis::hget('add_news_recovery_push_activity'.$uid, 'time'))                        {                                //9,通过RebitMQ推送热门书籍到指定用户                                $data = array();                                $data['openid'] = $force_user[$i]['openid'];                                $data['appid'] = $force_user[$i]['appid'];                                $url = env('PROTOCOL').'://site'.encodeDistributionChannelId($distribution_channel_id).'.'.env('CUSTOM_HOST').'.com'.$custom_url;                                $data['news_content'] = '[[{"title":"'.$custom_title.'"},{"description":""},{"url":"'.$url.'"},{"image":"'.$custom_image.'"}]]';                                $data['type'] = 'one_task';                                $data['task_id'] = 3;                                $data['send_time'] = date("Y-m-d H:i:s");                                $send_data=array(                                    'send_time'=>date("Y-m-d H:i:s"),                                    'data' => $data                                );                                $delay = 0;                                //\Log::info('<---- 客服消息发送内容 参数---->');                                //\Log::info($data['openid']);                                //\Log::info($data['appid']);                                //\Log::info($data['news_content']);                                //\Log::info('<----Rebit-MQ 发送三天回本活动推送---->');                                $job = (new SendNews($send_data))->onConnection('rabbitmq')->delay($delay)->onQueue('send_news_list');//                                $job = (new SendNews($send_data))->onConnection('redis')->delay($delay)->onQueue('send_news_list');                                dispatch($job);                                Redis::hset('add_news_recovery_push_activity'.$uid, 'time', time());                                                                                                                                   }                                            }                }            }        }    }    /**     *  定制书籍推送(定时任务) point_push     */    static function add_news_point_book(){        \Log::info('=======================定制书籍推荐客服消息');        //1,遍历渠道表        $distribution_channels =  ChannelService::getAllChannels();        for ($k=0; $k < count($distribution_channels); $k++) {                         //2,判断该渠道下有没有开启 未支付订单的智能推送            $distribution_channel_id = $distribution_channels[$k]['id'];                        $customMsgSwitch = CustomMsgSwitchsMsgs::customMsgSwitchsByChannelCate($distribution_channel_id,'point_push');                        if (!empty($customMsgSwitch)) {                                if ($customMsgSwitch['status'] == '1') {                    //\Log::info('<----开启客服的 渠道号---->');                    //\Log::info($distribution_channel_id);                    //3,开通智能推送的渠道获取 渠道下的强关用户                    $forceSubscribeUsersPrams['distribution_channel_id'] = $distribution_channel_id;                    $forceSubscribeUsersPrams['timeset'] = 151200;// 定制数据是42小时后推送                    $force_user = ForceSubscribeService::forceSubscribeUsersByChannelidAndTimeset($forceSubscribeUsersPrams);                    //\Log::info('<----渠道下强关用户数---->');                    //\Log::info(count($force_user));                    $customSendStatsCount = CustomSendDayStats::customSendDayStatsByChannelAndFromAndDay($distribution_channel_id,'point_push',date("Y-m-d"));                    if (empty($customSendStatsCount)) {                        $customSendDayStats['distribution_channel_id'] = $distribution_channel_id;                        $customSendDayStats['from'] = 'point_push';                        $customSendDayStats['push_user_num'] = count($force_user);                        $customSendDayStats['date'] = date("Y-m-d");                        CustomSendDayStats::create($customSendDayStats);                    }else{                        $customSendStatsCount['push_user_num'] = $customSendStatsCount['push_user_num']+count($force_user);                        $customSendStatsCount->save();                    }                    for ($i=0; $i < count($force_user); $i++) {                                               //(1)通过uid去已发送客服消息Redis中获取是否推送过该类型客服消息                        //(2)如果有,获取插入的时间,                        // 如果时间在今天之内,那就不发送,                        // 如果不是,就发送,并往Redis中插入一条数据                        $uid = $force_user[$i]['uid'];                        if(Redis::hget('add_news_top_book_uid'.$uid, 'time'))                        {                            //\Log::info('<----Redis中存在  获取uid 时间---->');                            //\Log::info($force_user[$i]['uid']);                            //\Log::info(Redis::hget('add_news_top_book_uid'.$uid, 'time'));                            $time = Redis::hget('add_news_top_book_uid'.$uid, 'time');                            if (date("Y-m-d",$time) == date("Y-m-d"))                            {                                // Redis::hdel('add_news_top_book_uid'.$uid,'time');                            }else{                                //获取定制图书推送是否是在这个时间段推送过,如果推送过这个时间点就不推送了                                $point_time = Redis::hget('add_news_point_book_uid'.$uid, 'time');                                if ($point_time) {                                    if (date("Y-m-d",$point_time) == date("Y-m-d")) {                                        $matchTime = time() - $point_time;                                        if ($matchTime < 3600) {                                            continue;                                        }                                    }                                                                    }                                //\Log::info('<----Redis中时间 不是今天---->');                                $bid = $force_user[$i]['bid'];                                $booksArray = [];                                //4,获取男频女频的标签文案                                $manPromotion = PromotionService::getRandomHeadline(1,5);                                $womanPromotion = PromotionService::getRandomHeadline(2,5);                                //5,获取用户最近阅读的书籍信息                                $userBook = ReadRecordService::getFirstReadRecord($uid);                                if (!empty($userBook)) {                                    //有最近阅读的书籍!! 头条为最近阅读,次4条为随机选取                                    //\Log::info('<----获取用户最近阅读的书籍--->');                                    //6,推送第一条拼接用户最近阅读的书籍信息                                    //并通过判断该书是男频还是女频分别拼接上不同的标签文案                                    $continueReadUrl = env('PROTOCOL').'://site'.encodeDistributionChannelId($distribution_channel_id).'.'.env('CUSTOM_HOST').'.com/continue?fromtype=point_push';                                    $channelName = $userBook['channel_name'];                                    if($channelName == '男频'){                                        $book['title'] = $manPromotion[0]['title'];                                        $book['description'] = $manPromotion[0]['title'];                                    }else{                                        $book['title'] = $womanPromotion[0]['title'];                                        $book['description'] = $womanPromotion[0]['title'];                                    }                                    $book['url'] = $continueReadUrl;                                    //头条的图片从财哥个图库中随机取一张                                    $promotionImages = PromotionService::getMessageRandomDocumentCovers(3);                                    if ($promotionImages) {                                        $book['image'] = $promotionImages[0]['link'];                                    }else{                                        $book['image'] = $userBook['cover'];                                    }                                                                                                                                                $booksArray[] = [['title'=>$book['title']],['description'=>$book['description']],['url'=>$book['url']],['image'=>$book['image']]];                                    //\Log::info(json_encode($booksArray));                                    //7,获取和用户强关进来的书相同类型的4本优质评分的书籍//                                     $books = BookConfigService::getSimpleChannelBook($bid,4);                                    $books = BookConfigService::getSimpleChannelBookLoop($bid,4,$uid);                                    $bookUrl = env('PROTOCOL').'://site'.encodeDistributionChannelId($distribution_channel_id).'.'.env('CUSTOM_HOST').'.com';                                    $promotionNum = 1;                                    if ($books) {                                                                                foreach ($books as $key => $value) {                                            //8,将这四本书作为推送的2-5条信息,同样拼接书籍信息和标签文案                                            $urlBook = $value->url = $bookUrl.$value->url.'&fromtype=point_push';                                            $channelName = $value->channel_name;                                            $cover = $value->cover;                                            if($channelName == '男频'){                                                $book['title'] = $manPromotion[$promotionNum]['title'];                                                $book['description'] = $manPromotion[$promotionNum]['title'];                                            }else{                                                $book['title'] = $womanPromotion[$promotionNum]['title'];                                                $book['description'] = $womanPromotion[$promotionNum]['title'];                                            }                                            $book['url'] = $urlBook;                                            $book['image'] = $cover;                                            $booksArray[] = [['title'=>$book['title']],['description'=>$book['description']],['url'=>$book['url']],['image'=>$book['image']]];                                            $promotionNum++;                                        }                                        //9,通过RebitMQ推送热门书籍到指定用户                                        $data = array();                                        $data['openid'] = $force_user[$i]['openid'];                                        $data['appid'] = $force_user[$i]['appid'];                                        $data['news_content'] = json_encode($booksArray);                                        $data['type'] = 'one_task';                                        $data['task_id'] = 3;                                        $data['send_time'] = date("Y-m-d H:i:s");                                        $send_data=array(                                            'send_time'=>date("Y-m-d H:i:s"),                                            'data' => $data                                        );                                        $delay = 0;                                        //\Log::info('<---- 客服消息发送内容 参数---->');                                        //\Log::info($data['openid']);                                        //\Log::info($data['appid']);                                        //\Log::info($data['news_content']);                                        //\Log::info('<----Rebit-MQ 发送热门书籍推送客服消息---->');                                        $job = (new SendNews($send_data))->onConnection('rabbitmq')->delay($delay)->onQueue('send_news_list');                                        dispatch($job);                                        Redis::hset('add_news_top_book_uid'.$uid, 'time', time());                                    }                                }else{                                    //没有最近阅读的书籍!! 从书库随机选取5本,第一本的图片用财哥图库的图片                                    //7,获取和用户强关进来的书相同类型的4本优质评分的书籍//                                     $books = BookConfigService::getSimpleChannelBook($bid,5);                                    $books = BookConfigService::getSimpleChannelBookLoop($bid,5,$uid);                                    $bookUrl = env('PROTOCOL').'://site'.encodeDistributionChannelId($distribution_channel_id).'.'.env('CUSTOM_HOST').'.com';                                    $promotionNum = 0;                                    if ($books) {                                                                                foreach ($books as $key => $value) {                                            //8,将这四本书作为推送的2-5条信息,同样拼接书籍信息和标签文案                                            $urlBook = $value->url = $bookUrl.$value->url.'&fromtype=point_push';                                            $channelName = $value->channel_name;                                            $cover = $value->cover;                                            if($channelName == '男频'){                                                $book['title'] = $manPromotion[$promotionNum]['title'];                                                $book['description'] = $manPromotion[$promotionNum]['title'];                                            }else{                                                $book['title'] = $womanPromotion[$promotionNum]['title'];                                                $book['description'] = $womanPromotion[$promotionNum]['title'];                                            }                                            $book['url'] = $urlBook;                                            $book['image'] = $cover;                                            if ($promotionNum == 0) {                                                //第一条图片选用图库中的图片地址                                                // $book['image'] = $cover;                                                $promotionImages = PromotionService::getMessageRandomDocumentCovers(3);                                                if ($promotionImages) {                                                    $book['image'] = $promotionImages[0]['link'];                                                }else{                                                    $book['image'] = $cover;                                                }                                            }else{                                                $book['image'] = $cover;                                            }                                                                                        $booksArray[] = [['title'=>$book['title']],['description'=>$book['description']],['url'=>$book['url']],['image'=>$book['image']]];                                            $promotionNum++;                                        }                                        //9,通过RebitMQ推送热门书籍到指定用户                                        $data = array();                                        $data['openid'] = $force_user[$i]['openid'];                                        $data['appid'] = $force_user[$i]['appid'];                                        $data['news_content'] = json_encode($booksArray);                                        $data['type'] = 'one_task';                                        $data['task_id'] = 3;                                        $data['send_time'] = date("Y-m-d H:i:s");                                        $send_data=array(                                            'send_time'=>date("Y-m-d H:i:s"),                                            'data' => $data                                        );                                        $delay = 0;                                        //\Log::info('<---- 客服消息发送内容 参数---->');                                        //\Log::info($data['openid']);                                        //\Log::info($data['appid']);                                        //\Log::info($data['news_content']);                                        //\Log::info('<----Rebit-MQ 发送热门书籍推送客服消息---->');                                        $job = (new SendNews($send_data))->onConnection('rabbitmq')->delay($delay)->onQueue('send_news_list');                                        dispatch($job);                                        Redis::hset('add_news_point_book_uid'.$uid, 'time', time());                                    }                                }                                                            }                                                   }else{                            //获取热门图书推送是否是在这个时间段推送过,如果推送过这个时间点就不推送了                            $point_time = Redis::hget('add_news_top_book_uid'.$uid, 'time');                            if ($point_time) {                                if (date("Y-m-d",$point_time) == date("Y-m-d")) {                                    $matchTime = time() - $point_time;                                    if ($matchTime < 3600) {                                        continue;                                    }                                }                                                            }                            //\Log::info('<----Redis中时间 不是今天---->');                            $bid = $force_user[$i]['bid'];                            $booksArray = [];                            //4,获取男频女频的标签文案                            $manPromotion = PromotionService::getRandomHeadline(1,5);                            $womanPromotion = PromotionService::getRandomHeadline(2,5);                            //5,获取用户最近阅读的书籍信息                            $userBook = ReadRecordService::getFirstReadRecord($uid);                            if (!empty($userBook)) {                                //有最近阅读的书籍!! 头条为最近阅读,次4条为随机选取                                //\Log::info('<----获取用户最近阅读的书籍--->');                                //6,推送第一条拼接用户最近阅读的书籍信息                                //并通过判断该书是男频还是女频分别拼接上不同的标签文案                                $continueReadUrl = env('PROTOCOL').'://site'.encodeDistributionChannelId($distribution_channel_id).'.'.env('CUSTOM_HOST').'.com/continue?fromtype=point_push';                                $channelName = $userBook['channel_name'];                                if($channelName == '男频'){                                    $book['title'] = $manPromotion[0]['title'];                                    $book['description'] = $manPromotion[0]['title'];                                }else{                                    $book['title'] = $womanPromotion[0]['title'];                                    $book['description'] = $womanPromotion[0]['title'];                                }                                $book['url'] = $continueReadUrl;                                //头条的图片从财哥个图库中随机取一张                                $promotionImages = PromotionService::getMessageRandomDocumentCovers(3);                                if ($promotionImages) {                                    $book['image'] = $promotionImages[0]['link'];                                }else{                                    $book['image'] = $userBook['cover'];                                }                                                                                               $booksArray[] = [['title'=>$book['title']],['description'=>$book['description']],['url'=>$book['url']],['image'=>$book['image']]];                                //\Log::info(json_encode($booksArray));                                //7,获取和用户强关进来的书相同类型的4本优质评分的书籍//                                 $books = BookConfigService::getSimpleChannelBook($bid,4);                                $books = BookConfigService::getSimpleChannelBookLoop($bid,4,$uid);                                $bookUrl = env('PROTOCOL').'://site'.encodeDistributionChannelId($distribution_channel_id).'.'.env('CUSTOM_HOST').'.com';                                $promotionNum = 1;                                if ($books) {                                                                        foreach ($books as $key => $value) {                                        //8,将这四本书作为推送的2-5条信息,同样拼接书籍信息和标签文案                                        $urlBook = $value->url = $bookUrl.$value->url.'&fromtype=point_push';                                        $channelName = $value->channel_name;                                        $cover = $value->cover;                                        if($channelName == '男频'){                                            $book['title'] = $manPromotion[$promotionNum]['title'];                                            $book['description'] = $manPromotion[$promotionNum]['title'];                                        }else{                                            $book['title'] = $womanPromotion[$promotionNum]['title'];                                            $book['description'] = $womanPromotion[$promotionNum]['title'];                                        }                                        $book['url'] = $urlBook;                                                                                $promotionImages = PromotionService::getMessageRandomDocumentCovers(3);                                        if ($promotionImages) {                                            $book['image'] = $promotionImages[0]['link'];                                        }else{                                            $book['image'] = $cover;                                        }                                        $booksArray[] = [['title'=>$book['title']],['description'=>$book['description']],['url'=>$book['url']],['image'=>$book['image']]];                                        $promotionNum++;                                    }                                    //9,通过RebitMQ推送热门书籍到指定用户                                    $data = array();                                    $data['openid'] = $force_user[$i]['openid'];                                    $data['appid'] = $force_user[$i]['appid'];                                    $data['news_content'] = json_encode($booksArray);                                    $data['type'] = 'one_task';                                    $data['task_id'] = 3;                                    $data['send_time'] = date("Y-m-d H:i:s");                                    $send_data=array(                                        'send_time'=>date("Y-m-d H:i:s"),                                        'data' => $data                                    );                                    $delay = 0;                                    //\Log::info('<---- 客服消息发送内容 参数---->');                                    //\Log::info($data['openid']);                                    //\Log::info($data['appid']);                                    //\Log::info($data['news_content']);                                    //\Log::info('<----Rebit-MQ 发送热门书籍推送客服消息---->');                                    $job = (new SendNews($send_data))->onConnection('rabbitmq')->delay($delay)->onQueue('send_news_list');                                    dispatch($job);                                    Redis::hset('add_news_point_book_uid'.$uid, 'time', time());                                }                            }else{                                //没有最近阅读的书籍!! 从书库随机选取5本,第一本的图片用财哥图库的图片                                //7,获取和用户强关进来的书相同类型的4本优质评分的书籍//                                 $books = BookConfigService::getSimpleChannelBook($bid,5);                                $books = BookConfigService::getSimpleChannelBookLoop($bid,5,$uid);                                $bookUrl = env('PROTOCOL').'://site'.encodeDistributionChannelId($distribution_channel_id).'.'.env('CUSTOM_HOST').'.com';                                $promotionNum = 0;                                if ($books) {                                                                        foreach ($books as $key => $value) {                                        //8,将这四本书作为推送的2-5条信息,同样拼接书籍信息和标签文案                                        $urlBook = $value->url = $bookUrl.$value->url.'&fromtype=point_push';                                        $channelName = $value->channel_name;                                        $cover = $value->cover;                                        if($channelName == '男频'){                                            $book['title'] = $manPromotion[$promotionNum]['title'];                                            $book['description'] = $manPromotion[$promotionNum]['title'];                                        }else{                                            $book['title'] = $womanPromotion[$promotionNum]['title'];                                            $book['description'] = $womanPromotion[$promotionNum]['title'];                                        }                                        $book['url'] = $urlBook;                                        $book['image'] = $cover;                                        if ($promotionNum == 0) {                                            //第一条图片选用图库中的图片地址                                            $promotionImages = PromotionService::getMessageRandomDocumentCovers(3);                                            if ($promotionImages) {                                                $book['image'] = $promotionImages[0]['link'];                                            }else{                                                $book['image'] = $cover;                                            }                                                                                    }else{                                            $book['image'] = $cover;                                        }                                                                                $booksArray[] = [['title'=>$book['title']],['description'=>$book['description']],['url'=>$book['url']],['image'=>$book['image']]];                                        $promotionNum++;                                    }                                    //9,通过RebitMQ推送热门书籍到指定用户                                    $data = array();                                    $data['openid'] = $force_user[$i]['openid'];                                    $data['appid'] = $force_user[$i]['appid'];                                    $data['news_content'] = json_encode($booksArray);                                    $data['type'] = 'one_task';                                    $data['task_id'] = 3;                                    $data['send_time'] = date("Y-m-d H:i:s");                                    $send_data=array(                                        'send_time'=>date("Y-m-d H:i:s"),                                        'data' => $data                                    );                                    $delay = 0;                                    //\Log::info('<---- 客服消息发送内容 参数---->');                                    //\Log::info($data['openid']);                                    //\Log::info($data['appid']);                                    //\Log::info($data['news_content']);                                    //\Log::info('<----Rebit-MQ 发送热门书籍推送客服消息---->');                                    $job = (new SendNews($send_data))->onConnection('rabbitmq')->delay($delay)->onQueue('send_news_list');                                    dispatch($job);                                    Redis::hset('add_news_point_book_uid'.$uid, 'time', time());                                }                            }                                                                              }                                            }                }            }        }    }    /**     *  未充值用户推送客服消息(24-48小时内关注)(定时任务)     */    static function unPaidUserActivity(){        	\Log::info('=======================未充值用户推荐客服消息');    	//1,遍历渠道表    	$distribution_channels =  ChannelService::getAllChannels();        	for ($k=0; $k < count($distribution_channels); $k++) {    		//2,判断该渠道下有没有开启 未支付订单的智能推送    		$distribution_channel_id = $distribution_channels[$k]['id'];    		    		// 嘉言小说//     		if(!in_array($distribution_channel_id,array('2'))){// //     			\Log::info('unPaidUserActivity_continue,$distribution_channel_id:'.$distribution_channel_id);//     			continue;//     		}        		$customMsgSwitch = CustomMsgSwitchsMsgs::customMsgSwitchsByChannelCate($distribution_channel_id,'unpaid_send_activity');        		if (!empty($customMsgSwitch)) {        			if ($customMsgSwitch['status'] == '1') {        				//\Log::info('<----开启未付费推送的 渠道号---->:'.$distribution_channel_id);    				//3,开通智能推送的渠道获取 渠道下的强关用户    				$forceSubscribeUsersPrams['distribution_channel_id'] = $distribution_channel_id;    				$forceSubscribeUsersPrams['start_time'] = date('Y-m-d H:i:s',strtotime('-2 day'));    				$forceSubscribeUsersPrams['end_time'] = date('Y-m-d H:i:s',strtotime('-1 day'));    				$force_user = ForceSubscribeService::forceSubscribeNewUnpaidUsersByTime($forceSubscribeUsersPrams);    				//\Log::info('<----渠道下强关用户数---->');    				//\Log::info($force_user);    				//\Log::info(count($force_user));    				    				$push_user_num = 0;        				for ($i=0; $i < count($force_user); $i++) {        					//(1)通过uid去已发送客服消息Redis中获取是否推送过该类型客服消息    					//(2)如果有,获取插入的时间,    					// 每个新关用户只发送一次    					// 如果不是,就发送,并往Redis中插入一条数据    					$uid = $force_user[$i]['uid'];        					if(!Redis::hget('unpaid_send_activity_uid:'.$uid, 'time'))    					{    							$bid = $force_user[$i]['bid'];        							$data = array();					            $data['openid'] = $force_user[$i]['openid'];					            $data['appid'] = $force_user[$i]['appid'];										            //活动链接					            $continueReadUrl = env('PROTOCOL').'://site'.encodeDistributionChannelId($distribution_channel_id).'.'.env('CUSTOM_HOST').'.com/sale/newUserActivity?fromtype=unpaid_send_activity&send_time='.time();					            					            $data['content'] = '您的新用户专享礼包已送达'."\n\n".'充9.9元,得2000书币,只有一次机会哦!'."\n\n".'过期失效,不要错过!'."\n\n".'<a href="'.$continueReadUrl.'">点击立即领取> ></a>'."\n\n".'为方便下次阅读,请'.'<a href="https://help.leyuee.com/top.html">'.'置顶公众号'.'</a>';					            $data['type'] = 'one_task';// last_task,one_task					            $data['task_id'] = 1;					            $data['send_time'] = date("Y-m-d H:i:s");					            $send_data=array(					                'send_time'=>date("Y-m-d H:i:s"),					                'data' => $data					            );					            //\Log::info('unpaid_send_activity_openid:'.$data['openid'].' appid:'.$data['appid'].' content:'.$data['content']);										            $delay = 0;										            $job = (new SendTexts($send_data))->onConnection('rabbitmq')->delay($delay)->onQueue('send_texts_list');					            dispatch($job);    							    							Redis::hset('unpaid_send_activity_uid:'.$uid, 'time', time());                                Redis::EXPIRE('unpaid_send_activity_uid:'.$uid,86400);    							//\Log::info('unpaid_send_activity_settime_uid:'.$uid.' time:'.time());    							    							$push_user_num++;    								    					}else{    						\Log::info('unpaid_send_activity_exist_uid:'.$force_user[$i]['uid'].' time:'.Redis::hget('unpaid_send_activity_uid:'.$uid, 'time'));    					}    				}    				    				\Log::info('unpaid_send_activity,push_user_num:'.$push_user_num);    				// 因为有些用户重复筛选,所以人数在后面更新    				$customSendStatsCount = CustomSendDayStats::customSendDayStatsByChannelAndFromAndDay($distribution_channel_id,'unpaid_send_activity',date("Y-m-d"));    				if (empty($customSendStatsCount)) {    					$customSendDayStats['distribution_channel_id'] = $distribution_channel_id;    					$customSendDayStats['from'] = 'unpaid_send_activity';    					$customSendDayStats['push_user_num'] = $push_user_num;    					$customSendDayStats['date'] = date("Y-m-d");    					CustomSendDayStats::create($customSendDayStats);    				}else{    					$customSendStatsCount['push_user_num'] = $customSendStatsCount['push_user_num']+$push_user_num;    					$customSendStatsCount->save();    				}    			}else{    				\Log::info('<----未开启 未付费推送的 渠道号---->:'.$distribution_channel_id);    			}    		}    	}    }    /**     *  热门书籍推送(定时任务)hot_push     */    static function add_news_top_book(){         //1,遍历渠道表        $distribution_channels =  ChannelService::getAllChannels();        for ($k=0; $k < count($distribution_channels); $k++) {                         //2,判断该渠道下有没有开启 未支付订单的智能推送            $distribution_channel_id = $distribution_channels[$k]['id'];            $customMsgSwitch = CustomMsgSwitchsMsgs::customMsgSwitchsByChannelCate($distribution_channel_id,'hot_push');                        if (!empty($customMsgSwitch)) {                                if ($customMsgSwitch['status'] == '1') {                                        //\Log::info('<----开启客服的 渠道号---->');                    //\Log::info($distribution_channel_id);                    //3,开通智能推送的渠道获取 渠道下的强关用户                    $forceSubscribeUsersPrams['distribution_channel_id'] = $distribution_channel_id;                    $forceSubscribeUsersPrams['timeset'] = 86400;//热门书籍24小时                    $force_user = ForceSubscribeService::forceSubscribeUsersByChannelidAndTimeset($forceSubscribeUsersPrams);                   // \Log::info('<----符合条件的用户数---->');                   // \Log::info(count($force_user));                    $customSendStatsCount = CustomSendDayStats::customSendDayStatsByChannelAndFromAndDay($distribution_channel_id,'hot_push',date("Y-m-d"));                    if (empty($customSendStatsCount)) {                        $customSendDayStats['distribution_channel_id'] = $distribution_channel_id;                        $customSendDayStats['from'] = 'point_push';                        $customSendDayStats['push_user_num'] = count($force_user);                        $customSendDayStats['date'] = date("Y-m-d");                        CustomSendDayStats::create($customSendDayStats);                    }else{                        $customSendStatsCount['push_user_num'] = $customSendStatsCount['push_user_num']+count($force_user);                        $customSendStatsCount->save();                    }                    for ($i=0; $i < count($force_user); $i++) {                                                $uid = $force_user[$i]['uid'];                           if(Redis::hget('add_news_top_book_uid'.$uid, 'time'))                        {                            $time = Redis::hget('add_news_point_book_uid'.$uid, 'time');                            if (date("Y-m-d",$time) == date("Y-m-d"))                            {                            }else{                                //获取定制图书推送是否是在这个时间段推送过,如果推送过这个时间点就不推送了                                $top_time = Redis::hget('add_news_point_book_uid'.$uid, 'time');                                if ($top_time) {                                    if (date("Y-m-d",$top_time) == date("Y-m-d")) {                                        $matchTime = time() - $top_time;                                        if ($matchTime < 3600) {                                            continue;                                        }                                    }                                                                    }                                //\Log::info('<---- Redis中存在 且满足条件的 强关用户 uid---->');                                //\Log::info($uid);                                //4,获取和用户强关进来的书相同类型的5本优质评分的书籍                                $bid = $force_user[$i]['bid'];//                                 $books = BookConfigService::getSimpleChannelBook($bid,5);                                $books = BookConfigService::getSimpleChannelBookLoop($bid,5,$uid);                                $bookUrl = env('PROTOCOL').'://site'.encodeDistributionChannelId($distribution_channel_id).'.'.env('CUSTOM_HOST').'.com';                                $booksArray = [];                                //5,获取男频女频的标签文案                                $womanPromotion = PromotionService::getRandomHeadline(2,count($books));                                $manPromotion = PromotionService::getRandomHeadline(1,count($books));                                $promotionNum = 0;                                if ($books) {                                                                       foreach ($books as $key => $value) {                                        //6,将这5本书作为推送的1-5条信息,                                        //通过判断书籍是男频还是女频拼接书籍信息的不同标签文案                                        $urlBook = $value->url = $bookUrl.$value->url.'&fromtype=hot_push';                                        $channelName = $value->channel_name;                                        $cover = $value->cover;                                        if($channelName == '男频'){                                            $book['title'] = $manPromotion[$promotionNum]['title'];                                            $book['description'] = $manPromotion[$promotionNum]['title'];                                        }else{                                            $book['title'] = $womanPromotion[$promotionNum]['title'];                                            $book['description'] = $womanPromotion[$promotionNum]['title'];                                        }                                        $book['url'] = $urlBook;                                        // $book['image'] = $cover;                                        if ($promotionNum == 0) {                                            //第一条图片选用图库中的图片地址                                            $promotionImages = PromotionService::getMessageRandomDocumentCovers(3);                                            if ($promotionImages) {                                                $book['image'] = $promotionImages[0]['link'];                                            }else{                                                $book['image'] = $cover;                                            }                                                                                    }else{                                            $book['image'] = $cover;                                        }                                        $booksArray[$key] = [['title'=>$book['title']],['description'=>$book['description']],['url'=>$book['url']],['image'=>$book['image']]];                                        $promotionNum++;                                    }                                    //7,通过RebitMQ推送热门书籍到指定用户                                    $data = array();                                    $data['openid'] = $force_user[$i]['openid'];                                    $data['appid'] = $force_user[$i]['appid'];                                    $data['news_content'] = json_encode($booksArray);                                    $data['type'] = 'one_task';                                    $data['task_id'] = 3;                                    $data['send_time'] = date("Y-m-d H:i:s");                                    $send_data=array(                                        'send_time'=>date("Y-m-d H:i:s"),                                        'data' => $data                                    );                                    $delay = 0;                                    /*\Log::info('<---- 客服消息发送内容 参数---->');                                    \Log::info($data['openid']);                                    \Log::info($data['appid']);*/                                    //\Log::info($data['news_content']);                                    $job = (new SendNews($send_data))->onConnection('rabbitmq')->delay($delay)->onQueue('send_news_list');                                    dispatch($job);                                    Redis::hset('add_news_point_book_uid'.$uid, 'time', time());                                }                                                            }                        }else{                            //获取定制图书推送是否是在这个时间段推送过,如果推送过这个时间点就不推送了                            $top_time = Redis::hget('add_news_point_book_uid'.$uid, 'time');                            if ($top_time) {                                if (date("Y-m-d",$top_time) == date("Y-m-d")) {                                    $matchTime = time() - $top_time;                                    if ($matchTime < 3600) {                                        continue;                                    }                                }                                                            }                                                        //\Log::info('<---- Redis不存在的 强关用户 uid---->');                            //\Log::info($uid);                            //4,获取和用户强关进来的书相同类型的5本优质评分的书籍                            $bid = $force_user[$i]['bid'];//                             $books = BookConfigService::getSimpleChannelBook($bid,5);                            $books = BookConfigService::getSimpleChannelBookLoop($bid,5,$uid);                            // if (count($books)>0) {                            //     # code...                            // }                            $bookUrl = env('PROTOCOL').'://site'.encodeDistributionChannelId($distribution_channel_id).'.'.env('CUSTOM_HOST').'.com';                            $booksArray = [];                            //5,获取男频女频的标签文案                            $womanPromotion = PromotionService::getRandomHeadline(2,count($books));                            $manPromotion = PromotionService::getRandomHeadline(1,count($books));                            $promotionNum = 0;                            if ($books) {                                                                foreach ($books as $key => $value) {                                    //6,将这5本书作为推送的1-5条信息,                                    //通过判断书籍是男频还是女频拼接书籍信息的不同标签文案                                    $urlBook = $value->url = $bookUrl.$value->url.'&fromtype=hot_push';                                    $channelName = $value->channel_name;                                    $cover = $value->cover;                                    if($channelName == '男频'){                                        $book['title'] = $manPromotion[$promotionNum]['title'];                                        $book['description'] = $manPromotion[$promotionNum]['title'];                                    }else{                                        $book['title'] = $womanPromotion[$promotionNum]['title'];                                        $book['description'] = $womanPromotion[$promotionNum]['title'];                                    }                                    $book['url'] = $urlBook;                                    if ($promotionNum == 0) {                                        //第一条图片选用图库中的图片地址                                        $promotionImages = PromotionService::getMessageRandomDocumentCovers(3);                                        if ($promotionImages) {                                            $book['image'] = $promotionImages[0]['link'];                                        }else{                                            $book['image'] = $cover;                                        }                                    }else{                                        $book['image'] = $cover;                                    }                                    $booksArray[$key] = [['title'=>$book['title']],['description'=>$book['description']],['url'=>$book['url']],['image'=>$book['image']]];                                    $promotionNum++;                                }                                //7,通过RebitMQ推送热门书籍到指定用户                                $data = array();                                $data['openid'] = $force_user[$i]['openid'];                                $data['appid'] = $force_user[$i]['appid'];                                $data['news_content'] = json_encode($booksArray);                                $data['type'] = 'one_task';                                $data['task_id'] = 3;                                $data['send_time'] = date("Y-m-d H:i:s");                                $send_data=array(                                    'send_time'=>date("Y-m-d H:i:s"),                                    'data' => $data                                );                                $delay = 0;                                /*\Log::info('<---- 客服消息发送内容 参数---->');                                \Log::info($data['openid']);                                \Log::info($data['appid']);*/                                //\Log::info($data['news_content']);                                $job = (new SendNews($send_data))->onConnection('rabbitmq')->delay($delay)->onQueue('send_news_list');                                dispatch($job);                                Redis::hset('add_news_top_book_uid'.$uid, 'time', time());                            }                        }                                            }                }            }        }    }    /**     * 测试向指定用户发送热门书籍     */    static function add_news_top_book_test($force_user){        $bid = $force_user['bid'];        $distribution_channel_id = $force_user['distribution_channel_id'];        $uid = $force_user['uid'];        $booksArray = [];        //获取男频女频标签文案        $womanPromotion = PromotionService::getRandomHeadline(2,5);        $manPromotion = PromotionService::getRandomHeadline(1,5);        //获取用户最近阅读记录的书籍        $userBook = ReadRecordService::getFirstReadRecord($uid);        if (!empty($userBook)) {            //推送第一条放最近阅读的书籍,并通过该书分类拼接上标签文案            $continueReadUrl = env('PROTOCOL').'://site'.encodeDistributionChannelId($distribution_channel_id).'.'.env('CUSTOM_HOST').'.com/continue';            $channelName = $userBook['channel_name'];            if($channelName == '男频'){                $book['title'] = $manPromotion[0]['title'];                $book['description'] = $manPromotion[0]['title'];            }else{                $book['title'] = $womanPromotion[0]['title'];                $book['description'] = $womanPromotion[0]['title'];            }            $book['url'] = $continueReadUrl;            $book['image'] = $userBook['cover'];            $booksArray[] = [['title'=>$book['title']],['description'=>$book['description']],['url'=>$book['url']],['image'=>$book['image']]];//             $books = BookConfigService::getSimpleChannelBook($bid,4);            $books = BookConfigService::getSimpleChannelBookLoop($bid,4,$uid);            $bookUrl = env('PROTOCOL').'://site'.encodeDistributionChannelId($distribution_channel_id).'.'.env('CUSTOM_HOST').'.com';            $promotionNum = 1;            foreach ($books as $key => $value) {                //推送2-4条放相同类别的4本高评分的书籍                $urlBook = $value->url = $bookUrl.$value->url;                $channelName = $value->channel_name;                $cover = $value->cover;                if($channelName == '男频'){                    $book['title'] = $manPromotion[$promotionNum]['title'];                    $book['description'] = $manPromotion[$promotionNum]['title'];                }else{                    $book['title'] = $womanPromotion[$promotionNum]['title'];                    $book['description'] = $womanPromotion[$promotionNum]['title'];                }                $book['url'] = $urlBook;                $book['image'] = $cover;                $booksArray[] = [['title'=>$book['title']],['description'=>$book['description']],['url'=>$book['url']],['image'=>$book['image']]];                $promotionNum++;            }            //7,通过RebitMQ推送热门书籍到指定用户            $data = array();            $data['openid'] = $force_user['openid'];            $data['appid'] = $force_user['appid'];            $data['news_content'] = json_encode($booksArray);            $data['type'] = 'one_task';            $data['task_id'] = 3;            $data['send_time'] = date("Y-m-d H:i:s");            $send_data=array(                'send_time'=>date("Y-m-d H:i:s"),                'data' => $data            );            $delay = 0;            $job = (new SendNews($send_data))->onConnection('rabbitmq')->delay($delay)->onQueue('send_news_list');            dispatch($job);        }    }    /**     *  付费用户每天智能推送(定时任务 每天8点推送一次昨天的用户)     *  需要开关控制     */    static function add_template_pay_push_daily() {    	// 从动态推送表中获取    	$customPushConfig = CustomPushConfigs::customPushConfigs('pay_daily_push');    	//\Log::info($customPushConfig);    	//\Log::info('add_template_pay_push_daily_customPushConfig:'.json_encode($customPushConfig));    	    	// 随机文案    	$config_contents = CustomPushConfigContents::getCustomPushConfigContents();//     	\Log::info($config_contents);    	$template_content_num = rand(0,count($config_contents)-1);//     	$template_content_num = 9;    	$template_content = $common_template_id = '';    	foreach($config_contents as $key=>$config_content){    		if($template_content_num == $key){    			$template_content = $config_content['template_format_content'];    			$common_template_id = $config_content['common_template_id'];    			break;    		}//     		\Log::info('add_template_pay_push_daily_$key:'.$key.' template_content:'.$config_content);    	}    	\Log::info('add_template_pay_push_daily_template_content_num:'.$template_content_num.' template_content:'.$template_content);    	 	    	if(empty($template_content)){    		$template_content = $customPushConfig['template_content'];    	}    	if(empty($common_template_id)){    		$common_template_id = $customPushConfig['common_template_id'];    	}    	//     	$template_content = $customPushConfig['template_content'];    	$name = $customPushConfig['name'];    	$is_all_push = $customPushConfig['is_all_push'];    	$remark = $customPushConfig['remark'];    	$redirect_url = $customPushConfig['redirect_url'];    	    	//1,遍历渠道表    	$distribution_channels =  ChannelService::getAllChannels();    	    	for ($k=0; $k < count($distribution_channels); $k++) {    	    		//2,判断该渠道下有没有开启 付费用户每天智能推送    		$distribution_channel_id = $distribution_channels[$k]['id'];    		\Log::info('add_template_pay_push_daily_start:'.$distribution_channel_id);    		$customMsgSwitch = CustomMsgSwitchsMsgs::customMsgSwitchsByChannelCate($distribution_channel_id,'pay_daily_push');    	    		if (!empty($customMsgSwitch)) {    	    			if ($customMsgSwitch['status'] == '1') {	                    \Log::info('add_template_pay_push_daily_open_start:'.$distribution_channel_id);    					$official_accounts = OfficialAccount::officialAuthAccountBydistributionChannelId($distribution_channel_id,1,1);    					$appids = array();    					foreach($official_accounts as $official_account){    						$appids[] = $official_account->appid;    					}    					$appids_str = implode(',', $appids);    					$wechatTemplateMsgs['appid'] = $appids_str;// 由渠道得到appids    					$wechatTemplateMsgs['common_template_id'] = $common_template_id;    					$wechatTemplateMsgs['name'] = $name;    					$wechatTemplateMsgs['send_time']  = date('Y-m-d H:i:s',strtotime('+1 minute'));//  马上执行    					$wechatTemplateMsgs['template_content'] = $template_content;    					//用户最近阅读链接    					$continueReadUrl = env('PROTOCOL').'://site'.encodeDistributionChannelId($distribution_channel_id).'.'.env('CUSTOM_HOST').'.com/'.$redirect_url;    					$wechatTemplateMsgs['redirect_url'] = $continueReadUrl;    					$wechatTemplateMsgs['distribution_channel_id'] = $distribution_channel_id;    					$wechatTemplateMsgs['remark'] = $remark;    					$wechatTemplateMsgs['is_show_list'] = 0;// 界面不展示    					     					$wechatTemplateMsgs['subscribe_time'] = 'z';// 关注时间不限    					$wechatTemplateMsgs['sex'] = 'z';    					$wechatTemplateMsgs['balance'] = 'z';    					$wechatTemplateMsgs['order_type'] = 'd';// 昨天消费    					$wechatTemplateMsgs['category_id'] = 'z';    					//\Log::info('$wechatTemplateMsgs:'.json_encode($wechatTemplateMsgs));    					$resultStatus = WechatTemplateService::addWechatTemplateMsg($wechatTemplateMsgs);    			}    		}    	}    }        /**     * 客服消息智能推送方法--公用版     * 以下3个板块找到对应的推送     * 1、用户     * 2、内容     * 3、队列类型     */    static function SmartPush($category_type){    	if(empty($category_type)) return false;    	$base_category_type = self::get_base_category_type($category_type);    	\Log::info('smart_push:'.$category_type.' base_category_type:'.$base_category_type);    	     	// 先更新书库和测书信息,避免频繁查询    	BookConfigService::resetBookLibRedis($category_type);    	    	//1,遍历渠道表    	$distribution_channels =  ChannelService::getAllChannels();    	     	for ($k=0; $k < count($distribution_channels); $k++) {    		     		//2,判断该渠道下有没有开启 未支付订单的智能推送    		$distribution_channel_id = $distribution_channels[$k]['id'];    		$customMsgSwitch = CustomMsgSwitchsMsgs::customMsgSwitchsByChannelCate($distribution_channel_id,$base_category_type);    		     		if (!empty($customMsgSwitch)) {    			     			if ($customMsgSwitch['status'] == '1') {    				\Log::info('SmartPush_channel_id:'.$distribution_channel_id.' category_type:'.$category_type.' is_self_content:'.$customMsgSwitch['is_self_content']);    				    				// 如果自定义内容发送    				$sexs = array('z');    				if($customMsgSwitch['is_self_content']){    					$sexs = array('a','b');    				}    				    				$user_total_count = 0;    				    				foreach($sexs as $sex){    					\Log::info('smart_push_sex:'.$sex);    					$smartPushsMsg = array();    					$smartPushsMsg['distribution_channel_id'] = $distribution_channel_id;    					$smartPushsMsg['category_type'] = $category_type;    					$smartPushsMsg['sex'] = $sex;    					$send_content = '';    					if($customMsgSwitch['is_self_content']){    						$smartPushsMsgData = SmartPushMsgService::smartPushByDistributionChannelIdAndCategorySex($smartPushsMsg);    						//\Log::info('$smartPushsMsgData:');    						//\Log::info($smartPushsMsgData);    						if(!empty($smartPushsMsgData)){    							// 带上参数    							$send_content = TemplateCustomSendService::convert_custom_content($smartPushsMsgData->content, 'smart_push_'.$base_category_type, $distribution_channel_id,0);    							$send_content = json_decode($send_content);    						}    					}    					    					$skip = 0;    					$loop = 0;    					    					while ( $skip <= 250000) {    						$loop++;    						$force_user = null;    						$force_user = self::get_send_force_users($distribution_channel_id,$category_type,$sex,$skip);    						\Log::info('SmartPush_usernum:'.count($force_user).' loop:'.$loop.' distribution_channel_id:'.$distribution_channel_id.' memory:'.memory_get_usage());    						$force_user_num = count($force_user);    						$skip += $force_user_num;    						$user_total_count += $force_user_num;    						if($force_user_num > 0){    							for ($i=0; $i < $force_user_num; $i++) {    								$uid = $force_user[$i]['uid'];    								$bid = $force_user[$i]['bid'];    								if(empty($bid)) $bid=1;// TODO    							    								// 非自定义,则根据bid取系统推荐的书籍    								if(empty($customMsgSwitch['is_self_content'])){    									\Log::info('get_user_send_content_start');    									$send_content = null;    									$send_content = self::get_user_send_content($bid,$distribution_channel_id,$category_type,$uid);    								}else{    									\Log::info('get_user_send_content_not_start:'.$uid.' memory:'.memory_get_usage());    								}    								if(empty($send_content)){    									\Log::info('smart_push:openid:'.$force_user[$i]['openid'].' appid:'.$force_user[$i]['appid'].' content_is_null');    									continue;    								}    								    								$smart_push_queue = self::get_smart_push_queue($category_type);    								$data = array();    								$data['openid'] = $force_user[$i]['openid'];    								$data['appid'] = $force_user[$i]['appid'];    								if (isset($smart_push_queue['is_news']) && $smart_push_queue['is_news']){    									$data[$smart_push_queue['content']] = json_encode($send_content);    								}else{    									$data[$smart_push_queue['content']] = $send_content;    								}    								$data['type'] = 'one_task';    								$data['task_id'] = 3;    								$data['send_time'] = date("Y-m-d H:i:s");    								$send_data=array(    										'send_time'=>date("Y-m-d H:i:s"),    										'data' => $data    								);    							    								$delay = 0;    							//     								\Log::info('smart_push:'.json_encode($data));    								if (isset($smart_push_queue['is_news']) && $smart_push_queue['is_news']){    									$job = (new SendNews($send_data))->onConnection('rabbitmq')->delay($delay)->onQueue($smart_push_queue['queue']);    								}else{    									$job = (new SendTexts($send_data))->onConnection('rabbitmq')->delay($delay)->onQueue($smart_push_queue['queue']);    								}    								dispatch($job);    								\Log::info('smart_push_user_end:'.$uid.' memory:'.memory_get_usage());    								// 释放内存    								$send_data = $data = null;    							}//end users                                if($force_user_num < 10000)//低于单次获取的10000条,所以下次不必获取,必须与单次获取的数值保持一致!                                {                                    \Log::info('smart_push user num less than once get num, so break ,distribution_channel_id:'.$distribution_channel_id.' category_type:'. $category_type.' sex:'.$sex.' loop:'.$loop.' memory:'.memory_get_usage());                                    break;                                }    							    						}else{    							\Log::info('smart_push_has_no_user,distribution_channel_id:'.$distribution_channel_id.' category_type:'. $category_type.' sex:'.$sex.' loop:'.$loop.' memory:'.memory_get_usage());    							break;    						}    						    						    					}    					    				} // end sex    				    				\Log::info('SmartPush_end:'.' distribution_channel_id:'.$distribution_channel_id.' memory:'.memory_get_usage());    				    				// 后面计数    				$customSendStatsCount = CustomSendDayStats::customSendDayStatsByChannelAndFromAndDay($distribution_channel_id,$base_category_type,date("Y-m-d"));    				if (empty($customSendStatsCount)) {    					$customSendDayStats['distribution_channel_id'] = $distribution_channel_id;    					$customSendDayStats['from'] = $base_category_type;    					$customSendDayStats['push_user_num'] = $user_total_count;    					$customSendDayStats['date'] = date("Y-m-d");    					CustomSendDayStats::create($customSendDayStats);    				}else{    					$customSendStatsCount['push_user_num'] = $customSendStatsCount['push_user_num']+$user_total_count;    					$customSendStatsCount->save();    				}    			}    		}// end 开关    	}    }        static function get_base_category_type($category_type){    	if($category_type == 'unpaid_hot_push' || $category_type =='all_hot_push'){    		return 'hot_push';    	}    	if($category_type == 'paid_point_push' || $category_type =='unpaid_point_push'){    		return 'point_push';    	}    	if($category_type == 'unpaid_send_big_activity'){    		return 'unpaid_send_activity';    	}    	    	return $category_type;    }        static function get_smart_push_queue($category_type){    	$smart_push_queue = array();    	    	$text_queue = array('unpaid_send_activity','unpaid_send_big_activity','pay_daily_push');    	     	if(in_array($category_type,$text_queue)){    		$smart_push_queue['is_news'] = false;    		$smart_push_queue['content'] = 'content';    		$smart_push_queue['queue'] = 'send_texts_list';    	}else{    		$smart_push_queue['is_news'] = true;    		$smart_push_queue['content'] = 'news_content';    		$smart_push_queue['queue'] = 'send_news_list';    	}//     	\Log::info('$smart_push_queue');\Log::info($smart_push_queue);    	    	return $smart_push_queue;    }        static function get_base_custom_param(){    	$param = array();    	$param['appids'] = array();    	$param['subscribe_time'] = 'z';    	$param['sex'] = 'z';    	$param['balance'] = 'z';    	$param['category_id'] = 'z';    	$param['order_type'] = 'z';    	$param['sign_time'] = 'z';        //$param['skip'] = 0;    	return $param;    }        static function get_appids_str($distribution_channel_id){    	$official_accounts = OfficialAccount::officialAuthAccountBydistributionChannelId($distribution_channel_id,1,1);    	$appids = array();    	foreach($official_accounts as $official_account){    		$appids[] = $official_account->appid;    	}    	$appids_str = implode(',', $appids);    	return $appids_str;    }        /**     * 去重筛选的用户,已经推送过的不再推送     * @param unknown_type $force_users     * @param unknown_type $redis_pre_str     */    static function get_unique_users($force_users,$redis_pre_str,$expire_time=3600){    	//  去重    	if(!empty($force_users)){    		\Log::info('before_'.$redis_pre_str.'_quchong::'.count($force_users));    		foreach($force_users as $key=>$force_user){    			$uid = $force_user['uid'];    			$user_key = $redis_pre_str.':'.$uid;    			if(Redis::get($user_key)){    				unset($force_users[$key]);//     				\Log::info($redis_pre_str.'_exist_user:'.$uid);    				continue;    			}else{//     				\Log::info($redis_pre_str.'_push_add_user:'.$uid);    				Redis::set($user_key,date('Y-m-d H:i:s'));    				Redis::expire($user_key,$expire_time);    			}    		}    		\Log::info('after_'.$redis_pre_str.'_push_quchong::'.count($force_users));    	}    	return $force_users;    }        /**     * 得到指定类型智能推送发送的用户列表     */    static function get_send_force_users($distribution_channel_id,$category_type,$sex,$skip=0){    	$force_users = array();    	$custom_param = self::get_base_custom_param();        $custom_param['skip'] = $skip;//skip传进来    	$custom_param['distribution_channel_id'] = $distribution_channel_id;    	$custom_param['appids'] = self::get_appids_str($distribution_channel_id);    	$custom_param['sex'] = $sex;    	// 签到推送    	if($category_type == 'sign_push'){    		$custom_param['sign_time'] = 'a';// 60-120分钟内    		$custom_param['subscribe_time'] = 'g';// 1天前老用户    		    		$force_users = ForceSubscribeService::forceUserCountByCustomPrams($custom_param['appids'],$custom_param['distribution_channel_id'],$custom_param['subscribe_time'],$custom_param['sex'],$custom_param['balance'],$custom_param['category_id'],$custom_param['order_type'],$custom_param['sign_time'],$custom_param['skip']);    		$force_users = self::get_unique_users($force_users,'sign_push_user',7200);    	       	}    	// 关注推送    	elseif($category_type == 'subscribe_push'){    		$custom_param['subscribe_time'] = 'h';// 10-25分钟内    		    		$force_users = ForceSubscribeService::forceUserCountByCustomPrams($custom_param['appids'],$custom_param['distribution_channel_id'],$custom_param['subscribe_time'],$custom_param['sex'],$custom_param['balance'],$custom_param['category_id'],$custom_param['order_type'],$custom_param['sign_time'],$custom_param['skip']);    	    $force_users = self::get_unique_users($force_users,'subscribe_push_user',3600);    	       	}    	// 全量热门书籍推送    	elseif($category_type == 'all_hot_push'){    		$custom_param['subscribe_time'] = 'l';//12-48小时    		$custom_param['order_type'] = 'z';//全量    		$force_users = ForceSubscribeService::forceUserCountByCustomPrams($custom_param['appids'],$custom_param['distribution_channel_id'],$custom_param['subscribe_time'],$custom_param['sex'],$custom_param['balance'],$custom_param['category_id'],$custom_param['order_type'],$custom_param['sign_time'],$custom_param['skip']);    		$force_users = self::get_unique_users($force_users,'all_hot_push',3600*48);    	}    	// 已付费定制书籍推送    	elseif($category_type == 'paid_point_push'){    		$custom_param['subscribe_time'] = 'k';//42-48小时    		$custom_param['order_type'] = 'b';//已充值    		$force_users = ForceSubscribeService::forceUserCountByCustomPrams($custom_param['appids'],$custom_param['distribution_channel_id'],$custom_param['subscribe_time'],$custom_param['sex'],$custom_param['balance'],$custom_param['category_id'],$custom_param['order_type'],$custom_param['sign_time'],$custom_param['skip']);    		$force_users = self::get_unique_users($force_users,'paid_point_push',3600*48);    		// 排除测试的用户//     		$force_users = self::get_minus_test_users($force_users);    	}    	// 未付费热门书籍推送    	elseif($category_type == 'unpaid_hot_push'){    		$custom_param['subscribe_time'] = 'f';//24-48小时    		$custom_param['order_type'] = 'a';//未充值    		    		$force_users = ForceSubscribeService::forceUserCountByCustomPrams($custom_param['appids'],$custom_param['distribution_channel_id'],$custom_param['subscribe_time'],$custom_param['sex'],$custom_param['balance'],$custom_param['category_id'],$custom_param['order_type'],$custom_param['sign_time'],$custom_param['skip']);    		$force_users = self::get_unique_users($force_users,'unpaid_hot_push',3600*48);    	}    	// 未付费定制书籍推送    	elseif($category_type == 'unpaid_point_push'){    		$custom_param['subscribe_time'] = 'k';//42-48小时    		$custom_param['order_type'] = 'a';//未充值    		$force_users = ForceSubscribeService::forceUserCountByCustomPrams($custom_param['appids'],$custom_param['distribution_channel_id'],$custom_param['subscribe_time'],$custom_param['sex'],$custom_param['balance'],$custom_param['category_id'],$custom_param['order_type'],$custom_param['sign_time'],$custom_param['skip']);    		$force_users = self::get_unique_users($force_users,'unpaid_point_push',3600*48);    		// 排除测试的用户//     		$force_users = self::get_minus_test_users($force_users);    	}    	// 未付费优惠充值活动推送(多选项)    	elseif($category_type == 'unpaid_send_big_activity'){    		$custom_param['subscribe_time'] = 'j';//20-48小时    		$custom_param['order_type'] = 'a';//未充值    		$force_users = ForceSubscribeService::forceUserCountByCustomPrams($custom_param['appids'],$custom_param['distribution_channel_id'],$custom_param['subscribe_time'],$custom_param['sex'],$custom_param['balance'],$custom_param['category_id'],$custom_param['order_type'],$custom_param['sign_time'],$custom_param['skip']);    		$force_users = self::get_unique_users($force_users,'unpaid_send_big_activity',3600*48);    	}    	// 未付费9.9活动推送    	elseif($category_type == 'unpaid_send_activity'){    		$custom_param['subscribe_time'] = 'i';//36-48小时    		$custom_param['order_type'] = 'a';//未充值    		$force_users = ForceSubscribeService::forceUserCountByCustomPrams($custom_param['appids'],$custom_param['distribution_channel_id'],$custom_param['subscribe_time'],$custom_param['sex'],$custom_param['balance'],$custom_param['category_id'],$custom_param['order_type'],$custom_param['sign_time'],$custom_param['skip']);    		$force_users = self::get_unique_users($force_users,'unpaid_send_activity',3600*48);    	}    	// 付费用户推送    	elseif($category_type == 'pay_daily_push'){    		$custom_param['order_type'] = 'd';//6-13小时充值,考虑到0-6点不推送    		$force_users = ForceSubscribeService::forceUserCountByCustomPrams($custom_param['appids'],$custom_param['distribution_channel_id'],$custom_param['subscribe_time'],$custom_param['sex'],$custom_param['balance'],$custom_param['category_id'],$custom_param['order_type'],$custom_param['sign_time'],$custom_param['skip']);    		$force_users = self::get_unique_users($force_users,'pay_daily_push',3600*24);    	}    	else{    		    	}    	    	// key重新排序    	$temp_force_users = array();    	if(!empty($force_users)){    		foreach($force_users as $force_user){    			$temp_force_users[] = $force_user;    		}    	}        	return $temp_force_users;    }        /**     * 得到指定用户,发送的图文内容     */    static function get_user_send_content($bid,$distribution_channel_id,$category_type,$uid){    	     	$send_content = '';    	$recommend_book_category_types = array('sign_push','subscribe_push');    	// 改版,书籍数量只能选1本    	$send_book_num = 1;    	     	// 推荐图书    	if(in_array($category_type,$recommend_book_category_types)){    		$send_content = self::get_user_recommend_books($bid,$distribution_channel_id,$send_book_num,$category_type,$uid);    	}    	// 已付费热门书籍推送 12小时    	elseif($category_type == 'all_hot_push'){    		$send_content = self::get_user_recommend_books($bid,$distribution_channel_id,$send_book_num,$category_type,$uid);    	}    	// 未付费热门书籍推送 24小时    	elseif($category_type == 'unpaid_hot_push'){    		// 优惠充值活动    		$send_content = array();    		$send_content[] = [    		['title'=>'新用户专享:点此领取25000书币'],    		['description'=>'新用户专享:点此领取25000书币'],    		['url'=> env('PROTOCOL').'://site'.encodeDistributionChannelId($distribution_channel_id).'.'.env('CUSTOM_HOST').'.com/sale/newUserSale?fromtype=unpaid_send_activity&send_time='.time()],    		['image'=>'https://zhuishuyun.oss-cn-hangzhou.aliyuncs.com/smart_push/citiao.jpg']    		];    	}    	// 已付费定制书籍推送 42小时    	elseif($category_type == 'paid_point_push'){    		$send_content = self::get_user_recommend_books($bid,$distribution_channel_id,$send_book_num,$category_type,$uid);    	}    	// 未付费定制书籍推送 42小时    	elseif($category_type == 'unpaid_point_push'){    		$send_content = array();    		if(in_array($distribution_channel_id,array('14'))){    			// 头条为终身充值活动    			$first_activity = [    			['title'=>'全年免费看书的机会来啦!限时优惠'],    			['description'=>'全年免费看书的机会来啦!限时优惠'],    			['url'=> env('PROTOCOL').'://site'.encodeDistributionChannelId($distribution_channel_id).'.'.env('CUSTOM_HOST').'.com/sale/seYearActivity?fromtype=unpaid_send_activity&send_time='.time()],    			['image'=>'https://cdn-novel.iycdm.com/h5/2018111201.jpg']    			];    		}else{    			// 头条为9.9元活动    			$first_activity = [    			['title'=>'充9.9元,得2000书币!'],    			['description'=>'充9.9元,得2000书币,只有一次机会哦!过期失效,不要错过!'],    			['url'=> env('PROTOCOL').'://site'.encodeDistributionChannelId($distribution_channel_id).'.'.env('CUSTOM_HOST').'.com/sale/newUserActivity?fromtype=unpaid_send_activity&send_time='.time()],    			['image'=>'https://zhuishuyun.oss-cn-hangzhou.aliyuncs.com/smart_push/toutiao.jpg']    			];    		}    		$send_content[] = $first_activity;    		    	}    	// 未付费优惠充值活动推送(多选项)    	elseif($category_type == 'unpaid_send_big_activity'){    		//活动链接    		$continueReadUrl = env('PROTOCOL').'://site'.encodeDistributionChannelId($distribution_channel_id).'.'.env('CUSTOM_HOST').'.com/sale/newUserSale?fromtype=unpaid_send_activity&send_time='.time();    		$send_content = '您的新用户专享礼包已送达'."\n\n".'送25000书币及优惠券,畅读全站小说无压力!'."\n\n".'过期失效,只有1次机会哦!'."\n\n".'<a href="'.$continueReadUrl.'">点击立即领取> ></a>'."\n\n".'为方便下次阅读,请'.'<a href="https://help.leyuee.com/top.html">'.'置顶公众号'.'</a>';    	}    	// 未付费9.9活动推送    	elseif($category_type == 'unpaid_send_activity'){    		//活动链接    		$continueReadUrl = env('PROTOCOL').'://site'.encodeDistributionChannelId($distribution_channel_id).'.'.env('CUSTOM_HOST').'.com/sale/newUserActivity?fromtype=unpaid_send_activity&send_time='.time();    		$send_content = '您的新用户专享礼包已送达'."\n\n".'充9.9元,得2000书币,只有一次机会哦!'."\n\n".'过期失效,不要错过!'."\n\n".'<a href="'.$continueReadUrl.'">点击立即领取> ></a>'."\n\n".'为方便下次阅读,请'.'<a href="https://help.leyuee.com/top.html">'.'置顶公众号'.'</a>';    	}    	    	// 付费用户推送    	elseif($category_type == 'pay_daily_push'){    		$userBook = ReadRecordService::getFirstReadRecord($uid);    		$book_name = isset($userBook['book_name'])?$userBook['book_name']:'';    		$user = UserService::getById($uid);    		$balance = isset($user->balance)?$user->balance:'0';    		$nickname = isset($user->nickname)?$user->nickname:'';    		//用户最近阅读链接    		$continueReadUrl = env('PROTOCOL').'://site'.encodeDistributionChannelId($distribution_channel_id).'.'.env('CUSTOM_HOST').'.com/continue?fromtype=pay_daily_push';    		//拼接文案    		if(empty($book_name)){    			$send_content = '尊敬的会员:'.$nickname."\n\n".'您的账户余额:'.$balance."\n\n".'<a href="'.$continueReadUrl.'">点击继续阅读~</a>'."\n";    		}else{    			$send_content = '尊敬的会员:'.$nickname."\n\n".'您的账户余额:'.$balance."\n\n".'最近阅读书籍:《'.$book_name.'》'."\n\n".'<a href="'.$continueReadUrl.'">点击继续阅读~</a>'."\n";    		}    		\Log::info('pay_daily_push_send_content:'.$uid);\Log::info($send_content);    		    	}    	     	// TODO最近阅读?    	else{}        	return $send_content;    }        /**     * 得到指定用户,发送的图文内容     * 多条图文版--老版     */    static function get_user_send_content_multy($bid,$distribution_channel_id,$category_type,$uid){    	    	$send_content = '';    	$recommend_book_category_types = array('sign_push','subscribe_push');    	    	// 推荐图书    	if(in_array($category_type,$recommend_book_category_types)){    		$send_content = self::get_user_recommend_books($bid,$distribution_channel_id,4,$category_type,$uid);    	}    	// 已付费热门书籍推送 12小时    	elseif($category_type == 'all_hot_push'){    		$send_content = self::get_user_recommend_books($bid,$distribution_channel_id,5,$category_type,$uid);    	}     	// 未付费热门书籍推送 24小时    	elseif($category_type == 'unpaid_hot_push'){    		// 次条增加优惠充值活动    		$send_content_temp = self::get_user_recommend_books($bid,$distribution_channel_id,4,$category_type,$uid);    		$send_content = array();    		$send_content[0] = $send_content_temp[0];    		$send_content[1] = [	    		['title'=>'新用户专享:点此领取25000书币'],	    		['description'=>'新用户专享:点此领取25000书币'],	    		['url'=> env('PROTOCOL').'://site'.encodeDistributionChannelId($distribution_channel_id).'.'.env('CUSTOM_HOST').'.com/sale/newUserSale?fromtype=unpaid_send_activity&send_time='.time()],	    		['image'=>'https://zhuishuyun.oss-cn-hangzhou.aliyuncs.com/smart_push/citiao.jpg']    		];    		$send_content[2] = $send_content_temp[1];    		$send_content[3] = $send_content_temp[2];    		$send_content[4] = $send_content_temp[3];    	}    	// 已付费定制书籍推送 42小时    	elseif($category_type == 'paid_point_push'){    		// 头条为最近阅读记录链接    		$recent_read_book = self::get_user_recent_read_books($uid,$distribution_channel_id,$category_type);    		$send_content = self::get_user_recommend_books($bid,$distribution_channel_id,4,$category_type,$uid);    		array_unshift($send_content,$recent_read_book);// 前插    	}    	// 未付费定制书籍推送 42小时    	elseif($category_type == 'unpaid_point_push'){    		$send_content = self::get_user_recommend_books($bid,$distribution_channel_id,3,$category_type,$uid);    		    		// 次条为最近阅读记录链接    		$recent_read_book = self::get_user_recent_read_books($uid,$distribution_channel_id,$category_type);    		array_unshift($send_content,$recent_read_book);    		    		// 头条为9.9元活动    		$first_activity = [	    		['title'=>'充9.9元,得2000书币!'],	    		['description'=>'充9.9元,得2000书币,只有一次机会哦!过期失效,不要错过!'],	    		['url'=> env('PROTOCOL').'://site'.encodeDistributionChannelId($distribution_channel_id).'.'.env('CUSTOM_HOST').'.com/sale/newUserActivity?fromtype=unpaid_send_activity&send_time='.time()],	    		['image'=>'https://zhuishuyun.oss-cn-hangzhou.aliyuncs.com/smart_push/toutiao.jpg']    		];    		array_unshift($send_content,$first_activity);    	}    	// 未付费优惠充值活动推送(多选项)    	elseif($category_type == 'unpaid_send_big_activity'){    		//活动链接    		$continueReadUrl = env('PROTOCOL').'://site'.encodeDistributionChannelId($distribution_channel_id).'.'.env('CUSTOM_HOST').'.com/sale/newUserSale?fromtype=unpaid_send_activity&send_time='.time();    		$send_content = '您的新用户专享礼包已送达'."\n\n".'送25000书币及优惠券,畅读全站小说无压力!'."\n\n".'过期失效,只有1次机会哦!'."\n\n".'<a href="'.$continueReadUrl.'">点击立即领取> ></a>'."\n\n".'为方便下次阅读,请'.'<a href="https://help.leyuee.com/top.html">'.'置顶公众号'.'</a>';    	}    	// 未付费9.9活动推送    	elseif($category_type == 'unpaid_send_activity'){    		//活动链接    		$continueReadUrl = env('PROTOCOL').'://site'.encodeDistributionChannelId($distribution_channel_id).'.'.env('CUSTOM_HOST').'.com/sale/newUserActivity?fromtype=unpaid_send_activity&send_time='.time();    		$send_content = '您的新用户专享礼包已送达'."\n\n".'充9.9元,得2000书币,只有一次机会哦!'."\n\n".'过期失效,不要错过!'."\n\n".'<a href="'.$continueReadUrl.'">点击立即领取> ></a>'."\n\n".'为方便下次阅读,请'.'<a href="https://help.leyuee.com/top.html">'.'置顶公众号'.'</a>';    	}    	    	// TODO最近阅读?    	else{}    	     	return $send_content;    }        /**     * 得到指定用户,系统推荐的书籍列表     */    static function get_user_recommend_books($bid,$distribution_channel_id,$book_num=4,$category_type,$uid){    	$base_category_type = self::get_base_category_type($category_type);    	\Log::info('get_user_recommend_books,bid:'.$bid.' distribution_channel_id:'.$distribution_channel_id.' book_num:'.$book_num.' uid:'.$uid.' base_category_type:'.$base_category_type.' category_type:'.$category_type);//     	$books = BookConfigService::getSimpleChannelBook($bid,$book_num);    	$books = BookConfigService::getSimpleChannelBookLoop($bid,$book_num,$uid);    	$bookUrl = env('PROTOCOL').'://site'.encodeDistributionChannelId($distribution_channel_id).'.'.env('CUSTOM_HOST').'.com';    	$booksArray = [];        	    	// 标题加余额     	$pre_title = '';    	if(in_array($distribution_channel_id,array('123','211','14'))){    		$user = UserService::getById($uid);    		$balance = isset($user->balance)?$user->balance:'0';    		if($balance >= 100){    			$pre_title = '您的账户余额:'.$balance.'书币 ';    		}    	}        	    	//5,获取男频女频的标签文案    	$womanPromotion = PromotionService::getRandomHeadline(2,count($books));    	$manPromotion = PromotionService::getRandomHeadline(1,count($books));    	$promotionNum = 0;    	if ($books) {    		foreach ($books as $key => $value) {    			// 标题图片id标识    			$title_image = [];    			    			$channelName = $value->channel_name;    			$cover = $value->cover;    			if($channelName == '男频'){    				$book['title'] = $manPromotion[$promotionNum]['title'];    				$book['description'] = $manPromotion[$promotionNum]['title'];    				$title_image['title_id'] = $manPromotion[$promotionNum]['id'];    			}else{    				$book['title'] = $womanPromotion[$promotionNum]['title'];    				$book['description'] = $womanPromotion[$promotionNum]['title'];    				$title_image['title_id'] = $womanPromotion[$promotionNum]['id'];    			}    			    			if ($promotionNum == 0) {    				//第一条图片选用图库中的图片地址    				$promotionImages = PromotionService::getMessageRandomDocumentCovers(3);    				if ($promotionImages) {    					$book['image'] = $promotionImages[0]['link'];    					$title_image['image_id'] = $promotionImages[0]['id'];    				}else{    					$book['image'] = $cover;    					$title_image['image_id'] = 0;    				}    					    			}else{    				$book['image'] = $cover;    				$title_image['image_id'] = 0;    			}    			    			// 记录标题图片推送的redis    			$title_image_key = $title_image['title_id'].'_'.$title_image['image_id'];    			\Log::info('title_image_smart_push:'.$base_category_type.' uid:'.$uid.' title_image_key:'.$title_image_key);    			$title_image_send_uv_key = 'smart_push_from_title_image_send_uv:'.$title_image_key;    			$title_image_statistics_key = 'smart_push_from_title_image:'.$title_image_key;    			Redis::sadd($title_image_send_uv_key,$uid);    			Redis::HINCRBY($title_image_statistics_key,'send_num',1);    			    			//通过判断书籍是男频还是女频拼接书籍信息的不同标签文案    			if(strpos($bookUrl.$value->url,'?') > -1){    				$urlBook = $value->url = $bookUrl.$value->url.'&fromtype='.$base_category_type.'&source=wechatmsg&fromsource=smart_push&from_title_image='.$title_image_key;    			}else{    				$urlBook = $value->url = $bookUrl.$value->url.'?fromtype='.$base_category_type.'&source=wechatmsg&fromsource=smart_push&from_title_image='.$title_image_key;    			}    			$book['url'] = $urlBook;    			// $book['image'] = $cover;    			if(!empty($pre_title)){    				$book['title'] = $pre_title.$book['title'];    			}    			$booksArray[$key] = [['title'=>$book['title']],['description'=>$book['description']],['url'=>$book['url']],['image'=>$book['image']]];        			$promotionNum++;        		}    	}    	     	return $booksArray;    }        /**     * 得到用户最近阅读的记录     */    static function get_user_recent_read_books($uid,$distribution_channel_id,$category_type){    	\Log::info('get_user_recent_read_books,distribution_channel_id:'.$distribution_channel_id.' uid:'.$uid);    	$base_category_type = self::get_base_category_type($category_type);    	$booksArray = [];    	    	// 获取用户最近阅读的书籍信息    	$userBook = ReadRecordService::getFirstReadRecord($uid);    	    	if ($userBook) {    		$book = array();    		    		$book['url'] = env('PROTOCOL').'://site'.encodeDistributionChannelId($distribution_channel_id).'.'.env('CUSTOM_HOST').'.com/continue?fromtype='.$base_category_type;    		$channelName = $userBook['channel_name'];    		    		    		//获取男频女频的标签文案    		$womanPromotion = PromotionService::getRandomHeadline(2,1);    		$manPromotion = PromotionService::getRandomHeadline(1,1);    		    		if($channelName == '男频'){    			$book['title'] = $manPromotion[0]['title'];    			$book['description'] = $manPromotion[0]['title'];    		}else{    			$book['title'] = $womanPromotion[0]['title'];    			$book['description'] = $womanPromotion[0]['title'];    		}    		    		//头条的图片从财哥个图库中随机取一张    		$promotionImages = PromotionService::getMessageRandomDocumentCovers(3);    		if ($promotionImages) {    			$book['image'] = $promotionImages[0]['link'];    		}else{    			$book['image'] = $userBook['cover'];    		}    		    		$booksArray = [['title'=>$book['title']],['description'=>$book['description']],['url'=>$book['url']],['image'=>$book['image']]];    	}        	return $booksArray;    }        /**     * 得到指定书籍的所有信息     */    static function get_book_full_infos($books,$category_type=''){    	$booksArray = [];        	//5,获取男频女频的标签文案    	$womanPromotion = PromotionService::getRandomHeadline(2,count($books));    	$manPromotion = PromotionService::getRandomHeadline(1,count($books));    	$promotionNum = 0;    	if ($books) {    		foreach ($books as $key => $value) {    			$channelName = $value->channel_name;    			$cover = $value->cover;    			if($channelName == '男频'){    				$book['title'] = $manPromotion[$promotionNum]['title'];    				$book['description'] = $manPromotion[$promotionNum]['title'];    			}else{    				$book['title'] = $womanPromotion[$promotionNum]['title'];    				$book['description'] = $womanPromotion[$promotionNum]['title'];    			}        			//通过判断书籍是男频还是女频拼接书籍信息的不同标签文案    			//     			if(strpos($bookUrl.$value->url,'?') > -1){    			//     				$urlBook = $value->url = $bookUrl.$value->url.'&fromtype='.$category_type.'&source=wechatmsg';    			//     			}else{    			//     				$urlBook = $value->url = $bookUrl.$value->url.'?fromtype='.$category_type.'&source=wechatmsg';    			//     			}    			$book['url'] = $value->url;    			// $book['image'] = $cover;    			if ($promotionNum == 0) {    				//第一条图片选用图库中的图片地址    				$promotionImages = PromotionService::getMessageRandomDocumentCovers(3);    				if ($promotionImages) {    					$book['image'] = $promotionImages[0]['link'];    				}else{    					$book['image'] = $cover;    				}    					    			}else{    				$book['image'] = $cover;    			}    			$booksArray[$key] = [['title'=>$book['title']],['description'=>$book['description']],['url'=>$book['url']],['image'=>$book['image']]];        			$promotionNum++;        		}    	}        	return $booksArray;    }//-------------------------------------------------客服消息配置开关Start---------------------------CustomMsgSwitchs    /**     * 开启或关闭客服消息     */    static function customMsgSwitchSetting($distribution_channel_id,$custom_category,$status,$is_self_content=0)    {        try {            //获取分销渠道下指定的一个智能推送            $customMsgSwitch = CustomMsgSwitchsMsgs::customMsgSwitchsByChannelCate($distribution_channel_id,$custom_category);            if (!empty($customMsgSwitch)) {                //设置推送状态 1,开启    2,关闭                $customMsgSwitch['status'] = $status;                $customMsgSwitch['is_self_content'] = $is_self_content;                $customMsgSwitch->save();                return 1;            }else{                return 0;            }        } catch (\Exception $e) {            return 2;        }    }    /**     * 根据distribution_channel_id获取客服消息开关     */    static function customMsgSwitchsByChannelId($distribution_channel_id)    {    	\Log::info('customMsgSwitchsByChannelId_start:'.$distribution_channel_id);    	$result = array();    	// 渠道个性配置    	$custom_msg_switch_infos = self::GetCustomMsgSwitchsByChannelId($distribution_channel_id);    	// 基础素材配置    	$customMsgSwitchs = CustomMsgSwitchs::getCustomMsgSwitchByCategorys();    	\Log::info('$custom_msg_switch_infos');\Log::info($custom_msg_switch_infos);    	\Log::info('$customMsgSwitchs');\Log::info($customMsgSwitchs);    	// 组装素材,全部后台配置    	foreach($custom_msg_switch_infos as $key => $custom_msg_switch_info){//     		\Log::info($custom_msg_switch_info);    		$customMsgSwitch = $customMsgSwitchs[$custom_msg_switch_info->custom_category];    		// 不展示    		if($customMsgSwitch['status'] == 0){    			continue;    		}    		$result[$key]['status'] = $custom_msg_switch_info->status;    		$result[$key]['id'] = $custom_msg_switch_info->id;    		$result[$key]['custom_category'] = $custom_msg_switch_info->custom_category;    		$result[$key]['distribution_channel_id'] = $custom_msg_switch_info->distribution_channel_id;    		$result[$key]['title'] = $customMsgSwitch['title'];    		$result[$key]['desc_content'] = $customMsgSwitch['desc_content'];    		$result[$key]['img_url'] = $customMsgSwitch['img_url'];    		$result[$key]['common_is_self_content'] = $customMsgSwitch['is_self_content'];    		$result[$key]['is_self_content'] = $custom_msg_switch_info->is_self_content;    	}    	return  $result;    }        /**     * 根据distribution_channel_id获取客服消息开关     */    static function GetCustomMsgSwitchsByChannelId($distribution_channel_id)    {        //1,首先尝试获取该渠道下的智能推送开关        $customMsgSwitchsMsgs = CustomMsgSwitchsMsgs::customMsgSwitchsMsgsByChannelId($distribution_channel_id);        if (count($customMsgSwitchsMsgs)>0) {            //2,该渠道下有智能推送的配置信息,开始对比过滤            $customMsgSwitchsMsgsArray = [];            //3,获取智能推送基础配置表的推送开关信息            $customMsgSwitchs = CustomMsgSwitchs::customMsgSwitchs();            //4,判断如果渠道下的只能推送开关数量和基础配置下的相同,则直接返回查到的所有客服开关            if (count($customMsgSwitchsMsgs) == count($customMsgSwitchs)) {                return $customMsgSwitchsMsgs;            }else{                //5,如果数量不一致,则渠道下需要更新智能开关的数量,与配置表保持一致,少补,多的保留                //先循环渠道下所有的只能客服推送数量,通过custom_category关联基础配置表,                //如果渠道下所查询到的custom_category在基础表中不存在,则说明该智能客服推送配置已删除,渠道下也要删除多余的配置项                for ($i=0; $i < count($customMsgSwitchsMsgs); $i++) {                    $customMsgSwitchsSerch = CustomMsgSwitchs::customMsgSwitchsBySwitchId($customMsgSwitchsMsgs[$i]['custom_category']);                    // 有些是需要特殊开着的,多的留着                    if (empty($customMsgSwitchsSerch)) {//                         $customMsgSwitchsMsgs[$i]->delete();                    }else{                        $customMsgSwitchsMsgsArray[] = $customMsgSwitchsMsgs[$i];                    }                }                //再循环基础配置表获取custom_category,看在渠道的智能客服推送配置中是否存在,                //如果不存在,则说明这是最新配置的智能客服推送项,该渠道需要新增一条默认为关闭的智能推送开关                for ($i=0; $i < count($customMsgSwitchs); $i++) {                    $customMsgSwitchsMsg = CustomMsgSwitchsMsgs::customMsgSwitchsByChannelCate($distribution_channel_id,$customMsgSwitchs[$i]['custom_category']);                    if (empty($customMsgSwitchsMsg)) {                        # code...                        $customMsg['custom_category'] = $customMsgSwitchs[$i]['custom_category'];                        if($customMsg['custom_category'] == 'auto_custom_trusteeship'){                        	$customMsg['status'] = '2';// 客服消息托管                        }else{                        	$customMsg['status'] = '1';// 默认开                        }                        $customMsg['distribution_channel_id'] = $distribution_channel_id;                        $customMsgSwitchsMsgNew = CustomMsgSwitchsMsgs::create($customMsg);                        $customMsgSwitchsMsgsArray[] = $customMsgSwitchsMsgNew;                    }                }                //6,同步完成后,返回正确的客服推送信息                return $customMsgSwitchsMsgsArray;            }        }else{            //7,如果该渠道没有智能开关配置,则说明该渠道是新增的渠道,            //通过基础配置表为该渠道创建相应的智能客服推送,默认关闭            $customMsgSwitchsMsgsArray = [];            $customMsgSwitchs = CustomMsgSwitchs::customMsgSwitchs();            if (count($customMsgSwitchs)>0) {                for ($i=0; $i < count($customMsgSwitchs); $i++) {                    $customMsgSwitchsMsg['custom_category'] = $customMsgSwitchs[$i]['custom_category'];                    if($customMsgSwitchsMsg['custom_category'] == 'auto_custom_trusteeship'){                    	$customMsgSwitchsMsg['status'] = '2';// 客服消息托管                    }else{                    	$customMsgSwitchsMsg['status'] = '1';// 默认开                    }                    $customMsgSwitchsMsg['distribution_channel_id'] = $distribution_channel_id;                    $customMsgSwitchsMsgNew = CustomMsgSwitchsMsgs::create($customMsgSwitchsMsg);                    $customMsgSwitchsMsgsArray[] = $customMsgSwitchsMsgNew;                }            }            return $customMsgSwitchsMsgsArray;        }    }    /**     * 获取指定客服消息开关     */    static function customMsgSwitchsByChannelCate($distribution_channel_id,$custom_category)    {        return CustomMsgSwitchsMsgs::customMsgSwitchsByChannelCate($distribution_channel_id,$custom_category);    }//-------------------------------------------------客服消息配置开关End---------------------------CustomMsgSwitchs//-------------------------------------------------编辑发送客服消息Start---------------------------CustomSendMsg    /**     * 根据distribution_channel_id获取发送客服消息列表     */    static function customSendMsgsByChannelId($distribution_channel_id)    {        return CustomSendMsgs::customSendMsgsByChannelId($distribution_channel_id);    }        /**     * 搜索     */    static function searchCustomSendMsgs($param,$is_all = false)    {        	return CustomSendMsgs::searchCustomSendMsgs($param,$is_all);        }        /**     * 根据distribution_channel_id和托管信息获取发送客服消息列表     */    static function customSendMsgsByChannelIdAndTrusteeship($customerPrams)    {        	return CustomSendMsgs::customSendMsgsByChannelIdAndTrusteeship($customerPrams['distribution_channel_id'],$customerPrams['trusteeship']);        }        /**     * 根据托管信息获取发送客服消息列表     */    static function customSendMsgsByTrusteeship($customerPrams)    {        	return CustomSendMsgs::customSendMsgsByTrusteeship($customerPrams['trusteeship']);        }    /**     * 托管信息信息     * @param $day     * @return mixed     */    public static function customSendMsgsByTrusteeshipGroup($day){        return CustomSendMsgs::where('trusteeship',1)            ->where('del_flag',0)            ->where('send_time','>=',$day)            ->where('send_time','<=',$day.' 23:59:59')            ->groupBy('distribution_channel_id')            ->select('distribution_channel_id',DB::raw('GROUP_CONCAT(id) as ids'),DB::raw('sum(user_num) as user_num'))            ->get();    }    /**     * 托管信息信息     * @param $day     * @return mixed     */    public static function customSendMsgsByTrusteeshipByChannelId($distribution_channel_id,$date){        return CustomSendMsgs::where('trusteeship',1)            ->where('del_flag',0)            ->where('distribution_channel_id','=',$distribution_channel_id)            ->where('send_time','>=',$date)            ->groupBy('distribution_channel_id')            ->select(DB::raw('GROUP_CONCAT(id) as ids'),DB::raw('sum(user_num) as user_num'))            ->first();    }        /**     * 根据托管信息获取发送客服消息列表     */    static function customSendMsgsByTrusteeshipAndBacthNo($customerPrams)    {        	return CustomSendMsgs::customSendMsgsByTrusteeshipAndBacthNo($customerPrams['trusteeship'],$customerPrams['batch_no']);        }        //判断1小时内是否有相同的客服消息插入过    static function isSendCustomerAtSameTime($customerPrams){        return CustomSendMsgs::isSendCustomerAtSameTime($customerPrams['distribution_channel_id'],$customerPrams['appid'],$customerPrams['send_time']);    }        //判断1小时内是否有相同的客服消息插入过    static function isSendCustomerAtSameTimeAndSex($customerPrams){        	return CustomSendMsgs::isSendCustomerAtSameTimeAndSex($customerPrams['distribution_channel_id'],$customerPrams['appid'],$customerPrams['send_time'],$customerPrams['sex']);        }    /**     * 根据task_id获取发送客服消息     */    static function customSendMsgsByTaskid($task_id)    {        return CustomSendMsgs::customSendMsgsByTaskid($task_id);    }    /**     * 根据id获取发送客服消息     */    static function customSendMsgsById($id)    {        return CustomSendMsgs::customSendMsgsById($id);    }    /**     * 停止客服消息发送     */    static function updateCustomSendMsgsStatus($id)    {        try {            $customSendMsgs = CustomSendMsgs::customSendMsgsById($id);            if (!empty($customSendMsgs)) {                if($customSendMsgs['status'] == '8'){                    \Log::info('该客服已经在发送状态,不允许编辑'.$customSendMsgs['task_id']);                    return 4;                }                $customSendMsgs['status'] = '4';                $customSendMsgs->save();                $officialAccountArray = $customSendMsgs->toArray();                Redis::hset('send_wechat_msg:task_id:'.$customSendMsgs['task_id'], 'wechat_msg', json_encode($officialAccountArray));                return 1;            }else{                return 2;            }        } catch (\Exception $e) {        	\Log::info('updateCustomSendMsgsStatus_ept:'.$e->getMessage());            return 0;        }    }        /**     * 更新客服消息发送,兼容删除     */    static function updateCustomSendMsgsStatusMulty($id,$status,$del_flag=0)    {    	try {        		$customSendMsgs = CustomSendMsgs::customSendMsgsById($id);    		if (!empty($customSendMsgs)) { // 由于批次状态暂时不更新,所以子渠道强制更新状态//     			if($customSendMsgs['status'] == '8'){//     				\Log::info('updateCustomSendMsgsStatusMulty,status=8:'.$customSendMsgs['task_id']);//     				return 4;//     			}        			$customSendMsgs['status'] = $status;    			$customSendMsgs['del_flag'] = $del_flag;    			$customSendMsgs->save();        			$officialAccountArray = $customSendMsgs->toArray();    			Redis::hset('send_wechat_msg:task_id:'.$customSendMsgs['task_id'], 'wechat_msg', json_encode($officialAccountArray));    			return 1;    		}else{    			return 2;    		}        	} catch (\Exception $e) {    		\Log::info('updateCustomSendMsgsStatusMulty_ept:'.$e->getMessage());    		return 0;    	}            }    /**     * 发送客服消息     */    static function addCustomSendMsgs($customSendMsgsPrams)    {        try {            $appids = $customSendMsgsPrams['appid'];            $appidArray  = explode(',', $appids);            $usercountnum = 0;            $customSendMsgsPrams['task_id'] = 'custom_#'.$customSendMsgsPrams['distribution_channel_id'].'#'.md5(uniqid());            //4,先在数据库创建一条新的客服消息            $customSendMsgsPrams['user_num'] = 0;            $customSendMsgsPrams['del_flag'] = 0;            $customSendMsgs = CustomSendMsgs::create($customSendMsgsPrams);            $customSendMsgsPrams['id'] = $customSendMsgs['id'];            $officialAccountArray = $customSendMsgs->toArray();            Redis::hset('send_wechat_msg:task_id:'.$customSendMsgs['task_id'], 'wechat_msg', json_encode($officialAccountArray));            return 1;        } catch (\Exception $e) {            \Log::info('===================================发送客服消息报错');            \Log::info($e->getMessage());            return 0;        }    }    /**     * 修改客服消息     */    static function editCustomSendMsgs($customSendMsgsPrams)    {        try {                        $customSendMsgs = CustomSendMsgs::customSendMsgsById($customSendMsgsPrams['id']);            if ($customSendMsgs) {                if($customSendMsgs['status'] == '8'){                    \Log::info('该客服已经在发送状态,不允许编辑'.$customSendMsgs['task_id']);                    return 4;                }                //1,先把原来的客服消息停止并删除                $customSendMsgs['status'] = '4';                $customSendMsgs['del_flag'] = 1;                $customSendMsgs->save();                $officialAccountArray = $customSendMsgs->toArray();                Redis::hset('send_wechat_msg:task_id:'.$customSendMsgs['task_id'], 'wechat_msg', json_encode($officialAccountArray));//                    Redis::hset('send_wechat_msg:task_id:'.$customSendMsgs['task_id'], 'wechat_msg', '[{user_num:'.$customSendMsgs['user_num'].'},{appid:'.$customSendMsgs['appid'].'},{name:'.$customSendMsgs['name'].'},{send_time:'.$customSendMsgs['send_time'].'},{content:'.$customSendMsgs['content'].'},{redirect_url:'.$customSendMsgs['redirect_url'].'},{distribution_channel_id:'.$customSendMsgs['distribution_channel_id'].'},{subscribe_time:'.$customSendMsgs['subscribe_time'].'},{sex:'.$customSendMsgs['sex'].'},{balance:'.$customSendMsgs['balance'].'},{order_type:'.$customSendMsgs['order_type'].'},{category_id:'.$customSendMsgs['category_id'].'}]');                $isSendCustomer = self::isSendCustomerAtSameTime($customSendMsgsPrams);                if (!empty($isSendCustomer)) {                    \Log::info('已经发送过该客服消息');                    \Log::info($isSendCustomer['id']);                    \Log::info($isSendCustomer['status']);                    \Log::info($isSendCustomer['del_flag']);                    return 3;                }                //2,创建一条新的模板消息                $appids = $customSendMsgsPrams['appid'];                $appidArray  = explode(',', $appids);                $usercountnum = 0;                $customSendMsgsPrams['task_id'] = 'custom_#'.$customSendMsgsPrams['distribution_channel_id'].'#'.md5(uniqid());                //4,先在数据库创建一条新的客服消息                $customSendMsgsPrams['user_num'] = 0;                $customSendMsgsPrams['del_flag'] = 0;                $customSendMsgs = CustomSendMsgs::create($customSendMsgsPrams);                $customSendMsgsPrams['id'] = $customSendMsgs['id'];                $officialAccountArray = $customSendMsgs->toArray();                Redis::hset('send_wechat_msg:task_id:'.$customSendMsgs['task_id'], 'wechat_msg', json_encode($officialAccountArray));                return 1;            }else{                return 2;            }        } catch (\Exception $e) {            \Log::info('===================================发送客服消息报错');            \Log::info($e->getMessage());            return 0;        }    }     /**     * 删除客服消息     */    static function delCustomSendMsgs($customSendMsgsPrams)    {        try {                            $customSendMsgs = CustomSendMsgs::customSendMsgsById($customSendMsgsPrams['id']);                if ($customSendMsgs) {                    if($customSendMsgs['status'] == '8'){                        \Log::info('该客服已经在发送状态,不允许编辑'.$customSendMsgs['task_id']);                        return 4;                    }                    //1,先把原来的客服消息停止并删除                    $customSendMsgs['status'] = '4';                    $customSendMsgs['del_flag'] = 1;                    $customSendMsgs->save();                    $officialAccountArray = $customSendMsgs->toArray();                    Redis::hset('send_wechat_msg:task_id:'.$customSendMsgs['task_id'], 'wechat_msg', json_encode($officialAccountArray));                    return 1;                                    }else{                    return 2;                }        } catch (\Exception $e) {            \Log::info('===================================发送客服消息报错');            \Log::info($e->getMessage());            return 0;        }    }    /**     * 测试发送客服消息     */    static function testAddCustomSendMsgs($customSendMsgsPrams)    {        try {        	// 测试链接加上域名        	$customSendMsgsPrams['content'] = TemplateCustomSendService::convert_custom_content($customSendMsgsPrams['content'], 'test', $customSendMsgsPrams['distribution_channel_id'],0);        	             $appids = $customSendMsgsPrams['appid'];             $appidArray  = explode(',', $appids);            for ($j=0; $j < count($appidArray); $j++) {            	\Log::info('testAddCustomSendMsgs_appid:'.$appidArray[$j]);                //1,获取指定的用户                $forceSubscribeUserPram['uid'] = $customSendMsgsPrams['uid'];                $forceSubscribeUserPram['appid'] = $appidArray[$j];                $forceSubscribeUserPram['distribution_channel_id'] = $customSendMsgsPrams['distribution_channel_id'];                $force_user = array();                $temp_force_user =  ForceSubscribeService::forceSubscribeUsersByUidAndAppidAndChannelId($forceSubscribeUserPram);                \Log::info('temp_force_user');\Log::info($temp_force_user);                if(count($temp_force_user) == 0){                	\Log::info('testAddCustomSendMsgs_has_no_user:'.$customSendMsgsPrams['uid']);                	$direct_user = array('openid'=>$customSendMsgsPrams['uid']);                	$force_user[] = $direct_user;                }else{                	$force_user = $temp_force_user;                }                \Log::info('force_user');\Log::info($force_user);                                if (count($force_user)>0) {                    for ($i=0; $i < count($force_user); $i++) {                        //2,测试循环用户发送客服消息                        $data = array();                        $data['openid'] = $force_user[$i]['openid'];                        $data['appid'] = $appidArray[$j];                        $data['news_content'] = $customSendMsgsPrams['content'];                        $data['type'] = 'last_task';                        $data['task_id'] = 'custom_f69556c4eb5274cefdb9ba0a477736366';                        $data['send_time'] = date("Y-m-d H:i:s");                        $send_data=array(                            'send_time'=>date("Y-m-d H:i:s"),                            'data' => $data                        );                        $delay = 0;                        // \Log::info('客服消息找到用户并发送===================================');                        \Log::info('test_custom_msg_send:'.$data['openid']);                        // \Log::info($data['appid']);                        \Log::info($data['news_content']);                        $job = (new SendNews($send_data))->onConnection('rabbitmq')->delay($delay)->onQueue('send_news_list');                        dispatch($job);                    }                                   }            }            return 1;                    } catch (\Exception $e) {            \Log::info('===================================');            \Log::info($e->getMessage());            return 0;        }    }//-------------------------------------------------编辑发送客服消息End---------------------------CustomSendMsg//-------------------------------------------------生成图文链接Start---------------------------    /**     * 上传微信图片     * @param unknown_type $gzh_app_id     * @param unknown_type $img_url     * @param unknown_type $group_nick     * @param unknown_type $timestamp     */    static function upload_material_img($param) {    	$params = array("gzh_app_id"=>$param['gzh_app_id'],"img_url"=>$param['img_url'],"group_nick"=>$param['group_nick'],"timestamp"=>$param['timestamp']);    	$sign = get_sign($params);    	    	//获取封面图片media_id    	$mediaCustomerJson = self::getUserClient()->request("GET","upload_material_img/",    			['query'=>['gzh_app_id'=>$param['gzh_app_id'],'img_url'=>$param['img_url'],'group_nick'=>$param['group_nick'],'timestamp'=>$param['timestamp'],'sign'=>$sign],'connect_timeout' => 3]    	)->getBody()->getContents();    	    	\Log::info("alter_upload_material_img:".$param['gzh_app_id'].' img_url:'.$param['img_url']);    	\Log::info($mediaCustomerJson);    	    	$mediaCustomerArray = json_decode($mediaCustomerJson,true);    	return $mediaCustomerArray;    }        public static function multy_upload_material_imgs($content,$last_urls,$base_param){    	\Log::info('multy_upload_material_imgs_start');    	\Log::info('last_urls');\Log::info($last_urls);    	$multy_urls = [];    	foreach($last_urls as $last_url){    		if(strpos($last_url,'mmbiz.qpic.cn') > -1){    			\Log::info('wx_url_continue:'.$last_url);    			continue;    		}    		$last_url = str_replace(array("&",""","amp;","quot;"), "", 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;    }        /**     * 转化章节图片为微信的url     * @param unknown_type $content     */    static function convert_content_wechat_url($content,$param){    	\Log::info('convert_content_wechat_url_start:'.json_encode($param));    	// 获取url list    	// 防封模式、第一条封面图要去掉    	//<img src="http://yueduyun.oss-cn-hangzhou.aliyuncs.com/book_chapter_image_test/5pNo6A7wqQmB1WgQygDjkOM9VZn2vXeY/1/1_0.jpg"    	preg_match_all('/<img src="(.*)"/U',$content,$ff_matchs);    	$ff_urls = isset($ff_matchs[1])?$ff_matchs[1]:array();    	if(isset($ff_urls[0])){    		unset($ff_urls[0]);    	}    	\Log::info('ff_matchs:');    	\Log::info($ff_urls);    	    	// 背景图模式    	//background: url("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 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;    }    }
 |