package com.ecep.contract.controller;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

import org.controlsfx.control.TaskProgressView;
import org.controlsfx.glyphfont.Glyph;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Scope;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import com.ecep.contract.Desktop;
import com.ecep.contract.DesktopUtils;
import com.ecep.contract.WebSocketService;
import com.ecep.contract.controller.bank.BankManagerWindowController;
import com.ecep.contract.controller.company.CompanyManagerWindowController;
import com.ecep.contract.controller.contract.ContractManagerWindowController;
import com.ecep.contract.controller.customer.CompanyCustomerManagerWindowController;
import com.ecep.contract.controller.department.DepartmentManagerWindowController;
import com.ecep.contract.controller.employee.EmployeeManagerWindowController;
import com.ecep.contract.controller.inventory.InventoryManagerWindowController;
import com.ecep.contract.controller.permission.EmployeeFunctionsManagerWindowController;
import com.ecep.contract.controller.permission.EmployeeRoleManagerWindowController;
import com.ecep.contract.controller.project.ProjectManagerWindowController;
import com.ecep.contract.controller.vendor.CompanyVendorManagerWindowController;
import com.ecep.contract.service.CloudRkService;
import com.ecep.contract.service.YongYouU8Service;
import com.ecep.contract.task.ContractSyncTask;
import com.ecep.contract.util.FxmlPath;
import com.ecep.contract.util.FxmlUtils;
import com.ecep.contract.vm.CurrentEmployee;

import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.MenuItem;
import javafx.scene.layout.VBox;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;

