using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Newtonsoft.Json;
namespace DH.Commons.Helper
{
public static class SchemeHelper
{
private const string DefaultSchemeName = "默认方案";
private static readonly string ConfigFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "schemes.json");
///
/// 方案配置数据结构
///
private class SchemeConfig
{
public List Schemes { get; set; } = new List();
public string CurrentScheme { get; set; } = DefaultSchemeName;
}
///
/// 初始化配置(首次运行时调用)
///
public static void Initialize()
{
if (!File.Exists(ConfigFilePath))
{
var defaultConfig = new SchemeConfig
{
Schemes = new List { DefaultSchemeName },
CurrentScheme = DefaultSchemeName
};
SaveConfig(defaultConfig);
}
}
///
/// 获取所有方案
///
public static List GetAllSchemes()
{
var config = LoadConfig();
return config.Schemes ?? new List();
}
///
/// 添加新方案
///
public static void AddScheme(string schemeName)
{
if (string.IsNullOrWhiteSpace(schemeName))
throw new ArgumentException("方案名称无效");
var config = LoadConfig();
if (config.Schemes.Contains(schemeName))
throw new InvalidOperationException($"方案 {schemeName} 已存在");
config.Schemes.Add(schemeName);
SaveConfig(config);
}
///
/// 设置当前方案
///
public static void SetCurrentScheme(string schemeName)
{
var config = LoadConfig();
if (!config.Schemes.Contains(schemeName))
throw new KeyNotFoundException($"方案 {schemeName} 不存在");
config.CurrentScheme = schemeName;
SaveConfig(config);
}
///
/// 获取当前方案
///
public static string GetCurrentScheme()
{
var config = LoadConfig();
return !string.IsNullOrEmpty(config.CurrentScheme)
? config.CurrentScheme
: DefaultSchemeName;
}
///
/// 删除指定方案
///
public static void DeleteScheme(string schemeName)
{
if (string.IsNullOrWhiteSpace(schemeName))
throw new ArgumentException("方案名称无效");
var config = LoadConfig();
if (!config.Schemes.Contains(schemeName))
throw new KeyNotFoundException($"方案 {schemeName} 不存在");
// 如果是当前方案,需要先切换
if (config.CurrentScheme == schemeName)
{
var otherScheme = config.Schemes.FirstOrDefault(s => s != schemeName);
if (otherScheme != null)
{
config.CurrentScheme = otherScheme;
}
else
{
config.CurrentScheme = DefaultSchemeName;
if (!config.Schemes.Contains(DefaultSchemeName))
{
config.Schemes.Add(DefaultSchemeName);
}
}
}
config.Schemes.Remove(schemeName);
SaveConfig(config);
}
///
/// 加载配置文件
///
private static SchemeConfig LoadConfig()
{
if (!File.Exists(ConfigFilePath))
{
Initialize();
}
try
{
string json = File.ReadAllText(ConfigFilePath);
return JsonConvert.DeserializeObject(json) ?? new SchemeConfig();
}
catch
{
// 如果读取失败,返回默认配置
return new SchemeConfig
{
Schemes = new List { DefaultSchemeName },
CurrentScheme = DefaultSchemeName
};
}
}
///
/// 保存配置文件
///
private static void SaveConfig(SchemeConfig config)
{
try
{
string json = JsonConvert.SerializeObject(config, Formatting.Indented);
File.WriteAllText(ConfigFilePath, json);
}
catch (Exception ex)
{
// 处理保存失败的情况
throw new InvalidOperationException("保存方案配置失败", ex);
}
}
}
}