package com.nmgs.util;

import com.alibaba.fastjson.JSON;
import com.nmgs.config.RedisSessionConfig;
import com.nmgs.entity.Consistant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;

import java.util.concurrent.TimeUnit;

@Component
public class redisConfigUtil {
    public  static  RedisTemplate<String, Object> redisTemplate;

    @Autowired
    public redisConfigUtil(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }


    /**
     * 消息发布
     *key  频道值
     * value 发送的内容
     * @param key
     */
    public static void publish(String key, String value) {
        redisTemplate.convertAndSend(key, value);
    }

    /**
     * 删除积分核销的KEY
     * @param key
     * @return
     */
    public static Long delIntegral(String key){
        if (redisTemplate == null) {
            return -1L;
        }

        Boolean exists = redisTemplate.hasKey(Consistant.INTEGRAL_PRE + key);
        if(exists){
            redisTemplate.delete(Consistant.INTEGRAL_PRE + key);
        }
        return 0L;
    }

    /**
     * 设置积分核销，设置缓存的数据, 缓存35s
     * @param key
     * @param obj
     * @return
     */
    public static Long setIntegral(String key, String obj) {
        if (redisTemplate == null) {
            return -1L;
        }
        redisTemplate.opsForValue().set(Consistant.INTEGRAL_PRE + key, obj, 35, TimeUnit.SECONDS);
        return 0L;
    }

    /**
     * 设置积分核销，获取缓存的数据
     * @param key
     * @return
     */
    public static Object getIntegral(String key){
        if (redisTemplate == null) {
            return null;
        }
        Boolean exists = redisTemplate.hasKey(Consistant.INTEGRAL_PRE + key);
        if(exists){
            return redisTemplate.opsForValue().get(Consistant.INTEGRAL_PRE + key);
        }else{
            return null;
        }
    }

    /**
     * 设置缓存的数据
     *
     * @param key
     * @param obj
     * @return
     */
    public static Long set(String key, String obj) {
        if (redisTemplate == null) {
            return -1L;
        }
        redisTemplate.opsForValue().set(key, obj);
        return 0L;
    }

    /**
     * 获取缓存的数据
     *
     * @param key
     * @return
     */
    public static Object get(String key) {
        if (redisTemplate == null) {
            return null;
        }
        Boolean exists = redisTemplate.hasKey(key);
        if (exists) {
            return redisTemplate.opsForValue().get(key);
        } else {
            return null;
        }
    }

}
