<?php


namespace App\Cache\Activity;


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

class ActivityCache
{
    public static function incrActivityPv($activityId, $date)
    {
        $cacheKey = Utils::getCacheKey('activity.statsPv', [$activityId, $date]);
        Redis::incrBy($cacheKey, 1);
        $ttl = Redis::ttl($cacheKey);
        if ((int)$ttl < 1) {
            Redis::expire($cacheKey, BaseConst::ONE_DAY_SECONDS * 3);
        }
        return true;
    }

    public static function zAddActivityUv($activityId, $date, $uid): bool
    {
        $cacheKey = Utils::getCacheKey('activity.statsUv', [$activityId, $date]);
        Redis::zAdd($cacheKey, time(), $uid);
        $ttl = Redis::ttl($cacheKey);
        if ((int)$ttl < 1) {
            Redis::expire($cacheKey, BaseConst::ONE_WEEK_SECONDS);
        }

        return true;
    }

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

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

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

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