package com.xhkjedu.utils;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.TimeUnit;

/**
 * @author ywx
 * @classname JedisUtil
 * @description Redis工具类
 * @date 2019/8/2 16:48
 **/
@Component
public class JedisUtil {
	@Autowired
	private StringRedisTemplate stringRedisTemplate;
	private ValueOperations<String, String> valueOperations;

	@PostConstruct
	public void init(){
		this.valueOperations = stringRedisTemplate.opsForValue();
	}

	/**  不设置过期时长 */
	public final static long NOT_EXPIRE = -1;

	public boolean set(String key, Object value, Integer expire){
		boolean rtn = false;
		valueOperations.set(key, toJson(value));
		if(expire != NOT_EXPIRE){
			rtn = stringRedisTemplate.expire(key, expire, TimeUnit.SECONDS);
		}
		return rtn;
	}

	public Boolean setObject(String key, Object value, int cacheSeconds) {
		String val = toJson(value);
		return set(key,val,cacheSeconds);
	}

	public <T> T get(String key, Class<T> clazz, long expire) {
		String value = valueOperations.get(key);
		if(expire != NOT_EXPIRE){
			stringRedisTemplate.expire(key, expire, TimeUnit.SECONDS);
		}
		return value == null ? null : fromJson(value, clazz);
	}

	public <T> T get(String key, Class<T> clazz) {
		return get(key, clazz, NOT_EXPIRE);
	}

	public String get(String key, long expire) {
		String value = valueOperations.get(key);
		if (expire != NOT_EXPIRE) {
			stringRedisTemplate.expire(key, expire, TimeUnit.SECONDS);
		}
		return value;
	}

	public String get(String key) {
		try {
			return get(key, NOT_EXPIRE);
		} catch (Exception e) {
			return "0";
		}
	}

	//获取剩余有效期
	public Long getExpire(String key) {
		return stringRedisTemplate.getExpire(key);
	}

	public Object getObject(String key, Class<?> clazz) {
		String value = get(key);
		return fromJson(value, clazz);
	}

	public boolean delete(String key) {
		return stringRedisTemplate.delete(key);
	}

	/**
	 * Object转成JSON数据
	 */
	private String toJson(Object object){
		if(object instanceof Integer || object instanceof Long || object instanceof Float ||
				object instanceof Double || object instanceof Boolean || object instanceof String){
			return String.valueOf(object);
		}
		return JSON.toJSONString(object);
	}

	/**
	 * JSON数据，转成Object
	 */
	private <T> T fromJson(String json, Class<T> clazz){
		return JSON.parseObject(json, clazz);
	}

}
