<?php
/**
 * Created by PhpStorm.
 * User: gevnc
 * Date: 2018/8/16
 * Time: 14:03
 */

namespace App\Services;


use App\Traits\Singleton;
use Illuminate\Support\Facades\Redis;

class PushMessageService
{
    use Singleton;
    const PUSH_QUEUE_DELAY = "bs_push_queue:delay";

    /**
     * Websocket 消息发送接口
     * @param $channel
     * @param $action
     * @param $data
     * @param $userId
     * @param int $delay
     * @return null
     */
    public function pushByUserId($channel, $action, $data, $userId, $delay = 0)
    {
        $value = [
            "key" => uniqid(),
            "channel" => $channel,
            "action" => $action,
            "data" => $data,
            "user_id" => $userId
        ];

        $userOnlineInfo = UserService::getInstance()->getOnlineInfo($userId);
        if(isset($userOnlineInfo["fd"])){
            if($userOnlineInfo["fd"]>0){
                $server = $userOnlineInfo["server"];
                $score = time() + $delay;
                return Redis::zAdd(self::PUSH_QUEUE_DELAY . ":" . $server, $score, json_encode($value));
            }else{
                return null;
            }
        }else{
            return null;
        }

    }

}