package com.ruoyi.base.task;

import com.ruoyi.base.service.IRobotOpsBroadcastTaskService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 播报任务调度器
 * 定时检查并触发播报任务
 */
@Component
public class BroadcastScheduler {

    private static final Logger log = LoggerFactory.getLogger(BroadcastScheduler.class);

    private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();

    @Autowired
    private IRobotOpsBroadcastTaskService robotOpsBroadcastTaskService;

    @PostConstruct
    public void init() {
        scheduler.scheduleAtFixedRate(() -> {
            try {
                checkAndTriggerBroadcast();
            } catch (Exception e) {
                log.error("[BroadcastScheduler] 检查播报任务异常", e);
            }
        }, 0, 10, TimeUnit.SECONDS);

        log.info("[BroadcastScheduler] 播报任务调度器已启动");
    }

    private void checkAndTriggerBroadcast() {
        try {
            robotOpsBroadcastTaskService.selectCurrentBroadcastTask();
        } catch (Exception e) {
            log.error("[BroadcastScheduler] 触发播报任务异常", e);
        }
    }

    @PreDestroy
    public void destroy() {
        scheduler.shutdown();
        log.info("[BroadcastScheduler] 播报任务调度器已停止");
    }
}
