PIbd-31_Teryokhin.A.S._COP_23/WinForms/FormMain.cs

387 lines
12 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using BusinessLogics.BusinessLogics;
using Components.Components.NonVisualComponents.HelperModels;
using Components.Components.VisualComponents;
using Components.NonVisualComponents;
using Components.NonVisualComponents.HelperModels;
using ComponentsLibraryNet60.DocumentWithChart;
using ComponentsLibraryNet60.Models;
using Contracts.BindingModels;
using Contracts.BusinessLogicsContracts;
using Contracts.ViewModels;
using ControlsLibraryNet60.Models;
using DocumentFormat.OpenXml.Spreadsheet;
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;
using MergeCells = Components.NonVisualComponents.HelperModels.MergeCells;
namespace WinForms
{
public partial class FormMain : Form
{
private readonly IOrderLogic _orderLogic;
private readonly IDishLogic _dishLogic;
public FormMain(IDishLogic dishLogic, IOrderLogic orderLogic)
{
_dishLogic = dishLogic;
_orderLogic = orderLogic;
InitializeComponent();
List<DataTableColumnConfig> columnConfigs = new List<DataTableColumnConfig>
{
new DataTableColumnConfig
{
ColumnHeader = "Идентификатор",
PropertyName = "Id",
Width = 150,
Visible = true
},
new DataTableColumnConfig
{
ColumnHeader = "ФИО официанта",
PropertyName = "WaiterFullName",
Width = 250,
Visible = true
},
new DataTableColumnConfig
{
ColumnHeader = "Заказанное блюдо",
PropertyName = "Dish",
Width = 200,
Visible = true
},
new DataTableColumnConfig
{
ColumnHeader = "Дата оплаты счета",
PropertyName = "OrderDate",
Width = 200,
Visible = true
}
};
controlDataTableRow1.LoadColumns(columnConfigs);
controlDataTableRow1.ContextMenuStrip = contextMenuStrip;
}
private void FormMain_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
controlDataTableRow1.Clear();
try
{
var orders = _orderLogic.ReadList(null);
if (orders == null)
{
return;
}
foreach (var order in orders)
{
controlDataTableRow1.AddRow(order);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void AddElement()
{
var service = Program.ServiceProvider?.GetService(typeof(FormOrder));
if (!(service is FormOrder form))
{
return;
}
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
private void UpdateElement()
{
var service = Program.ServiceProvider?.GetService(typeof(FormOrder));
if (!(service is FormOrder form))
{
return;
}
var selectedOrder = controlDataTableRow1.GetSelectedObject<OrderViewModel>();
if (selectedOrder == null)
{
MessageBox.Show("Выберите счет для редактирования!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
form.Id = Convert.ToInt32(selectedOrder.Id);
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
private void DeleteElement()
{
if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
{
return;
}
var selectedOrder = controlDataTableRow1.GetSelectedObject<OrderViewModel>();
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();
}
private void CreatePdf()
{
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);
}
else return;
}
List<string> images = new List<string>();
var list = _orderLogic.ReadList(null);
try
{
if (list != null)
{
foreach (var item in list)
{
images.Add(item.PicturePath);
}
string[] imagesArray = images.ToArray();
pdfImage.CreatePdfDoc(new DataForImage(fileName, "Сканы чеков", imagesArray));
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка");
}
}
private void CreateExcel()
{
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);
}
else return;
}
string title = "Документ с таблицей";
List<MergeCells> mergeCells = new List<MergeCells>()
{
new MergeCells("Счет", new int[] { 1, 2})
};
List<ColumnInfo> columns = new List<ColumnInfo>()
{
new ColumnInfo("Id", "Идент.", 10),
new ColumnInfo("WaiterFullName", "ФИО официанта", 20),
new ColumnInfo("Dish", "Блюдо", 20),
new ColumnInfo("OrderDate", "Дата оплаты чека", 30),
new ColumnInfo("", "заглушка", 0),
};
var list = _orderLogic.ReadList(null);
try
{
tableComponent.CreateDocument(fileName, title,
mergeCells, columns,
list);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка");
}
}
private void CreateWord()
{
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
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);
}
else return;
}
var data = new Dictionary<string, List<(int Date, double Value)>>();
var orders = _orderLogic.ReadList(null);
var groupedOrders = orders.GroupBy(order => order.Dish)
.Select(group => new
{
DishName = group.Key,
OrderCount = group.Count()
})
.ToList();
data["Блюда"] = new List<(int Date, double Value)>();
int counter = 1;
foreach (var group in groupedOrders)
{
data["Блюда"].Add((counter, group.OrderCount));
counter++;
}
try
{
componentDocumentWithChartBarWord.CreateDoc(new ComponentDocumentWithChartConfig
{
Header = "test",
FilePath = fileName,
ChartTitle = "Количество заказов определенных блюд",
LegendLocation = ComponentsLibraryNet60.Models.Location.Bottom,
Data = data
});
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка");
}
}
private void созToolStripMenuItem_Click(object sender, EventArgs e)
{
AddElement();
}
private void редактироватьToolStripMenuItem_Click(object sender, EventArgs e)
{
UpdateElement();
}
private void удалитьToolStripMenuItem_Click(object sender, EventArgs e)
{
DeleteElement();
}
private void wordToolStripMenuItem_Click(object sender, EventArgs e)
{
CreateWord();
}
private void excelToolStripMenuItem_Click(object sender, EventArgs e)
{
CreateExcel();
}
private void pdfToolStripMenuItem_Click(object sender, EventArgs e)
{
CreatePdf();
}
private void ShowFormDish()
{
var service = Program.ServiceProvider?.GetService(typeof(FormDish));
if (!(service is FormDish form))
{
return;
}
form.ShowDialog();
}
private void блюдоToolStripMenuItem_Click(object sender, EventArgs e)
{
ShowFormDish();
}
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
// Ctrl+A - добавить запись
if (keyData == (Keys.Control | Keys.A))
{
AddElement();
return true;
}
// Ctrl+U - редактировать запись
if (keyData == (Keys.Control | Keys.U))
{
UpdateElement();
return true;
}
// Ctrl+D - удалить запись
if (keyData == (Keys.Control | Keys.D))
{
DeleteElement();
return true;
}
// Ctrl+S - создать документ Word
if (keyData == (Keys.Control | Keys.S))
{
CreateWord();
return true;
}
// Ctrl+T - создать документ Excel
if (keyData == (Keys.Control | Keys.T))
{
CreateExcel();
return true;
}
// Ctrl+C - создать документ Pdf
if (keyData == (Keys.Control | Keys.C))
{
CreatePdf();
return true;
}
// Ctrl+M - вывести форму списка блюд
if (keyData == (Keys.Control | Keys.M))
{
ShowFormDish();
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
}
}