package com.ads.common.redis;

import cn.hutool.core.util.ObjectUtil;
import com.ads.common.util.UtilConst;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;

import java.util.Locale;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author wuyifeng
 * @Description redis工具类
 * @Date 2020/7/29 14:30
 */
@Service
public class RedisManager {

    private RedisTemplate redisTemplate;

    @Autowired(required = false)
    public void setRedisTemplate(RedisTemplate redisTemplate) {
        RedisSerializer stringSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringSerializer);
        redisTemplate.setValueSerializer(stringSerializer);
        redisTemplate.setHashKeySerializer(stringSerializer);
        redisTemplate.setHashValueSerializer(stringSerializer);
        this.redisTemplate = redisTemplate;
    }


    public void set(String key, Object value) {
        ValueOperations<String, Object> operation = redisTemplate.opsForValue();
        operation.set(key, value);
    }

    public void set(String key, Object value, long second) {
        ValueOperations<String, Object> operation = redisTemplate.opsForValue();
        operation.set(key, value, second, TimeUnit.SECONDS);
    }

    public Object get(String key) {
        ValueOperations<String, Object> operation = redisTemplate.opsForValue();
        return operation.get(key);
    }

    /**
     * 获得缓存的语言。
     *
     * @param key      缓存键值
     * @param language 语言
     * @return 缓存键值对应的数据
     */
    public String getLanguage(String key,String language) {
        if (ObjectUtil.isEmpty(language)) {
            language = Locale.SIMPLIFIED_CHINESE.toString();
        }
        String mapKey = UtilConst.CACHE_MY_MESSAGE_KEY + language.toUpperCase();
        ValueOperations<String, String> operation = redisTemplate.opsForValue();
        return operation.get(key + mapKey);
    }


    public void setHash(String key, Map map) {
        HashOperations operation = redisTemplate.opsForHash();
        operation.putAll(key, map);
    }

    public void setHash(String key, Map map,Long hour) {
        HashOperations operation = redisTemplate.opsForHash();
        operation.putAll(key, map);
        redisTemplate.expire(key,hour,TimeUnit.HOURS);
    }

    public Object getHash(String key) {
        HashOperations operation = redisTemplate.opsForHash();
        return operation.entries(key);
    }

    public void delete(String key) {
        redisTemplate.delete(key);
    }

    public Boolean hasKey(String key){
        return redisTemplate.hasKey(key);
    }
}
