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.module.RoleType;
import com.zhangmeng.online.exam.ui.service.RoleService;
import com.zhangmeng.online.exam.ui.utils.AlertUtils;
import com.zhangmeng.online.exam.ui.utils.FxUtils;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import javafx.util.StringConverter;

/**
 * @author zm
 * @date 2025/4/10 10:20
 * @version: 1.0
 */
public class RoleEditController {

    @FXML
    public ComboBox<RoleType> roleComboBox;

    @FXML
    public TextField rolenameField;

    @FXML
    public TextField descriptionField;

    private Role role;

    public void setRole(Role role) {
        this.role = role;
        this.rolenameField.setText(role.getName());
        this.descriptionField.setText(role.getDescription());
    }

    @FXML
    public void initialize() {
        roleComboBox.getItems().addAll(RoleService.getRoleTypes());
        roleComboBox.setConverter(new StringConverter<RoleType>() {
            @Override
            public String toString(RoleType object) {
                if (object == null){
                    return null;
                }
                return object.getDesc();
            }

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

    @FXML
    public void handleSave(ActionEvent actionEvent) {

        RoleType roleType = roleComboBox.getSelectionModel().getSelectedItem();
        if (roleType == null){
            AlertUtils.alert_warning("请选择角色类型");
            return;
        }

        if (rolenameField.getText().trim().isEmpty()){
            AlertUtils.alert_warning("请输入角色名称");
            return;
        }

        if (descriptionField.getText().trim().isEmpty()){
            AlertUtils.alert_warning("请输入角色描述");
            return;
        }

        String roleId = role == null ? "": String.valueOf(role.getId());

        boolean flag = RoleService.saveRole(roleId, rolenameField.getText(), descriptionField.getText(), roleType.getType());
        if (flag){
            AlertUtils.alert_msg("保存成功");
            closeDialog();
            //TODO 刷新角色列表
            FxUtils.FX_BEANS.get(FxUtils.Role_DynamicTableComponent).flushData();
        }else{
            AlertUtils.alert_warning("保存失败");
        }

    }

    @FXML
    public void handleCancel(ActionEvent actionEvent) {
        closeDialog();
    }

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