package com.yiqi.delay.impl;

import cn.hutool.json.JSONUtil;
import com.yiqi.common.core.redis.RedisUtils;
import com.yiqi.delay.DelayMessage;
import com.yiqi.delay.DelayQueueCache;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author douya
 * @version 1.0
 * @date 2020/4/8 23:20
 * @desc 延迟队列缓存管理
 */
@Component
public class DelayQueueCacheManager implements DelayQueueCache {

    @Resource
    private RedisUtils redisUtils;

    private final static String DELAY_TASK_CACHE = "DELAY_TASK_CACHE";

    @Override
    public void addDelayJob(DelayMessage delayMessage, long delaySeconds) {
        //redis 中排序时间
        long seconds = System.currentTimeMillis() / 1000 + delaySeconds;
        delayMessage.setRunTime(seconds);
        //如果唯一key存在，则记录，这种情况可以删除延迟队列逻辑
        if (StringUtils.isNotBlank(delayMessage.getUniqueKey())) {
            redisUtils.set(DELAY_TASK_CACHE + ":KEY:" + delayMessage.getUniqueKey(), JSONUtil.toJsonStr(delayMessage), 24 * 3600 * 15);
        }
        //增加延时任务 参数依次为：队列名称、执行时间、任务id
        redisUtils.zAdd(DELAY_TASK_CACHE, delayMessage.getUniqueKey(), seconds);
    }

    @Override
    public void deleteDelayJob(String uniqueKey) {
        redisUtils.zRemove(DELAY_TASK_CACHE, uniqueKey);
        redisUtils.del(DELAY_TASK_CACHE + ":KEY:" + uniqueKey);
    }

    @Override
    public DelayMessage getDelayMessageByKey(String uniqueKey) {
        String message = redisUtils.get(DELAY_TASK_CACHE + ":KEY:" + uniqueKey);
        return message != null ? JSONUtil.toBean(message, DelayMessage.class) : null;
    }
}
