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.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;

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

    @FXML
    private TextField nameField;

    @FXML
    private PasswordField passwordField;

    @FXML
    private TextField emailField;

    @FXML
    private ComboBox<String> statusComboBox;

    @FXML
    private ListView<Role> roleListView;

    private User user;
    private boolean saveClicked = false;

    @FXML
    public void initialize() {
        // 初始化状态下拉框
        statusComboBox.getItems().addAll("启用", "禁用");
        statusComboBox.setValue("启用");

        // 初始化角色列表
        roleListView.setItems(FXCollections.observableArrayList(RoleService.getAllRoles()));
        roleListView.setCellFactory(CheckBoxListCell.forListView(role -> {
            return role.selectedProperty();
        }));
    }

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

        usernameField.setText(user.getUsername());
        nameField.setText(user.getName());
        emailField.setText(user.getEmail());
        statusComboBox.setValue(user.getStatus());

        // 设置已有角色的选中状态
        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.setName(nameField.getText());
            user.setEmail(emailField.getText());
            user.setStatus(statusComboBox.getValue());

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

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

            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 (nameField.getText() == null || nameField.getText().trim().isEmpty()) {
            errorMessage.append("姓名不能为空！\n");
        }
        if (user == null && (passwordField.getText() == null || passwordField.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");
        }

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

}
