PIbd-32_Artamonova_T.V._COP_2/UniversityView/FormMain.cs

265 lines
11 KiB
C#
Raw 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 COP.Info;
using COPWinForms;
using DocumentFormat.OpenXml.Office2016.Drawing.ChartDrawing;
using DocumentFormat.OpenXml.Spreadsheet;
using Microsoft.Extensions.Logging;
using System.Windows.Forms;
using UniversityBusinessLogic.BusinessLogics;
using UniversityContracts.BindingModels;
using UniversityContracts.BusinessLogicsContracts;
using UniversityContracts.SearchModels;
using UniversityContracts.ViewModels;
using WinFormsControlLibrary;
using static COP.ExcelComponent;
using static COPWinForms.ComponentWord2;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Window;
using LegendPosition = WinFormsControlLibrary.LegendPosition;
namespace UniversityView
{
public partial class FormMain : Form
{
private readonly ILogger _logger;
private readonly IStudentLogic _studentLogic;
private readonly IDirectionLogic _directionLogic;
public FormMain(ILogger<FormMain> logger, IStudentLogic studentLogic, IDirectionLogic directionLogic)
{
InitializeComponent();
_logger = logger;
_studentLogic = studentLogic;
_directionLogic = directionLogic;
Configure();
; }
private void LoadData()
{
_logger.LogInformation("Загрузка студентов");
try
{
tableOfValues.ClearRows();
var list = _studentLogic.Read(null);
if (list != null)
{
tableOfValues.SetCellValueFromList(list);
}
_logger.LogInformation("Загрузка студентов");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки студентов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void FormMain_Load(object sender, EventArgs e)
{
LoadData();
}
private void СоздатьToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormStudent));
if (service is FormStudent form)
{
form.ShowDialog();
}
LoadData();
}
private void Configure()
{
var columnConfigs = new List<GridColumnConfig>
{
new GridColumnConfig { HeaderText = "Id", Width = 100, Visible = false, PropertyName = "Id" },
new GridColumnConfig { HeaderText = "ФИО", Width = 100, Visible = true, PropertyName = "FIO" },
new GridColumnConfig { HeaderText = "Направление", Width = 80, Visible = true, PropertyName = "DirectionName" },
new GridColumnConfig { HeaderText = "Электронная почта", Width = 80, Visible = true, PropertyName = "Email" },
};
tableOfValues.ConfigureColumns(columnConfigs);
}
private void ИзменитьToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormStudent));
if (service is FormStudent form)
{
if (tableOfValues.SelectedRowIndex != -1)
{
var selectedStudent = tableOfValues.GetSelectedObject<StudentSearchModel>();
form.Id = Convert.ToInt32(selectedStudent.Id);
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
else
{
MessageBox.Show("Выберите студента для редактирования");
}
}
}
private void УдалитьToolStripMenuItem_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
var selectedStudent = tableOfValues.GetSelectedObject<StudentSearchModel>();
int id = Convert.ToInt32(selectedStudent.Id);
try
{
_studentLogic.Delete(new StudentBindingModel { Id = id });
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
LoadData();
}
}
private void СоздатьПростойДокументToolStripMenuItem_Click(object sender, EventArgs e)
{
var list = _studentLogic.Read(null);
List<ImageInfo> images = new();
using var dialog = new SaveFileDialog
{
Filter = "xlsx|*.xlsx"
};
if (dialog.ShowDialog() == DialogResult.OK)
{
try
{
if (list != null)
{
foreach (var item in list)
{
images.Add(new ImageInfo() { FilePath = item.PhotoFilePath });
}
}
ExcelImageInfo info = new(dialog.FileName, "Документ с фотографиями студентов", images);
excelComponent.GenerateExcelWithImages(info);
MessageBox.Show("Сохарнено успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void СоздатьДокументСТаблицейToolStripMenuItem_Click(object sender, EventArgs e)
{
var list = _studentLogic.Read(null);
List<StudentBindingModel> data = new();
List<int[]> mergedColumns = new()
{
new int[] { 1, 2 }
};
List<ColumnDefinition> columnDefinitions = new()
{
new ColumnDefinition { Header = "ID", PropertyName = "Id", Width = 11 },
new ColumnDefinition { Header = "Личные данные", PropertyName = "PersonalData", Width = 11 },
new ColumnDefinition { Header = "Личные данные", PropertyName = "PersonalData1", Width = 11 },
new ColumnDefinition { Header = "Направление", PropertyName = "DirectionName", Width = 21 }
};
List<ColumnDefinition> columnDefinitions2 = new()
{
new ColumnDefinition { Header = "ID", PropertyName = "Id", Width = 11 },
new ColumnDefinition { Header = "ФИО", PropertyName = "FIO", Width = 11 },
new ColumnDefinition { Header = "Электронная почта", PropertyName = "Email", Width = 70 },
new ColumnDefinition { Header = "Направление", PropertyName = "DirectionName", Width = 21 }
};
using var dialog = new SaveFileDialog
{
Filter = "docx|*.docx"
};
if (dialog.ShowDialog() == DialogResult.OK)
{
try
{
if (list != null)
{
foreach (var item in list)
{
data.Add(new StudentBindingModel() { Id = item.Id, FIO = item.FIO, Email = item.Email, DirectionName = item.DirectionName});
}
}
TableWord<StudentBindingModel> tableWord = new(dialog.FileName, "Таблица со студентами", columnDefinitions, columnDefinitions2, data, mergedColumns);
componentWord.CreateTable(tableWord);
MessageBox.Show("Сохарнено успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void СоздатьДокументСДиаграммойToolStripMenuItem_Click(object sender, EventArgs e)
{
var listStudents = _studentLogic.Read(null);
var listDirections = _directionLogic.Read(null);
List<(string, int)> data = new();
List<HistogramData> gistData = new();
using var dialog = new SaveFileDialog
{
Filter = "pdf|*.pdf"
};
if (dialog.ShowDialog() == DialogResult.OK)
{
try
{
for (int i = 0; i < listDirections.Count; i++)
{
int count = 0;
for (int j = 0; j < listStudents.Count; j++)
{
string[] dirs = listStudents[j].DirectionName.Split(";");
foreach (var dir in dirs)
{
if (dir == listDirections[i].Name) count++;
}
}
data.Add((listDirections[i].Name, count));
}
if (data != null) {
foreach (var item in data)
{
gistData.Add(new HistogramData
{
SeriesName = item.Item1,
Data = new double[] { item.Item2 }
});
}
}
gistogramPdfComponent.GenerateHistogramDocument(dialog.FileName, "Histogram", "Students-Directions", LegendPosition.TopRight, gistData);
MessageBox.Show("Сохарнено успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void СправочникиToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormHandbooks));
if (service is FormHandbooks form)
{
form.ShowDialog();
}
LoadData();
}
}
}