package com.ycwl.basic.repository;

import com.alibaba.fastjson.JSON;
import com.ycwl.basic.mapper.PriceConfigMapper;
import com.ycwl.basic.model.pc.price.entity.PriceConfigEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

@Component
public class PriceRepository {
    @Autowired
    private PriceConfigMapper mapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    public static final String PRICE_SCENIC_TYPE_GOODS_CACHE = "price:s%s:t%s:g%s";
    public static final String PRICE_ID_CACHE = "price:%s";

    public PriceConfigEntity getPriceConfigByScenicTypeGoods(Long scenicId, Integer type, String goodsId) {
        String cacheKey = String.format(PRICE_SCENIC_TYPE_GOODS_CACHE, scenicId, type, goodsId);
        PriceConfigEntity priceConfigEntity = null;
        if (redisTemplate.hasKey(cacheKey)) {
            priceConfigEntity = JSON.parseObject(redisTemplate.opsForValue().get(cacheKey), PriceConfigEntity.class);
        }
        if (priceConfigEntity == null) {
            priceConfigEntity = mapper.getPriceByScenicTypeGoods(scenicId, type, goodsId);
            if (priceConfigEntity != null) {
                redisTemplate.opsForValue().set(cacheKey, JSON.toJSONString(priceConfigEntity));
                redisTemplate.opsForValue().set(String.format(PRICE_ID_CACHE, priceConfigEntity.getId()), JSON.toJSONString(priceConfigEntity));
            }
        }
        return priceConfigEntity;
    }

    public PriceConfigEntity getPriceConfig(Integer id) {
        String cacheKey = String.format(PRICE_ID_CACHE, id);
        PriceConfigEntity priceConfigEntity = null;
        if (redisTemplate.hasKey(cacheKey)) {
            priceConfigEntity = JSON.parseObject(redisTemplate.opsForValue().get(cacheKey), PriceConfigEntity.class);
        }
        return priceConfigEntity;
    }

    public void clearPriceCache(Integer id) {
        if (redisTemplate.hasKey(String.format(PRICE_ID_CACHE, id))) {
            PriceConfigEntity priceConfig = getPriceConfig(id);
            if (priceConfig != null) {
                clearPriceCache(priceConfig.getScenicId(), priceConfig.getType(), priceConfig.getGoodsIds());
            }
        }
        redisTemplate.delete(String.format(PRICE_ID_CACHE, id));
    }

    public void clearPriceCache(Long scenicId, Integer type, String goodsId) {
        String cacheKey = String.format(PRICE_SCENIC_TYPE_GOODS_CACHE, scenicId, type, goodsId);
        redisTemplate.delete(cacheKey);
    }
}
