package com.fzm.mall.server.front.task.goods;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fzm.mall.server.front.constant.StateConst;
import com.fzm.mall.server.front.enums.GoodSpuSalesTypeEnum;
import com.fzm.mall.server.front.goods.mapper.GoodSkuMapper;
import com.fzm.mall.server.front.goods.mapper.GoodSpuMapper;
import com.fzm.mall.server.front.goods.model.GoodSpu;
import com.fzm.mall.server.front.goods.model.vo.SkuVo;
import com.fzm.mall.server.front.redis.GoodRedis;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author wulixian
 * @since 2022/3/10
 */
@Component
@Slf4j
public class GoodsSkuTask {

    @Autowired
    private GoodSkuMapper goodSkuMapper;

    @Autowired
    private GoodSpuMapper goodSpuMapper;

    @Autowired
    private GoodRedis goodRedis;

    //提前预加载盲盒商品
    @Scheduled(cron = "${goods.effective-sku-preload}")
    public void preLoadBlindBoxEffectiveSku() {
        log.info("开始预加载盲盒商品");
        QueryWrapper<GoodSpu> spuWrapper = new QueryWrapper<>();
        spuWrapper.eq("status", StateConst.ACTIVE_SUCCESS)
                .eq("sales_type", GoodSpuSalesTypeEnum.BLIND_BOX.getType());
        List<GoodSpu> spuList = goodSpuMapper.selectList(spuWrapper);
        if(CollectionUtils.isEmpty(spuList)){
            return;
        }
        spuList.forEach(goodSpu -> {
            List<SkuVo> skuList = goodSkuMapper.listAvailableSku(goodSpu.getGoodsId());
            /**
             * 定时任务预加载设置缓存时间为23小时
             */
            goodRedis.setEffecticveSku(goodSpu.getGoodsId(), skuList, 23, TimeUnit.HOURS);
        });
    }
}
