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