PIbd-31_MasenkinMS_COP_22/Components/WinForms/PluginsConvention.cs

336 lines
11 KiB
C#
Raw Normal View History

2024-09-25 01:12:58 +04:00
using BusinessLogics.BusinessLogics;
using Components.NonVisualComponents;
using ComponentsLibrary.NonVisualComponents.HelperModels;
using ComponentsLibrary.NonVisualComponents;
using ComponentsLibrary.VisualComponents;
using ComponentsLibraryNet60.DocumentWithTable;
using ComponentsLibraryNet60.Models;
using Contracts.BindingModels;
using Contracts.BusinessLogicsContracts;
using Contracts.ViewModels;
using DatabaseImplement.Implements;
using Microsoft.Extensions.Logging;
using Plugins;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NLog.Extensions.Logging;
namespace WinForms
{
/// <summary>
/// Реализация интерфейса-соглашения для плагинов
/// </summary>
public class PluginsConvention : IPluginsConvention
{
/// <summary>
/// Название плагина
/// </summary>
public string PluginName => "Orders";
/// <summary>
/// Визуальный компонент для вывода списка в виде дерева
/// </summary>
private readonly UserTreeView _userTreeView;
/// <summary>
/// Бизнес-логика для сущности "Счет"
/// </summary>
private readonly IOrderLogic _orderLogic;
/// <summary>
/// Бизнес-логика для сущности "Тип заказа"
/// </summary>
private readonly IOrderTypeLogic _orderTypeLogic;
/// <summary>
/// Конструктор
/// </summary>
public PluginsConvention()
{
_userTreeView = new UserTreeView();
var hierarchy = new List<string>()
{
"Type",
"Sum",
"Id",
"WaiterFullName"
};
_userTreeView.SetHierarchy(hierarchy);
var loggerFactory = LoggerFactory.Create(builder => builder.AddNLog());
var orderLogicLogger = loggerFactory.CreateLogger<OrderLogic>();
var orderTypeLogicLogger = loggerFactory.CreateLogger<OrderTypeLogic>();
_orderLogic = new OrderLogic(orderLogicLogger, new OrderStorage());
_orderTypeLogic = new OrderTypeLogic(orderTypeLogicLogger, new OrderTypeStorage());
}
/// <summary>
/// Получение контрола для вывода набора данных
/// </summary>
public UserControl GetControl
{
get
{
ReloadData();
return _userTreeView;
}
}
/// <summary>
/// Получение элемента, выбранного в контроле
/// </summary>
public PluginsConventionElement GetElement
{
get
{
var order = _userTreeView.GetSelectedObject<OrderViewModel>();
int id = -1;
if (order != null)
{
id = order.Id;
}
byte[] bytes = new byte[16];
BitConverter.GetBytes(id).CopyTo(bytes, 0);
return new PluginsConventionElement { Id = new Guid(bytes) };
}
}
/// <summary>
/// Получение формы для создания/редактирования объекта
/// </summary>
/// <param name="element"></param>
/// <returns></returns>
public Form GetForm(PluginsConventionElement element)
{
if (element == null)
{
return new FormOrder(_orderLogic, _orderTypeLogic);
}
if (element.Id.GetHashCode() >= 0)
{
byte[] bytes = element.Id.ToByteArray();
int Id = BitConverter.ToInt32(bytes, 0);
var form = new FormOrder(_orderLogic, _orderTypeLogic);
form.Id = Id;
return form;
}
return null;
}
/// <summary>
/// Получение формы для работы со справочником
/// </summary>
/// <returns></returns>
public Form GetThesaurus()
{
return new FormOrderTypes(_orderTypeLogic);
}
/// <summary>
/// Удаление элемента
/// </summary>
/// <param name="element"></param>
/// <returns></returns>
public bool DeleteElement(PluginsConventionElement element)
{
if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
{
return false;
}
byte[] bytes = element.Id.ToByteArray();
int Id = BitConverter.ToInt32(bytes, 0);
try
{
_orderLogic.Delete(new OrderBindingModel() { Id = Id });
ReloadData();
return true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
}
/// <summary>
/// Обновление набора данных в контроле
/// </summary>
public void ReloadData()
{
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>
/// <param name="saveDocument"></param>
/// <returns></returns>
public bool CreateSimpleDocument(PluginsConventionSaveDocument saveDocument)
{
try
{
var orders = _orderLogic.ReadList(null);
if (orders == null)
{
return false;
}
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();
var bigTextComponent = new BigTextComponent();
bigTextComponent.CreateDocument(saveDocument.FileName, title, rowsArray);
return true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
}
/// <summary>
/// Создание документа с настраиваемой таблицей
/// </summary>
/// <param name="saveDocument"></param>
/// <returns></returns>
public bool CreateTableDocument(PluginsConventionSaveDocument saveDocument)
{
try
{
var orders = _orderLogic.ReadList(null);
if (orders == null)
{
return false;
}
foreach (var order in orders)
{
if (string.IsNullOrEmpty(order.Sum))
{
order.Sum = "По акции";
}
}
var componentDocumentWithTableMultiHeaderWord = new ComponentDocumentWithTableMultiHeaderWord();
componentDocumentWithTableMultiHeaderWord.CreateDoc(new ComponentDocumentWithTableHeaderDataConfig<OrderViewModel>
{
FilePath = saveDocument.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,
});
return true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
}
/// <summary>
/// Создание документа с диаграммой
/// </summary>
/// <param name="saveDocument"></param>
/// <returns></returns>
public bool CreateChartDocument(PluginsConventionSaveDocument saveDocument)
{
try
{
var orders = _orderLogic.ReadList(null);
if (orders == null)
{
return false;
}
var orderTypes = _orderTypeLogic.ReadList(null);
if (orderTypes == null)
{
return false;
}
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));
}
var pdfPieChart = new PdfPieChart();
pdfPieChart.CreatePieChart(new DataForPieChart(saveDocument.FileName, "Информация по оплаченным счетам каждого типа заказов", "Круговая диаграмма", DiagramLegendEnum.Top, "Типы заказов", items));
return true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
}
}
}