package com.izouma.nineth.task;

import com.izouma.nineth.domain.GiftOrder;
import com.izouma.nineth.enums.OrderStatus;
import com.izouma.nineth.repo.GiftOrderRepo;
import com.izouma.nineth.service.GiftOrderService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
@AllArgsConstructor
@Slf4j
public class GiftOrderServiceTask {

    private GiftOrderRepo giftOrderRepo;

    private GiftOrderService giftOrderService;

    /**
     * 固定延迟，防止任务堆积
     */
    @Scheduled(fixedDelay = 60000)
    public void batchCancel() {
        List<Long> giftOrderIds = giftOrderRepo.findWaitingCancelList(OrderStatus.NOT_PAID,
                LocalDateTime.now().minusMinutes(5));
        giftOrderIds.forEach(giftOrderId -> {
            try {
                giftOrderService.cancel(giftOrderId);
            } catch (Exception err) {
                log.error("转赠订单取消失败, 转赠订单ID：" + giftOrderId, err);
            }
        });
    }
}
