PIAPS_CW/WinFormsApp/FormSuppliers.cs

252 lines
8.9 KiB
C#
Raw Normal View History

2024-06-23 17:04:26 +04:00
using Contracts.BindingModels;
using Contracts.BusinessLogicContracts;
using Contracts.SearchModels;
using Contracts.ViewModels;
using DataModels.Models;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.Extensions.Logging;
using Microsoft.VisualBasic.Logging;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WinFormsApp
{
public partial class FormSuppliers : Form
{
private Guid? _id;
private readonly ILogger _logger;
private readonly ISupplierLogic _supplierLogic;
private readonly IProductLogic _productLogic;
private Dictionary<Guid, (IProduct, int)> _supplierProducts;
private List<ProductViewModel> _productList;
public FormSuppliers(ILogger<FormMain> logger, ISupplierLogic supplierLogic, IProductLogic productLogic)
{
InitializeComponent();
_supplierLogic = supplierLogic;
_logger = logger;
_productLogic = productLogic;
_supplierProducts = new Dictionary<Guid, (IProduct, int)>();
_productList = _productLogic.ReadList(null);
if (_productList != null)
{
comboBoxProducts.DisplayMember = "Name";
comboBoxProducts.ValueMember = "Id";
comboBoxProducts.DataSource = _productList;
comboBoxProducts.SelectedItem = null;
}
}
private void FormSuppliers_Load(object sender, EventArgs e)
{
LoadData();
groupBoxCreateSupplier.Hide();
//groupBoxCreateProduct.Enabled = false;
}
private void LoadSupplierData()
{
if (_id.HasValue)
{
var view = _supplierLogic.ReadElement(new SupplierSearchModel
{
Id = _id.Value
});
_supplierProducts = view.AvailibleProducts;
textBoxName.Text = view.Name;
numericUpDownDeals.Value = view.Deals;
}
dataGridViewProducts.Rows.Clear();
foreach (var pc in _supplierProducts)
{
dataGridViewProducts.Rows.Add(new object[] { pc.Value.Item1.Name, pc.Value.Item2 });
}
}
private void LoadData()
{
_logger.LogInformation("Загрузка поставщиков");
try
{
var list = _supplierLogic.ReadList(null);
if (list != null)
{
dataGridView.DataSource = list;
}
_logger.LogInformation("Загрузка поставщиков");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки поставщиков");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void buttonCreateSupplier_Click(object sender, EventArgs e)
{
//надо сделать че нибудь с фронтом а то всё грустно
groupBoxControls.Hide();
//groupBoxControls.Enabled = false;
groupBoxCreateSupplier.Show();
//groupBoxCreateProduct.Enabled = true;
}
private void buttonUpdateSupplier_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count <= 0) return;
_id = (Guid)dataGridView.SelectedRows[0].Cells["Id"].Value;
groupBoxControls.Hide();
groupBoxCreateSupplier.Show();
_logger.LogInformation("Получение поставщика");
var view = _supplierLogic.ReadElement(new SupplierSearchModel
{
Id = _id.Value
});
LoadSupplierData();
}
private void buttonCancel_Click(object sender, EventArgs e)
{
_id = null;
_supplierProducts.Clear();
groupBoxControls.Show();
//groupBoxControls.Enabled = false;
groupBoxCreateSupplier.Hide();
//groupBoxCreateProduct.Enabled = true;
textBoxName.Text = string.Empty;
}
private void buttonDeleteSupplier_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
if (MessageBox.Show("Удалить запись?", "Вопрос",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
Guid id = (Guid)dataGridView.SelectedRows[0].Cells["Id"].Value;
_logger.LogInformation("Удаление товара");
try
{
if (!_productLogic.Delete(new ProductBindingModel
{
Id = id
}))
{
throw new Exception("Ошибка при удалении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка удаления товара");
MessageBox.Show(ex.Message, "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
public IProduct? ProductModel
{
get
{
if (_productList == null)
{
return null;
}
foreach (var elem in _productList)
{
if (elem.Id == Id)
{
return elem;
}
}
return null;
}
}
public Guid Id
{
get
{
return (Guid)comboBoxProducts.SelectedValue;
}
set
{
comboBoxProducts.SelectedValue = value;
}
}
private void buttonAddSupplierProduct_Click(object sender, EventArgs e)
{
Debug.WriteLine(comboBoxProducts.SelectedValue);
if (_supplierProducts.ContainsKey(Id))
{
_supplierProducts[Id] = (ProductModel, Convert.ToInt16(numericUpDownCount.Value));
}
else
{
_supplierProducts.Add(Id, (ProductModel, Convert.ToInt16(numericUpDownCount.Value)));
}
LoadSupplierData();
}
private void buttonSaveProduct_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxName.Text))
{
MessageBox.Show("Заполните имя поставщика", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Сохранение поставщика");
try
{
var model = new SupplierBindingModel
{
Id = _id ?? Guid.Empty,
Name = textBoxName.Text,
Deals = Convert.ToInt32(numericUpDownDeals.Value),
AvailibleProducts = _supplierProducts
};
var operationResult = _id.HasValue ? _supplierLogic.Update(model) : _supplierLogic.Create(model);
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
MessageBox.Show("Сохранение прошло успешно", "Сообщение",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка сохранения поставщика");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
finally
{
LoadData();
_id = null;
_supplierProducts.Clear();
textBoxName.Text = string.Empty;
numericUpDownDeals.Value = 0;
groupBoxControls.Enabled = true;
groupBoxControls.Show();
groupBoxCreateSupplier.Enabled = false;
groupBoxCreateSupplier.Hide();
textBoxName.Text = string.Empty;
}
}
}
}