package com.fzm.mall.server.front.redis;

import com.alibaba.fastjson.JSON;
import com.fzm.mall.server.front.asset.model.vo.BusinessVO;
import com.fzm.mall.server.front.merchant.model.Merchant;
import com.fzm.mall.server.front.repository.RedisRepository;
import com.fzm.mall.server.front.constant.cache.MallCacheHeader;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author tdz
 * @date 2021/02/22 11:26
 */
@Component
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class MerchantRedis {
    private final RedisRepository redisRepository;

    public void setMerchant(String merchantId, Merchant merchant) {
        redisRepository.setObj(MallCacheHeader.MALL_BUSINESS + merchantId, merchant, 7, TimeUnit.HOURS);
    }

    public Merchant getMerchant(String merchantId) {
        try {
            Object obj = redisRepository.getObj(MallCacheHeader.MALL_BUSINESS + merchantId);
            if (obj != null) {
                return JSON.parseObject(JSON.toJSONString(obj), Merchant.class);
            }
        } catch (Exception e) {
            // 缓存中获取的数据转换发生错误，重置缓存
            delsetMerchant(merchantId);
        }
        return null;
    }

    public void delsetMerchant(String merchantId) {
        redisRepository.delObj(MallCacheHeader.MALL_BUSINESS + merchantId);
    }
}
