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

    @FXML
    public ListView<Role> roleListView;

    private User user;
    public boolean saveClicked = false;

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

        // 初始化角色列表
        roleListView.setItems(FXCollections.observableArrayList(RoleService.getAllRoles()));

        Callback<ListView<Role>, ListCell<Role>> call = CheckBoxListCell.forListView(new Callback<Role, ObservableValue<Boolean>>() {
            @Override
            public ObservableValue<Boolean> call(Role param) {
                return param.selectedProperty();
            }
        }, new StringConverter<Role>() {
            @Override
            public String toString(Role object) {
                if (object != null) {
                    System.out.println("姓名:" + object.getName() + "  是否选择:" + object.isSelected());
                    return object.getName();
                }
               return null;
            }

            @Override
            public Role fromString(String string) {
                return null;
            }
        });


        roleListView.setCellFactory(call);
        roleListView.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<Role>() {
            @Override
            public void changed(ObservableValue<? extends Role> observable, Role oldValue, Role newValue) {
                System.out.println("姓名:" + newValue.getName() + "  是否选择:" + newValue.isSelected());
            }
        });


    }

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

        usernameField.setText(user.getUsername());
        phoneField.setText(user.getPhone());
        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.setPhone(phoneField.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 (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");
        }

        Role role = roleListView.getSelectionModel().getSelectedItem();

        if (role == null) {
            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());
    }

}
