package com.muyu.common.caffeine.utils;


import com.muyu.common.caffeine.enums.CacheNameEnums;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cache.CacheManager;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * Caffeine缓存工具
 * @Author: WangXin
 * @Name: CaffeineUtils
 * @Description: 缓存工具类
 * @CreatedDate: 2024/9/26 下午2:53
 * @FilePath: com.muyu.common.caffeine
 */
@Slf4j
@Component
public class CaffeineCacheUtils {
    @Resource
    private CacheManager cacheManager;
    @Resource
    private RedisTemplate<String, String> redisTemplate;


    /**
     * 车辆上线 - 新增缓存
     */
    public void addCarCache(String vin) {
        // 从Redis中获取缓存信息
        for (String name : CacheNameEnums.getCodes()) {
            String value = redisTemplate.opsForValue().get(name+":"+vin);
            cacheManager.getCache(name).put(vin, value);
            log.info("存储缓存, 缓存分区:[{}], 车辆编码:[{}], 存储值:[{}]", name, vin, value);
        }
        log.info("车辆编码:{},本地缓存完成...",vin);
    }

    /**
     * 车辆下线 - 删除缓存
     */
    public void deleteCarCache(String cacheName) {
        if (!hasCarVinCache(cacheName,null)) {
            log.warn("车辆编码:{},本地缓存不存在该车辆信息...", cacheName);
            return;
        }
        cacheManager.getCache(cacheName).invalidate();
        log.info("车辆编码:{},本地缓存删除完成...", cacheName);
    }

    /**
     * 获取车辆信息缓存
     */
    public Object getCarCache(String cacheName, String key) {
        if (!hasCarVinCache(cacheName, key)){
            log.warn("车辆编码:{},本地缓存不存在该车辆信息...",cacheName);
            return null;
        }
        return cacheManager.getCache(cacheName).get(key).get();
    }

    /**
     * 获取车辆信息缓存
     */
    public <T> T getCarCache(String cacheName, String key, Class<T> type) {
        if (!hasCarVinCache(cacheName,key)){
            log.warn("车辆编码:{},本地缓存不存在该车辆信息...",cacheName);
            return null;
        }
        return cacheManager.getCache(cacheName).get(key, type);
    }

    /**
     * 判断缓存存在与否
     */
    public Boolean hasCarVinCache(String cacheName,String key) {
        boolean notEmpty = ObjectUtils.isNotEmpty(cacheManager.getCache(cacheName));
        if (notEmpty && StringUtils.isNotEmpty(key)){
            return ObjectUtils.isNotEmpty(cacheManager.getCache(cacheName).get(key).get());
        }
        return notEmpty;

    }

}
