package com.rrtx.services.common.redis;

import cn.hutool.json.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author MrBird
 */

/**
 * ClassName: RedisServiceImpl<br>
 * Description: Redis 工具类，只封装了几个常用的 redis 命令， <br>
 *     可根据实际需要按类似的方式扩展即可。
 * Company: rrtx
 * @author rrtx
 * @version v1.0.0    2019/7/24 5:13 PM  xugz    文件初始创建
 *
 */
@Service
public class RedisServiceImpl implements IRedisService {


	@Autowired
	RedisTemplate redisTemplate;



	@Override
	public String get(String key)  {
		return (String)redisTemplate.opsForValue().get(key);
	}

	@Override
	public <T> T getObject(String key, Class<T> requiredType) {
		String value = (String) redisTemplate.opsForValue().get(key);
		T t = JSONUtil.toBean(value, requiredType);
		return t;
	}

	@Override
	public <T> List<T> getList(String key) {
		return (List<T>)redisTemplate.opsForList().range(key, 0, -1);
	}

	@Override
	public String set(String key, String value)  {
		redisTemplate.opsForValue().set(key, value);
		//TODO
		return value;
	}

	@Override
	public String set(String key, String value, Long milliscends)  {
		String result = this.set(key, value);
		this.pexpire(key, milliscends);
		return result;
	}

	@Override
	public <T> void set(String key, List<T> value) {
		redisTemplate.delete(key);
		redisTemplate.opsForList().leftPushAll(key, value);
	}

	@Override
	public <T> void set(String key, List<T> value, Long milliscends) {
		set(key, value);
		redisTemplate.expire(key, milliscends, TimeUnit.MILLISECONDS);
	}

	@Override
	public void set(String key, Serializable obj) {
		String value = JSONUtil.toJsonStr(obj);
		redisTemplate.opsForValue().set(key, value);
	}

	@Override
	public void set(String key, Serializable obj, Long milliscends) {
		set(key, obj);
		redisTemplate.expire(key, milliscends, TimeUnit.MILLISECONDS);
	}

	@Override
	public Long del(String... key) {
		for (int i = 0; i < key.length; i++) {
			redisTemplate.delete(key[i]);
		}
		//
		return Long.valueOf(key.length);
	}

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

	@Override
	public Long pttl(String key)  {
		return redisTemplate.getExpire(key, TimeUnit.MILLISECONDS);
	}

	@Override
	public Long pexpire(String key, Long milliseconds) {
		redisTemplate.expire(key, milliseconds, TimeUnit.MILLISECONDS);
		return milliseconds;
	}


}
