<?php


namespace Daemon;


use Api\PhpServices\Daemon\DaemonServiceInterface;
use Api\PhpUtils\Log\DaemonLog;
use App\Models\marketing\mysql\Marketing;
use Api\PhpServices\Wechat\Msg;
use App\Models\marketing\mysql\MarketingPindan;

class Pindan implements DaemonServiceInterface
{
    const DEFAULT_DESC = '9.9元吃午餐开始预定啦，戳这里点餐吧';

    public function run()
    {
        //只在16:40执行逻辑
        if(date('H') != 16 || date('i')!= 40) {
            sleep(5);
            return false;
        }

        try{
            //查询进行中的 今天开始的 拼单活动 --昨天16:40以后开始的活动 视为新上的活动
            $lastStartTime = date("Y-m-d 16:40:00",strtotime('-1 days'));
            $now = date("Y-m-d H:i:00");
            $where['marketing_type'] = 4;
            $where['online_status'] = 1;
            $where["start_time[<=]"] = $now;
            $where["start_time[>]"] = $lastStartTime;
            $where["end_time[>=]"] = $now;
            $where['ORDER'] = ["update_time" => "DESC"];
            $marketing = Marketing::get(['marketing_id','marketing_name','start_time'], $where);

            if(empty($marketing)) {
                DaemonLog::info(
                    'DaemonServiceInterface_pindan',
                    'no need to send at'.date('Y-m-d H:i:s')
                );
                sleep(60);
                return false;
            }
            $pindan = MarketingPindan::get(["pindan_desc"], ["marketing_id" => $marketing["marketing_id"]]);

            //给订阅用户发送消息
            //http://ydwiki.yidian-inc.com/pages/viewpage.action?pageId=71667995
            $app_id = 'wx4e0d92499185fb74';
            $template_id = 'LqGgPLdQPh2CHAFN1B8UK7NVc4LQt2zpjOZoyNuwaEI';
            $page_url = '/pages/home/index?messageNotify=1';
            $type = 2; // 1 公众号 2 小程序
            //活动信息
            $params = [
                self::emojiFilter($marketing['marketing_name']),
                $marketing['start_time'],
                $pindan['pindan_desc'] ?: self::DEFAULT_DESC,
                $marketing['marketing_id']
            ];

            //发送消息
            DaemonLog::info(
                'DaemonServiceInterface_pindan',
                'send at '.date('Y-m-d H:i:s').' params:'.json_encode($params)
            );
            Msg::send(999, $app_id, $template_id, $page_url, $type, $params);

            sleep(60);//保证16:40只执行一次
        }catch (Exception $e) {
            DaemonLog::error(
                'DaemonServiceInterface_pindan',
                'params:'.json_encode($params).' exception:'.$e->getMessage()
            );
        }
    }

    /**
     * 过滤emoji表情
     * @param string $str
     * @return string
     */
    private function emojiFilter($str) {
        $str = preg_replace_callback('/./u',function(array $match){
            return strlen($match[0]) >= 4 ? '' : $match[0];
        },$str);

        return $str;
    }
}