PIbd-33_Nevaeva_KA_COP_28/NevaevaLibrary/AccountsView/FormAccount.cs
2023-12-01 01:17:26 +04:00

104 lines
3.8 KiB
C#

using AbazovViewComponents.Components;
using AccountContracts.BindingModels;
using AccountContracts.BusinessLogicsContracts;
using AccountContracts.SearchModels;
using AccountContracts.ViewModels;
using NevaevaLibrary;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AccountsView
{
public partial class FormAccount : Form
{
private int? _id;
private readonly IAccountLogic _logic;
private readonly IRoleLogic _roleLogic;
private List<RoleViewModel> _roles;
public int Id { set { _id = value; } }
public FormAccount(IAccountLogic logic, IRoleLogic roleLogic)
{
InitializeComponent();
_logic = logic;
_roleLogic = roleLogic;
_roles = new List<RoleViewModel>();
}
private void FormAccount_Load(object sender, EventArgs e)
{
_roles = _roleLogic.ReadList();
comboBoxControlRole.addItems(_roles.Select(x => x.RoleName).ToList());
if (_id.HasValue)
{
try
{
var view = _logic.ReadElement(new AccountSearchModel { Id = _id.Value });
if (view != null)
{
textBoxLogin.Text = view.Login;
textBoxWarnings.Text = view.Warnings;
controlInputRating.Value = view.Rating;
comboBoxControlRole.SelectedValue = view.RoleName;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void buttonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
private void buttonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxLogin.Text))
{
MessageBox.Show("Заполните логин", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.IsNullOrEmpty(comboBoxControlRole.SelectedValue))
{
MessageBox.Show("Выберете роль", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
try
{
var model = new AccountBindingModel
{
Id = _id ?? 0,
Login = textBoxLogin.Text,
Warnings = textBoxWarnings.Text,
Rating = controlInputRating.Value.HasValue ? (float)controlInputRating.Value.GetValueOrDefault() : null,
RoleId = _roles.First(x => x.RoleName == comboBoxControlRole.SelectedValue).Id,
};
var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model);
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}