package com.kym.miniapp.jobs;

import com.kym.common.utils.CommUtil;
import com.kym.entity.miniapp.UserRechargeRights;
import com.kym.service.miniapp.UserRechargeRightsService;
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 UserRechargeRightsJob {

    private final UserRechargeRightsService userRechargeRightsService;

    public UserRechargeRightsJob(UserRechargeRightsService userRechargeRightsService) {
        this.userRechargeRightsService = userRechargeRightsService;
    }

    // 每天凌晨0点执行一次
    @Scheduled(cron = "0 0 0 * * ?")
    public void execute() {
        log.info("用户权益到期处理启动...");
        var list = userRechargeRightsService.lambdaQuery()
                .eq(UserRechargeRights::getStatus, UserRechargeRights.STATUS_有效)
                .le(UserRechargeRights::getEndTime, LocalDateTime.now())
                .list();
        if (!CommUtil.isEmptyOrNull(list)) {
            userRechargeRightsService.lambdaUpdate()
                    .set(UserRechargeRights::getStatus, UserRechargeRights.STATUS_无效)
                    .in(UserRechargeRights::getId, list.stream().map(UserRechargeRights::getId).toList())
                    .update();
        }
        log.info("用户权益到期处理结束，共处理{}条数据", list.size());
    }
}
