package com.fzm.mall.server.admin.marketing.manager;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.SystemClock;
import com.fzm.mall.server.admin.marketing.mapper.PromotionMapper;
import com.fzm.mall.server.admin.marketing.model.Promotion;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

/**
 * @author wulixian
 * @since 2021/4/20
 */
@Component
@EnableScheduling
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class PromotionManager {

    private final PromotionMapper promotionMapper;

    @Scheduled(cron = "${marketing.promotion.status-detection-task}")
    private void configureTasks() {
        QueryWrapper<Promotion> queryWrapper = new QueryWrapper<>();
        List<Integer> statusList = Arrays.asList(Promotion.PROMOTION_STATUS_EFFECTIVE, Promotion.PROMOTION_STATUS_NOT_STARTED);
        queryWrapper.in("status", statusList);
        List<Promotion> promotionList = promotionMapper.selectList(queryWrapper);
        promotionList.forEach(promotion -> {
            if (promotion.getStartTime() <= SystemClock.now() && promotion.getEndTime() >= SystemClock.now()) {
                promotion.setStatus(Promotion.PROMOTION_STATUS_EFFECTIVE);
            }
            if (promotion.getEndTime() < SystemClock.now()) {
                promotion.setStatus(Promotion.PROMOTION_STATUS_EXPIRED);
            }
            promotionMapper.update(promotion, new UpdateWrapper<Promotion>().eq("promotion_id", promotion.getPromotionId())
                    .eq("merchant_id", promotion.getMerchantId()));
        });
    }
}
