198 lines
8.8 KiB
C#
198 lines
8.8 KiB
C#
using System;
|
||
using System.Collections.Generic;
|
||
using System.Linq;
|
||
using System.Security.Cryptography;
|
||
using System.Text;
|
||
using System.Windows.Forms;
|
||
using MaterialSkin; // Используем MaterialSkin
|
||
using MaterialSkin.Controls; // Используем MaterialSkin
|
||
using Newtonsoft.Json;
|
||
using SKLADm.Properties; // Используем Settings
|
||
|
||
namespace OzonInternalLabelPrinter // Замените на ваше пространство имен
|
||
{
|
||
// Наследуемся от MaterialForm
|
||
public partial class FormManageStores : MaterialForm
|
||
{
|
||
private List<OzonStore> _stores;
|
||
// Энтропия (можно оставить null или использовать свой секрет, ГЛАВНОЕ - одинаковый в Form1 и FormManageStores)
|
||
private static readonly byte[] s_entropy = null;
|
||
|
||
public FormManageStores()
|
||
{
|
||
InitializeComponent();
|
||
|
||
// Настройка MaterialSkin для этой формы
|
||
var materialSkinManager = MaterialSkinManager.Instance;
|
||
materialSkinManager.AddFormToManage(this);
|
||
// Тема и схема наследуются от Form1, т.к. она тоже управляется менеджером
|
||
|
||
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)
|
||
{
|
||
MaterialMessageBox.Show(this, $"Ошибка шифрования ключа: {ex.Message}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||
return null;
|
||
}
|
||
}
|
||
|
||
// Загрузка магазинов из настроек в ListBox
|
||
private void LoadStoresToListBox()
|
||
{
|
||
string json = Settings.Default.SavedStoresJson;
|
||
_stores = new List<OzonStore>();
|
||
if (!string.IsNullOrEmpty(json))
|
||
{
|
||
try
|
||
{
|
||
_stores = JsonConvert.DeserializeObject<List<OzonStore>>(json) ?? new List<OzonStore>();
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
MaterialMessageBox.Show(this, $"Ошибка загрузки списка магазинов: {ex.Message}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Warning);
|
||
_stores = new List<OzonStore>();
|
||
}
|
||
}
|
||
// Сортируем по имени для удобства
|
||
_stores = _stores.OrderBy(s => s.StoreName).ToList();
|
||
UpdateListBox();
|
||
}
|
||
|
||
// Сохранение магазинов в настройки
|
||
private void SaveStores()
|
||
{
|
||
try
|
||
{
|
||
// Сортируем перед сохранением
|
||
_stores = _stores.OrderBy(s => s.StoreName).ToList();
|
||
string json = JsonConvert.SerializeObject(_stores, Formatting.Indented);
|
||
Settings.Default.SavedStoresJson = json;
|
||
Settings.Default.Save(); // Сохраняем изменения
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
MaterialMessageBox.Show(this, $"Ошибка сохранения списка магазинов: {ex.Message}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||
}
|
||
}
|
||
|
||
// Обновление MaterialListBox
|
||
private void UpdateListBox()
|
||
{
|
||
lstStores.Items.Clear(); // Очищаем старые элементы
|
||
if (_stores != null)
|
||
{
|
||
foreach (var store in _stores)
|
||
{
|
||
// Добавляем каждый магазин как MaterialListBoxItem
|
||
lstStores.Items.Add(new MaterialListBoxItem(store.StoreName) { Tag = store });
|
||
}
|
||
}
|
||
// Очищаем поля редактирования
|
||
// txtStoreName.Clear();
|
||
// txtEditClientId.Clear();
|
||
// txtEditApiKey.Clear();
|
||
// lstStores.SelectedIndex = -1; // Сбрасываем выбор
|
||
}
|
||
|
||
// Кнопка "Добавить магазин"
|
||
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))
|
||
{
|
||
MaterialMessageBox.Show(this, "Пожалуйста, заполните все поля: Название, Client ID, Api-Key.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Warning);
|
||
return;
|
||
}
|
||
|
||
// Проверяем уникальность имени
|
||
if (_stores.Any(s => s.StoreName.Equals(storeName, StringComparison.OrdinalIgnoreCase)))
|
||
{
|
||
MaterialMessageBox.Show(this, "Магазин с таким названием уже существует.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Warning);
|
||
return;
|
||
}
|
||
// Проверяем уникальность Client ID (опционально, но полезно)
|
||
if (_stores.Any(s => s.ClientId.Equals(clientId, StringComparison.OrdinalIgnoreCase)))
|
||
{
|
||
if (MaterialMessageBox.Show(this, "Магазин с таким Client ID уже существует. Все равно добавить?", "Предупреждение", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
|
||
{
|
||
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();
|
||
txtStoreName.Focus(); // Фокус на первое поле
|
||
}
|
||
|
||
// Кнопка "Удалить выбранный"
|
||
private void btnDeleteStore_Click(object sender, EventArgs e)
|
||
{
|
||
if (lstStores.SelectedItem is MaterialListBoxItem selectedItem && selectedItem.Tag is OzonStore selectedStore)
|
||
{
|
||
if (MaterialMessageBox.Show(this, $"Вы уверены, что хотите удалить магазин '{selectedStore.StoreName}'?", "Подтверждение", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
|
||
{
|
||
_stores.Remove(selectedStore);
|
||
SaveStores();
|
||
UpdateListBox(); // Обновляем список на форме
|
||
}
|
||
}
|
||
else
|
||
{
|
||
MaterialMessageBox.Show(this, "Выберите магазин для удаления из списка.", "Информация", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||
}
|
||
}
|
||
|
||
// Кнопка "Закрыть"
|
||
private void btnClose_Click(object sender, EventArgs e)
|
||
{
|
||
this.DialogResult = DialogResult.OK; // Возвращаем OK при закрытии
|
||
this.Close();
|
||
}
|
||
|
||
// Можно добавить обработчик lstStores_SelectedIndexChanged, если нужно
|
||
// отображать ClientID (но не ApiKey!) при выборе магазина в списке.
|
||
/*
|
||
private void lstStores_SelectedIndexChanged(MaterialListBoxItem item)
|
||
{
|
||
if (item != null && item.Tag is OzonStore selectedStore)
|
||
{
|
||
txtStoreName.Text = selectedStore.StoreName;
|
||
txtEditClientId.Text = selectedStore.ClientId;
|
||
txtEditApiKey.Text = ""; // Никогда не показываем ключ
|
||
}
|
||
else
|
||
{
|
||
txtStoreName.Clear();
|
||
txtEditClientId.Clear();
|
||
txtEditApiKey.Clear();
|
||
}
|
||
}
|
||
*/
|
||
}
|
||
} |