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)); } 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.UpdateAdvocate(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) { LicenseType licenseType = LicenseType.None; foreach (var elem in checkedListBox.CheckedItems) { licenseType |= (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); } } }