81 lines
2.8 KiB
C#

using Publication.Entites.Enums;
using Publication.Repositories;
using System;
using System.Collections.Generic;
namespace Publication.Forms;
public partial class FormCustomer : Form
{
private readonly ICustomerRepository customerRepository;
private int? customerId;
public int Id
{
set
{
try
{
var customer = customerRepository.ReadCustomerById(value);
if (customer == null)
{
throw new InvalidDataException(nameof(customer));
}
textBoxFullName.Text = customer.FullName;
numericUpDownAge.Value = customer.Age;
textBoxPhone.Text = customer.Phone;
textBoxEmail.Text = customer.Email;
comboBoxTypeCustomer.SelectedItem = customer.TypeCustomer;
customer.Age = int.Parse(numericUpDownAge.Value.ToString());
customerId = value;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при получении данных", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
}
public FormCustomer(ICustomerRepository _customerRepository)
{
customerRepository = _customerRepository ??
throw new ArgumentNullException(nameof(_customerRepository));
InitializeComponent();
comboBoxTypeCustomer.DataSource = Enum.GetValues(typeof(TypeCustomers));
}
private void buttonSave_Click(object sender, EventArgs e)
{
try
{
if (string.IsNullOrWhiteSpace(textBoxFullName.Text) ||
string.IsNullOrWhiteSpace(textBoxPhone.Text) ||
string.IsNullOrWhiteSpace(textBoxEmail.Text) ||
comboBoxTypeCustomer.SelectedIndex < 1 ||
int.Parse(numericUpDownAge.Value.ToString()) <= 0)
{
throw new Exception("Имеются незаполненные поля");
}
if (customerId.HasValue)
{
customerRepository.UpdateCustomer(CreateCustomer(customerId.Value));
}
else
{
customerRepository.CreateCustomer(CreateCustomer(0));
}
Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при сохранении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void buttonBreak_Click(object sender, EventArgs e) => Close();
private Customers CreateCustomer(int id) => Customers.CreateEntity(id, textBoxFullName.Text, int.Parse(numericUpDownAge.Value.ToString()), (TypeCustomers)comboBoxTypeCustomer.SelectedItem!, textBoxPhone.Text, textBoxEmail.Text);
}