package com.gxwebsoft.glt.task;

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

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 冻结水票自动释放任务：每月1日凌晨1-3点每2分钟执行一次任务
 * - 扫描 glt_user_ticket_release 中本月到期且待释放（status=0）的记录
 * - 释放成功：
 *      1.修改水票释放任务为已释放状态                  glt_user_ticket_release
 *      2.修改个人水票中：可用数量、冻结数量、已释放数量   glt_user_ticket
 *      3.同步生产水票释放记录数据                     glt_user_ticket_log
 */
@Slf4j
@Component
@RequiredArgsConstructor
@ConditionalOnProperty(prefix = "glt.ticket.auto-release", name = "enabled", havingValue = "true", matchIfMissing = true)
public class GltUserTicketAutoReleaseTask {

    private final GltUserTicketAutoReleaseService autoReleaseService;

    private final AtomicBoolean running = new AtomicBoolean(false);

    @Scheduled(cron = "${glt.ticket.auto-release.cron:0 */2 1-3 1 * ?}")
    @IgnoreTenant("定时任务无登录态，需忽略租户隔离；释放记录自带 tenantId，更新时会校验 tenantId")
    public void run() {
        if (!running.compareAndSet(false, true)) {
            log.warn("冻结水票自动释放任务仍在执行中，本轮跳过");
            return;
        }
        try {
            autoReleaseService.releaseTask();
        } finally {
            running.set(false);
        }
    }
}
