兼容win7版应用
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

236 lines
7.1 KiB

using System.Threading.Tasks;
using System.Threading;
using AIK.Models.SystemSettings;
using AIK.Service.IService;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
namespace AIK.Service.Service
{
public class ConfigurationService : IConfigurationService
{
private readonly string _configFilePath;
private AppConfig _config;
private readonly object _lockObject = new object();
public ConfigurationService()
{
_configFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "appsettings.json");
_config = LoadConfiguration() ?? new AppConfig();
}
public string Environment => _config.Environment;
public ApiSettings ApiSettings => _config.ApiSettings ?? new ApiSettings();
public CacheSettings CacheSettings => _config.CacheSettings ?? new CacheSettings();
public T GetSection<T>(string sectionName) where T : new()
{
return sectionName.ToLower() switch
{
"apisettings" when typeof(T) == typeof(ApiSettings) => (T)(object)(ApiSettings),
"cachesettings" when typeof(T) == typeof(CacheSettings) => (T)(object)(CacheSettings),
_ => new T()
};
}
public string GetConnectionString(string name) => string.Empty;
#region 新增方法 - 修改配置
/// <summary>
/// 更新语言设置
/// </summary>
public async Task UpdateLanguageAsync(string languageCode)
{
if (string.IsNullOrEmpty(languageCode))
throw new ArgumentException("语言代码不能为空", nameof(languageCode));
lock (_lockObject)
{
if (_config.ApiSettings == null)
_config.ApiSettings = new ApiSettings();
_config.ApiSettings.Language = languageCode;
}
await SaveConfigurationAsync();
}
/// <summary>
/// 更新 API 设置
/// </summary>
public async Task UpdateApiSettingsAsync(Action<ApiSettings> updateAction)
{
if (updateAction == null)
throw new ArgumentNullException(nameof(updateAction));
lock (_lockObject)
{
if (_config.ApiSettings == null)
_config.ApiSettings = new ApiSettings();
updateAction(_config.ApiSettings);
}
await SaveConfigurationAsync();
}
/// <summary>
/// 更新缓存设置
/// </summary>
public async Task UpdateCacheSettingsAsync(Action<CacheSettings> updateAction)
{
if (updateAction == null)
throw new ArgumentNullException(nameof(updateAction));
lock (_lockObject)
{
if (_config.CacheSettings == null)
_config.CacheSettings = new CacheSettings();
updateAction(_config.CacheSettings);
}
await SaveConfigurationAsync();
}
/// <summary>
/// 保存配置到文件
/// </summary>
public async Task SaveConfigurationAsync()
{
try
{
var json = JsonConvert.SerializeObject(_config, Formatting.Indented);
File.WriteAllText(_configFilePath, json, Encoding.UTF8);
await ReloadConfigurationAsync();
Debug.WriteLine($"配置已保存到: {_configFilePath}");
}
catch (Exception ex)
{
Debug.WriteLine($"保存配置失败: {ex.Message}");
throw new InvalidOperationException("保存配置文件失败", ex);
}
}
/// <summary>
/// 重新加载配置
/// </summary>
public async Task ReloadConfigurationAsync()
{
var newConfig = LoadConfiguration();
if (newConfig != null)
{
lock (_lockObject)
{
_config = newConfig;
}
}
await Task.CompletedTask;
}
#endregion
#region 私有方法
private AppConfig LoadConfiguration()
{
try
{
if (File.Exists(_configFilePath))
{
var json = File.ReadAllText(_configFilePath);
return JsonConvert.DeserializeObject<AppConfig>(json);
}
// 如果配置文件不存在,创建默认配置并保存
var defaultConfig = CreateDefaultConfig();
SaveConfigurationAsync().Wait(); // 同步保存默认配置
return defaultConfig;
}
catch (Exception ex)
{
Debug.WriteLine($"配置文件加载失败: {ex.Message}");
return CreateDefaultConfig();
}
}
private AppConfig CreateDefaultConfig()
{
return new AppConfig
{
Environment = Debugger.IsAttached ? "Development" : "Production",
ApiSettings = new ApiSettings
{
BaseUrl = Debugger.IsAttached ? "https://keytest.aik518.com" : "https://key.aik518.com",
Language = "zh",
Timeout = 30,
RetryCount = 3,
Endpoints = new ApiEndpoints
{
GetCarData = "/api/v1/cars",
GetCarModels = "/api/v1/models/{0}",
GetCarImages = "/api/v1/images/{0}",
Authentication = "/api/v1/auth/login"
}
},
CacheSettings = new CacheSettings
{
DataCacheExpiryHours = 3,
ImageCacheExpiryDays = 7,
MaxCacheSizeMB = 100
}
};
}
#endregion
#region 便捷方法
/// <summary>
/// 获取当前语言
/// </summary>
public string GetCurrentLanguage()
{
return _config?.ApiSettings?.Language ?? "zh";
}
/// <summary>
/// 检查语言是否支持
/// </summary>
public bool IsLanguageSupported(string languageCode)
{
var supportedLanguages = new[] { "zh", "en", "pt", "es" };
return supportedLanguages.Contains(languageCode);
}
/// <summary>
/// 批量更新设置
/// </summary>
public async Task UpdateSettingsAsync(Action<AppConfig> updateAction)
{
if (updateAction == null)
throw new ArgumentNullException(nameof(updateAction));
lock (_lockObject)
{
updateAction(_config);
}
await SaveConfigurationAsync();
}
#endregion
}
}