PIbd-31_MasenkinMS_COP_22/Components/WinForms/FormMain.cs
2024-09-23 05:00:01 +04:00

372 lines
12 KiB
C#

using ComponentsLibrary.NonVisualComponents.HelperModels;
using ComponentsLibraryNet60.Models;
using Contracts.BindingModels;
using Contracts.BusinessLogicsContracts;
using Contracts.ViewModels;
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 WinForms
{
/// <summary>
/// Главная форма
/// </summary>
public partial class FormMain : Form
{
/// <summary>
/// Бизнес-логика для сущности "Счет"
/// </summary>
private readonly IOrderLogic _orderLogic;
/// <summary>
/// Бизнес-логика для сущности "Тип заказа"
/// </summary>
private readonly IOrderTypeLogic _orderTypeLogic;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="orderLogic"></param>
/// <param name="orderTypeLogic"></param>
public FormMain(IOrderLogic orderLogic, IOrderTypeLogic orderTypeLogic)
{
InitializeComponent();
_orderLogic = orderLogic;
_orderTypeLogic = orderTypeLogic;
userTreeView.ContextMenuStrip = contextMenuStrip;
}
/// <summary>
/// Загрузка формы
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void FormMain_Load(object sender, EventArgs e)
{
var hierarchy = new List<string>()
{
"Type",
"Sum",
"Id",
"WaiterFullName",
};
userTreeView.SetHierarchy(hierarchy);
LoadData();
}
/// <summary>
/// Элемент контекстного меню "Добавить запись"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void createElementToolStripMenuItem_Click(object sender, EventArgs e)
{
AddElement();
}
/// <summary>
/// Элемент контекстного меню "Редактировать запись"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void updateElementToolStripMenuItem_Click(object sender, EventArgs e)
{
UpdateElement();
}
/// <summary>
/// Элемент контекстного меню "Удалить запись"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void deleteElementToolStripMenuItem_Click(object sender, EventArgs e)
{
DeleteElement();
}
/// <summary>
/// Элемент контекстного меню "Создать документ Word"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void createWordDocumentToolStripMenuItem_Click(object sender, EventArgs e)
{
CreateWordDocument();
}
/// <summary>
/// Элемент контекстного меню "Создать документ Excel"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void createExcelDocumentToolStripMenuItem_Click(object sender, EventArgs e)
{
CreateExcelDocument();
}
/// <summary>
/// Элемент контекстного меню "Создать документ Pdf"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void createPdfDocumentToolStripMenuItem_Click(object sender, EventArgs e)
{
CreatePdfDocument();
}
/// <summary>
/// Элемент контекстного меню "Типы заказов"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void orderTypesToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormOrderTypes));
if (!(service is FormOrderTypes form))
{
return;
}
form.ShowDialog();
}
/// <summary>
/// Загрузка данных
/// </summary>
private void LoadData()
{
try
{
var orders = _orderLogic.ReadList(null);
if (orders == null)
{
return;
}
foreach (var order in orders)
{
if (string.IsNullOrEmpty(order.Sum))
{
order.Sum = "По акции";
}
userTreeView.AddObjectToTree(order);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary>
/// Добавить запись
/// </summary>
private void AddElement()
{
var service = Program.ServiceProvider?.GetService(typeof(FormOrder));
if (!(service is FormOrder form))
{
return;
}
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
/// <summary>
/// Редактировать элемент
/// </summary>
private void UpdateElement()
{
var service = Program.ServiceProvider?.GetService(typeof(FormOrder));
if (!(service is FormOrder form))
{
return;
}
var selectedOrder = userTreeView.GetSelectedObject<OrderBindingModel>();
if (selectedOrder == null)
{
MessageBox.Show("Выберите счет для редактирования!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
form.Id = Convert.ToInt32(selectedOrder.Id);
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
/// <summary>
/// Удалить элемент
/// </summary>
private void DeleteElement()
{
if (MessageBox.Show("Удалить запись", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
{
return;
}
var selectedOrder = userTreeView.GetSelectedObject<OrderBindingModel>();
int id = Convert.ToInt32(selectedOrder.Id);
try
{
_orderLogic.Delete(new OrderBindingModel { Id = id });
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
LoadData();
}
/// <summary>
/// Создать документ Word
/// </summary>
private void CreateWordDocument()
{
string fileName = "";
using (var dialog = new SaveFileDialog { Filter = "docx|*.docx" })
{
if (dialog.ShowDialog() == DialogResult.OK)
{
fileName = dialog.FileName.ToString();
MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
var orders = _orderLogic.ReadList(null);
if (orders == null)
{
return;
}
foreach (var order in orders)
{
if (string.IsNullOrEmpty(order.Sum))
{
order.Sum = "По акции";
}
}
componentDocumentWithTableMultiHeaderWord1.CreateDoc(new ComponentDocumentWithTableHeaderDataConfig<OrderViewModel>
{
FilePath = fileName,
Header = "Информация по счетам.",
ColumnsRowsWidth = new List<(int Column, int Row)>()
{
(5, 5),
(10, 5),
(15, 0),
(15, 0),
},
Headers = new List<(int ColumnIndex, int RowIndex, string Header, string PropertyName)>()
{
(0, 0, "Id", "Id"),
(1, 0, "ФИО официанта", "WaiterFullName"),
(2, 0, "Тип заказа", "Type"),
(3, 0, "Сумма заказа", "Sum")
},
Data = orders,
});
}
/// <summary>
/// Создать документ Excel
/// </summary>
private void CreateExcelDocument()
{
string fileName = "";
using (var dialog = new SaveFileDialog { Filter = "xlsx|*.xlsx" })
{
if (dialog.ShowDialog() == DialogResult.OK)
{
fileName = dialog.FileName.ToString();
MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
var orders = _orderLogic.ReadList(null);
if (orders == null)
{
return;
}
string title = "Информация по аукционным счетам.";
List<string> rows = new List<string>();
foreach (var order in orders)
{
if (string.IsNullOrEmpty(order.Sum))
{
string row = $"ФИО официанта: {order.WaiterFullName} -- Описание счета: {order.Info}";
rows.Add(row);
}
}
string[] rowsArray = rows.ToArray();
bigTextComponent1.CreateDocument(fileName, title, rowsArray);
}
/// <summary>
/// Создать документ Pdf
/// </summary>
private void CreatePdfDocument()
{
string fileName = "";
using (var dialog = new SaveFileDialog { Filter = "pdf|*.pdf" })
{
if (dialog.ShowDialog() == DialogResult.OK)
{
fileName = dialog.FileName.ToString();
MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
var orders = _orderLogic.ReadList(null);
if (orders == null)
{
return;
}
var orderTypes = _orderTypeLogic.ReadList(null);
if (orderTypes == null)
{
return;
}
List<(double, string)> items = new List<(double, string)>();
foreach (var orderType in orderTypes)
{
int count = 0;
foreach (var order in orders)
{
if (order.Type == orderType.Name && !string.IsNullOrEmpty(order.Sum))
{
count++;
}
}
items.Add((count, orderType.Name));
}
pdfPieChart1.CreatePieChart(new DataForPieChart(fileName, "Информация по оплаченным счетам каждого типа заказов", "Круговая диаграмма", DiagramLegendEnum.Top, "Типы заказов", items));
}
}
}