2024-11-25 19:46:00 +04:00

289 lines
10 KiB
C#

using ControlsLibraryNet60.Data;
using FormLibrary.HelperClasses;
using FormLibrary;
using InternetShopOrdersBusinessLogic.BusinessLogics;
using InternetShopOrdersContracts.BusinessLogicContracts;
using InternetShopOrdersContracts.ViewModels;
using InternetShopOrdersDatabaseImplement.Implements;
using PluginsConventionLibrary.Plugins;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WinFormsLibraryVolkov.NonVisualComponents;
using ComponentsLibraryNet60.DocumentWithChart;
using ComponentsLibraryNet60.Models;
using ControlsLibraryNet60.Models;
using DocumentFormat.OpenXml.Drawing.Charts;
namespace Lab3Form
{
public class PluginsConvention : IPluginsConvention
{
private readonly IOrderLogic _orderLogic;
private readonly ICityLogic _selecteditemLogic;
private readonly ControlDataTableTable _controlDataTableTable;
private readonly ExcelTableComponent _excelComponent;
private readonly ComponentHistogramToPdf _componentHistogramToPdf;
public string PluginName { get; set; } = "Plugin";
public UserControl GetControl
{
get { return _controlDataTableTable; }
}
public PluginsConvention()
{
_orderLogic = new OrderLogic(new OrderStorage());
_selecteditemLogic = new CityLogic(new CityStorage());
_controlDataTableTable = new();
_excelComponent = new();
_componentHistogramToPdf = new();
}
public PluginsConventionElement GetElement
{
get
{
int Id = _controlDataTableTable.GetSelectedObject<OrderViewModel>()!.Id;
byte[] bytes = new byte[16];
BitConverter.GetBytes(Id).CopyTo(bytes, 0);
Guid guid = new Guid(bytes);
return new PluginsConventionElement() { Id = guid };
}
}
public Form GetForm(PluginsConventionElement element)
{
if (element == null)
{
return new FormOrder(_orderLogic, _selecteditemLogic);
}
else
{
FormOrder form = new FormOrder(_orderLogic, _selecteditemLogic);
form.Id = element.Id.GetHashCode();
return form;
}
}
public Form GetThesaurus()
{
return new FormCities(_selecteditemLogic);
}
public bool DeleteElement(PluginsConventionElement element)
{
_orderLogic.Delete(new InternetShopOrdersContracts.BindingModels.OrderBindingModel { Id = element.Id.GetHashCode() });
return true;
}
public void ReloadData()
{
try
{
var orders = _orderLogic.ReadList(null);
if (_orderLogic != null)
{
_controlDataTableTable.Clear();
_controlDataTableTable.LoadColumns(new List<DataTableColumnConfig>
{
new DataTableColumnConfig { ColumnHeader = "Идентификатор", PropertyName = "Id", Visible = true, Width = 100 },
new DataTableColumnConfig { ColumnHeader = "ФИО заказчика", PropertyName = "Fullname", Visible = true, Width = 200 },
new DataTableColumnConfig { ColumnHeader = "Город назначения", PropertyName = "DestinationCityName", Visible = true, Width = 150 },
new DataTableColumnConfig { ColumnHeader = "История передвижения", PropertyName = "OrderStatusHistory", Visible = true, Width = 250 },
new DataTableColumnConfig { ColumnHeader = "Дата выдачи", PropertyName = "ExpectedDeliveryDate", Visible = true, Width = 125 },
});
_controlDataTableTable.AddTable(orders);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
public bool CreateSimpleDocument(PluginsConventionSaveDocument saveDocument)
{
try
{
var orders = _orderLogic.ReadList(null);
var orderTables = new List<string[,]>();
foreach (var order in orders)
{
int rowCount = order.OrderStatusHistory.Count;
string[,] orderTable = new string[rowCount + 1, 4];
orderTable[0, 0] = "Статус";
orderTable[0, 1] = "Идентификатор заказа";
orderTable[0, 2] = "Город назначения";
orderTable[0, 3] = "Дата доставки";
for (int i = 0; i < rowCount; i++)
{
orderTable[i + 1, 0] = order.OrderStatusHistory[i];
orderTable[i + 1, 1] = order.Id.ToString();
orderTable[i + 1, 2] = order.DestinationCityName;
orderTable[i + 1, 3] = order.ExpectedDeliveryDate.ToString("yyyy-MM-dd");
}
orderTables.Add(orderTable);
}
var pdfData = new PdfDocumentData(
saveDocument.FileName,
"Отчет по заказам",
orderTables
);
var documentGenerator = new PDFTable();
documentGenerator.GeneratePdf(pdfData);
MessageBox.Show("PDF-документ успешно создан!", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
return true;
}
catch (Exception ex)
{
MessageBox.Show($"Произошла ошибка: {ex.Message}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return false;
}
public bool CreateTableDocument(PluginsConventionSaveDocument saveDocument)
{
var orders = _orderLogic.ReadList(null);
if (orders == null || orders.Count == 0)
{
MessageBox.Show("Нет заказов для отчета.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
var tableData = new List<OrderExcelViewModel>();
foreach (var order in orders)
{
if (order != null)
{
tableData.Add(new OrderExcelViewModel(
order.Id,
order.Fullname,
order.DestinationCityName,
order.ExpectedDeliveryDate
));
}
}
string path = saveDocument.FileName;
List<(int, int)> merges = new List<(int, int)>
{
(0,1),
(2, 3)
};
List<int> heights = Enumerable.Repeat(20, 4).ToList();
List<(string, string)> headers = new List<(string, string)>
{
("","Данные"),
("Id", "Идентификатор"),
("Fullname", "ФИО заказчика"),
("", "Заказ"),
("DestinationCityName", "Город назначения"),
("ExpectedDeliveryDate", "Дата получения заказа")
};
if (merges.Count == 0 || heights.Count == 0 || headers.Count == 0 || tableData.Count == 0)
{
MessageBox.Show("Недостаточно данных для создания отчета.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
Console.WriteLine($"Merges Count: {merges.Count}");
Console.WriteLine($"Heights Count: {heights.Count}");
Console.WriteLine($"Headers Count: {headers.Count}");
Console.WriteLine($"TableData Count: {tableData.Count}");
if (_excelComponent.createWithTable(path, "Отчет по заказам", merges, heights, headers, tableData))
{
MessageBox.Show("Отчет успешно создан!");
}
else
{
MessageBox.Show("Ошибка при создании отчета.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return true;
}
public bool CreateChartDocument(PluginsConventionSaveDocument saveDocument)
{
var orders = _orderLogic.ReadList(null).Cast<OrderViewModel>().ToList();
var chartData = new Dictionary<string, List<(DateTime Date, int Count)>>();
foreach (var order in orders)
{
if (!chartData.ContainsKey(order.DestinationCityName))
{
chartData[order.DestinationCityName] = new List<(DateTime Date, int Count)>();
}
var existingData = chartData[order.DestinationCityName]
.FirstOrDefault(d => d.Date.Date == order.ExpectedDeliveryDate.Date);
if (existingData.Date == default)
{
chartData[order.DestinationCityName].Add((order.ExpectedDeliveryDate.Date, 1));
}
else
{
int index = chartData[order.DestinationCityName].FindIndex(d => d.Date.Date == order.ExpectedDeliveryDate.Date);
var updatedValue = chartData[order.DestinationCityName][index];
chartData[order.DestinationCityName][index] = (updatedValue.Date, updatedValue.Count + 1);
}
}
string filePath = saveDocument.FileName;
var config = new ComponentDocumentWithChartConfig
{
ChartTitle = "Отчет по заказам",
LegendLocation = ComponentsLibraryNet60.Models.Location.Bottom,
Data = chartData.ToDictionary(
entry => entry.Key,
entry => entry.Value.Select(d => ((d.Date.Day), (double)d.Count)).ToList()),
FilePath = filePath,
Header = "Заголовок отчета"
};
var documentComponent = new ComponentDocumentWithChartLineWord();
documentComponent.CreateDoc(config);
MessageBox.Show("Документ создан успешно!");
return false;
}
}
}