/*
 * Copyright (c) 2018-2999 广州亚米信息科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 */

package com.yami.shop.seckill.comment.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yami.shop.common.util.CacheManagerUtil;
import com.yami.shop.seckill.comment.model.SeckillSku;
import com.yami.shop.seckill.comment.dao.SeckillSkuMapper;
import com.yami.shop.seckill.comment.service.SeckillSkuService;
import lombok.AllArgsConstructor;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 秒杀活动sku
 *
 * @author LGH
 * @date 2019-08-28 09:36:59
 */
@Service
@AllArgsConstructor
public class SeckillSkuServiceImpl extends ServiceImpl<SeckillSkuMapper, SeckillSku> implements SeckillSkuService {

    private final SeckillSkuMapper seckillSkuMapper;

    private final CacheManagerUtil cacheManagerUtil;

    @Override
    @Cacheable(cacheNames = "SeckillSkuBySeckillId", key = "#seckillId")
    public List<SeckillSku> listSeckillSkuBySeckillId(Long seckillId) {
        return seckillSkuMapper.selectList(new LambdaQueryWrapper<SeckillSku>().eq(SeckillSku::getSeckillId,seckillId));
    }

    @Override
    @CacheEvict(cacheNames = "SeckillSkuBySeckillId", key = "#seckillId")
    public void removeSeckillSkuCacheBySeckillId(Long seckillId) {
        List<SeckillSku> seckillSkus = listSeckillSkuBySeckillId(seckillId);
        //清除缓存
        if (CollectionUtils.isNotEmpty(seckillSkus)) {
            for (SeckillSku seckillSku : seckillSkus) {
                // 不能采用this清除缓存，因为这样没有aop
                cacheManagerUtil.evictCache("SeckillSkuById", String.valueOf(seckillSku.getSeckillSkuId()));
            }
        }
    }

    @Override
    @Cacheable(cacheNames = "SeckillSkuById", key = "#seckillSkuId")
    public SeckillSku getSeckillSkuById(Long seckillSkuId) {
        return seckillSkuMapper.selectById(seckillSkuId);
    }

    @Override
    @Caching(evict = {
            @CacheEvict(cacheNames = "SeckillSkuById", key = "#seckillSkuId"),
            @CacheEvict(cacheNames = "SeckillSkuBySeckillId", key = "#seckillId"),
            @CacheEvict(cacheNames = "SeckillById", key = "#seckillId")
    })
    public void removeSeckillCacheSkuById(Long seckillSkuId,Long seckillId) {

    }
}
