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.CouponMapper;
import com.fzm.mall.server.admin.marketing.model.Coupon;
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 CouponManager {

    private final CouponMapper couponMapper;

    @Scheduled(cron = "${marketing.coupon.status-detection-task}")
    private void configureTasks() {
        QueryWrapper<Coupon> queryWrapper = new QueryWrapper<>();
        List<Integer> statusList = Arrays.asList(Coupon.COUPON_STATUS_EFFECTIVE, Coupon.COUPON_STATUS_NOT_STARTED);
        queryWrapper.in("status", statusList);
        List<Coupon> couponList = couponMapper.selectList(queryWrapper);
        couponList.forEach(coupon -> {
            if(coupon.getStartTime() <= SystemClock.now() && coupon.getEndTime() >= SystemClock.now()){
                coupon.setStatus(Coupon.COUPON_STATUS_EFFECTIVE);
            }
            if(coupon.getEndTime() < SystemClock.now()){
                coupon.setStatus(Coupon.COUPON_STATUS_EXPIRED);
            }
            couponMapper.update(coupon, new UpdateWrapper<Coupon>().eq("coupon_id", coupon.getCouponId())
                    .eq("merchant_id", coupon.getMerchantId()));
        });
    }
}
