ISEbd-22_Rozhkov.I.E._Simple/GasStation/Forms/FormProduct.cs

95 lines
3.1 KiB
C#
Raw Normal View History

2024-11-15 18:27:06 +04:00
using GasStation.Entities.Enums;
using GasStation.Repositories;
using GasStation.Entities;
namespace GasStation.Forms
{
public partial class FormProduct : Form
{
private readonly IProductRepository _productRepository;
private int? _productId;
public FormProduct(IProductRepository productRepository)
{
InitializeComponent();
_productRepository = productRepository ??
throw new ArgumentNullException(nameof(productRepository));
foreach (var elem in Enum.GetValues(typeof(Gasmen)))
{
checkedListBoxGasman.Items.Add(elem);
}
}
public int ID
{
set
{
try
{
var product = _productRepository.ReadProductByID(value);
if (product == null)
{
throw new InvalidDataException(nameof(product));
}
foreach(Gasmen elem in Enum.GetValues(typeof(Gasmen)))
{
if ((elem & product.Gasmen) != 0)
{
checkedListBoxGasman.SetItemChecked(checkedListBoxGasman.Items.IndexOf(elem), true);
}
}
checkedListBoxGasman.SelectedItem = product.Gasmen;
comboBoxProduct.SelectedItem = product.ProductType;
_productId = value;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при получении данных", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
}
private void ButtonSave_Click(object sender, EventArgs e)
{
try
{
if (checkedListBoxGasman.CheckedItems.Count == 0)
{
throw new Exception("Имеются незаполненые поля");
}
if (_productId.HasValue)
{
_productRepository.UpdateProduct(CreateProduct(_productId.Value));
}
else
{
_productRepository.CreateProduct(CreateProduct(0));
}
Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при сохранении", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
private void ButtonCancel_Click(object sender, EventArgs e) => Close();
private Product CreateProduct(int id)
{
Gasmen gasmen = Gasmen.None;
foreach (var elem in checkedListBoxGasman.CheckedItems)
{
gasmen |= (Gasmen)elem;
}
return Product.CreateProduct(id, Convert.ToInt32(numericUpDownCost.Value), gasmen, (ProductType)comboBoxProduct.SelectedItem!);
}
}
}