MsgLogService.class.php 2.19 KB
<?php
/**
 * 直播消息通知记录表 (防止重复推送)
 */

namespace Common\Service;

use Common\Common\Constant;
use Common\Model\MsgLogModel;

class MsgLogService extends AbstractService
{
    // 构造方法
    public function __construct()
    {
        $this->_d = new MsgLogModel();

        parent::__construct();
    }

    /**
     * 获取目标范围内没有发送过消息的 uids
     * @param int   $lmId
     * @param array $rangeUids 范围对象内的人员 ID
     * @param bool  $rangeIsAll 如果范围是全公司
     * @return array
     */
    public function sendMsgRangeDiffUids($lmId, $rangeUids, $rangeIsAll = false)
    {
        // 获取历史消息推送记录
        $msgLogList = [];
        $msgLogServ = new MsgLogService();
        if (!empty($lmId)) {
            $msgLogConds = ['lm_id' => $lmId, 'type' => MsgLogModel::TYPE_LIVE_PUSH];
            $msgLogList = $msgLogServ->list_by_conds($msgLogConds);
        }

        if (!empty($msgLogList)) {
            // 有全公司 不用再发消息了
            if (in_array(Constant::RANGE_TYPE_ALL, array_column($msgLogList, 'obj_id'))) {
                return [];
            }

            // 去掉已经发过的
            foreach ($msgLogList as $item) {
                $uids = explode(',', $item['obj_id']);
                $rangeUids = array_diff($rangeUids, $uids);
            }
        }

        // 写入数据库
        if (!empty($rangeUids)) {
            // 如果是全公司
            if ($rangeIsAll) {
                $msgLogServ->insert([
                    'lm_id' => $lmId,
                    'obj_id' => Constant::RANGE_TYPE_ALL,
                    'type' => MsgLogModel::TYPE_LIVE_PUSH
                ]);
            } else {
                $insertLog = [];
                foreach (array_chunk($rangeUids, Constant::OBJ_ID_SINGLE_TOTAL) as $item) {
                    $insertLog[] = [
                        'lm_id' => $lmId,
                        'obj_id' => implode(',', $item),
                        'type' => MsgLogModel::TYPE_LIVE_PUSH
                    ];
                }
                $msgLogServ->insert_all($insertLog);
            }
        }

        return $rangeUids;
    }
}