PIBD14-Boyko-M.S.-GSM-Autot.../ProjectGSM/Forms/FormAdvocate.cs
2024-12-02 20:36:33 +04:00

123 lines
4.3 KiB
C#

using Microsoft.VisualBasic.FileIO;
using ProjectGSM.Entities;
using ProjectGSM.Entities.Enums;
using ProjectGSM.Repositories;
namespace ProjectGSM.Forms
{
public partial class FormAdvocate : Form
{
private readonly IAdvocateRepository _advocateRepository;
private int? _advocateId;
public int Id
{
set
{
try
{
var advocate =
_advocateRepository.ReadAdvocateById(value);
if (advocate == null)
{
throw new
InvalidDataException(nameof(advocate));
}
_advocateId = value;
foreach (LicenseType elem in Enum.GetValues(typeof(LicenseType)))
{
if ((elem & advocate.LicenseType) != 0)
{
checkedListBox.SetItemChecked(checkedListBox.Items.IndexOf(
elem), true);
}
}
nameTextBox.Text = advocate.Name;
sexCheckBox.Checked = advocate.Sex;
dateTimePicker.Value = new DateTime(advocate.DateOfBirth.Year, advocate.DateOfBirth.Month,
advocate.DateOfBirth.Day);
expNumeric.Value = advocate.Experience;
tasksNumeric.Value = advocate.CompletedTasks;
ratingNumeric.Value = advocate.Rating;
emailTextBox.Text = advocate.Email;
phoneText.Text = advocate.PhoneNumber;
adressBox.Text = advocate.Address;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при получении данных", MessageBoxButtons.OK,
MessageBoxIcon.Error);
return;
}
}
}
public FormAdvocate(IAdvocateRepository advocateRepository)
{
InitializeComponent();
_advocateRepository = advocateRepository ??
throw new
ArgumentNullException(nameof(advocateRepository));
foreach (var elem in Enum.GetValues(typeof(LicenseType)))
{
checkedListBox.Items.Add(elem);
}
}
private void saveButton_Click(object sender, EventArgs e)
{
try
{
if (string.IsNullOrWhiteSpace(nameTextBox.Text) ||
string.IsNullOrWhiteSpace(emailTextBox.Text) ||
string.IsNullOrWhiteSpace(phoneText.Text) ||
string.IsNullOrWhiteSpace(adressBox.Text) || checkedListBox.CheckedItems.Count == 0)
{
throw new Exception("Имеются незаполненные поля");
}
if (_advocateId.HasValue)
{
_advocateRepository.UpdateAdvocate(CreateAdvocate(_advocateId.Value));
}
else
{
_advocateRepository.CreateAdvocate(CreateAdvocate(0));
}
Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при сохранении",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void cancelButton_Click(object sender, EventArgs e) => Close();
private Advocate CreateAdvocate(int id)
{
int licenseType = 0;
foreach (int elem in checkedListBox.CheckedItems)
{
licenseType |= elem;
}
return Advocate.CreateEntity(id,
nameTextBox.Text,
sexCheckBox.Checked,
dateTimePicker.Value,
Convert.ToInt32(expNumeric.Value),
Convert.ToInt32(tasksNumeric.Value),
Convert.ToInt32(ratingNumeric.Value),
emailTextBox.Text,
phoneText.Text,
adressBox.Text, (LicenseType)licenseType);
}
}
}