package com.gxwebsoft.glt.task;

import com.gxwebsoft.common.core.annotation.IgnoreTenant;
import com.gxwebsoft.glt.service.GltTicketOrderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 租户10584：送水订单超时自动确认收货任务
 *
 * <p>扫描已送达待确认(30)且送达时间超过24小时的订单，自动置为已完成(40)。</p>
 * <p>自动确认后会触发配送员提成结算（幂等）。</p>
 */
@Slf4j
@Component
@RequiredArgsConstructor
@ConditionalOnProperty(prefix = "glt.ticket-order.auto-confirm10584", name = "enabled", havingValue = "true", matchIfMissing = true)
public class GltTicketOrderAutoConfirm10584Task {

    private static final int TENANT_ID = 10584;
    private static final int TIMEOUT_HOURS = 24;

    private final GltTicketOrderService gltTicketOrderService;

    @Value("${glt.ticket-order.auto-confirm10584.batch-size:200}")
    private int batchSize;

    private final AtomicBoolean running = new AtomicBoolean(false);

    @Scheduled(cron = "${glt.ticket-order.auto-confirm10584.cron:0/33 * * * * ?}")
    @IgnoreTenant("定时任务无登录态，需忽略租户隔离；内部使用 tenantId=10584 精确过滤")
    public void run() {
        if (!running.compareAndSet(false, true)) {
            log.warn("送水订单超时自动确认任务仍在执行中，本轮跳过 - tenantId={}", TENANT_ID);
            return;
        }

        try {
            LocalDateTime now = LocalDateTime.now();
            int confirmed = gltTicketOrderService.autoConfirmTimeout(TENANT_ID, now, TIMEOUT_HOURS, Math.max(batchSize, 1));
            if (confirmed > 0) {
                log.info("送水订单超时自动确认完成 - tenantId={}, confirmed={}, now={}", TENANT_ID, confirmed, now);
            }
        } finally {
            running.set(false);
        }
    }
}
