package com.ecep.contract.controller;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;

import com.ecep.contract.util.FxmlPath;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.ecep.contract.Desktop;
import com.ecep.contract.Message;
import com.ecep.contract.MyDateTimeUtils;
import com.ecep.contract.task.MonitoredTask;
import com.ecep.contract.task.TaskHistory;
import com.ecep.contract.task.TaskMonitorCenter;

import javafx.beans.property.SimpleStringProperty;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressBar;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableRow;
import javafx.scene.control.TableView;
import javafx.scene.control.TextArea;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
import javafx.stage.WindowEvent;

/**
 * 任务监控界面控制器
 */
@Lazy
@Scope("prototype")
@Component
@FxmlPath(value = "/ui/task/TaskMonitorView.fxml")
public class TaskMonitorViewController extends BaseController {
    @FXML
    private TableView<MonitoredTask<?>> activeTasksTable;
    @FXML
    private TableColumn<MonitoredTask<?>, String> activeTaskIdColumn;
    @FXML
    private TableColumn<MonitoredTask<?>, String> activeTaskTitleColumn;
    @FXML
    private TableColumn<MonitoredTask<?>, Number> activeTaskProgressColumn;
    @FXML
    private TableColumn<MonitoredTask<?>, String> activeTaskStatusColumn;

    @FXML
    private TableView<TaskHistory> historyTasksTable;
    @FXML
    private TableColumn<TaskHistory, String> historyTaskIdColumn;
    @FXML
    private TableColumn<TaskHistory, String> historyTaskTitleColumn;
    @FXML
    private TableColumn<TaskHistory, String> historyTaskStatusColumn;
    @FXML
    private TableColumn<TaskHistory, String> historyTaskStartTimeColumn;
    @FXML
    private TableColumn<TaskHistory, String> historyTaskExecutionTimeColumn;

    @FXML
    private Button cancelTaskButton;
    @FXML
    private Button clearHistoryButton;
    @FXML
    private Button refreshExecutorInfoButton;
    @FXML
    private TableView<ExecutorInfo> executorInfoTable;
    @FXML
    private TableColumn<ExecutorInfo, String> executorFieldColumn;
    @FXML
    private TableColumn<ExecutorInfo, String> executorValueColumn;
    @FXML
    private TableColumn<ExecutorInfo, String> executorDescriptionColumn;

    public TaskMonitorViewController() {
    }

    /**
     * 用于存储ExecutorService信息的内部类
     */
    public static class ExecutorInfo {
        private final String field;
        private final String value;
        private final String description;

        public ExecutorInfo(String field, String value, String description) {
            this.field = field;
            this.value = value;
            this.description = description;
        }

        public String getField() {
            return field;
        }

        public String getValue() {
            return value;
        }

        public String getDescription() {
            return description;
        }
    }

