package com.yn.bftl.thirdparty.common.redis;

import org.springframework.data.redis.core.StringRedisTemplate;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * 公共redis
 */
abstract class CommonRedis {

    @Resource
    protected StringRedisTemplate stringRedisTemplate;

    final protected static String redisKey = "service:";

    public Boolean hasKey(String reKey) {
        if (reKey == null) return false;
        return Boolean.TRUE.equals(stringRedisTemplate.hasKey(reKey));
    }

    public String hashGet(String reKey, Object hashKey) {
        if (reKey == null) return null;
        return (String) stringRedisTemplate.opsForHash().get(reKey, hashKey);
    }

    public Boolean hashHasKey(String reKey, Object hashKey) {
        if (reKey == null) return false;
        return Boolean.TRUE.equals(stringRedisTemplate.opsForHash().hasKey(reKey, hashKey));
    }

    public Map hashGetAll(String reKey) {
        if (reKey == null) return null;
        return stringRedisTemplate.opsForHash().entries(reKey);
    }

    public void hashPut(String reKey, Object hashKey, Object hashVal) {
        if (reKey == null) return;
        stringRedisTemplate.opsForHash().put(reKey, hashKey, hashVal.toString());
    }

    public void hashDelete(String reKey, Object... hashKeys) {
        if (reKey == null) return;
        stringRedisTemplate.opsForHash().delete(reKey, hashKeys);
    }

    public void hashPutAll(String reKey, Map<String, Object> map) {
        if (reKey == null) return;
        stringRedisTemplate.opsForHash().putAll(reKey, map);
    }

    public Set<String> setGetAll(String reKey) {
        if (reKey == null) return null;
        return stringRedisTemplate.opsForSet().members(reKey);
    }

    public Boolean setIsNotNull(String reKey, Object setVal) {
        if (reKey == null) return null;
        return stringRedisTemplate.opsForSet().isMember(reKey, setVal);
    }

    public Long setAdd(String reKey, String... setVal) {
        if (reKey == null) return null;
        return stringRedisTemplate.opsForSet().add(reKey, setVal);
    }

    /**
     * 设置过期时间
     *
     * @param time
     */
    public Boolean expire(String reKey, long time) {
        if (reKey == null) return false;
        return stringRedisTemplate.expire(reKey, time, TimeUnit.SECONDS);
    }

    public void delete(Set<String> keys) {
        stringRedisTemplate.delete(keys);
    }

    public Set<String> keys(String reKey) {
        if (reKey == null) return null;
        return stringRedisTemplate.keys(reKey + "*");
    }

}
