using FreeRedis; using SJZY.Expand.ABP.Core; using SJZY.Track.Application.Contract.Services; using SJZY.Track.Domain.Aggregates.ForewarningAggregate; using SJZY.Track.Domain.Consts; using SJZY.Track.Domain.Dtos.Forewarning; using SJZY.Track.Domain.Enums; using Volo.Abp.DependencyInjection; namespace SJZY.Track.Application.Services.ForewarningServices; /// /// 用于处理预警通知 /// public class ForewarningNotifyService : IForewarningNotifyService, ITransientDependency { IReadOnlyDictionary> _ruleGroupDict; IReadOnlyDictionary> _factorDict; private IReadOnlyDictionary _rules; readonly INotifyService _notifyService; public ForewarningNotifyService(INotifyService notifyService) { _notifyService = notifyService; } /// /// 创建预警通知 /// /// 创建预警通知需要的订单信息 /// 创建的通知总量,0表示没有规则 public async Task WarningCalculateAsync(List order) { throw new NotImplementedException(); } public Task DeleteForewarningNotify(WarningOrderDto order) { throw new NotImplementedException(); } public void SendNotification(int intervalMinute) { var currentTimestamp = GetTimestamp(DateTime.Now); var notifyMembers = RedisHelper.Client.ZRangeByScore(GlobalConst.ForewarningNotifyKeyPrefix, 0, currentTimestamp); if (notifyMembers == null || notifyMembers.Length == 0) return; var notifyValues = notifyMembers.Select(val => new RuleNotifyValue(val)); foreach (var notifyValue in notifyValues) { if (!_rules.TryGetValue(notifyValue.RuleId, out var rule)) continue; //todo 发送通知 _notifyService.SendNotification(""); } } public void ClearCache() { _ruleGroupDict = null; _factorDict = null; _rules = null; } private List DeleteNotifyValue(ForewarningRuleItem ruleItem, int orderId) { var members = new List(); for (var index = 0; index < ruleItem.Count; index++) { var notifyValue = NotifyValue(ruleItem, orderId, index); members.Add(notifyValue); } return members; } private async ValueTask ExecuteRule(List rules, int orderId) { var members = new List(); foreach (var rule in rules) { var notifys = ExecuteRule(rule, orderId); members.AddRange(notifys); } await RedisHelper.Client.ZAddAsync(GlobalConst.ForewarningNotifyKeyPrefix, members.ToArray()); return members.Count; } private List ExecuteRule(ForewarningRuleItem ruleItem, int orderId) { var members = new List(); var intervalMinute = 60 * ((ruleItem.Timeliness - ruleItem.Remind) / ruleItem.Count); // 间隔多少分钟 for (var index = 0; index < ruleItem.Count; index++) { var notifyTime = (ruleItem.Remind * 60) + intervalMinute * index; var notifyTimestamp = GetTimestamp(DateTime.Now.AddMinutes(notifyTime)); var notifyValue = new ZMember(NotifyValue(ruleItem, orderId, index), notifyTimestamp); members.Add(notifyValue); } return members; } private long GetTimestamp(DateTime dateTime) { return new DateTimeOffset(dateTime).ToUnixTimeSeconds(); } private string NotifyValue(ForewarningRuleItem ruleItem, int orderId, int sort) { var result = new RuleNotifyValue(ruleItem.Id, orderId, sort, ruleItem.TrackEnd); return result.ToString(); } }