@Lazy
@Scope("prototype")
@Component
@FxmlPath("/ui/home.fxml")
public class HomeWindowController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(HomeWindowController.class);

    public static CompletableFuture<Void> show() {
        return show(HomeWindowController.class, null);
    }

    // searcher
    public VBox root;
    public Label statusLabel;
    public Button openCompanyManagerWindow;
    public Button openProjectManagerWindow;
    public Button openContractManagerWindow;
    public Button openVendorManagerWindow;
    public Button openCustomManagerWindow;
    public TaskProgressView<Task<?>> taskProgressView;
    public Label taskMonitorLabel;
    public Label webSocketMonitorLabel;
    public Glyph webSocketMonitorIcon;
    public Label employeeStatusLabel;

    public void initialize() {
        openCompanyManagerWindow.setOnAction(event -> showInOwner(CompanyManagerWindowController.class));
        openProjectManagerWindow.setOnAction(event -> showInOwner(ProjectManagerWindowController.class));
        openContractManagerWindow.setOnAction(event -> showInOwner(ContractManagerWindowController.class));
        openVendorManagerWindow.setOnAction(event -> showInOwner(CompanyVendorManagerWindowController.class));
        openCustomManagerWindow.setOnAction(event -> showInOwner(CompanyCustomerManagerWindowController.class));
    }

    private <T extends BaseController> void showInOwner(Class<T> clz) {
        show(clz, root.getScene().getWindow());
    }

    @Override
    public void onShown(WindowEvent windowEvent) {
        super.onShown(windowEvent);
        getTitle().set("销售与采购流程管理");
        // ((TaskProgressViewSkin<Task<?>>)taskProgressView.getSkin()).
        taskProgressView.setRetainTasks(false);
        Node listView = taskProgressView.getSkin().getNode().lookup("ListView");
        Node placeholder = ((ListView<?>) listView).getPlaceholder();
        ((Label) placeholder).setText("没有运行的任务");

        employeeStatusLabel.textProperty().bind(Desktop.instance.getActiveEmployee().getName());
        Desktop.instance.getTaskMonitorCenter().bindStatusLabel(taskMonitorLabel);
        Desktop.instance.getActiveEmployee().initialize();

        WebSocketService webSocketService = getBean(WebSocketService.class);
        webSocketMonitorIcon.iconProperty()
                .bind(webSocketService.getOnlineProperty().map(b -> b ? "CHAIN" : "CHAIN_BROKEN"));
        webSocketMonitorLabel.textProperty().bind(webSocketService.getMessageProperty());
        webSocketMonitorLabel.setOnMouseClicked(event -> {
            webSocketService.send("webSocketUrl - " + LocalDateTime.now().toString());
        });
        webSocketService.initWebSocket();
    }

    @EventListener
    public void onCurrentEmployeeInitialed(CurrentEmployeeInitialedEvent event) {
        CurrentEmployee currentEmployee = event.getEmployee();
        if (currentEmployee.isSystemAdministrator()) {
            if (logger.isInfoEnabled()) {
                logger.info("You are administrator, try schedule sync tasks.");
            }
            Desktop.instance.getExecutorService().schedule(() -> {
                try {
                    getBean(YongYouU8Service.class).scheduledTasks(taskProgressView);
                } catch (BeansException ignored) {
                }
                try {
                    getBean(CloudRkService.class).scheduledTasks(taskProgressView);
                } catch (BeansException ignored) {
                }
            }, 15, TimeUnit.SECONDS);
        }
    }

    @Override
    public void onHiding(WindowEvent windowEvent) {
        super.onHiding(windowEvent);
        List<Task<?>> tasks = new ArrayList<>(taskProgressView.getTasks());
        for (Task<?> task : tasks) {
            task.cancel();
        }

        // scheduledExecutorService.shutdown();
        // scheduledExecutorService.shutdownNow();
    }

    /**
     * 打开 配置 窗口
     */
    public void openConfigWindow(ActionEvent actionEvent) {
        FxmlUtils.newLoaderAsyncWithRunLater("/ui/configs.fxml", null, loader -> {
            Scene scene = new Scene(loader.getRoot());
            Stage stage = new Stage();
            stage.initOwner(root.getScene().getWindow());
            stage.initModality(Modality.NONE);
            stage.setTitle("选项");
            stage.setScene(scene);
            stage.show();
        });
    }

    public void createNewU8ContractSyncTaskAction(ActionEvent event) {
        try {
            ContractSyncTask task = new ContractSyncTask();
            Desktop.instance.getTaskMonitorCenter().registerAndStartTask(task);
        } catch (Exception e) {
            handleException("创建U8合同同步任务失败", e);
        }
    }

    public void openInBrowse(ActionEvent event) {
        MenuItem source = (MenuItem) event.getSource();
        String url = (String) source.getUserData();
        DesktopUtils.showInBrowse(url);
    }

    public void openGroupRKResourceWindow(ActionEvent event) {
        CloudRkManagerWindowController.show();
    }

    public void openTycResourceWindow(ActionEvent event) {
        CloudTycManagerWindowController.show();
    }

    public void openYongYouResourceWindow(ActionEvent event) {
        YongYouU8ManagerWindowController.show();
    }

    public void onShowEmployeeManagerWindowAction(ActionEvent event) {
        showInOwner(EmployeeManagerWindowController.class);
    }

    public void onShowDepartmentManagerWindowAction(ActionEvent event) {
        showInOwner(DepartmentManagerWindowController.class);
    }

    public void onShowRolesManagerWindowAction(ActionEvent event) {
        showInOwner(EmployeeRoleManagerWindowController.class);
    }

    public void onShowFunctionManagerWindowAction(ActionEvent event) {
        showInOwner(EmployeeFunctionsManagerWindowController.class);
    }

    public void onShowBankManagerWindowAction(ActionEvent event) {
        showInOwner(BankManagerWindowController.class);
    }

    public void onShowInventoryManagerWindowAction(ActionEvent event) {
        showInOwner(InventoryManagerWindowController.class);
    }

    /**
     * 打开任务监控中心窗口
     */
    public void onShowTaskMonitorWindowAction(ActionEvent event) {
        showInOwner(TaskMonitorViewController.class);
    }

    @Override
    public void onHidden(WindowEvent windowEvent) {
        System.out.println("windowEvent = " + windowEvent);
        WebSocketService webSocketService = getBean(WebSocketService.class);
        webSocketService.closeWebSocket(); // 在窗口隐藏时关闭WebSocket连接
        super.onHidden(windowEvent);
    }
}
