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

import com.zhangmeng.online.exam.ui.module.Role;
import com.zhangmeng.online.exam.ui.module.User;
import com.zhangmeng.online.exam.ui.service.LogService;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.collections.transformation.SortedList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.CheckBoxListCell;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.HBox;
import javafx.stage.Modality;
import javafx.stage.Stage;
import com.zhangmeng.online.exam.ui.service.RoleService;
import com.zhangmeng.online.exam.ui.service.UserService;
import javafx.util.Callback;
import javafx.util.StringConverter;

/**
 * @author zm
 * @date 2025/3/31 16:59
 * @version: 1.0
 */
public class UserEditController {
    @FXML
    public TextField usernameField;

    @FXML
    public TextField phoneField;

    @FXML
    public PasswordField passwordField;

    @FXML
    public TextField emailField;

    @FXML
    public ComboBox<PaperEditController.Status> statusComboBox;

    @FXML
    public ListView<Role> roleListView;

    private User user;
    public boolean saveClicked = false;

    @FXML
    public void initialize() {
        // 初始化状态下拉框
        /**
         *         DISABLED("已停用"),
         *         VALID("正常"),
         *         LOCKED("锁定");
         */
        PaperEditController.Status status1 = new PaperEditController.Status("已停用", 0);
        PaperEditController.Status status2 = new PaperEditController.Status("正常", 1);
        PaperEditController.Status status3 = new PaperEditController.Status("已锁定", 2);
        statusComboBox.getItems().addAll(status2, status1,status3);
        statusComboBox.setValue(status2);

        statusComboBox.setConverter(new StringConverter<PaperEditController.Status>() {
            @Override
            public String toString(PaperEditController.Status object) {
                return object.getName();
            }

            @Override
            public PaperEditController.Status fromString(String string) {
                return null;
            }
        });

        statusComboBox.setCellFactory(new Callback<ListView<PaperEditController.Status>, ListCell<PaperEditController.Status>>() {
            @Override
            public ListCell<PaperEditController.Status> call(ListView<PaperEditController.Status> statusListView) {
                return new ListCell<>() {
                    @Override
                    protected void updateItem(PaperEditController.Status item, boolean empty) {
                        super.updateItem(item, empty);
                        if (item != null && !empty) {
                            HBox hBox = new HBox();
                            Label label = new Label(item.getName());
                            hBox.getChildren().add(label);
                            setGraphic(hBox);
                        }
                    }
                };
            }
        });

        // 初始化角色列表
        roleListView.setItems(FXCollections.observableArrayList(RoleService.getAllRoles()));
        roleListView.setCellFactory(CheckBoxListCell.forListView(Role::selectedProperty));
    }

    public void setUser(User user) {
        this.user = user;

        usernameField.setText(user.getUsername());
        phoneField.setText(user.getPhone());
        emailField.setText(user.getEmail());


        // 设置已有角色的选中状态
        user.getRoles().forEach(role -> {
            role.setSelected(true);
        });

        // 编辑模式下禁用用户名修改
        usernameField.setDisable(true);
        // 编辑模式下密码为可选
        passwordField.setPromptText("不修改请留空");
    }

    @FXML
    private void handleSave() {
        if (!validateInput()) {
            return;
        }

        try {
            if (user == null) {
                // 创建新用户
                user = new User();
                user.setUsername(usernameField.getText());
                user.setPassword(passwordField.getText());
            } else if (!passwordField.getText().isEmpty()) {
                // 如果输入了新密码，则更新密码
                user.setPassword(passwordField.getText());
            }

            // 更新基本信息
            user.setPhone(phoneField.getText());
            user.setEmail(emailField.getText());
            user.setStatus(String.valueOf(statusComboBox.getValue().getValue()));

            // 更新角色
            user.getRoles().clear();
            roleListView.getItems().stream()
                    .filter(Role::isSelected)
                    .forEach(user::addRole);

            // 保存用户
            if (user.getId() == 0) {
                LogService.log("用户管理", "创建", "创建用户：" + user.getUsername());
            } else {
                LogService.log("用户管理", "更新", "更新用户：" + user.getUsername());
            }

            UserService.saveUser(user);

            saveClicked = true;
            closeDialog();
        } catch (Exception e) {
            LogService.log("用户管理", "保存", "保存用户失败", e);
            showError("保存失败", e);
        }
    }

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

    private boolean validateInput() {
        StringBuilder errorMessage = new StringBuilder();

        if (usernameField.getText() == null || usernameField.getText().trim().isEmpty()) {
            errorMessage.append("用户名不能为空！\n");
        }

        if (passwordField.getText() == null || passwordField.getText().trim().isEmpty()) {
            errorMessage.append("密码不能为空！\n");
        }

        if (phoneField.getText() == null || phoneField.getText().trim().isEmpty()) {
            errorMessage.append("手机号不能为空！\n");
        }

        if (emailField.getText() == null || emailField.getText().trim().isEmpty()) {
            errorMessage.append("邮箱不能为空！\n");
        }

        if (roleListView.getItems().stream().noneMatch(Role::isSelected)) {
            errorMessage.append("至少选择一个角色！\n");
        }

//        for (Role role : roleListView.getItems()) {
//            System.out.println("角色名称：" + role.getName() + "  是否选择：" + role.isSelected());
//        }

        if (errorMessage.length() == 0) {
            return true;
        } else {
            showError("输入错误", errorMessage.toString());
            return false;
        }
    }

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

    public User getUser() {
        return user;
    }

    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();
    }

    private void showError(String title, Exception e) {
        showError(title, e.getMessage());
    }

}