    @Override
    public void onShown(WindowEvent windowEvent) {
        super.onShown(windowEvent);
        getTitle().set("任务监控中心");

        // 初始化活动任务表格
        activeTaskIdColumn.setCellValueFactory(new PropertyValueFactory<>("taskId"));
        activeTaskTitleColumn.setCellValueFactory(new PropertyValueFactory<>("title"));

        // 进度条列
        activeTaskProgressColumn.setCellValueFactory(
                param -> param.getValue().progressProperty().divide(param.getValue().totalWorkProperty()));
        activeTaskProgressColumn.setCellFactory(column -> new TableCell<>() {
            private final ProgressBar progressBar = new ProgressBar();
            {
                // 设置进度条最大宽度和水平扩展属性
                progressBar.setMaxWidth(Double.MAX_VALUE);
                HBox.setHgrow(progressBar, Priority.ALWAYS);
            }

            @Override
            protected void updateItem(Number item, boolean empty) {
                super.updateItem(item, empty);
                if (empty || item == null) {
                    setText(null);
                    setGraphic(null);
                    return;
                }
                setGraphic(progressBar);
                progressBar.setProgress(item.doubleValue());
            }
        });

        // 状态列
        activeTaskStatusColumn.setCellValueFactory(cellData -> {
            MonitoredTask<?> task = cellData.getValue();
            String description = "";
            if (task.stateProperty().get() != null) {
                description = task.stateProperty().get().getDescription();
            }
            return new SimpleStringProperty(description);
        });

        // 初始化历史任务表格
        historyTaskIdColumn.setCellValueFactory(new PropertyValueFactory<>("taskId"));
        historyTaskTitleColumn.setCellValueFactory(new PropertyValueFactory<>("title"));
        historyTaskStatusColumn.setCellValueFactory(
                cellData -> new SimpleStringProperty(cellData.getValue().getStatus().getDescription()));
        historyTaskStartTimeColumn.setCellValueFactory(
                cellData -> new SimpleStringProperty(MyDateTimeUtils.format(cellData.getValue().getStartTime())));
        historyTaskExecutionTimeColumn.setCellValueFactory(
                cellData -> new SimpleStringProperty(cellData.getValue().getFormattedExecutionTime()));

        // 绑定数据
        TaskMonitorCenter taskMonitorCenter = Desktop.instance.getTaskMonitorCenter();
        activeTasksTable.setItems(taskMonitorCenter.getActiveTasks());
        historyTasksTable.setItems(taskMonitorCenter.getTaskHistory());

        // 添加任务双击事件（显示详情）
        historyTasksTable.setRowFactory(tv -> {
            TableRow<TaskHistory> row = new TableRow<>();
            row.setOnMouseClicked(event -> {
                if (event.getClickCount() == 2 && !row.isEmpty()) {
                    TaskHistory history = row.getItem();
                    showTaskDetails(history);
                }
            });
            return row;
        });

        cancelTaskButton.disableProperty().bind(activeTasksTable.getSelectionModel().selectedItemProperty().isNull());
        // 初始化Executor信息表格
        initializeExecutorInfoTable();
    }

    /**
     * 初始化Executor信息表格
     */
    private void initializeExecutorInfoTable() {
        executorFieldColumn.setCellValueFactory(param -> new SimpleStringProperty(param.getValue().getField()));
        executorValueColumn.setCellValueFactory(param -> new SimpleStringProperty(param.getValue().getValue()));
        executorDescriptionColumn
                .setCellValueFactory(param -> new SimpleStringProperty(param.getValue().getDescription()));

        // 初始加载Executor信息
        refreshExecutorInfo();
        // 绑定刷新按钮事件
        refreshExecutorInfoButton.setOnAction(event -> refreshExecutorInfo());
    }

    /**
     * 刷新Executor信息
     */
    @FXML
    private void refreshExecutorInfo() {
        executorInfoTable.getItems().clear();

        try {
            ExecutorService executorService = Desktop.instance.getExecutorService();
            if (executorService instanceof ThreadPoolExecutor threadPoolExecutor) {
                executorInfoTable.getItems().add(new ExecutorInfo(
                        "PoolSize",
                        String.valueOf(threadPoolExecutor.getPoolSize()),
                        "PoolSize"));
                executorInfoTable.getItems().add(new ExecutorInfo(
                        "活动线程数",
                        String.valueOf(threadPoolExecutor.getActiveCount()),
                        "当前正在执行任务的线程数"));
                // 添加线程池信息
                executorInfoTable.getItems().add(new ExecutorInfo(
                        "核心线程数",
                        String.valueOf(threadPoolExecutor.getCorePoolSize()),
                        "线程池维护的最小线程数"));
                executorInfoTable.getItems().add(new ExecutorInfo(
                        "最大线程数",
                        String.valueOf(threadPoolExecutor.getMaximumPoolSize()),
                        "线程池允许的最大线程数"));
                executorInfoTable.getItems().add(new ExecutorInfo(
                        "KeepAliveTime",
                        String.valueOf(threadPoolExecutor.getKeepAliveTime(TimeUnit.SECONDS)),
                        "the thread keep-alive time, which is the amount of time that threads may remain idle before being terminated. Threads that wait this amount of time without processing a task will be terminated if there are more than the core number of threads currently in the pool, or if this pool allows core thread timeout."));

                executorInfoTable.getItems().add(new ExecutorInfo(
                        "任务队列大小",
                        String.valueOf(threadPoolExecutor.getQueue().size()),
                        "等待执行的任务数量"));
                executorInfoTable.getItems().add(new ExecutorInfo(
                        "已完成任务数",
                        String.valueOf(threadPoolExecutor.getCompletedTaskCount()),
                        "已完成执行的任务总数"));
                executorInfoTable.getItems().add(new ExecutorInfo(
                        "LargestPoolSize",
                        String.valueOf(threadPoolExecutor.getLargestPoolSize()),
                        "线程池当前状态"));

                // 如果是ScheduledExecutorService，添加额外信息
                if (executorService instanceof ScheduledExecutorService) {
                    executorInfoTable.getItems().add(new ExecutorInfo(
                            "线程池类型",
                            "ScheduledExecutorService",
                            "可调度的线程池"));
                } else {
                    executorInfoTable.getItems().add(new ExecutorInfo(
                            "线程池类型",
                            "ThreadPoolExecutor",
                            "普通线程池"));
                }
            } else {
                executorInfoTable.getItems().add(new ExecutorInfo(
                        "错误",
                        "未知的ExecutorService类型",
                        "无法获取线程池详细信息"));
            }
        } catch (Exception e) {
            executorInfoTable.getItems().add(new ExecutorInfo(
                    "异常",
                    e.getMessage(),
                    "获取ExecutorService信息时发生错误"));
        }
    }

