package com.ecep.contract.task;

import java.util.ArrayList;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ecep.contract.Desktop;
import com.ecep.contract.TaskStatus;
import com.ecep.contract.controller.BaseController;
import com.ecep.contract.controller.TaskMonitorViewController;

import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.scene.control.Label;
import javafx.scene.control.Tooltip;
import lombok.Getter;

/**
 * 任务监控中心 - 统一管理所有异步任务
 */
public class TaskMonitorCenter {
    private static final Logger logger = LoggerFactory.getLogger(TaskMonitorCenter.class);

    // 正在运行的任务列表
    @Getter
    private final ObservableList<MonitoredTask<?>> activeTasks = FXCollections.observableArrayList();

    // 任务历史记录
    @Getter
    private final ObservableList<TaskHistory> taskHistory = FXCollections.observableArrayList();

    // 任务ID映射
    private final Map<String, MonitoredTask<?>> taskMap = new ConcurrentHashMap<>();

    // 任务计数器
    private final AtomicInteger taskCounter = new AtomicInteger(0);

    /**
     * 注册并启动任务
     */
    public <T> MonitoredTask<T> registerTask(Tasker<T> task) {
        return registerTask(task, null);
    }

    /**
     * 注册并启动任务，支持设置超时时间
     */
    public <T> MonitoredTask<T> registerTask(Tasker<T> task, Long timeoutSeconds) {
        String taskId = generateTaskId();
        MonitoredTask<T> monitoredTask = new MonitoredTask<>(task, taskId);

        // 设置超时处理
        if (timeoutSeconds != null && timeoutSeconds > 0) {
            monitoredTask.setTimeout(timeoutSeconds);
        }

        // 添加任务状态变更监听器
        monitoredTask.setOnSucceeded(() -> {
            if (logger.isInfoEnabled()) {
                logger.info("任务[{}]执行成功: {}", taskId, monitoredTask.titleProperty().get());
            }
            recordHistory(monitoredTask, TaskStatus.SUCCEEDED);
            removeActiveTask(monitoredTask);
        });

        monitoredTask.setOnFailed(() -> {
            if (logger.isErrorEnabled()) {
                logger.error("任务[{}]执行失败: {}", taskId, monitoredTask.titleProperty().get(),
                        monitoredTask.exceptionProperty().get());
            }
            recordHistory(monitoredTask, TaskStatus.FAILED);
            removeActiveTask(monitoredTask);
        });

        monitoredTask.setOnCancelled(() -> {
            if (logger.isInfoEnabled()) {
                logger.info("任务[{}]被取消: {}", taskId, monitoredTask.titleProperty().get());
            }
            recordHistory(monitoredTask, TaskStatus.CANCELLED);
            removeActiveTask(monitoredTask);
        });

        // 保存任务引用并启动
        taskMap.put(taskId, monitoredTask);
        activeTasks.add(monitoredTask);

        if (logger.isInfoEnabled()) {
            logger.info("任务[{}]已注册并启动: {}", taskId, monitoredTask.titleProperty().get());
        }
        return monitoredTask;
    }

    /**
     * 取消任务
     */
    public boolean cancelTask(String taskId) {
        MonitoredTask<?> task = taskMap.get(taskId);
        if (task != null && task.isRunning()) {
            task.cancel();
            return true;
        }
        return false;
    }

    /**
     * 取消所有任务
     */
    public void cancelAllTasks() {
        for (MonitoredTask<?> task : new ArrayList<>(activeTasks)) {
            task.cancel();
        }
    }

    /**
     * 从活动列表中移除任务
     */
    private void removeActiveTask(MonitoredTask<?> task) {
        Platform.runLater(() -> activeTasks.remove(task));
        taskMap.remove(task.getTaskId());
    }

    /**
     * 记录任务历史
     */
    private void recordHistory(MonitoredTask<?> task, TaskStatus status) {
        TaskHistory history = new TaskHistory(
                task,
                status,
                System.currentTimeMillis(), null);

        Platform.runLater(() -> {
            taskHistory.add(0, history);
            // 只保留最近100条历史记录
            if (taskHistory.size() > 100) {
                taskHistory.remove(taskHistory.size() - 1);
            }
        });
    }

    /**
     * 生成任务ID
     */
    private String generateTaskId() {
        return "task-" + UUID.randomUUID().toString().substring(0, 8) + "-" + taskCounter.incrementAndGet();
    }

    public <T> void registerAndStartTask(Tasker<T> task) {
        MonitoredTask<T> registerTask = registerTask(task);
        Desktop.instance.getExecutorService().submit(registerTask);
    }

    public void bindStatusLabel(Label monitorLabel) {
        Tooltip tooltip = new Tooltip("当前运行任务数: " + activeTasks.size());
        monitorLabel.setTooltip(tooltip);
        activeTasks.addListener((ListChangeListener<MonitoredTask<?>>) change -> {
            tooltip.setText("当前运行任务数: " + activeTasks.size());
        });
        monitorLabel.setOnMouseClicked(event -> {
            BaseController.show(TaskMonitorViewController.class, monitorLabel.getScene().getWindow());
        });
    }
}