DHDHSoftware/DH.Commons/Helper/SchemeHelper.cs
2025-03-21 08:51:20 +08:00

118 lines
3.8 KiB
C#
Raw 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.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DH.Commons.Helper
{
public static class SchemeHelper
{
private const string SchemesKey = "Schemes";
private const string CurrentSchemeKey = "CurrentScheme";
private const char Separator = '|';
/// <summary>
/// 初始化配置(首次运行时调用)
/// </summary>
public static void Initialize()
{
// 如果Schemes不存在创建空键
if (!SystemConfigHelper.KeyExists(SchemesKey))
{
SystemConfigHelper.SetValue(SchemesKey, "");
}
// 如果CurrentScheme不存在创建空键
if (!SystemConfigHelper.KeyExists(CurrentSchemeKey))
{
SystemConfigHelper.SetValue(CurrentSchemeKey, "");
}
}
/// <summary>
/// 获取所有方案(自动处理空值)
/// </summary>
public static List<string> GetAllSchemes()
{
var schemeString = SystemConfigHelper.GetValue(SchemesKey, "");
return string.IsNullOrEmpty(schemeString)
? new List<string>()
: new List<string>(schemeString.Split(Separator));
}
/// <summary>
/// 添加新方案(自动初始化处理)
/// </summary>
public static void AddScheme(string schemeName)
{
if (string.IsNullOrWhiteSpace(schemeName))
throw new ArgumentException("方案名称无效");
var schemes = GetAllSchemes();
if (schemes.Contains(schemeName))
throw new InvalidOperationException($"方案 {schemeName} 已存在");
schemes.Add(schemeName);
SaveSchemes(schemes);
}
/// <summary>
/// 设置当前方案(空值安全处理)
/// </summary>
public static void SetCurrentScheme(string schemeName)
{
var schemes = GetAllSchemes();
if (!schemes.Contains(schemeName))
throw new KeyNotFoundException($"方案 {schemeName} 不存在");
SystemConfigHelper.SetValue(CurrentSchemeKey, schemeName);
}
/// <summary>
/// 获取当前方案(默认值处理)
/// </summary>
public static string GetCurrentScheme()
{
var current = SystemConfigHelper.GetValue(CurrentSchemeKey, "");
return !string.IsNullOrEmpty(current) ? current : "默认方案";
}
private static void SaveSchemes(List<string> schemes)
{
var schemeString = schemes.Count > 0
? string.Join(Separator.ToString(), schemes)
: "";
SystemConfigHelper.SetValue(SchemesKey, schemeString);
}
/// <summary>
/// 删除指定方案(自动同步当前方案状态)
/// </summary>
/// <param name="schemeName">要删除的方案名称</param>
/// <exception cref="ArgumentException">当方案名称为空时抛出</exception>
/// <exception cref="KeyNotFoundException">当方案不存在时抛出</exception>
public static void DeleteScheme(string schemeName)
{
if (string.IsNullOrWhiteSpace(schemeName))
throw new ArgumentException("方案名称无效");
var schemes = GetAllSchemes();
if (!schemes.Contains(schemeName))
throw new KeyNotFoundException($"方案 {schemeName} 不存在");
// 删除前检查是否是当前方案
bool isCurrent = GetCurrentScheme() == schemeName;
// 执行删除操作
schemes.Remove(schemeName);
SaveSchemes(schemes);
}
}
}