dmeo040225/NewOrder.axaml.cs
2025-03-02 16:05:35 +03:00

185 lines
5.9 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using Avalonia.Controls;
using Avalonia.Interactivity;
using System.IO;
using ZXing;
using ZXing.Common;
using PdfSharpCore.Drawing;
using PdfSharpCore.Pdf;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;
using dmeo040225.Models;
using dmeo040225.Services;
namespace dmeo040225;
public partial class NewOrder : Window
{
public List<string> OrderServicesList { get; }
public List<string> OrderClientsList { get; }
public NewOrder()
{
InitializeComponent();
LoadOrderId();
using var context = new DatabaseContext();
OrderClientsList = context.Users.Select(it => it.Fio).ToList();
OrderClientComboBox.ItemsSource = OrderClientsList;
OrderServicesList = context.Services.Select(it => it.Name).ToList();
OrderServicesListBox.ItemsSource = OrderServicesList;
// Подключаемся к обновлениям таймера
TimerService.Instance.TimeUpdated += UpdateTimerText;
TimerService.Instance.TimerExpired += LogoutUser;
}
private void UpdateTimerText(TimeSpan time)
{
TimerText.Text = $"Осталось: {time:mm\\:ss}";
}
private void LogoutUser()
{
Close();
var mainWindow = new MainWindow();
mainWindow.Show();
}
private void Back_OnClick(object? sender, RoutedEventArgs e)
{
Close();
}
protected override void OnClosed(EventArgs e)
{
TimerService.Instance.TimeUpdated -= UpdateTimerText;
TimerService.Instance.TimerExpired -= LogoutUser;
base.OnClosed(e);
}
private void LoadOrderId()
{
using var context = new DatabaseContext();
var maxId = context.Orders.Any() ? context.Orders.Max(order => order.Id) : 0;
var newOrderId = maxId + 1;
OrderIdTextBox.Text = newOrderId.ToString();
}
private void CreateOrderButton_OnClick(object? sender, RoutedEventArgs e)
{
using var context = new DatabaseContext();
var maxId = context.Orders.Any() ? context.Orders.Max(order => order.Id) : 0;
var newOrderId = maxId + 1;
var newCodeOrder = $"{newOrderId}/{DateTime.Now:dd.MM.yyyy}";
var newPeriod = int.TryParse(PeriodTextBox.Text, out int period) ? period : 0;
var selectedClientFio = OrderClientComboBox.SelectedItem as string;
if (string.IsNullOrEmpty(selectedClientFio))
{
Console.WriteLine("Выберите клиента!");
return;
}
var client = context.Users.FirstOrDefault(it => it.Fio == selectedClientFio);
if (client == null)
{
Console.WriteLine("Ошибка: клиент не найден!");
return;
}
var selectedServices = OrderServicesListBox.SelectedItems.Cast<string>().ToList();
if (selectedServices.Count == 0)
{
Console.WriteLine("Выберите хотя бы одну услугу!");
return;
}
var services = context.Services.Where(s => selectedServices.Contains(s.Name)).ToList();
var newOrder = new Order
{
Id = newOrderId,
Code = newCodeOrder,
Orderdata = DateTime.Now,
Ordertime = TimeOnly.FromDateTime(DateTime.Now),
UserId = client.Id,
Status = "Открыт",
Prokattime = newPeriod
};
context.Orders.Add(newOrder);
context.SaveChanges();
// foreach (var service in services)
// {
// var orderService = new OrdersService
// {
// OrderId = newOrder.Id,
// ServiceId = service.Id
// };
// context.OrdersServices.Add(orderService);
// }
context.SaveChanges();
LoadOrderId();
Console.WriteLine("Заказ создан");
GenerateBarcodeAndSavePdf(newOrderId, DateTime.Now, newPeriod);
}
public void GenerateBarcodeAndSavePdf(int orderId, DateTime orderDate, int rentalPeriod)
{
var random = new Random();
string uniqueCode = string.Concat(Enumerable.Range(0, 6).Select(_ => random.Next(0, 10)));
string barcodeData = $"{orderId}{orderDate:ddMMyy}{rentalPeriod}{uniqueCode}";
var writer = new BarcodeWriterPixelData
{
Format = BarcodeFormat.CODE_128,
Options = new EncodingOptions
{
Height = 229,
Width = 350,
Margin = 0
}
};
var pixelData = writer.Write(barcodeData);
using var image = new Image<Rgba32>(pixelData.Width, pixelData.Height);
image.Mutate(ctx =>
{
for (int y = 0; y < pixelData.Height; y++)
{
for (int x = 0; x < pixelData.Width; x++)
{
byte value = pixelData.Pixels[(y * pixelData.Width + x) * 4];
image[x, y] = new Rgba32(value, value, value, 255);
}
}
});
using var ms = new MemoryStream();
image.SaveAsPng(ms);
ms.Position = 0;
using var document = new PdfDocument();
var page = document.AddPage();
var gfx = XGraphics.FromPdfPage(page);
using var img = XImage.FromStream(() => new MemoryStream(ms.ToArray()));
gfx.DrawImage(img, 10, 10, 150, 50);
gfx.DrawString(barcodeData, new XFont("Arial", 10), XBrushes.Black, new XPoint(10, 70));
string filePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), $"Order_{orderId}.pdf");
document.Save(filePath);
Console.WriteLine($"PDF сохранен: {filePath}");
}
}