using Avalonia; using Avalonia.Controls; using Avalonia.Markup.Xaml; using Avalonia.Media.Imaging; using AvaloniaAppApplication.DTO; using AvaloniaAppApplication.Models; using Microsoft.EntityFrameworkCore; using MsBox.Avalonia; using System; using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Text; using System.Xml.Linq; namespace AvaloniaAppApplication; public partial class AddEditWindow : Window { ServiceDTO currentService = new ServiceDTO(); ObservableCollection serviceImages = new ObservableCollection(); // добавление public AddEditWindow() { InitializeComponent(); DataContext = currentService; } // редактирование public AddEditWindow(ServiceDTO service) { InitializeComponent(); currentService = service; DataContext = currentService; TitleTB.Text = "Редактирование"; LoadImages(); } public void LoadImages() { var servicePhotosList = Manager.context.Servicephotos .Where(s => s.Id == currentService.Id) .Select(s => new ServicePhotoDTO { ServiceId = s.Serviceid, PhotoPath = s.Photopath }) .ToList(); foreach (var photo in servicePhotosList) { serviceImages.Add(photo); } if (serviceImages.Any()) { foreach (var serviceImage in serviceImages) { Bitmap bitmap = new Bitmap(AppDomain.CurrentDomain.BaseDirectory.ToString().Replace("\\bin\\Debug\\net7.0\\", "\\") + serviceImage.PhotoPath.Trim()); currentService.ServiceBitmaps.Add(new ServicePhotoDTO { Bitmap = bitmap, PhotoPath = currentService.MainImagePath, ServiceId = currentService.Id }); } } } private async void SaveButton_Click(object? sender, Avalonia.Interactivity.RoutedEventArgs e) { try { StringBuilder errors = new StringBuilder(); if (string.IsNullOrEmpty(TitleTX.Text) || string.IsNullOrWhiteSpace(TitleTX.Text) || string.IsNullOrEmpty(CostTX.Text) || string.IsNullOrWhiteSpace(CostTX.Text) || string.IsNullOrEmpty(DescriptionTX.Text) || string.IsNullOrWhiteSpace(DescriptionTX.Text) || string.IsNullOrEmpty(DiscountTX.Text) || string.IsNullOrWhiteSpace(DiscountTX.Text) || string.IsNullOrEmpty(DurationTX.Text) || string.IsNullOrWhiteSpace(DurationTX.Text)) { var msbox = MessageBoxManager.GetMessageBoxStandard("Ошибка!", "Заполните пустые поля!"); var res = await msbox.ShowWindowDialogAsync(this); return; } if (!DurationTX.Text.All(char.IsDigit) || !CostTX.Text.All(char.IsDigit)) { errors.AppendLine("Введённые данные о цене или длительности не являются числовыми значениями!"); } if (int.Parse(DurationTX.Text) > 2400) { errors.AppendLine("Длительность оказания услуги не может быть больше, чем 4 часа!"); } if (errors.Length > 0) { var msbox = MessageBoxManager.GetMessageBoxStandard("Ошибка!", errors.ToString()); var res = await msbox.ShowWindowDialogAsync(this); return; } if (currentService.Discount > 100) { var msbox = MessageBoxManager.GetMessageBoxStandard("Ошибка!", "Скидка не может быть больше 100%"); var res = await msbox.ShowWindowDialogAsync(this); return; } if (errors.Length > 0) { var msbox = MessageBoxManager.GetMessageBoxStandard("Ошибка!", errors.ToString()); var res = await msbox.ShowWindowDialogAsync(this); return; } var service = new Service() { Title = currentService.Title, Cost = (decimal)currentService.Cost, Description = currentService.Description, Discount = currentService.Discount, Mainimagepath = currentService.MainImagePath, Durationinseconds = (int)currentService.Durationinseconds }; // добавление if (currentService.Id == 0) { if (Manager.context.Services.Any(s => s.Title == currentService.Title)) { var ms = MessageBoxManager.GetMessageBoxStandard("Ошибка!", "Сервис с таким названием уже существует!"); var ress = await ms.ShowWindowDialogAsync(this); return; } ManageBitmaps(); Manager.context.Add(service); Manager.context.SaveChanges(); var msbox = MessageBoxManager.GetMessageBoxStandard("OK!", "Информация была успешно добавлена!"); var res = await msbox.ShowWindowDialogAsync(this); } else // редактирование { var serviceToEdit = Manager.context.Services.FirstOrDefault(s => s.Id == currentService.Id); serviceToEdit.Title = currentService.Title; serviceToEdit.Cost = (decimal)currentService.Cost; serviceToEdit.Description = currentService.Description; serviceToEdit.Discount = currentService.Discount; serviceToEdit.Mainimagepath = currentService.MainImagePath; serviceToEdit.Durationinseconds = (int)currentService.Durationinseconds; ManageBitmaps(); Manager.context.Update(serviceToEdit); Manager.context.SaveChanges(); var msbox = MessageBoxManager.GetMessageBoxStandard("OK!", "Информация была успешно редактирована!"); var res = await msbox.ShowWindowDialogAsync(this); } Close(); } catch (Exception ex) { var msbox = MessageBoxManager.GetMessageBoxStandard("Ошибка!", "Произошла ошибка при изменении данных!"); var res = await msbox.ShowWindowDialogAsync(this); return; } } public void ManageBitmaps() { var servicePhotosInDB = Manager.context.Servicephotos.ToList(); foreach (var servicePhoto in servicePhotosInDB) { if (!currentService.ServiceBitmaps.Any(b => b.ServiceId == servicePhoto.Id && b.PhotoPath == servicePhoto.Photopath)) { var imageToRemove = Manager.context.Servicephotos.FirstOrDefault(b => b.Serviceid == currentService.Id && b.Photopath == servicePhoto.Photopath); if (imageToRemove != null) Manager.context.Servicephotos.Remove(imageToRemove); } } foreach (var serviceBitmap in currentService.ServiceBitmaps) { if (!currentService.ServiceBitmaps.Any(b => b.ServiceId == serviceBitmap.Id && b.PhotoPath == serviceBitmap.PhotoPath)) { var newServicePhotoToAdd = new Servicephoto { Serviceid = currentService.Id, Photopath = serviceBitmap.PhotoPath }; Manager.context.Add(newServicePhotoToAdd); } } Manager.context.SaveChanges(); } private async void AddPictureButton_Click(object? sender, Avalonia.Interactivity.RoutedEventArgs e) { try { var openFileDialog = new OpenFileDialog(); openFileDialog.Filters.Add(new FileDialogFilter { Name = "Выбор изображения", Extensions = { "jpg", "jpeg", "png", "bmp" } }); openFileDialog.AllowMultiple = false; var result = await openFileDialog.ShowAsync(this); if (result != null && result.Length > 0) { var picToAdd = new Bitmap(result[0]); string picName = "asset" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".jpg"; string appDataPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory.ToString().Replace("\\bin\\Debug\\net7.0\\", "\\"), "Услуги автосервиса"); using (var fileStream = new FileStream(Path.Combine(appDataPath, picName), FileMode.Create)) { picToAdd.Save(fileStream); } currentService.ImageBitmap = picToAdd; currentService.MainImagePath = Path.Combine("Услуги автосервиса", picName); } } catch (Exception ex) { var msbox = MessageBoxManager.GetMessageBoxStandard("Ошибка!", ex.Message); var res = await msbox.ShowWindowDialogAsync(this); return; } } private async void AddImageButton_Click(object? sender, Avalonia.Interactivity.RoutedEventArgs e) { var openFileDialog = new OpenFileDialog(); openFileDialog.Filters.Add(new FileDialogFilter { Extensions = { "png", "jpeg", "jpg", "bmp" } }); openFileDialog.AllowMultiple = false; try { var result = await openFileDialog.ShowAsync(this); if (result != null && result.Length > 0) { string imagePath = result[0].ToString(); Bitmap bitmap = new Bitmap(imagePath); string assetsFolderPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory.ToString().Replace("\\bin\\Debug\\net7.0\\", "\\"), "Услуги автосервиса"); string fileName = Guid.NewGuid().ToString() + ".jpg"; string savedImagePath = Path.Combine(assetsFolderPath, fileName); if (currentService.ServiceBitmaps.Any(b => b.PhotoPath == ("Услуги автосервиса/" + fileName).Trim())) { var msbox = MessageBoxManager.GetMessageBoxStandard("Ошибка", "Вы не можете добавить одно и то же фото дважды!"); var res = await msbox.ShowWindowDialogAsync(this); return; } using (var stream = File.OpenWrite(savedImagePath)) { bitmap.Save(stream); } var imageToAdd = new ServicePhotoDTO { Bitmap = bitmap, PhotoPath = ("Услуги автосервиса/" + fileName).Trim(), ServiceId = currentService.Id }; currentService.ServiceBitmaps.Add(imageToAdd); currentService.MainImagePath = ("Услуги автосервиса/" + fileName).Trim(); } } catch { return; } } private void DeleteImageButton_Click(object? sender, Avalonia.Interactivity.RoutedEventArgs e) { if (currentService.ServicePhotos.Count > 0) currentService.ServiceBitmaps.RemoveAt(PictureLB.SelectedIndex); } }