demMalyhinMerkulov_shoe_store/ManagerMainForm.cs
2025-11-26 11:52:04 +04:00

297 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 System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace demMalyhin
{
public partial class ManagerMainForm : Form
{
private MySqlDataAdapter dataAdapter;
private DataTable prodTable;
private BindingSource bindingSource = new BindingSource();
public ManagerMainForm()
{
InitializeComponent();
LoadProdData();
LoadSortOptions();
LoadFilterOptions();
}
private void LoadProdData() // загрузка данных в дгв
{
try
{
DB db = new DB();
using (MySqlConnection connection = db.getConnection())
{
connection.Open();
string query = "SELECT article_product AS `Артикул`, product_name AS `Название товара`, price AS `Цена`, supplier_name AS `Поставщик`, Manufacturer_name AS `Производитель`, Category_name AS `Категория`, sale_percent AS `Скидка`, unit_type AS `Единица измерения`, description AS `описание`, quantity_in_stock AS `Количество на складе`, photo AS `фото` FROM products LEFT JOIN Category ON products.category_id = Category.id_Category JOIN Supplier ON products.supplier_id = Supplier.id_Supplier JOIN Manufacturer ON products.manufacturer_id = Manufacturer.id_Manufacturer";
dataAdapter = new MySqlDataAdapter(query, connection);
prodTable = new DataTable();
dataAdapter.Fill(prodTable);
DataGridViewProduct.RowTemplate.Height = 60;
bindingSource.DataSource = prodTable;
DataGridViewProduct.DataSource = bindingSource;
DataGridViewProduct.AllowUserToAddRows = false;
DataGridViewProduct.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells;
DataGridViewProduct.ReadOnly = true; // настройки дгв
}
}
catch (MySqlException ex)
{
MessageBox.Show("Ошибка при подключении к базе данных или выполнении запроса: " + ex.Message);
}
catch (Exception ex)
{
MessageBox.Show("Произошла общая ошибка: " + ex.Message);
}
}
private void dataGridViewProd_Click(object sender, EventArgs e)
{
textBoxDesc.Text = DataGridViewProduct.CurrentRow.Cells[8].Value.ToString();
textBoxManuf.Text = DataGridViewProduct.CurrentRow.Cells[4].Value.ToString();
textBoxSup.Text = DataGridViewProduct.CurrentRow.Cells[3].Value.ToString();
textBoxPrice.Text = DataGridViewProduct.CurrentRow.Cells[2].Value.ToString();
textBoxUnit.Text = DataGridViewProduct.CurrentRow.Cells[7].Value.ToString();
textBoxStock.Text = DataGridViewProduct.CurrentRow.Cells[9].Value.ToString();
NameLabel.Text = DataGridViewProduct.CurrentRow.Cells[1].Value.ToString();
CategoryLabel.Text = DataGridViewProduct.CurrentRow.Cells[5].Value.ToString();
SaleLabel.Text = DataGridViewProduct.CurrentRow.Cells[6].Value.ToString() + "%";
try
{
object photoData = DataGridViewProduct.CurrentRow.Cells[10].Value;
if (photoData != DBNull.Value)
{
byte[] imageData = (byte[])photoData;
if (imageData != null && imageData.Length > 0)
{
using (MemoryStream ms = new MemoryStream(imageData))
{
pictureBoxPhoto.Image = Image.FromStream(ms);
pictureBoxPhoto.SizeMode = PictureBoxSizeMode.Zoom;
}
}
else
{
pictureBoxPhoto.Image = Properties.Resources.picture;
pictureBoxPhoto.SizeMode = PictureBoxSizeMode.Zoom;
}
}
else
{
pictureBoxPhoto.Image = Properties.Resources.picture;
pictureBoxPhoto.SizeMode = PictureBoxSizeMode.Zoom;
}
}
catch (Exception ex)
{
MessageBox.Show("Ошибка при загрузке изображения: " + ex.Message);
pictureBoxPhoto.Image = Properties.Resources.picture;
pictureBoxPhoto.SizeMode = PictureBoxSizeMode.Zoom;
}
try
{
var currentRow = DataGridViewProduct.CurrentRow;
if (currentRow == null) return;
Color defaultColor = SystemColors.Window;
textBoxPrice.BackColor = defaultColor;
textBoxSup.BackColor = defaultColor;
textBoxManuf.BackColor = defaultColor;
textBoxStock.BackColor = defaultColor;
textBoxPrice.ForeColor = Color.Black;
textBoxPrice.Font = new Font(textBoxPrice.Font, FontStyle.Regular);
textBoxFP.Text = "";
decimal originalPrice = 0m;
int salePercent = 0;
int quantityInStock = 0;
decimal.TryParse(currentRow.Cells[2].Value?.ToString(), out originalPrice);
int.TryParse(currentRow.Cells[6].Value?.ToString(), out salePercent);
int.TryParse(currentRow.Cells[9].Value?.ToString(), out quantityInStock);
if (salePercent > 15)
{
Color highDiscountColor = ColorTranslator.FromHtml("#2E8B57");
textBoxPrice.BackColor = highDiscountColor;
textBoxSup.BackColor = highDiscountColor;
textBoxManuf.BackColor = highDiscountColor;
textBoxStock.BackColor = highDiscountColor;
textBoxDesc.BackColor = highDiscountColor;
textBoxFP.BackColor = highDiscountColor;
textBoxUnit.BackColor = highDiscountColor;
panel3.BackColor = highDiscountColor;
}
else
{
textBoxPrice.BackColor = Color.White;
textBoxSup.BackColor = Color.White;
textBoxManuf.BackColor = Color.White;
textBoxStock.BackColor = Color.White;
textBoxDesc.BackColor = Color.White;
textBoxFP.BackColor = Color.White;
textBoxUnit.BackColor = Color.White;
panel3.BackColor = Color.White;
}
if (salePercent > 0)
{
decimal finalPrice = originalPrice * (1 - (decimal)salePercent / 100);
textBoxPrice.Text = $"{originalPrice:N2}";
textBoxPrice.ForeColor = Color.Red;
textBoxPrice.Font = new Font(textBoxPrice.Font, FontStyle.Strikeout);
textBoxFP.Text = $"{finalPrice:N2}";
textBoxFP.ForeColor = Color.Black;
textBoxFP.Font = new Font(textBoxFP.Font, FontStyle.Regular);
}
else
{
textBoxPrice.Text = $"{originalPrice:N2}";
}
if (quantityInStock <= 0)
{
textBoxStock.BackColor = Color.LightBlue;
}
}
catch (Exception ex)
{
MessageBox.Show("Ошибка при обработке данных товара: " + ex.Message);
}
}
private void LoadSortOptions()
{
comboBoxSort.Items.Add("По умолчанию");
comboBoxSort.Items.Add("Название (А-Я)");
comboBoxSort.Items.Add("Название (Я-А)");
comboBoxSort.Items.Add("Цена (возрастающая)");
comboBoxSort.Items.Add("Цена (убывающая)");
comboBoxSort.SelectedIndex = 0;
}
private void comboBoxSort_SelectedIndexChanged(object sender, EventArgs e)
{
string sortOption = comboBoxSort.SelectedItem.ToString();
switch (sortOption)
{
case "По умолчанию":
bindingSource.Sort = "";
break;
case "Название (А-Я)":
bindingSource.Sort = "Название товара ASC";
break;
case "Название (Я-А)":
bindingSource.Sort = "Название товара DESC";
break;
case "Цена (возрастающая)":
bindingSource.Sort = "Цена ASC";
break;
case "Цена (убывающая)":
bindingSource.Sort = "Цена DESC";
break;
}
}
private void LoadFilterOptions()
{
comboBoxFilter.Items.Add("По умолчанию");
comboBoxFilter.Items.Add("Мужская обувь");
comboBoxFilter.Items.Add("Женская обувь");
comboBoxSort.SelectedIndex = 0;
}
private void comboBoxFilter_SelectedIndexChanged(object sender, EventArgs e)
{
string filterOption = comboBoxFilter.SelectedItem.ToString().Trim();
switch (filterOption)
{
case "По умолчанию":
bindingSource.Filter = "";
break;
case "Мужская обувь":
bindingSource.Filter = "[Категория] = 'Мужская обувь'";
break;
case "Женская обувь":
bindingSource.Filter = "[Категория] = 'Женская обувь'";
break;
default:
bindingSource.Filter = "";
break;
}
}
private void textBoxSearch_TextChanged(object sender, EventArgs e)
{
string searchText = textBoxSearch.Text.Trim();
if (string.IsNullOrEmpty(searchText))
{
bindingSource.Filter = "";
}
else
{
string s = searchText.Replace("'", "''");
string pattern = string.Format("%{0}%", s);
bindingSource.Filter = string.Format(
"[Артикул] LIKE '{0}' OR [Название товара] LIKE '{0}' OR [Поставщик] LIKE '{0}' OR [Производитель] LIKE '{0}' OR [Категория] LIKE '{0}' OR [Единица измерения] LIKE '{0}' OR " +
"Convert([Цена], 'System.String') LIKE '{0}' OR Convert([Скидка], 'System.String') LIKE '{0}' OR Convert([Количество на складе], 'System.String') LIKE '{0}'",
pattern);
}
}
private void AdmMainForm_Load(object sender, EventArgs e)
{
labelFIO.Text = LoginForm.ClientSurname + " " + LoginForm.ClientName + " " + LoginForm.ClientPatronymic;
}
private void btnBack_Click(object sender, EventArgs e)
{
this.Hide();
LoginForm log = new LoginForm();
log.Show();
}
private void OrdersBtn_Click(object sender, EventArgs e)
{
this.Hide();
ManagerOrder mo = new ManagerOrder();
mo.Show();
}
private void btnExit_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void ManagerMainForm_Load(object sender, EventArgs e)
{
labelFIO.Text = LoginForm.ClientSurname + " " + LoginForm.ClientName + " " + LoginForm.ClientPatronymic;
}
}
}