package com.kym.miniapp.jobs;

import com.kym.common.utils.CommUtil;
import com.kym.entity.miniapp.UserCoupon;
import com.kym.entity.miniapp.UserRechargeRights;
import com.kym.service.miniapp.AccountService;
import com.kym.service.miniapp.UserCouponService;
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 UserDiscountExpiredJob {

    private final UserRechargeRightsService userRechargeRightsService;

    private final UserCouponService userCouponService;
    private final AccountService accountService;

    public UserDiscountExpiredJob(UserRechargeRightsService userRechargeRightsService, UserCouponService userCouponService, AccountService accountService) {
        this.userRechargeRightsService = userRechargeRightsService;
        this.userCouponService = userCouponService;
        this.accountService = accountService;
    }

    // 每天凌晨0点执行一次
    @Scheduled(cron = "0 0 0 * * ?")
    public void executeUserRechargeRightsJob() {
        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();
            // 权益失效时，用户Account中discountAmount今天需要减去当前失效权益已产生的优惠金额
            accountService.batchHandleDiscountAmount(list);
        }
        log.info("用户权益卡到期处理结束，共处理{}条数据", list.size());
    }

    @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());
    }
}
