package com.yami.shop.seckill.comment.listener;

import com.yami.shop.bean.event.ProdChangeStatusEvent;
import com.yami.shop.bean.model.Product;
import com.yami.shop.seckill.comment.model.Seckill;
import com.yami.shop.seckill.comment.service.SeckillService;
import com.yami.shop.seckill.comment.service.SeckillSkuService;
import com.yami.shop.service.ProductService;
import lombok.AllArgsConstructor;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 秒杀商品状态修改监听
 * @author LGH
 */
@Component("seckillProdChangeStatus")
@AllArgsConstructor
public class ProdChangeStatusListener {
    private final SeckillService seckillService;

    private final ProductService productService;

    private final SeckillSkuService seckillSkuService;

    /**
     * 使秒杀活动失效
     */
    @EventListener(ProdChangeStatusEvent.class)
    public void seckillProdChangeStatusListener(ProdChangeStatusEvent event) {
        Product product = event.getProduct();
        // 不是秒杀商品，就不用管他
        if(!Objects.equals(product.getProdType(), 2)){
            return;
        }

        // 如果是商品上线，就不管他了
        if (Objects.equals(product.getStatus(), 1)) {
            return;
        }

        Seckill seckill = seckillService.getSeckillById(product.getActivityId());

        seckillService.invalidById(seckill);

        productService.removeProductCacheByProdId(seckill.getProdId());
        seckillSkuService.removeSeckillSkuCacheBySeckillId(seckill.getSeckillId());
        seckillService.removeSeckillCacheById(seckill.getSeckillId());
    }
}
