package com.njcn.product.event.config;

/**
 * @Author: cdf
 * @CreateTime: 2025-10-28
 * @Description:
 */
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * Redis 工具类 - 基于 RedisTemplate
 */
@Component
@Slf4j
public class RedisUtil {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    // ==================== 通用操作 ====================

    /**
     * 设置缓存
     */
    public void saveByKey(String key, Object value) {
        try {
            redisTemplate.opsForValue().set(key, value);
        } catch (Exception e) {
            log.error("Redis set操作失败 key: {}", key, e);
            throw e;
        }
    }

    /**
     * 设置缓存带过期时间
     */
    public void setex(String key, Object value, long time, TimeUnit timeUnit) {
        try {
            if (time > 0) {
                redisTemplate.opsForValue().set(key, value, time, timeUnit);
            } else {
                saveByKey(key, value);
            }
        } catch (Exception e) {
            log.error("Redis setex操作失败 key: {}", key, e);
            throw e;
        }
    }

    /**
     * 获取缓存
     */
    public Object get(String key) {
        try {
            return key != null ? redisTemplate.opsForValue().get(key) : null;
        } catch (Exception e) {
            log.error("Redis get操作失败 key: {}", key, e);
            throw e;
        }
    }

    /**
     * 获取对象 - 你在代码中使用的方法
     */
    public Object getObjectByKey(String key) {
        return get(key);
    }


    /**
     * 获取value为字符串的
     * @param key
     * @return
     */
    public String getRawValue(String key) {
        return redisTemplate.execute((RedisCallback<String>) connection -> {
            byte[] data = connection.get(key.getBytes());
            return data == null ? null : new String(data, StandardCharsets.UTF_8);
        });
    }

    /**
     * 删除缓存
     */
    public void deleteKeysByString(String... keys) {
        try {
            if (keys != null && keys.length > 0) {
                if (keys.length == 1) {
                    redisTemplate.delete(keys[0]);
                } else {
                    redisTemplate.delete(CollectionUtils.arrayToList(keys));
                }
            }
        } catch (Exception e) {
            log.error("Redis del操作失败", e);
            throw e;
        }
    }

    /**
     * 设置过期时间
     */
    public boolean expire(String key, long time, TimeUnit timeUnit) {
        try {
            if (time > 0) {
                redisTemplate.expire(key, time, timeUnit);
                return true;
            }
            return false;
        } catch (Exception e) {
            log.error("Redis expire操作失败 key: {}", key, e);
            throw e;
        }
    }

    /**
     * 获取过期时间
     */
    public long getExpire(String key, TimeUnit timeUnit) {
        try {
            return redisTemplate.getExpire(key, timeUnit);
        } catch (Exception e) {
            log.error("Redis getExpire操作失败 key: {}", key, e);
            throw e;
        }
    }

    /**
     * 判断key是否存在
     */
    public boolean hasKey(String key) {
        try {
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
            log.error("Redis hasKey操作失败 key: {}", key, e);
            throw e;
        }
    }

    // ==================== Hash 操作 ====================

    public void hset(String key, String item, Object value) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
        } catch (Exception e) {
            log.error("Redis hset操作失败 key: {}, item: {}", key, item, e);
            throw e;
        }
    }

    public Object hget(String key, String item) {
        try {
            return redisTemplate.opsForHash().get(key, item);
        } catch (Exception e) {
            log.error("Redis hget操作失败 key: {}, item: {}", key, item, e);
            throw e;
        }
    }

    public Map<Object, Object> hgetall(String key) {
        try {
            return redisTemplate.opsForHash().entries(key);
        } catch (Exception e) {
            log.error("Redis hgetall操作失败 key: {}", key, e);
            throw e;
        }
    }

    // ==================== 其他常用操作 ====================

    /**
     * 递增
     */
    public long incr(String key, long delta) {
        try {
            return redisTemplate.opsForValue().increment(key, delta);
        } catch (Exception e) {
            log.error("Redis incr操作失败 key: {}", key, e);
            throw e;
        }
    }

    /**
     * 递减
     */
    public long decr(String key, long delta) {
        try {
            return redisTemplate.opsForValue().increment(key, -delta);
        } catch (Exception e) {
            log.error("Redis decr操作失败 key: {}", key, e);
            throw e;
        }
    }


}
