package com.gxwebsoft.glt.task;

import com.gxwebsoft.common.core.annotation.IgnoreTenant;
import com.gxwebsoft.glt.entity.GltTicketTemplate;
import com.gxwebsoft.glt.service.GltTicketIssueService;
import com.gxwebsoft.glt.service.GltTicketTemplateService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * GLT 套票发放任务：
 * - 每30秒扫描一次今日订单（tenantId=10584, formId in 套票模板 goodsId, payStatus=1, orderStatus=0）
 * - 为订单生成用户套票账户 + 释放计划（幂等）
 * - 按整改需求：发放阶段不再自动核销/自动下单；“送水下单核销”由用户在履约时主动触发
 */
@Slf4j
@Component
@RequiredArgsConstructor
@ConditionalOnProperty(prefix = "glt.ticket.issue10584", name = "enabled", havingValue = "true", matchIfMissing = true)
public class GltTicketIssue10584Task {

    private static final int TENANT_ID = 10584;

    private final GltTicketIssueService gltTicketIssueService;
    private final GltTicketTemplateService gltTicketTemplateService;

    private final AtomicBoolean running = new AtomicBoolean(false);

//    @Scheduled(cron = "${glt.ticket.issue10584.cron:0/15 * * * * ?}")
    @IgnoreTenant("定时任务无登录态，需忽略租户隔离；内部使用 tenantId=10584 精确过滤")
    public void run() {
        if (!running.compareAndSet(false, true)) {
            log.warn("套票发放任务仍在执行中，本轮跳过 - tenantId={}", TENANT_ID);
            return;
        }

        try {
            List<Integer> goodsIds = gltTicketTemplateService.list(
                    new LambdaQueryWrapper<GltTicketTemplate>()
                        .eq(GltTicketTemplate::getTenantId, TENANT_ID)
                        .eq(GltTicketTemplate::getDeleted, 0)
                        .eq(GltTicketTemplate::getEnabled, true)
                        .isNotNull(GltTicketTemplate::getGoodsId)
            ).stream()
                .map(GltTicketTemplate::getGoodsId)
                .distinct()
                .toList();

            if (goodsIds.isEmpty()) {
                log.warn("套票发放任务跳过：未配置/未启用套票模板 - tenantId={}", TENANT_ID);
                return;
            }

            gltTicketIssueService.issueTodayOrders(TENANT_ID, goodsIds);
        } finally {
            running.set(false);
        }
    }
}
