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

import com.zhangmeng.online.exam.ui.module.Permission;
import com.zhangmeng.online.exam.ui.module.Role;
import com.zhangmeng.online.exam.ui.service.LogService;
import com.zhangmeng.online.exam.ui.service.RoleService;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.Parent;
import javafx.scene.control.Alert;
import javafx.scene.control.CheckBoxTreeItem;
import javafx.scene.control.Label;
import javafx.scene.control.TreeView;
import javafx.scene.control.cell.CheckBoxTreeCell;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import com.zhangmeng.online.exam.ui.service.PermissionService;

/**
 * @author zm
 * @date 2025/4/10 11:14
 * @version: 1.0
 */
public class PermissionChooseController {

    @FXML
    public VBox permissionChooseVBox;

    @FXML
    private Label titleLabel;

    @FXML
    private TreeView<PermissionWrapper> permissionTree;

    private Role role;
    private boolean saveClicked = false;

    private static final ObservableList<Permission> permissions = FXCollections.observableArrayList();

    // 添加一个包装类来存储Permission对象
    private static class PermissionWrapper {
        private final Permission permission;

        public PermissionWrapper(Permission permission) {
            this.permission = permission;
        }

        public Permission getPermission() {
            return permission;
        }

        @Override
        public String toString() {
            return permission.getName();
        }
    }

    @FXML
    public void initialize() {
        initializePermissionTree();
    }

    private void initializePermissionTree() {
        // 使用CheckBoxTreeItem作为根节点
        CheckBoxTreeItem<PermissionWrapper> root = new CheckBoxTreeItem<>(new PermissionWrapper(null));
        root.setValue(new PermissionWrapper(null) {
            @Override
            public String toString() {
                return "所有权限";
            }
        });

        // 加载系统权限
        for (Permission permission : PermissionService.getRootPermissions()) {
            CheckBoxTreeItem<PermissionWrapper> item = createPermissionTreeItem(permission);
            root.getChildren().add(item);
        }

        root.setExpanded(true);
        permissionTree.setRoot(root);
        permissionTree.setCellFactory(CheckBoxTreeCell.forTreeView());

    }

    private CheckBoxTreeItem<PermissionWrapper> createPermissionTreeItem(Permission permission) {
        CheckBoxTreeItem<PermissionWrapper> item = new CheckBoxTreeItem<>(new PermissionWrapper(permission));
//        item.selectedProperty().addListener((observable, oldValue, newValue) -> {
//            if (newValue) {
//                System.out.println("selected: " + permission.getName());
//            } else {
//                System.out.println("unselected: " + permission.getName());
//            }
//        });

        for (Permission child : permission.getChildren()) {
            item.getChildren().add(createPermissionTreeItem(child));
        }

        item.setExpanded(true);
        return item;
    }

    public void setRole(Role role) {
        this.role = role;
        titleLabel.setText("设置角色权限 - " + role.getName());

        // 设置已有权限的选中状态
        setPermissionChecked((CheckBoxTreeItem<PermissionWrapper>) permissionTree.getRoot());
    }

    private void setPermissionChecked(CheckBoxTreeItem<PermissionWrapper> item) {
        Permission permission = item.getValue().getPermission();
        if (permission != null && role.hasPermission(permission.getId())) {

            if (permission.getParentId() == 0){
                item.setIndeterminate(true);
            }else {
                item.setSelected(true);
            }

        }

        item.getChildren().forEach(child ->
                setPermissionChecked((CheckBoxTreeItem<PermissionWrapper>) child)
        );
    }

    @FXML
    private void handleSave() {
        try {
            permissions.clear();
            // 收集选中的权限
            collectSelectedPermissions((CheckBoxTreeItem<PermissionWrapper>) permissionTree.getRoot());

            if (role != null) {
                // 清除现有权限
                role.getPermissions().clear();
                role.getPermissions().addAll(permissions);
            }
            for (Permission permission : permissions) {
                System.out.println(permission.getName());
            }
            LogService.log("角色管理", "更新", "更新角色权限：" + role.getName());

            RoleService.updatePermission(role.getId(), permissions);

            saveClicked = true;
            closeDialog();
        } catch (Exception e) {
            LogService.log("角色管理", "更新", "更新角色权限失败", e);
            showError("保存失败", e.getMessage());
        }
    }

    private void collectSelectedPermissions(CheckBoxTreeItem<PermissionWrapper> item) {

        if (item.isSelected() || item.isIndeterminate() ) {
            Permission permission = item.getValue().getPermission();
            if (permission != null) {
                permissions.add(permission);
            }
        }

        item.getChildren().forEach(child ->
                collectSelectedPermissions((CheckBoxTreeItem<PermissionWrapper>) child)
        );
    }

    @FXML
    private void handleCancel() {
        closeDialog();
    }

    private void closeDialog() {
        Stage stage = (Stage) titleLabel.getScene().getWindow();
        stage.close();
    }

    public boolean isSaveClicked() {
        return saveClicked;
    }

    private void showError(String title, String message) {
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(message);
        alert.showAndWait();
    }
}
