package com.sqx.common.utils;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.sqx.modules.redisService.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Component;

import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Redis工具类
 */
@Component
public class RedisUtils {
    @Autowired
    private RedisService redisService;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private ValueOperations<String, String> valueOperations;
    @Autowired
    private HashOperations<String, String, Object> hashOperations;
    @Autowired
    private ListOperations<String, Object> listOperations;
    @Autowired
    private SetOperations<String, Object> setOperations;
    @Autowired
    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();


    public <T> Map<String, List<T>> getMapData(String key, String method, Class<T> clazz) {
        String jsonStr = getDate(key, method);
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            JsonNode jsonNode = objectMapper.readTree(jsonStr);

            return jsonNodeToMap(jsonNode, clazz);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public <T> List<T> getListData(String key, Class<T> clazz, String method) {
        String jsonStr = getDate(key, method);
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            // 将JSON字符串转换为List<T>
            return objectMapper.readValue(jsonStr, objectMapper.getTypeFactory().constructCollectionType(List.class, clazz));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取缓存里的数据 如果不存在 则插入 并返回
     *
     * @param key    redis Key
     * @param clazz  返回类型
     * @param method RedisService调用的方法名 如果数据不存在会执行该调用方法
     */
    public <T> T getObjectDate(String key, Class<T> clazz, String method) {
        String jsonStr = getDate(key, method);
        return this.fromJson(jsonStr, clazz);
    }

    public <T> T getObjectDate(String key, Class<T> clazz) {
        String jsonStr = get(key);
        return this.fromJson(jsonStr, clazz);
    }

    public String getDate(String key, String method) {
        if (!this.hasKey(key)) {
            try {
                // 获取Lookup对象
                MethodHandles.Lookup lookup = MethodHandles.lookup();
                // 构建方法类型（这里假设方法无参数，返回类型为void）
                MethodType methodType = MethodType.methodType(void.class, String.class);
                // 获取方法句柄
                MethodHandle methodHandle = lookup.findVirtual(redisService.getClass(), method, methodType);
                // 调用方法句柄
                methodHandle.invoke(redisService, key);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            } catch (Throwable e) {
                throw new RuntimeException(e);
            }
        }
        return this.get(key);
    }

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

    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 boolean setIfAbsent(String key, Object value, long expire){
        Boolean absent = valueOperations.setIfAbsent(key, toJson(value));
        if (Boolean.FALSE.equals(absent)) {
            return false;
        }
        if(expire != NOT_EXPIRE){
            redisTemplate.expire(key, expire, TimeUnit.SECONDS);
        }

        return true;

    }

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

    public void expire(String key, long seconds){
        redisTemplate.expire(key, seconds, TimeUnit.SECONDS);
    }

    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 boolean isExpiredSet(String key) {
        // 获取过期时间，单位是秒
        Long expireTime = redisTemplate.getExpire(key);

        if (expireTime == null) {
            return false; // 如果返回 null，表示键不存在
        }

        return expireTime != -1; // 如果是 -1，说明没有设置过期时间
    }

    public Long getExpire(String key) {
        Long currentExpireTime = redisTemplate.getExpire(key);
        if (currentExpireTime == null || currentExpireTime == -2 || currentExpireTime == -1) {
            return null;
        }
        return currentExpireTime;
    }

    // 累加过期时间
    public boolean extendExpireTime(String key, long additionalTimeInSeconds) {
        // 获取当前键的剩余过期时间（单位：秒）
        Long currentExpireTime = redisTemplate.getExpire(key);

        if (currentExpireTime == null || currentExpireTime == -2) {
            // 键不存在或已经过期，无法进行累加
            return false;
        }

        if (currentExpireTime == -1) {
            redisTemplate.expire(key, additionalTimeInSeconds, java.util.concurrent.TimeUnit.SECONDS);
        }

        // 累加剩余过期时间和新增时间
        long newExpireTime = currentExpireTime + additionalTimeInSeconds;

        // 设置新的过期时间
        return Boolean.TRUE.equals(redisTemplate.expire(key, newExpireTime, TimeUnit.SECONDS));
    }

    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) {
            redisTemplate.expire(key, expire, TimeUnit.SECONDS);
        }
        return value;
    }

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

    /**
     * 对指定的键执行自增操作，返回自增后的值
     *
     * @param key 要自增的键
     * @return 自增后的值，如果键不存在则初始化为1后返回1，如果出现异常返回null
     */
    public Long incr(String key) {
        try {
            return redisTemplate.opsForValue().increment(key);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public void delete(String key) {
        redisTemplate.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 Gson.toJson(object);
    }

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


    public <T> Map<String, List<T>> jsonNodeToMap(JsonNode jsonNode, Class<T> clazz) {
        Map<String, List<T>> resultMap = new HashMap<>();
        ObjectMapper objectMapper = new ObjectMapper();

        if (jsonNode.isObject()) {
            // 获取字段名（也就是键）的迭代器
            Iterator<String> fieldNames = jsonNode.fieldNames();
            while (fieldNames.hasNext()) {
                String key = fieldNames.next();
                JsonNode elementNode = jsonNode.get(key);
                resultMap.put(key, objectMapper.convertValue(elementNode,
                        objectMapper.getTypeFactory().constructCollectionType(List.class, clazz)));
            }
        }
        return resultMap;
    }
}
