package com.ruoyi.cai.cache;

import com.ruoyi.cai.constant.RedisConstant;
import com.ruoyi.cai.enums.SystemConfigEnum;
import com.ruoyi.cai.manager.SystemConfigManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;

@Component
public class DynamicTotalCache {

    @Autowired
    private SystemConfigManager systemConfigManager;
    @Autowired
    private StringRedisTemplate redisTemplate;


    public String getKey(Long userId){
        String now = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        return String.format(RedisConstant.DYNAMIC_TOTAL_CACHE_REDIS,now,userId);
    }

    public void add(Long userId){
        String key = getKey(userId);
        redisTemplate.opsForValue().increment(key);
        redisTemplate.expire(key,1, TimeUnit.DAYS);
    }

    public int get(Long userId){
        String va = redisTemplate.opsForValue().get(getKey(userId));
        if(va == null){
            return 0;
        }
        return Integer.parseInt(va);
    }

    public boolean checkAllPush(Long userId){
        String va = redisTemplate.opsForValue().get(getKey(userId));
        if(va == null){
            return true;
        }
        Integer config = systemConfigManager.getSystemConfigOfInt(SystemConfigEnum.DAY_MAX_DYNAMIC);
        if(config > Integer.parseInt(va)){
            return true;
        }
        return false;
    }


}
