package com.ruoyi.app.flashdelivery.task;

import com.ruoyi.app.flashdelivery.service.FlashDeliveryApplicationService;
import com.ruoyi.system.domain.flash.FlashDeliveryOrder;
import org.springframework.stereotype.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Date;

/**
 * 将送达超过 24 小时且用户未确认的订单自动收口为已完成。
 * 由若依任务调度调用 {@code flashDeliveryAutoCompleteTask.completeDeliveredOrders()}。
 */
@Component("flashDeliveryAutoCompleteTask")
public class FlashDeliveryAutoCompleteTask {
    private static final Logger log = LoggerFactory.getLogger(FlashDeliveryAutoCompleteTask.class);
    private final FlashDeliveryApplicationService service;
    public FlashDeliveryAutoCompleteTask(FlashDeliveryApplicationService service) { this.service = service; }

    public void completeDeliveredOrders() {
        Date deadline = Date.from(Instant.now().minus(24, ChronoUnit.HOURS));
        // 分批处理避免单次扫描过多；条件更新保证与用户确认/平台完成并发时只有一方成功。
        for (FlashDeliveryOrder order : service.autoCompleteCandidates(deadline, 200)) {
            try {
                service.complete(null, "SYSTEM", order.getId());
            } catch (RuntimeException exception) {
                log.error("Flash delivery auto-complete failed, orderId={}", order.getId(), exception);
            }
        }
    }
}
