ProductEditForm.cs 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. using System.Drawing;
  2. using System.Drawing.Drawing2D;
  3. using System.Windows.Forms;
  4. namespace TradeApp.WinForms.V08;
  5. public sealed partial class ProductEditForm : Form
  6. {
  7. private readonly DatabaseClient _db;
  8. private readonly ProductView _product;
  9. private readonly string _originalImagePath;
  10. public ProductEditForm(DatabaseClient db, ProductView? product)
  11. {
  12. _db = db;
  13. _product = product ?? new ProductView();
  14. _originalImagePath = _product.ImagePath;
  15. InitializeComponent();
  16. Text = product is null ? "Добавление товара" : "Редактирование товара";
  17. LoadLookups();
  18. Fill();
  19. }
  20. private void ChooseImageButton_Click(object? sender, EventArgs e)
  21. {
  22. using var dialog = new OpenFileDialog { Filter = "Изображения|*.jpg;*.jpeg;*.png;*.bmp" };
  23. if (dialog.ShowDialog(this) != DialogResult.OK)
  24. {
  25. return;
  26. }
  27. var targetDir = Path.Combine(AppContext.BaseDirectory, "Images");
  28. Directory.CreateDirectory(targetDir);
  29. var targetName = Path.GetFileName(dialog.FileName);
  30. var targetPath = Path.Combine(targetDir, targetName);
  31. if (!string.Equals(Path.GetFullPath(dialog.FileName), Path.GetFullPath(targetPath), StringComparison.OrdinalIgnoreCase))
  32. {
  33. SaveProductImage(dialog.FileName, targetPath);
  34. }
  35. imageTextBox.Text = targetName;
  36. }
  37. private void SaveButton_Click(object? sender, EventArgs e)
  38. {
  39. if (string.IsNullOrWhiteSpace(articleTextBox.Text) || string.IsNullOrWhiteSpace(nameTextBox.Text))
  40. {
  41. MessageBox.Show("Артикул и название обязательны.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
  42. return;
  43. }
  44. _product.Article = articleTextBox.Text.Trim();
  45. _product.Name = nameTextBox.Text.Trim();
  46. _product.Unit = unitComboBox.Text.Trim();
  47. _product.Price = priceNumeric.Value;
  48. _product.Supplier = supplierComboBox.Text.Trim();
  49. _product.Manufacturer = manufacturerComboBox.Text.Trim();
  50. _product.Category = categoryComboBox.Text.Trim();
  51. _product.DiscountPercent = discountNumeric.Value;
  52. _product.StockQuantity = (int)stockNumeric.Value;
  53. _product.Description = descriptionTextBox.Text.Trim();
  54. _product.ImagePath = string.IsNullOrWhiteSpace(imageTextBox.Text) ? "picture.png" : imageTextBox.Text.Trim();
  55. _db.SaveProduct(_product);
  56. DeleteReplacedImage(_originalImagePath, _product.ImagePath);
  57. DialogResult = DialogResult.OK;
  58. }
  59. private void LoadLookups()
  60. {
  61. unitComboBox.Items.AddRange(_db.LoadUnits().Cast<object>().ToArray());
  62. supplierComboBox.Items.AddRange(_db.LoadSuppliers().Cast<object>().ToArray());
  63. manufacturerComboBox.Items.AddRange(_db.LoadManufacturers().Cast<object>().ToArray());
  64. categoryComboBox.Items.AddRange(_db.LoadCategories().Cast<object>().ToArray());
  65. }
  66. private void Fill()
  67. {
  68. articleTextBox.Text = _product.Article;
  69. nameTextBox.Text = _product.Name;
  70. unitComboBox.Text = _product.Unit;
  71. priceNumeric.Value = Clamp(_product.Price, priceNumeric.Minimum, priceNumeric.Maximum);
  72. supplierComboBox.Text = _product.Supplier;
  73. manufacturerComboBox.Text = _product.Manufacturer;
  74. categoryComboBox.Text = _product.Category;
  75. discountNumeric.Value = Clamp(_product.DiscountPercent, discountNumeric.Minimum, discountNumeric.Maximum);
  76. stockNumeric.Value = Clamp(_product.StockQuantity, stockNumeric.Minimum, stockNumeric.Maximum);
  77. descriptionTextBox.Text = _product.Description;
  78. imageTextBox.Text = string.IsNullOrWhiteSpace(_product.ImagePath) ? "picture.png" : _product.ImagePath;
  79. }
  80. private static decimal Clamp(decimal value, decimal minimum, decimal maximum)
  81. {
  82. return Math.Min(Math.Max(value, minimum), maximum);
  83. }
  84. private static void SaveProductImage(string sourcePath, string targetPath)
  85. {
  86. using var source = Image.FromFile(sourcePath);
  87. var scale = Math.Min(1d, Math.Min(300d / source.Width, 200d / source.Height));
  88. var width = Math.Max(1, (int)Math.Round(source.Width * scale));
  89. var height = Math.Max(1, (int)Math.Round(source.Height * scale));
  90. using var resized = new Bitmap(width, height);
  91. resized.SetResolution(source.HorizontalResolution, source.VerticalResolution);
  92. using (var graphics = Graphics.FromImage(resized))
  93. {
  94. graphics.Clear(Color.Transparent);
  95. graphics.CompositingQuality = CompositingQuality.HighQuality;
  96. graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
  97. graphics.SmoothingMode = SmoothingMode.HighQuality;
  98. graphics.DrawImage(source, 0, 0, width, height);
  99. }
  100. if (File.Exists(targetPath))
  101. {
  102. File.Delete(targetPath);
  103. }
  104. resized.Save(targetPath, source.RawFormat);
  105. }
  106. private void DeleteReplacedImage(string oldImagePath, string newImagePath)
  107. {
  108. if (string.IsNullOrWhiteSpace(oldImagePath) ||
  109. oldImagePath.Equals(newImagePath, StringComparison.OrdinalIgnoreCase) ||
  110. oldImagePath.Equals("picture.png", StringComparison.OrdinalIgnoreCase) ||
  111. _db.ProductImageIsUsed(oldImagePath, _product.ProductId))
  112. {
  113. return;
  114. }
  115. var path = Path.Combine(AppContext.BaseDirectory, "Images", oldImagePath);
  116. if (!File.Exists(path))
  117. {
  118. return;
  119. }
  120. try
  121. {
  122. File.Delete(path);
  123. }
  124. catch (IOException)
  125. {
  126. MessageBox.Show("Старое фото сохранено, потому что файл сейчас занят.", "Фото товара", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  127. }
  128. catch (UnauthorizedAccessException)
  129. {
  130. MessageBox.Show("Старое фото не удалено: нет доступа к файлу.", "Фото товара", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  131. }
  132. }
  133. }