package com.njzscloud.common.sichen.executor;

import com.njzscloud.common.sichen.service.TaskScheduleRecodeService;
import com.njzscloud.common.sichen.support.TaskHandle;
import com.njzscloud.common.sichen.support.TaskInfo;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;

@Slf4j
public class SichenExecutor {
    private final ThreadPoolExecutor taskThreadPool;
    private final TaskScheduleRecodeService taskScheduleRecodeService;

    public SichenExecutor(ThreadPoolExecutor taskThreadPool, TaskScheduleRecodeService taskScheduleRecodeService) {
        log.info("任务执行器启动中...");
        this.taskScheduleRecodeService = taskScheduleRecodeService;
        this.taskThreadPool = taskThreadPool;
        log.info("任务执行器已启动");
    }

    public void execute(TaskInfo task, boolean manually) {
        if (task == null) {
            log.warn("未提交任务");
            return;
        }
        TaskHandle taskHandle = new TaskHandle(taskScheduleRecodeService, manually, task);
        try {
            taskHandle.pending();
            taskThreadPool.execute(taskHandle);
        } catch (Exception e) {
            log.error("任务调度失败，任务：{}", taskHandle.getTaskName(), e);
        }
    }

    public void execute(List<TaskInfo> tasks, boolean manually) {
        if (tasks == null || tasks.isEmpty()) {
            log.warn("任务列表不能为空");
            return;
        }
        for (TaskInfo task : tasks) {
            this.execute(task, manually);
        }
    }

    public void stop() {
        log.info("正在停止任务执行器...");
        taskThreadPool.shutdownNow();
        log.info("任务执行器已停止");
    }
}
