package com.xjrsoft.common.utils;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xjrsoft.common.exception.MyException;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

/**
 * @author tzx
 * @description reidis操作工具类
 * @date 2022-03-02
 **/
@Component
@AllArgsConstructor
@Slf4j
public class RedisUtil {

    private RedisTemplate<String, Object> redisTemplate;
    private ValueOperations<String, String> valueOperations;
    private HashOperations<String, String, Object> hashOperations;
    private ListOperations<String, Object> listOperations;
    private SetOperations<String, Object> setOperations;
    private ZSetOperations<String, Object> zSetOperations;
    /**
     * 默认过期时长，单位：秒
     */
    public final static long DEFAULT_EXPIRE = 60 * 60 * 24;
    /**
     * 不设置过期时长
     */
    public final static long NOT_EXPIRE = -1;
//    private final static Gson GSON = new Gson();

    private final ObjectMapper objectMapper;

    public void set(String key, Object value, long expire) {
        valueOperations.set(key, toJson(value));
        if (expire != NOT_EXPIRE) {
            redisTemplate.expire(key, expire, TimeUnit.SECONDS);
        }
    }

    public void set(String key, Object value) {
        set(key, value, NOT_EXPIRE);
    }

    public void setStrValue(String key, String value) {
        valueOperations.set(key, value);
    }


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

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

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

    public <T> T get(String key, TypeReference<T> typeReference) {
        return get(key, typeReference, NOT_EXPIRE);
    }

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

    public String get(String key) {
        return get(key, NOT_EXPIRE);
    }

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

    public Long getExpire(String key) {
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }

    public Boolean isExpired(String key) {
        return redisTemplate.getExpire(key) > 0;
    }

    public Long incr(String key, long delta) {
        if (delta < 0) {
            throw new MyException("递增因子必须大于0");
        }
        return valueOperations.increment(key, delta);
    }

    public Long decr(String key, long delta) {
        if (delta < 0) {
            throw new MyException("递减因子必须大于0");
        }
        return valueOperations.increment(key, -delta);
    }

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

    /**
     * 批量删除
     *
     * @param key
     */
    public void deleteBatch(String key) {
        if (key != null) {

            Set<String> keys = redisTemplate.keys(Pattern.matches("\\*$", key) ? key : key + "*");
            if (keys != null && keys.size() > 0) {
                redisTemplate.delete(keys);
            }
        }
    }

    /**
     * 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);
        }
        try {
            return objectMapper.writeValueAsString(object);
        } catch (IOException e) {
            log.error("toJson(Object)", e); //$NON-NLS-1$
        }
        return null;
//        return GSON.toJson(object);
    }

    /**
     * JSON数据，转成Object
     */
    private <T> T fromJson(String json, Class<T> clazz) {
//        return JSONUtil.toBean(json, clazz, true);
        try {
            return objectMapper.readValue(json, clazz);
        } catch (IOException e) {
            log.error("fromJson(String, Class<T>)", e);
        }
        return null;
    }

    /**
     * JSON数据，转成Object
     */
    private <T> T fromJson(String json, TypeReference<T> typeReference) {
//        return JSONUtil.toBean(json, typeReference, true);
        try {
            return objectMapper.readValue(json, typeReference);
        } catch (IOException e) {
            log.error("fromJson(String, JsonTypeReference<T>)", e);
        }
        return null;
    }
}