package com.fs.store.cache.impl;

import cn.hutool.core.util.ObjectUtil;
import com.fs.store.cache.IFsStoreProductCacheService;
import com.fs.store.cache.IFsWarehouseCacheService;
import com.fs.store.domain.FsStoreProduct;
import com.fs.store.domain.FsStoreProductPackage;
import com.fs.store.domain.FsWarehouses;
import com.fs.store.service.IFsStoreProductService;
import com.fs.system.cache.impl.SysDictDataCacheServiceImpl;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
@Slf4j
@RequiredArgsConstructor
public class IFsStoreProductCacheServiceImpl implements IFsStoreProductCacheService {
    private final IFsStoreProductService fsStoreProductService;
    private final IFsWarehouseCacheService fsWarehouseCacheService;

    private static final Cache<Long, String> WAREHOUSE_CACHE = Caffeine.newBuilder()
            .maximumSize(1000)
            .expireAfterWrite(10, TimeUnit.SECONDS)
            .build();

    private final RedisTemplate<String,Object> redisTemplate;

    @Override
    public FsStoreProduct selectFsStoreProductById(Long productId) {
        log.info("开始查询商品信息，商品ID：{}", productId);
        if(productId == null) {
            throw new IllegalArgumentException("产品id不能为空！");
        }
        // 尝试从缓存获取
        try {
            String redisKey = String.format("fs:store:product:%d", productId);
            FsStoreProduct product = (FsStoreProduct) redisTemplate.opsForValue().get(redisKey);
            if(product != null) {
                log.debug("缓存命中产品信息, productId: {}", productId);
                return product;
            }
        } catch (Exception e) {
            log.error("获取产品缓存异常, productId: {}, 异常信息: {}", productId, e.getMessage(), e);
        }

        log.debug("缓存未命中产品信息, productId: {}, 从数据库查询", productId);
        FsStoreProduct fsStoreProduct = fsStoreProductService.selectFsStoreProductById(productId);

        return fsStoreProduct;
    }

    @Override
    public String getWarehouseCodeByProductId(Long productId) {
        log.info("开始根据商品ID获取仓库编码，商品ID：{}", productId);

        return WAREHOUSE_CACHE.get(productId,e->{
            FsStoreProduct fsStoreProduct = selectFsStoreProductById(productId);
            if(ObjectUtil.isNotNull(fsStoreProduct) && ObjectUtil.isNotNull(fsStoreProduct.getWarehouseId())){
                    FsWarehouses fsWarehouses = fsWarehouseCacheService.selectFsWarehousesById(fsStoreProduct.getWarehouseId());
                    if(ObjectUtil.isNotNull(fsWarehouses)){
                        return fsWarehouses.getWarehouseCode();
                    }
                }

            return null;
        });

    }
}
