package com.ruoyi.framework.manager;

import java.util.TimerTask;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import com.ruoyi.common.utils.Threads;
import com.ruoyi.common.utils.spring.SpringUtils;

/**
 * 异步任务管理器
 *
 * @author ruoyi
 */
public class AsyncManager
{
    /**
     * 操作延迟10毫秒
     */
    private final int OPERATE_DELAY_TIME = 10;

    /**
     * 异步操作任务调度线程池
     */
    private volatile ScheduledExecutorService executor;

    /**
     * 单例模式
     */
    private AsyncManager(){}

    private static AsyncManager me = new AsyncManager();

    public static AsyncManager me()
    {
        return me;
    }

    /**
     * 获取线程池执行器（延迟初始化）
     */
    private ScheduledExecutorService getExecutor()
    {
        if (executor == null)
        {
            synchronized (this)
            {
                if (executor == null)
                {
                    try
                    {
                        // 检查Spring上下文是否已经初始化
                        if (SpringUtils.getApplicationContext() != null)
                        {
                            executor = SpringUtils.getBean("scheduledExecutorService");
                        }
                        else
                        {
                            // Spring上下文未初始化，创建临时线程池
                            executor = java.util.concurrent.Executors.newScheduledThreadPool(10);
                        }
                    }
                    catch (Exception e)
                    {
                        // 如果获取失败，创建临时线程池
                        System.err.println("Failed to get scheduledExecutorService bean, creating temporary executor: " + e.getMessage());
                        executor = java.util.concurrent.Executors.newScheduledThreadPool(10);
                    }
                }
            }
        }
        return executor;
    }

    /**
     * 执行任务
     *
     * @param task 任务
     */
    public void execute(TimerTask task)
    {
        ScheduledExecutorService exec = getExecutor();
        if (exec != null)
        {
            exec.schedule(task, OPERATE_DELAY_TIME, TimeUnit.MILLISECONDS);
        }
        else
        {
            // 如果线程池不可用，直接在当前线程执行
            System.err.println("Executor is null, running task in current thread");
            task.run();
        }
    }

    /**
     * 停止任务线程池
     */
    public void shutdown()
    {
        if (executor != null)
        {
            Threads.shutdownAndAwaitTermination(executor);
        }
    }
}
