ProjectLib/ProjectLibrary/Forms/FOrder.cs

123 lines
4.0 KiB
C#
Raw Normal View History

using ProjectLibrary.Repositories;
using Unity;
using ProjectLibrary.Entites;
namespace ProjectLibrary.Forms
{
public partial class FOrder : Form
{
private readonly IUnityContainer _container;
private readonly IOrderRepository _orderRepository;
private int? _orderId;
public FOrder(IUnityContainer container, IOrderRepository orderRepository, IBookOrderRepository bookOrderRepository)
{
InitializeComponent();
_container = container ?? throw new ArgumentNullException(nameof(container));
_orderRepository = orderRepository ?? throw new ArgumentNullException(nameof(orderRepository));
}
private void FOrder_Load(object sender, EventArgs e)
{
try
{
if (_orderId.HasValue)
{
LoadOrderData(_orderId.Value);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при загрузке данных", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
public int OrderID
{
set
{
_orderId = value;
}
}
private void LoadOrderData(int orderId)
{
var order = _orderRepository.ReadOrderById(orderId);
//var bookOrders = _bookOrderRepository.GetBookOrderByOrderId(orderId);
if (order == null)
{
throw new InvalidOperationException("Данные заказа не найдены.");
}
txtOrderDate.Text = order.OrderDate.ToString("yyyy-MM-dd");
txtReturnDate.Text = order.ReturnDate.ToString("yyyy-MM-dd");
comboBox1.SelectedItem = order.ReaderID.ToString();
dataGridViewIDBook.Rows.Clear();
//foreach (var bookOrder in bookOrders)
//{
// dataGridViewIDBook.Rows.Add(bookOrder.BookID);
//}
}
private List<Book_Orders> CreateListMaterialFromDataGrid()
{
var list = new List<Book_Orders>();
foreach (DataGridViewRow row in dataGridViewIDBook.Rows)
{
if (row.Cells["ColumnMaterials"].Value == null || row.Cells["ColumnCount"].Value == null)
{
continue;
}
list.Add(Book_Orders.CreateEntity(0, Convert.ToInt32(row.Cells["ColumnMaterials"].Value)));
}
return list;
}
private void ButtonSave_Click(object sender, EventArgs e)
{
try
{
if (string.IsNullOrWhiteSpace(txtOrderDate.Text) || string.IsNullOrWhiteSpace(txtReturnDate.Text))
{
throw new Exception("Не все поля заполнены.");
}
var updatedOrder = Orders.CreateEntity(
_orderId ?? 0,
DateTime.Parse(txtOrderDate.Text),
DateTime.Parse(txtReturnDate.Text),
int.Parse(comboBox1.SelectedItem.ToString()),
CreateListMaterialFromDataGrid()
);
if (_orderId.HasValue)
{
_orderRepository.UpdateOrder(updatedOrder);
}
else
{
_orderRepository.CreateOrder(updatedOrder);
}
MessageBox.Show("Данные успешно сохранены.", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при сохранении данных", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonCancel_Click(object sender, EventArgs e)
{
Close();
}
}
}