PIbd-23_Sergunov_M.A._SUBD/BookShop/BookShopView/FormBook.cs

243 lines
9.4 KiB
C#

using BookShopContracts.BindingModels;
using BookShopContracts.BusinessLogicsContracts;
using BookShopContracts.SearchModels;
using BookShopContracts.ViewModels;
using BookShopDataModels.Models;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace BookShopView
{
public partial class FormBook : Form
{
private readonly ILogger _logger;
private readonly IBookLogic _logic;
private readonly IGenreLogic _logicG;
private int? _id;
private Dictionary<int, IAuthorModel> _bookAuthors;
public int Id { set { _id = value; } }
public FormBook(ILogger<FormBook> logger, IBookLogic logic, IGenreLogic logicG)
{
InitializeComponent();
_logger = logger;
_logic = logic;
_bookAuthors = new Dictionary<int, IAuthorModel>();
_logicG = logicG;
}
private void FormBook_Load(object sender, EventArgs e)
{
_logger.LogInformation("Загрузка жанров");
try
{
var list = _logicG.ReadList(null);
if (list != null)
{
comboBoxGenre.DisplayMember = "Genre";
comboBoxGenre.ValueMember = "ID";
comboBoxGenre.DataSource = list.Select(c => c.GenreName).ToList();
comboBoxGenre.SelectedItem = null;
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки списка жанров");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
if (_id.HasValue)
{
_logger.LogInformation("Загрузка книги");
try
{
var view = _logic.ReadElement(new BookSearchModel
{
Id = _id.Value
});
if (view != null)
{
TextBoxName.Text = view.BookName;
textBoxCost.Text = view.Cost.ToString();
textBoxCount.Text = view.Count.ToString();
comboBoxGenre.SelectedIndex = view.GenreId;
_bookAuthors = view.BookAuthors ?? new Dictionary<int, IAuthorModel>();
LoadData();
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки книги");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
private void LoadData()
{
_logger.LogInformation("Загрузка автора книги");
try
{
if (_bookAuthors != null)
{
dataGridView.Rows.Clear();
foreach (var pc in _bookAuthors)
{
dataGridView.Rows.Add(new object[] { pc.Key, pc.Value.AuthorSurname });
}
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки автора книги");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonAdd_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormBookAuthor));
if (service is FormBookAuthor form)
{
if (form.ShowDialog() == DialogResult.OK)
{
if (form.AuthorModel == null)
{
return;
}
if (_bookAuthors.ContainsKey(form.Id))
{
_bookAuthors[form.Id] = (form.AuthorModel);
}
else
{
_bookAuthors.Add(form.Id, (form.AuthorModel));
}
_logger.LogInformation("Добавление автора:{ AuthorSurname}", form.AuthorModel.AuthorSurname);
LoadData();
}
}
}
private void ButtonUpd_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
var service =
Program.ServiceProvider?.GetService(typeof(FormBookAuthor));
if (service is FormBookAuthor form)
{
int id =
Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value);
form.Id = id;
if (form.ShowDialog() == DialogResult.OK)
{
if (form.AuthorModel == null)
{
return;
}
_logger.LogInformation("Изменение компонента:{ ComponentName} - { Count}", form.AuthorModel.AuthorSurname);
_bookAuthors[form.Id] = (form.AuthorModel);
LoadData();
}
}
}
}
private void ButtonDel_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
try
{
_logger.LogInformation("Удаление компонента: { AuthorSurname}", dataGridView.SelectedRows[0].Cells[1].Value);
_bookAuthors?.Remove(Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
LoadData();
}
}
}
private void ButtonRef_Click(object sender, EventArgs e)
{
LoadData();
}
private void ButtonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(TextBoxName.Text))
{
MessageBox.Show("Заполните название", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.IsNullOrEmpty(textBoxCost.Text))
{
MessageBox.Show("Заполните цену", "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
return;
}
if (string.IsNullOrEmpty(textBoxCount.Text))
{
MessageBox.Show("Заполните количество", "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
return;
}
if (comboBoxGenre.SelectedItem == null)
{
MessageBox.Show("Выберите жанр", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (_bookAuthors == null || _bookAuthors.Count == 0)
{
MessageBox.Show("Заполните авторов", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Сохранение изделия");
try
{
var model = new BookBindingModel
{
Id = _id ?? 0,
BookName = TextBoxName.Text,
Cost = Convert.ToDouble(textBoxCost.Text),
Count = Convert.ToInt32(textBoxCount.Text),
GenreId = comboBoxGenre.SelectedIndex + 1,
BookAuthors = _bookAuthors
};
var operationResult = _id.HasValue ? _logic.Update(model) :
_logic.Create(model);
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
MessageBox.Show("Сохранение прошло успешно", "Сообщение",
MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
Close();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка сохранения книги");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}