SKLADm/FormManageStores.cs
2025-04-21 21:14:48 +07:00

151 lines
6.4 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 Newtonsoft.Json;
using OzonInternalLabelPrinter; // Добавляем пространство имен для OzonStore
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography; // Для ProtectedData
using System.Text;
using System.Windows.Forms;
namespace SKLADm
{
public partial class FormManageStores : Form
{
private List<OzonStore> _stores;
// Энтропия для шифрования (можно оставить null или использовать свой секрет)
private static readonly byte[] s_entropy = null; // Или Encoding.UTF8.GetBytes("MyOptionalEntropy");
public FormManageStores()
{
InitializeComponent();
LoadStoresToListBox();
}
// --- Шифрование Api-Key ---
private string EncryptApiKey(string apiKey)
{
if (string.IsNullOrEmpty(apiKey)) return string.Empty;
try
{
byte[] apiKeyBytes = Encoding.UTF8.GetBytes(apiKey);
byte[] encryptedBytes = ProtectedData.Protect(apiKeyBytes, s_entropy, DataProtectionScope.CurrentUser);
return Convert.ToBase64String(encryptedBytes);
}
catch (Exception ex)
{
MessageBox.Show($"Ошибка шифрования ключа: {ex.Message}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return null; // Возвращаем null при ошибке
}
}
// --- Загрузка магазинов из настроек ---
private void LoadStoresToListBox()
{
string json = Properties.Settings.Default.SavedStoresJson;
_stores = new List<OzonStore>();
if (!string.IsNullOrEmpty(json))
{
try
{
_stores = JsonConvert.DeserializeObject<List<OzonStore>>(json) ?? new List<OzonStore>();
}
catch (Exception ex)
{
MessageBox.Show($"Ошибка загрузки списка магазинов: {ex.Message}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Warning);
_stores = new List<OzonStore>(); // Создаем пустой список при ошибке
}
}
UpdateListBox();
}
// --- Сохранение магазинов в настройки ---
private void SaveStores()
{
try
{
string json = JsonConvert.SerializeObject(_stores, Formatting.Indented);
Properties.Settings.Default.SavedStoresJson = json;
Properties.Settings.Default.Save();
}
catch (Exception ex)
{
MessageBox.Show($"Ошибка сохранения списка магазинов: {ex.Message}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
// --- Обновление ListBox ---
private void UpdateListBox()
{
lstStores.DataSource = null; // Сначала отвязываем источник
lstStores.DataSource = _stores; // Привязываем обновленный список
lstStores.DisplayMember = "StoreName"; // Отображаем имя
}
// --- Кнопка "Добавить магазин" ---
private void btnAddStore_Click(object sender, EventArgs e)
{
string storeName = txtStoreName.Text.Trim();
string clientId = txtEditClientId.Text.Trim();
string apiKey = txtEditApiKey.Text.Trim(); // Берем ключ как есть
if (string.IsNullOrEmpty(storeName) || string.IsNullOrEmpty(clientId) || string.IsNullOrEmpty(apiKey))
{
MessageBox.Show("Пожалуйста, заполните все поля: Название, Client ID, Api-Key.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
// Проверяем, нет ли уже магазина с таким именем
if (_stores.Any(s => s.StoreName.Equals(storeName, StringComparison.OrdinalIgnoreCase)))
{
MessageBox.Show("Магазин с таким названием уже существует.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
// Шифруем ключ
string encryptedKey = EncryptApiKey(apiKey);
if (encryptedKey == null) // Если шифрование не удалось
{
return;
}
// Создаем и добавляем магазин
OzonStore newStore = new OzonStore(storeName, clientId, encryptedKey);
_stores.Add(newStore);
// Сохраняем и обновляем список
SaveStores();
UpdateListBox();
// Очищаем поля ввода
txtStoreName.Clear();
txtEditClientId.Clear();
txtEditApiKey.Clear();
}
// --- Кнопка "Удалить выбранный" (Опционально) ---
private void btnDeleteStore_Click(object sender, EventArgs e)
{
if (lstStores.SelectedItem is OzonStore selectedStore)
{
if (MessageBox.Show($"Вы уверены, что хотите удалить магазин '{selectedStore.StoreName}'?", "Подтверждение", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_stores.Remove(selectedStore);
SaveStores();
UpdateListBox();
}
}
else
{
MessageBox.Show("Выберите магазин для удаления.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
// --- Кнопка "Закрыть" ---
private void btnClose_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.OK; // Указываем, что форма закрыта штатно
this.Close();
}
}
}