package com.zhangmeng.online.exam.ui.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.zhangmeng.online.exam.ui.admin.IndexPage;
import com.zhangmeng.online.exam.ui.admin.UserListPage;
import com.zhangmeng.online.exam.ui.api.ApiUtils;
import com.zhangmeng.online.exam.ui.components.DynamicTableComponent;
import com.zhangmeng.online.exam.ui.components.callBack.DynamicTableComponentCallBackImpl;
import com.zhangmeng.online.exam.ui.layouts.SideMenu;
import com.zhangmeng.online.exam.ui.module.MenuData;
import com.zhangmeng.online.exam.ui.module.User;
import com.zhangmeng.online.exam.ui.utils.FxUtils;
import com.zhangmeng.online.exam.ui.utils.HttpUtils;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

import java.util.ArrayList;
import java.util.List;

import com.zhangmeng.online.exam.ui.service.UserService;
import javafx.util.Callback;

/**
 * @author zm
 * @date 2025/3/31 15:17
 * @version: 1.0
 */
public class MainController {

    @FXML
    private TreeView<MenuData> menuTree;

    @FXML
    private TabPane contentTabPane;

    @FXML
    private Label userLabel;

    @FXML
    public void initialize() {
        initializeMenu();
        // 显示当前用户
        User currentUser = UserService.getCurrentUser();
        if (currentUser != null) {
            userLabel.setText("当前用户：" + currentUser.getUsername());
        }

        // 添加菜单点击事件
        menuTree.setOnMouseClicked(event -> {
            TreeItem<MenuData> selectedItem = menuTree.getSelectionModel().getSelectedItem();
            if (selectedItem != null && selectedItem.isLeaf()) {
                openTab(selectedItem.getValue());
            }
        });
    }

    private void initializeMenu() {
        TreeItem<MenuData> root = new TreeItem<>(new MenuData("系统菜单", null, null));
        root.setGraphic(new Label(root.getValue().getTitle()));
        root.setExpanded(true);

        menuTree.setCellFactory(new Callback<TreeView<MenuData>, TreeCell<MenuData>>() {
            @Override
            public TreeCell<MenuData> call(TreeView<MenuData> menuDataTreeView) {
                return new TreeCell<MenuData>() {
                    @Override
                    protected void updateItem(MenuData item, boolean empty) {
                        super.updateItem(item, empty);
                        if (!empty) {
                            HBox hBox = new HBox();
                            hBox.setAlignment(Pos.CENTER);
                            Label label = new Label(item.getTitle());
                            hBox.getChildren().addAll(label);
                            hBox.setMaxWidth(50);
                            this.setGraphic(hBox);
                        } else {
                            this.setGraphic(null);
                        }
                    }
                };
            }
        });
        root.getChildren().addAll(UserService.menu_tree_item());
        menuTree.setRoot(root);

        ContextMenu contextMenu = new ContextMenu();
        MenuItem close_current_tab = new MenuItem("关闭当前标签");

        close_current_tab.setOnAction(actionEvent -> {
            Tab selectedItem = contentTabPane.getSelectionModel().getSelectedItem();
            contentTabPane.getTabs().remove(selectedItem);
        });

        MenuItem close_all_tab = new MenuItem("关闭全部标签");
        close_all_tab.setOnAction(actionEvent -> {
            contentTabPane.getTabs().clear();
        });


        contextMenu.getItems().add(close_current_tab);
        contextMenu.getItems().add(close_all_tab);
        contentTabPane.setContextMenu(contextMenu);
    }

    private void openTab(MenuData menuData) {
        // 检查是否已经存在相同的标签页
        for (Tab tab : contentTabPane.getTabs()) {
            MenuData userData = (MenuData) tab.getUserData();
            if (userData.getUrl().equals(menuData.getUrl())) {
                contentTabPane.getSelectionModel().select(tab);
                return;
            }
        }

        try {
            // 创建新的标签页
            Tab tab = new Tab(menuData.getTitle());
            tab.setUserData(menuData);

            // 根据标题加载不同的内容
            Node content = switch (menuData.getUrl()) {
                case "/user/list" ->  init_table( ApiUtils.getUserList(),FxUtils.User_DynamicTableComponent);
                case "/paper/list" -> init_table(ApiUtils.getExamPaper(),FxUtils.Paper_DynamicTableComponent);
                case "/role/list" -> init_table(ApiUtils.getRoleList(),FxUtils.Role_DynamicTableComponent);
                case "/question/list" -> init_table(ApiUtils.getQuestionList(),FxUtils.Question_DynamicTableComponent);
                case "/subject/list" -> init_table(ApiUtils.getSubjectList(),FxUtils.Subject_DynamicTableComponent);
                case "/questionOption/list" -> init_table(ApiUtils.getQuestionOptionList(),FxUtils.QuestionOption_DynamicTableComponent);
                case "/permission/list" -> init_table(ApiUtils.getPermissionList(),FxUtils.Permission_DynamicTableComponent);
                case "/profession/list" -> init_table(ApiUtils.getProfessionList(),FxUtils.Profession_DynamicTableComponent);
                case "发布公告" -> FXMLLoader.load(getClass().getResource("/fxml/notice-edit.fxml"));
                case "在线用户" -> FXMLLoader.load(getClass().getResource("/fxml/monitor-online.fxml"));
                case "系统日志" -> FXMLLoader.load(getClass().getResource("/fxml/monitor-log.fxml"));
                case "性能监控" -> FXMLLoader.load(getClass().getResource("/fxml/monitor-performance.fxml"));
                case "数据监控" -> FXMLLoader.load(getClass().getResource("/fxml/monitor-data.fxml"));
                default -> new Label("这是" + menuData.getTitle() + "的内容页面");
            };

            tab.setContent(content);
            contentTabPane.getTabs().add(tab);
            contentTabPane.getSelectionModel().select(tab);
        } catch (Exception e) {
            e.printStackTrace();
            Alert alert = new Alert(Alert.AlertType.ERROR);
            alert.setTitle("错误");
            alert.setHeaderText(null);
            alert.setContentText("加载页面失败：" + e.getMessage());
            alert.showAndWait();
        }
    }

    private DynamicTableComponent init_table(ApiUtils.DataView dataView,String type) {
        dataView.setPageNum(dataView.getPageNum());
        dataView.setPageSize(dataView.getPageSize());
        dataView.setTotal(dataView.getTotal());
        DynamicTableComponent dynamicTableComponent = new DynamicTableComponent(dataView);
        dynamicTableComponent.setCallBack(new DynamicTableComponentCallBackImpl(dataView.getDataLoad(),dataView.getDataLoad().getForm()));
        dynamicTableComponent.setPadding(new Insets(15));
        dynamicTableComponent.prefHeightProperty().bind(contentTabPane.heightProperty().subtract(15));

        FxUtils.FX_BEANS.put(type,dynamicTableComponent);

        return dynamicTableComponent;
    }

    @FXML
    private void handleLogout() {
        try {
            UserService.logout();
            Parent root = FXMLLoader.load(getClass().getResource("/fxml/login.fxml"));
            Stage stage = (Stage) userLabel.getScene().getWindow();
            stage.setScene(new Scene(root));
            stage.centerOnScreen();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
