package com.cn.fdapfe.common.core.redis;

import com.github.benmanes.caffeine.cache.Cache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component
public class CaffeineCache {
    @Autowired
    private Cache<String, Object> caffeineCacheCustomize;

    public void setCache(String key, Object value) {
        caffeineCacheCustomize.put(key, value);
    }

    /**
     * 动态设置缓存项的过期时间
     *
     * @param key   缓存键
     * @param value 缓存值
     * @param time  过期时间
     * @param unit  时间单位
     */
    public void setCacheWithExpiration(String key, Object value, long time, TimeUnit unit) {
        caffeineCacheCustomize.policy().expireAfterWrite()
                .ifPresent(policy -> policy.setExpiresAfter(time, unit));
        caffeineCacheCustomize.put(key, value);
    }

    public Object getCache(String key) {
        return caffeineCacheCustomize.getIfPresent(key);
    }

    /**
     * 删除指定 key 的缓存项
     */
    public void deleteCacheByKey(String key) {
        caffeineCacheCustomize.invalidate(key);
    }

    /**
     * 批量删除缓存项
     */
    public void deleteCacheByKeys(Set<String> keys) {
        caffeineCacheCustomize.invalidateAll(keys);
    }

    /**
     * 清空整个缓存
     */
    public void clearAllCache() {
        caffeineCacheCustomize.invalidateAll();
    }

    /**
     * 根据条件删除缓存项
     */
    public void deleteCacheByCondition() {
        Map<String, Object> cacheMap = caffeineCacheCustomize.asMap();
        cacheMap.entrySet().removeIf(entry -> {
            String key = entry.getKey();
            Object value = entry.getValue();
            // 自定义删除条件
            return key.startsWith("temp_") || value == null;
        });
    }


    /**
     * 按通配符删除缓存项
     *
     * @param pattern 通配符模式，例如 "user_*"
     */
    public void deleteCacheByPattern(String pattern) {
        Map<String, Object> cacheMap = caffeineCacheCustomize.asMap();
        cacheMap.keySet().removeIf(key -> key.matches(convertPatternToRegex(pattern)));
    }
    /**
     * 按通配符查找匹配的缓存键
     *
     * @param pattern 通配符模式，例如 "user_*"
     * @return 匹配的缓存键列表
     */
    public List<String> findKeysByPattern(String pattern) {
        List<String> matchedKeys = new ArrayList<>();
        Map<String, Object> cacheMap = caffeineCacheCustomize.asMap();
        String regex = convertPatternToRegex(pattern);

        for (String key : cacheMap.keySet()) {
            if (key.matches(regex)) {
                matchedKeys.add(key);
            }
        }

        return matchedKeys;
    }

    /**
     * 将通配符模式转换为正则表达式
     *
     * @param pattern 通配符模式，例如 "user_*"
     * @return 正则表达式
     */
    private String convertPatternToRegex(String pattern) {
        return pattern.replace("*", ".*");
    }

    /**
     * 检查 key 是否存在
     *
     * @param key       缓存键
     * @return 是否存在
     */
    public boolean isKeyExists(String key) {
        return caffeineCacheCustomize.getIfPresent(key) != null;
    }
}
