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(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 新增方法 - 修改配置 /// /// 更新语言设置 /// 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(); } /// /// 更新 API 设置 /// public async Task UpdateApiSettingsAsync(Action updateAction) { if (updateAction == null) throw new ArgumentNullException(nameof(updateAction)); lock (_lockObject) { if (_config.ApiSettings == null) _config.ApiSettings = new ApiSettings(); updateAction(_config.ApiSettings); } await SaveConfigurationAsync(); } /// /// 更新缓存设置 /// public async Task UpdateCacheSettingsAsync(Action updateAction) { if (updateAction == null) throw new ArgumentNullException(nameof(updateAction)); lock (_lockObject) { if (_config.CacheSettings == null) _config.CacheSettings = new CacheSettings(); updateAction(_config.CacheSettings); } await SaveConfigurationAsync(); } /// /// 保存配置到文件 /// 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); } } /// /// 重新加载配置 /// 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(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 便捷方法 /// /// 获取当前语言 /// public string GetCurrentLanguage() { return _config?.ApiSettings?.Language ?? "zh"; } /// /// 检查语言是否支持 /// public bool IsLanguageSupported(string languageCode) { var supportedLanguages = new[] { "zh", "en", "pt", "es" }; return supportedLanguages.Contains(languageCode); } /// /// 批量更新设置 /// public async Task UpdateSettingsAsync(Action updateAction) { if (updateAction == null) throw new ArgumentNullException(nameof(updateAction)); lock (_lockObject) { updateAction(_config); } await SaveConfigurationAsync(); } #endregion } }