    /**
     * 取消选中的任务
     */
    @FXML
    private void onCancelTask() {
        MonitoredTask<?> selectedTask = activeTasksTable.getSelectionModel().getSelectedItem();
        if (selectedTask != null) {
            Desktop.instance.getTaskMonitorCenter().cancelTask(selectedTask.getTaskId());
        }
    }

    /**
     * 清空历史记录
     */
    @FXML
    private void onClearHistory() {
        Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
        alert.setTitle("确认操作");
        alert.setHeaderText("清空任务历史");
        alert.setContentText("确定要清空所有任务历史记录吗？此操作不可恢复。");

        alert.showAndWait().ifPresent(response -> {
            if (response == ButtonType.OK) {
                Desktop.instance.getTaskMonitorCenter().getTaskHistory().clear();
            }
        });
    }

    /**
     * 显示任务详情
     */
    private void showTaskDetails(TaskHistory history) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle("任务详情");
        alert.setHeaderText(history.getTitle());

        ScrollPane scrollPane = new ScrollPane();
        scrollPane.setPrefHeight(300);
        VBox vBox = new VBox();

        Label taskIdLabel = new Label("任务ID: " + history.getTaskId());
        Label statusLabel = new Label("状态: " + history.getStatus().getDescription());
        Label startTimeLabel = new Label("开始时间: " + MyDateTimeUtils.format(history.getStartTime()));
        Label endTimeLabel = new Label("结束时间: " + MyDateTimeUtils.format(history.getEndTime()));
        Label executionTimeLabel = new Label("执行耗时: " + history.getFormattedExecutionTime());

        vBox.getChildren().addAll(taskIdLabel, statusLabel, startTimeLabel, endTimeLabel, executionTimeLabel);

        Label messageLabel = new Label("消息:");
        vBox.getChildren().add(messageLabel);

        for (Message msg : history.getMessages()) {
            Text text = new Text(msg.getMessage());
            if (msg.getLevel() == Level.INFO) {
                text.setFill(Color.BLUE);
            } else if (msg.getLevel() == Level.WARNING) {
                text.setFill(Color.ORANGE);
            } else if (msg.getLevel() == Level.SEVERE) {
                text.setFill(Color.RED);
            } else if (msg.getLevel() == Level.CONFIG) {
                text.setFill(Color.GRAY);
            }
            vBox.getChildren().add(text);
        }

        if (history.getErrorMessage() != null) {
            alert.getDialogPane().setExpandableContent(new TextArea(history.getErrorMessage()));
        }
        scrollPane.setContent(vBox);
        alert.getDialogPane().setContent(scrollPane);
        alert.showAndWait();
    }

    /**
     * 运行任务监控演示
     */
    public void onRunTaskMonitorDemo(ActionEvent event) {
        com.ecep.contract.task.DemoTask.runDemo();
    }
}