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.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.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
@Slf4j
@RequiredArgsConstructor
public class IFsStoreProductCacheServiceImpl implements IFsStoreProductCacheService {
    private final IFsStoreProductService fsStoreProductService;
    private final IFsWarehouseCacheService fsWarehouseCacheService;
    /**
     * 使用Caffeine本地缓存
     * maximumSize: 最大缓存条数
     * expireAfterWrite: 写入后多久过期（分钟）
     */
    private static final Cache<Long, FsStoreProduct> CACHE = Caffeine.newBuilder()
            .maximumSize(1000)
            .expireAfterWrite(10, TimeUnit.SECONDS)
            .build();

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

    @Override
    public FsStoreProduct selectFsStoreProductById(Long productId) {
        return CACHE.get(productId, e -> fsStoreProductService.selectFsStoreProductById(productId));
    }

    @Override
    public String getWarehouseCodeByProductId(Long 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;
        });

    }
}
