<?php


namespace App\Cache\Push;


use App\Consts\BaseConst;
use App\Libs\Utils;
use Illuminate\Support\Facades\Redis;

class PushCache
{
    /**
     * 获取用户reg id
     * @param $uid
     * @return mixed
     */
    public static function getUserPushRegId($uid)
    {
        $cacheKey = Utils::getCacheKey('push.user', [$uid]);
        return Redis::get($cacheKey);
    }

    /**
     * 设置用户reg id
     * @param $uid
     * @param $regId
     * @return mixed
     */
    public static function setUserPushRegId($uid, $regId)
    {
        $cacheKey = Utils::getCacheKey('push.user', [$uid]);
        return Redis::set($cacheKey, $regId);
    }

    /**
     * 增加pv
     * @param $pushId
     * @param $date
     * @return bool
     */
    public static function incrPushPv($pushId, $date): bool
    {
        if (empty($pushId) || empty($date)) {
            return false;
        }

        $cacheKey = Utils::getCacheKey('push.statsPv', [$pushId, $date]);
        Redis::incrBy($cacheKey, 1);
        $ttl = Redis::ttl($cacheKey);
        if ((int)$ttl < 1) {
            Redis::expire($cacheKey, BaseConst::ONE_DAY_SECONDS * 3);
        }
        return true;
    }

    /**
     * @param $pushId
     * @param $date
     * @param $uid
     * @return bool
     */
    public static function zAddPushUv($pushId, $date, $uid): bool
    {
        if (empty($pushId) || empty($date) || empty($uid)) {
            return false;
        }

        $cacheKey = Utils::getCacheKey('push.statsUv', [$pushId, $date]);
        Redis::zAdd($cacheKey, time(), $uid);
        $ttl = Redis::ttl($cacheKey);
        if ((int)$ttl < 1) {
            Redis::expire($cacheKey, BaseConst::ONE_DAY_SECONDS * 3);
        }

        return true;
    }

    /**
     * 获取pv数
     * @param $pushId
     * @param $date
     * @return int
     */
    public static function getPushyPv($pushId, $date): int
    {
        $cacheKey = Utils::getCacheKey('push.statsPv', [$pushId, $date]);
        $exist    = Redis::exists($cacheKey);
        if (!$exist) {
            return 0;
        }

        return (int)Redis::get($cacheKey);
    }

    /**
     * 获取uv数
     * @param $pushId
     * @param $date
     * @return int
     */
    public static function getPushUv($pushId, $date): int
    {
        $cacheKey = Utils::getCacheKey('push.statsUv', [$pushId, $date]);
        $exist    = Redis::exists($cacheKey);
        if (!$exist) {
            return 0;
        }

        return (int)Redis::zCount($cacheKey, 0, 99999999999999999999999999);
    }
}