using MyHomePage.Api.Common; using MyHomePage.Api.Models.Dtos; using MyHomePage.Api.Models.Entities; using SqlSugar; namespace MyHomePage.Api.Services; /// public class SettingService : ISettingService { private const int DefaultId = 1; private static readonly HashSet AllowedThemeModes = new(StringComparer.OrdinalIgnoreCase) { "dark", "light", "auto" }; private static readonly HashSet AllowedBackgroundTypes = new(StringComparer.OrdinalIgnoreCase) { "preset", "custom", "solid" }; // ===== P34 360 壁纸切换间隔合法值(分钟)===== private static readonly HashSet AllowedWallpaperIntervals = new() { 0, 1, 5, 15, 30, 60 }; private readonly ISqlSugarClient _db; private readonly SyncLogHelper _sync; public SettingService(ISqlSugarClient db, SyncLogHelper sync) { _db = db; _sync = sync; } /// public async Task GetAsync() { var entity = await _db.Queryable().InSingleAsync(DefaultId); if (entity is null) { // 兜底:写入默认值 entity = new Setting { Id = DefaultId }; await _db.Insertable(entity).ExecuteCommandAsync(); } return ToDto(entity); } /// public async Task UpdateAsync(SettingUpdateRequest request) { var entity = await _db.Queryable().InSingleAsync(DefaultId); if (entity is null) { entity = new Setting { Id = DefaultId }; await _db.Insertable(entity).ExecuteCommandAsync(); } if (!string.IsNullOrEmpty(request.ThemeMode)) { if (!AllowedThemeModes.Contains(request.ThemeMode)) throw new BusinessException("不支持的主题模式", 400); entity.ThemeMode = request.ThemeMode; } if (!string.IsNullOrEmpty(request.AccentColor)) { if (request.AccentColor.Length > 16) throw new BusinessException("主色调格式错误", 400); entity.AccentColor = request.AccentColor; } if (request.BackgroundImage is not null) entity.BackgroundImage = request.BackgroundImage; if (!string.IsNullOrEmpty(request.BackgroundType)) { if (!AllowedBackgroundTypes.Contains(request.BackgroundType)) throw new BusinessException("不支持的背景类型", 400); entity.BackgroundType = request.BackgroundType; } if (request.OpenLinksInNewTab.HasValue) entity.OpenLinksInNewTab = request.OpenLinksInNewTab.Value ? 1 : 0; if (request.OpenSearchInNewTab.HasValue) entity.OpenSearchInNewTab = request.OpenSearchInNewTab.Value ? 1 : 0; // ===== P34 360 壁纸模式 ===== if (request.WallpaperEnabled.HasValue) entity.WallpaperEnabled = request.WallpaperEnabled.Value ? 1 : 0; if (request.WallpaperCategoryId is not null) entity.WallpaperCategoryId = request.WallpaperCategoryId; if (request.WallpaperInterval.HasValue) { if (!AllowedWallpaperIntervals.Contains(request.WallpaperInterval.Value)) throw new BusinessException("不支持的壁纸切换间隔(允许:0/1/5/15/30/60 分钟)", 400); entity.WallpaperInterval = request.WallpaperInterval.Value; } entity.UpdatedAt = DateTime.UtcNow; await _db.Updateable(entity).ExecuteCommandAsync(); await _sync.WriteAsync("setting", entity.Id, "update"); return ToDto(entity); } private static SettingDto ToDto(Setting s) => SettingDto.FromEntity(s);}