using OrderSupportTicket.Models; using OrderSupportTicket.Models.Api; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace OrderSupportTicket.Services; /// /// 启动时从服务端工单列表和历史本地缓存计算未读消息。 /// public sealed class WorkOrderUnreadService { private const int PageSize = 100; private const int MaxPages = 20; private readonly TicketApiService _api; private readonly WorkOrderCacheService _cache; /// /// 使用默认工单 API 和缓存服务创建未读计算服务。 /// public WorkOrderUnreadService() : this(new TicketApiService(), new WorkOrderCacheService()) { } /// /// 创建未读计算服务。 /// public WorkOrderUnreadService( TicketApiService api, WorkOrderCacheService cache) { _api = api ?? throw new ArgumentNullException(nameof(api)); _cache = cache ?? throw new ArgumentNullException(nameof(cache)); } /// /// 获取每个工单的未读消息数。返回值的键为 "appId|wechatOrderId"。 /// public async Task> GetUnreadByTicketAsync( TicketClientOptions options) { if (options == null) throw new ArgumentNullException(nameof(options)); TicketApiService.ValidateOptions(options); var cache = _cache.Load(options.UserName); var workOrders = new List(); string cursor = null; var page = 0; do { var response = await _api.GetWorkOrdersAsync( options, limit: PageSize, cursor: cursor).ConfigureAwait(false); if (response?.Items != null) workOrders.AddRange(response.Items); cursor = response?.NextCursor; page++; if (response == null || !response.HasMore || string.IsNullOrWhiteSpace(cursor)) { break; } } while (page < MaxPages); return _cache.BuildUnreadMap(workOrders, cache); } }