package com.fs.store.cache.impl;

import com.fs.store.cache.IFsStoreProductAttrValueCacheService;
import com.fs.store.domain.FsStoreProductAttrValue;
import com.fs.store.domain.FsStoreProductPackage;
import com.fs.store.service.IFsStoreProductAttrValueService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
@Slf4j
@RequiredArgsConstructor
public class FsStoreProductAttrValueCacheServiceImpl implements IFsStoreProductAttrValueCacheService {
    private final RedisTemplate<String,Object> redisTemplate;
    private final IFsStoreProductAttrValueService productAttrValueCacheService;
    @Override
    public FsStoreProductAttrValue selectFsStoreProductAttrValueById(Long id) {
        if(id == null) {
            throw new IllegalArgumentException("商品属性id不能为空！");
        }
        // 尝试从缓存获取
        try {
            String redisKey = String.format("fs:store:product:attr:value:%d", id);
            FsStoreProductAttrValue productPackage = (FsStoreProductAttrValue) redisTemplate.opsForValue().get(redisKey);
            if(productPackage != null) {
                log.debug("缓存命中商品属性信息, id: {}", id);
                return productPackage;
            }
        } catch (Exception e) {
            log.error("获取商品属性缓存异常, id: {}, 异常信息: {}", id, e.getMessage(), e);
        }

        log.debug("缓存未命中商品属性信息, id: {}, 从数据库查询", id);
        FsStoreProductAttrValue productPackage = productAttrValueCacheService.selectFsStoreProductAttrValueById(id);

        return productPackage;
    }
}
