package com.kym.miniapp.jobs;

import com.kym.common.utils.CommUtil;
import com.kym.entity.UserCoupon;
import com.kym.service.UserCouponService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @author skyline
 * @description 用户优惠权益到期处理
 * @date 2023-11-15 14:00
 */
@Component
@Slf4j
public class UserDiscountExpiredJob {

    private final UserCouponService userCouponService;

    public UserDiscountExpiredJob(UserCouponService userCouponService) {
        this.userCouponService = userCouponService;
    }


    @Scheduled(cron = "0 0 0 * * ?")
    public void executeUserCouponJob() {
        log.info("用户优惠券到期处理启动...");
        var list = userCouponService.lambdaQuery()
                .eq(UserCoupon::getStatus, UserCoupon.STATUS_有效)
                .le(UserCoupon::getEndTime, LocalDateTime.now())
                .list();
        if (!CommUtil.isEmptyOrNull(list)) {
            userCouponService.lambdaUpdate()
                    .set(UserCoupon::getStatus, UserCoupon.STATUS_无效)
                    .in(UserCoupon::getId, list.stream().map(UserCoupon::getId).toList())
                    .update();
        }
        log.info("用户优惠券到期处理结束，共处理{}条数据", list.size());
    }
}
