WarningService.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. using EasyTemplate.Tool;
  2. using EasyTemplate.Tool.Entity;
  3. using EasyTemplate.Tool.Entity.App;
  4. using SqlSugar;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Linq;
  8. using System.Threading.Tasks;
  9. namespace EasyTemplate.Service
  10. {
  11. /// <summary>
  12. /// 预警告统计服务
  13. /// </summary>
  14. public class WarningService
  15. {
  16. private readonly SqlSugarRepository<TPrewarning> _prewarning;
  17. private readonly SqlSugarRepository<TRecord> _record;
  18. public WarningService(SqlSugarRepository<TPrewarning> prewarning, SqlSugarRepository<TRecord> record)
  19. {
  20. _prewarning = prewarning;
  21. _record = record;
  22. }
  23. /// <summary>
  24. /// 获取 35 天内所有油枪的统计数据
  25. /// </summary>
  26. public async Task<List<WarningStatistics>> Get35DaysStatisticsAsync()
  27. {
  28. var endDate = DateOnly.FromDateTime(DateTime.Today);
  29. var startDate = endDate.AddDays(-34); // 包含今天共 35 天
  30. return await CalculateStatisticsAsync(startDate, endDate);
  31. }
  32. /// <summary>
  33. /// 按日期范围获取统计数据
  34. /// </summary>
  35. public async Task<List<WarningStatistics>> GetStatisticsByDateRangeAsync(DateOnly startDate, DateOnly endDate)
  36. {
  37. return await CalculateStatisticsAsync(startDate, endDate);
  38. }
  39. /// <summary>
  40. /// 按油枪和日期范围筛选统计数据
  41. /// </summary>
  42. public async Task<List<WarningStatistics>> GetStatisticsByFilterAsync(WarningStatisticsQuery query)
  43. {
  44. var endDate = query.EndDate ?? DateOnly.FromDateTime(DateTime.Today);
  45. var startDate = query.StartDate ?? endDate.AddDays(-34);
  46. var allStats = await CalculateStatisticsAsync(startDate, endDate);
  47. // 按油枪筛选
  48. if (query.NozzleId.HasValue)
  49. {
  50. allStats = allStats.Where(s => s.nozzle == query.NozzleId.Value).ToList();
  51. }
  52. return allStats;
  53. }
  54. /// <summary>
  55. /// 更新指定日期的统计数据(用于新交易插入后)
  56. /// </summary>
  57. public async Task UpdateDailyStatisticsAsync(DateOnly date, int nozzleId)
  58. {
  59. try
  60. {
  61. Console.WriteLine($"[预警告统计] 开始更新油枪{nozzleId},日期:{date} 的统计数据");
  62. // 重新计算该油枪在该日期的统计
  63. var stats = await CalculateSingleDayStatisticsAsync(date, nozzleId);
  64. if (stats != null)
  65. {
  66. Console.WriteLine($"[预警告统计] 更新成功 - 总笔数:{stats.daily_total}, 超标:{stats.daily_overproof}, 超标率:{stats.daily_overproofrate}%");
  67. }
  68. }
  69. catch (Exception ex)
  70. {
  71. Console.WriteLine($"[预警告统计] 更新失败:{ex.Message}");
  72. }
  73. }
  74. /// <summary>
  75. /// 计算单个日期的统计数据
  76. /// </summary>
  77. private async Task<WarningStatistics> CalculateSingleDayStatisticsAsync(DateOnly date, int nozzleId)
  78. {
  79. // 获取当天的预警告记录
  80. var prewarning = await _prewarning.AsQueryable()
  81. .Where(p => p.date == date && p.nozzle == nozzleId)
  82. .FirstAsync();
  83. if (prewarning == null)
  84. {
  85. return null;
  86. }
  87. return new WarningStatistics
  88. {
  89. nozzle = nozzleId,
  90. statistics_date = date,
  91. daily_total = prewarning.total,
  92. daily_overproof = prewarning.overproof,
  93. daily_overproofrate = prewarning.overproofrate,
  94. daily_overproof_alert = prewarning.overproof_alert,
  95. daily_overproofrate_alert = prewarning.overproofrate_alert,
  96. daily_overproof_2 = prewarning.overproof_2,
  97. daily_overproofrate_2 = prewarning.overproofrate_2,
  98. is_accumulated = prewarning.total >= 5,
  99. accumulated_days = 1
  100. };
  101. }
  102. /// <summary>
  103. /// 核心统计计算逻辑
  104. /// </summary>
  105. private async Task<List<WarningStatistics>> CalculateStatisticsAsync(DateOnly startDate, DateOnly endDate)
  106. {
  107. Console.WriteLine($"[预警告统计] 开始计算统计,范围:{startDate} 至 {endDate}");
  108. var results = new List<WarningStatistics>();
  109. // 获取该日期范围内的所有预警告记录
  110. var prewarnings = await _prewarning.AsQueryable()
  111. .Where(p => p.date >= startDate && p.date <= endDate)
  112. .ToListAsync();
  113. // 按油枪分组
  114. var groupedByNozzle = prewarnings.GroupBy(p => p.nozzle);
  115. foreach (var nozzleGroup in groupedByNozzle)
  116. {
  117. var nozzleId = nozzleGroup.Key;
  118. var sortedData = nozzleGroup.OrderBy(p => p.date).ToList();
  119. // 为每一天计算统计数据
  120. for (int i = 0; i < sortedData.Count; i++)
  121. {
  122. var currentPrewarning = sortedData[i];
  123. var currentDate = currentPrewarning.date;
  124. var stats = new WarningStatistics
  125. {
  126. nozzle = nozzleId,
  127. statistics_date = currentDate,
  128. daily_total = currentPrewarning.total,
  129. daily_overproof = currentPrewarning.overproof,
  130. daily_overproofrate = currentPrewarning.overproofrate,
  131. daily_overproof_alert = currentPrewarning.overproof_alert,
  132. daily_overproofrate_alert = currentPrewarning.overproofrate_alert,
  133. daily_overproof_2 = currentPrewarning.overproof_2,
  134. daily_overproofrate_2 = currentPrewarning.overproofrate_2
  135. };
  136. // 计算 35 天累计统计
  137. CalculateAccumulatedStatistics(sortedData, i, stats);
  138. results.Add(stats);
  139. }
  140. }
  141. Console.WriteLine($"[预警告统计] 计算完成,共{results.Count}条记录");
  142. return results;
  143. }
  144. /// <summary>
  145. /// 计算累计统计数据(核心业务逻辑 - 按 C++ update_warning 实现)
  146. /// 规则:从最早日期正向迭代到当前日期,累加统计并在满足条件时清零
  147. /// </summary>
  148. private void CalculateAccumulatedStatistics(List<TPrewarning> sortedData, int currentIndex, WarningStatistics stats)
  149. {
  150. // 累加器初始化(对应 C++ acc_over, acc_over_alert, acc_total, acc_over_2)
  151. int acc_over = 0; // 累计超标记录
  152. int acc_over_alert = 0; // 累计严重超标记录
  153. int acc_total = 0; // 累计总数
  154. int acc_over_2 = 0; // 累计二级超标记录(广东中石化)
  155. // 连续天数计数器
  156. int continue_days = 0;
  157. int continue_days_2 = 0;
  158. int continue_days_alert = 0;
  159. // 最后计算的超标率
  160. int last_rate = 0;
  161. int last_rate_2 = 0;
  162. int last_rate_alert = 0;
  163. // 获取区域规则配置
  164. bool isBeijingMode = VRRules.RefReachCount; // 北京模式:ref_reach_count
  165. int refCount = VRRules.RefCount; // 标准模式阈值(通常 5)
  166. int refPrewarningIndex = VRRules.RefPrewarningIndex; // 超标率阈值
  167. int refPrewarningIndexAlert = VRRules.RefPrewarningIndexAlert; // 严重超标率阈值
  168. bool isZhejiangSpecial = VRRules.BCountAllDay; // 浙江中石化特殊逻辑
  169. // 正向迭代:从第 0 天到当前天(对应 C++ mapDayWarning.begin() 到 end)
  170. for (int i = 0; i <= currentIndex && i < sortedData.Count; i++)
  171. {
  172. var day = sortedData[i];
  173. // 累加数据
  174. acc_over += day.overproof;
  175. acc_over_alert += day.overproof_alert;
  176. acc_total += day.total;
  177. acc_over_2 += day.overproof_2;
  178. // 计算累计超标率(避免除以 0)
  179. last_rate = acc_total == 0 ? 0 : (acc_over * 100) / acc_total;
  180. last_rate_2 = acc_total == 0 ? 0 : (acc_over_2 * 100) / acc_total;
  181. last_rate_alert = acc_total == 0 ? 0 : (acc_over_alert * 100) / acc_total;
  182. // 更新警告对象中的累计值(用于显示)
  183. // 注意:这里不直接设置 stats,因为可能还需要清零
  184. if (isBeijingMode)
  185. {
  186. // === 北京模式(ref_reach_count)===
  187. // 规则:超标率>=阈值 且 总笔数>=5 时,连续天数 +1
  188. // 普通超标判断
  189. if (last_rate >= refPrewarningIndex)
  190. {
  191. if (acc_total >= 5)
  192. {
  193. continue_days++;
  194. }
  195. }
  196. else
  197. {
  198. if (acc_total >= 5)
  199. {
  200. continue_days = 0;
  201. }
  202. }
  203. // 严重超标判断
  204. if (last_rate_alert >= refPrewarningIndexAlert)
  205. {
  206. if (acc_total >= 5)
  207. {
  208. continue_days_alert++;
  209. }
  210. }
  211. else
  212. {
  213. if (acc_total >= 5)
  214. {
  215. continue_days_alert = 0;
  216. }
  217. }
  218. // 已经算入一天,清零累加器
  219. acc_over = 0;
  220. acc_over_alert = 0;
  221. acc_total = 0;
  222. acc_over_2 = 0;
  223. }
  224. else
  225. {
  226. // === 标准模式 ===
  227. // 规则:总笔数>=ref_count(通常 5) 时才检查超标率
  228. if (acc_total >= refCount)
  229. {
  230. // 普通超标判断
  231. if (last_rate >= refPrewarningIndex)
  232. {
  233. continue_days++;
  234. }
  235. else
  236. {
  237. continue_days = 0;
  238. }
  239. // 严重超标判断
  240. if (last_rate_alert >= refPrewarningIndexAlert)
  241. {
  242. continue_days_alert++;
  243. }
  244. else
  245. {
  246. continue_days_alert = 0;
  247. }
  248. // 二级超标判断(广东中石化)
  249. if (last_rate_2 >= refPrewarningIndex) // || day.continueoverproof == 1
  250. {
  251. continue_days_2++;
  252. }
  253. else
  254. {
  255. continue_days_2 = 0;
  256. }
  257. // 已经算入一天,清零累加器
  258. acc_over = 0;
  259. acc_over_alert = 0;
  260. acc_total = 0;
  261. acc_over_2 = 0;
  262. }
  263. else
  264. {
  265. // 该分支是 ref_count 大于 0(即需要进行累计)的情况下,
  266. // 而 acc_total 小于 ref_count 时进入
  267. if (isZhejiangSpecial)
  268. {
  269. // === 浙江中石化特殊逻辑 ===
  270. // 不足 5 笔时延续之前的预警状态
  271. if (continue_days > 0)
  272. {
  273. continue_days++;
  274. }
  275. if (continue_days_alert > 0)
  276. {
  277. continue_days_alert++;
  278. }
  279. }
  280. }
  281. }
  282. }
  283. // 设置最终统计结果
  284. stats.continue_days = continue_days;
  285. stats.continue_days_2 = continue_days_2;
  286. stats.continue_days_alert = continue_days_alert;
  287. stats.last_overproofrate = last_rate;
  288. stats.last_overproofrate_2 = last_rate_2;
  289. stats.last_overproofrate_alert = last_rate_alert;
  290. // 同时保留原有的累计字段(用于兼容)
  291. stats.total_count = acc_total;
  292. stats.total_overproof = acc_over;
  293. stats.total_overproof_alert = acc_over_alert;
  294. stats.total_overproof_2 = acc_over_2;
  295. stats.total_overproofrate = last_rate;
  296. stats.total_overproofrate_2 = last_rate_2;
  297. stats.total_overproofrate_alert = last_rate_alert;
  298. }
  299. /// <summary>
  300. /// 获取所有有数据的油枪 ID 列表
  301. /// </summary>
  302. public async Task<List<int>> GetAllNozzleIdsAsync()
  303. {
  304. var nozzles = await _prewarning.AsQueryable()
  305. .Select(p => p.nozzle)
  306. .Distinct()
  307. .ToListAsync();
  308. return nozzles;
  309. }
  310. /// <summary>
  311. /// 获取统计日期范围(最早到最新)
  312. /// </summary>
  313. public async Task<(DateOnly minDate, DateOnly maxDate)> GetDateRangeAsync()
  314. {
  315. var dates = await _prewarning.AsQueryable()
  316. .Select(p => p.date)
  317. .ToListAsync();
  318. if (dates == null || dates.Count == 0)
  319. {
  320. return (new DateOnly(), new DateOnly());
  321. }
  322. var minDate = dates.Min();
  323. var maxDate = dates.Max();
  324. return (minDate, maxDate);
  325. }
  326. }
  327. }