BulletinBoardService.cs
65.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
using Hh.Mes.Common.DataTableTo;
using Hh.Mes.Common.log;
using Hh.Mes.Pojo.System;
using Hh.Mes.POJO.ApiEntity;
using Hh.Mes.POJO.Entity;
using Hh.Mes.POJO.EnumEntitys;
using Hh.Mes.POJO.Response;
using Hh.Mes.POJO.ViewModel.Equipment;
using Hh.Mes.POJO.WebEntity;
using Hh.Mes.Service.Repository;
using Hh.Mes.Service.WebService.Equipment;
using MySqlX.XDevAPI.Relational;
using Newtonsoft.Json;
using NPOI.POIFS.FileSystem;
using NPOI.SS.Formula.Functions;
using SqlSugar;
using SqlSugar.Extensions;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
using System.Security.Claims;
using System.Security.Policy;
using System.Text;
using static Microsoft.AspNetCore.Hosting.Internal.HostingApplication;
namespace Hh.Mes.Service
{
public class BulletinBoardService : RepositorySqlSugar<sys_user>
{
#region 故障维护报表相关
/// <summary>
/// 故障报告
/// </summary>
/// <param name="yyyyMonth">日期</param>
/// <param name="project">项目</param>
/// <param name="equipmentType">设备类型</param>
/// <returns></returns>
public dynamic GetFaultReport(string yyyyMonth, string projectCode, string equipmentTypeCode)
{
var response = new ResponseNew();
return ExceptionsHelp.Instance.ExecuteT(() =>
{
var month = Convert.ToDateTime(yyyyMonth);
var whereSql = @" where t1.CreateTime>='{0}' and t1.CreateTime<='{1}' and t1.EquipmentTypeCode not in ('{2}')";
//月初、月末
var monthStart = month.AddDays(1 - month.Day);
var monthEnd = month.AddDays(1 - month.Day).Date.AddMonths(1).AddSeconds(-1);
var sqlWhereMonth = string.Format(whereSql, monthStart, monthEnd, SystemVariable.IotNotContainDevice);//月数据源查询条件
//周一、周末
var weekOne = month.AddDays(0 - (Convert.ToInt16(month.DayOfWeek) == 0 ? 7 : Convert.ToInt16(month.DayOfWeek)) + 1).ToString("yyyy-MM-dd 00:00:00");
var weekend = month.AddDays(6 - (Convert.ToInt16(month.DayOfWeek) == 0 ? 7 : Convert.ToInt16(month.DayOfWeek)) + 1).ToString("yyyy-MM-dd 23:59:59");
var sqlWhereWeek = string.Format(whereSql, weekOne, weekend, SystemVariable.IotNotContainDevice);
var sql = GetSql(sqlWhereMonth, sqlWhereWeek, projectCode, equipmentTypeCode);
var ds = Context.Ado.GetDataSetAll(sql);
var diffDay = DateTime.DaysInMonth(month.Year, month.Month);
var monthStr = monthStart.ToString("MM-dd") + "~" + monthEnd.ToString("MM-dd");
var weekStr = DateTime.Parse(weekOne).ToString("MM-dd") + "~" + DateTime.Parse(weekend).ToString("MM-dd");
Tuple<DataSet, int, string, string> dss = new Tuple<DataSet, int, string, string>(ds, diffDay, monthStr, weekStr);
//当天是否在本周内
var nowDay = DateTime.Now;
var selectDay = Convert.ToDateTime(yyyyMonth);
var startWeekDay = nowDay.AddDays(-(int)nowDay.DayOfWeek + 1).ToString("yyyy-MM-dd 00:00:00");//当前周的周一日期
var weekOnes = selectDay.AddDays(0 - (Convert.ToInt16(selectDay.DayOfWeek) == 0 ? 7 : Convert.ToInt16(selectDay.DayOfWeek)) + 1).ToString("yyyy-MM-dd 00:00:00");//当前所选周的周一日期
var isInterval = false;
if (startWeekDay == weekOnes) isInterval = true;
response.data = new
{
listMonth = dss.Item1.Tables[0],
listWeek = dss.Item1.Tables[1],
listAlarmSum40 = dss.Item1.Tables[2],
diffDay = dss.Item2,
monthStr = dss.Item3,
weekStr = dss.Item4,
weekDefault = dss.Item1.Tables[3],
properlyTarget = dss.Item1.Tables[4],
factoryTarget = dss.Item1.Tables[5],
isInterval = isInterval,
projectAlarmSum = dss.Item1.Tables[6],
projectAlarmSumInfo = dss.Item1.Tables[7]
};
return response;
});
}
public string GetSql(string sqlWhereMonth, string sqlWhereWeek, string projectCode, string equipmentTypeCode)
{
var selectSql = "SELECT ProjectCode,projectName,sumTime=SUM(ErrorDuration) ";
var sqlMonth = selectSql + "FROM #listMonth t";
var sqlWeek = selectSql + "FROM #listWeek t";
var sqlAlarm40 = "";
if (!string.IsNullOrEmpty(projectCode))
{
var whereSql = $" WHERE t.projectCode='{projectCode}'";
sqlMonth += whereSql;
sqlWeek += whereSql;
sqlAlarm40 = $" and t.projectCode='{projectCode}'";
}
var groupBySql = " group by projectCode,projectName order by sumTime desc";
sqlMonth += groupBySql;
sqlWeek += groupBySql;
var projectKeys = base.GetProjectInfoKeys(base.sysUserApiAccount);
var sql = @$" -----------------本月公共数据源 ErrorDuration 已转化分)--------------------------------------------
IF OBJECT_ID('Tempdb..#listMonth') IS NOT NULL
DROP TABLE #listMonth;
SELECT * INTO #listMonth FROM (
SELECT rownumber=ROW_NUMBER() OVER (PARTITION BY EquipmentCode, CONVERT(VARCHAR(16), t1.CreateTime, 120), CONVERT(VARCHAR(16), t1.UpdateTime, 120)
ORDER BY EquipmentCode),
t1.CreateTime AS Created,
t1.UpdateTime AS Updated,
ErrorDuration= CAST(t1.ErrorDuration/60.0 as DECIMAL(10, 2)) ,
t1.EquipmentCode,
t1.AlarmMessage + ';' + ISNULL(t1.Remark,'') AS Alarm,
t1.EquipmentName,
t1.EquipmentPropName,
t1.EquipmentTypeCode,
t1.ProjectCode,
p.projectName AS ProjectName
FROM dbo.daq_equipment_alarm_record t1 with(nolock)
LEFT JOIN dbo.base_project p ON p.projectCode = t1.ProjectCode
{sqlWhereMonth}
and p.keys in('{string.Join("','", projectKeys)}')
)t;
----------------<#listMonth 处理相同设备在同年月日时分数据>----------------
DELETE FROM #listMonth WHERE rownumber > 1;
-----------------本周公共数据源 #listWeek ErrorDuration 已转化分--------------------------------------------
IF OBJECT_ID('Tempdb..#listWeek') IS NOT NULL
DROP TABLE #listWeek;
SELECT *
INTO #listWeek
FROM
(
SELECT rownumber=ROW_NUMBER() OVER (PARTITION BY EquipmentCode, CONVERT(VARCHAR(16), t1.CreateTime, 120), CONVERT(VARCHAR(16), t1.UpdateTime, 120)
ORDER BY EquipmentCode),
t1.CreateTime AS created,
t1.UpdateTime AS updated,
ErrorDuration= CAST(t1.ErrorDuration/60.0 as DECIMAL(10, 2)),
t1.EquipmentCode,
t1.EquipmentName,
t1.EquipmentPropName,
t1.Id AS EquipmentAlarmId,
t1.AlarmMessage+ ';' + ISNULL(t1.Remark,'') AS Alarm,
t1.ProjectCode,
t1.EquipmentTypeCode,
p.projectName AS ProjectName
FROM dbo.daq_equipment_alarm_record t1 with(nolock)
LEFT JOIN dbo.base_project p ON p.projectCode = t1.ProjectCode
{sqlWhereWeek}
and p.keys in('{string.Join("','", projectKeys)}')
) t;
----------------listWeek 处理相同设备在同年月日时分数据>----------------
DELETE FROM #listWeek WHERE rownumber > 1;
----------------故障時間本月开始listMonth0 表格1-------------------------------
{sqlMonth}
----------------故障時間 月初、月末结束-------------------------------
----------------故障時間本周开始listWeek1 表格1-------------------------------
{sqlWeek}
----------------故障時間本周结束-------------------------------
--------------本周故障時間列表超過40分开始 ----------------
SELECT t.*,
eh.HandleInfo,
eh.HandleUser,
eh.Reason
FROM #listweek t
LEFT JOIN bus_equipment_alarm_handle eh ON eh.EquipmentAlarmRecordId = t.EquipmentAlarmId
WHERE t.ErrorDuration > 40 {sqlAlarm40}
ORDER BY t.ErrorDuration DESC;
-------------本周故障時間列表超過40分结束-------------------------------------
---weekDefault
SELECT dictValue FROM dbo.sys_dict_data WHERE dictLabel='weekDefault'
--妥善率目标
select dictValue FROM dbo.sys_dict_data WHERE dictLabel='properlyTarget'
--仓库可设定
select dictValue FROM dbo.sys_dict_data WHERE dictLabel='factoryTarget'
--项目设备报警统计
select t.ProjectCode, xAxis =convert(varchar(10),created,120),sumVal= SUM(t.ErrorDuration) from #listWeek t
group by t.ProjectCode,convert(varchar(10),created,120)
--项目设备报警统计明细信息
select xAxis =convert(varchar(10),created,120),timeVal=ErrorDuration,* from #listWeek ";
return sql;
}
/// <summary>
/// 故障統計分析
/// </summary>
/// <returns></returns>
public dynamic FaultStatistics(string begin, string end, string projectCode, string equipmentCode)
{
var response = new ResponseNew();
return ExceptionsHelp.Instance.ExecuteT(() =>
{
var whereSql = "";
if (!string.IsNullOrEmpty(projectCode)) whereSql = $"and t1.projectCode='{projectCode}'";
if (!string.IsNullOrEmpty(equipmentCode)) whereSql = $" and t1.equipmentCode='{equipmentCode}'";
var projectKeys = base.GetProjectInfoKeys(base.sysUserApiAccount);
var sql = GetAlarmSql(whereSql, begin, end, projectKeys);
var dt = Context.Ado.GetDataTable(sql);
response.data = dt;
response.count = dt.Rows.Count;
response.code = 200;
return response;
}, catchRetrunValue: "list");
}
/// <summary>
/// 妥善率报表查询
/// </summary>
/// <param name="startTime"></param>
/// <param name="endTime"></param>
/// <param name="eqCode"></param>
/// <param name="yearOrdaySelectVal">传年或者日</param>
/// <param name="timeFlag">值有year、month、day</param>
/// <returns></returns>
public dynamic GetProperRate(string startTime, string endTime, string yearOrdaySelectVal, string timeFlag, string projectCode, string equipmentCode)
{
var response = new ResponseNew();
return ExceptionsHelp.Instance.ExecuteT(() =>
{
if (timeFlag == "year")
{
startTime = yearOrdaySelectVal + "-01-01";
endTime = yearOrdaySelectVal + "-12-31";
}
else if (timeFlag == "day")
{
startTime = yearOrdaySelectVal;
endTime = yearOrdaySelectVal;
}
var whereSql = "";
if (!string.IsNullOrEmpty(projectCode) && !string.IsNullOrEmpty(equipmentCode))
{
whereSql = $"and t.projectCode='{projectCode}' and t.EquipmentCode='{equipmentCode}'";
}
if (!string.IsNullOrEmpty(projectCode) && string.IsNullOrEmpty(equipmentCode))
{
whereSql = $"and t.projectCode='{projectCode}'";
}
if (string.IsNullOrEmpty(projectCode) && !string.IsNullOrEmpty(equipmentCode))
{
whereSql = $"and t.EquipmentCode='{equipmentCode}'";
}
var startDate = startTime + " 00:00:00";
var endDate = endTime + " 23:59:59";
var sql = GetAlarmSql("", startDate, endDate) + GetRateSql(timeFlag, whereSql);
var ds = Context.Ado.GetDataSetAll(sql);
var resDt = ds.Tables[1];
//查询项目所有设备
if (string.IsNullOrEmpty(equipmentCode))
{
resDt = HandleDt(resDt, projectCode, startTime);
}
response.data = resDt;
response.count = ds.Tables[1].Rows.Count;
return response;
}, catchRetrunValue: "list");
}
public string GetRateSql(string timeFlag, string whereSql)
{
var sql = @"select {0} as date,
sumTime = sum(ErrorDuration),
ProjectName,EquipmentCode,EquipmentName,Sequence
from #tempdbRate t
where 1=1 {1}
group by {0},
ProjectName,EquipmentCode,EquipmentName,Sequence
order by Sequence";
if (timeFlag == "year")
{
sql = string.Format(sql, "CONVERT(varchar(7),created,120)", whereSql);//年月分组
}
else
{
sql = string.Format(sql, "CONVERT(varchar,created,23)", whereSql);//年月日分组
}
return sql;
}
/// <summary>
/// 查询故障月份对比数据(只查三个月)
/// </summary>
/// <param name="year"></param>
/// <param name="month"></param>
/// <param name="projectCode">项目</param>
/// <param name="equipmentTypeCode">设备类型</param>
/// <returns></returns>
public dynamic GetFailureMonthCompare(int year, int month, string projectCode, string equipmentTypeCode)
{
var response = new ResponseNew();
return ExceptionsHelp.Instance.ExecuteT(() =>
{
if (string.IsNullOrEmpty(projectCode))
{
response.code = 500;
response.status = false;
response.message = "请选择一个项目";
return response;
}
DateTime startTime = new DateTime(year, month, 1).AddMonths(-2);//所选日期近三月的第一天
DateTime endTime = new DateTime(year, month, 1, 23, 59, 59).AddMonths(1).AddDays(-1);//得出最后一天
var whereSql = "";
if (!string.IsNullOrEmpty(projectCode) && !string.IsNullOrEmpty(equipmentTypeCode))
{
whereSql = $"and t1.projectCode='{projectCode}' and t1.equipmentTypeCode='{equipmentTypeCode}'";
}
if (!string.IsNullOrEmpty(projectCode) && string.IsNullOrEmpty(equipmentTypeCode))
{
whereSql = $"and t1.projectCode='{projectCode}'";
}
var sql = GetAlarmSql(whereSql, startTime.ToString(), endTime.ToString());
sql = sql + @"
SELECT Alarm=t1.AlarmMessage ,
SumTime=SUM(t1.ErrorDuration) ,
YearMonth=CONVERT(CHAR(7), t1.CreateTime, 120)
FROM #tempdbRate t1
GROUP BY CONVERT(CHAR(7), t1.CreateTime, 120), t1.AlarmMessage
ORDER BY CONVERT(CHAR(7), t1.CreateTime,120);";
DataSet ds = Context.Ado.GetDataSetAll(sql);
//处理没有数据的赋值0
var dt = ds.Tables[1];
var alarmDt = dt.AsEnumerable().GroupBy(x => x["Alarm"]).Distinct().Select(x => x.Key).ToList();
var sumTime = dt.GetColumnValues<decimal>("SumTime").Sum();
var sumMsgInfo = "故障月份对比 ";
for (int i = 0; i < 3; i++)
{
DateTime t = new DateTime(year, month, 1).AddMonths(-i);
string currentTime = t.ToString("yyyy-MM");
var totalSumTime = dt.CalculateSumTime("YearMonth", "SumTime", currentTime);
sumMsgInfo += currentTime + "故障分钟:" + totalSumTime + ",";
foreach (string alarm in alarmDt)
{
var isHave = dt.AsEnumerable().Any(x => x["YearMonth"].ToString() == currentTime && x["Alarm"].ToString().TrimEnd() == alarm);
if (!isHave)
{
dt.Rows.Add(alarm, 0, currentTime);
}
}
}
response.code = 200;
response.data = new
{
data = dt,
allAlarm = ds.Tables[0],
sumMsgInfo = sumMsgInfo + " 总故障时间:" + sumTime + "(单位分钟)"
};
response.count = dt.Rows.Count;
return response;
}, catchRetrunValue: "list");
}
/// <summary>
/// 项目月 四周 故障次数&时间
/// </summary>
/// <param name="projectCode">项目号</param>
/// <param name="currentDate">时间日期</param>
/// <returns></returns>
public dynamic GetFailureMonthWeekCountAndTime(string projectCode, DateTime currentDate)
{
var response = new ResponseNew();
return ExceptionsHelp.Instance.ExecuteT(() =>
{
List<EquipmentAlarmCountTimeEntity> list = new List<EquipmentAlarmCountTimeEntity>();
//数据源查出来
var whereSql = "";
if (!string.IsNullOrEmpty(projectCode))
{
whereSql = $"and t1.projectCode='{projectCode}'";
}
var start = currentDate.AddDays(-28).ToString();
var end = currentDate.ToString();
var sql = GetAlarmSql(whereSql, start, end);
DataTable allAlarmDt = Context.Ado.GetDataTable(sql);
//近四周
for (int i = 0; i < 4; i++)
{
EquipmentAlarmCountTimeEntity entity = new EquipmentAlarmCountTimeEntity();
DateTime startTime = currentDate.AddDays(-(7 * (i + 1)));
DateTime endTime = currentDate.AddDays(-(7 * i));
var dt = allAlarmDt.AsEnumerable()
.Where(i => i.Field<DateTime>("CreateTime") >= startTime && i.Field<DateTime>("CreateTime") < endTime)
.ToList();
entity.WeekNo = $"第{4 - i}周";
entity.TimePeriod = $"{startTime.ToString().Replace(" 0:00:00", "")}~{endTime.ToString().Replace(" 0:00:00", "")}";
entity.AlarmSumTime = (decimal)dt.Sum(i => i.Field<decimal>("ErrorDuration"));
entity.AlarmCount = dt.Count;
entity.AlarmListData = dt.Count > 0 ? dt.CopyToDataTable() : null;
list.Add(entity);
}
response.count = allAlarmDt.Rows.Count;
response.data = list;
return response;
});
}
/// <summary>
/// 项目设备故障一天每小时故障次数
/// </summary>
/// <param name="projectCode"></param>
/// <param name="equipmentCode"></param>
/// <param name="currentDate"></param>
/// <returns></returns>
public dynamic GetFailureEveryHourCount(string projectCode, string equipmentCode, DateTime currentDate)
{
var response = new ResponseNew();
return ExceptionsHelp.Instance.ExecuteT(() =>
{
string startTime = currentDate.ToString("yyyy-MM-dd") + " 00:00:00";
string endTime = currentDate.ToString("yyyy-MM-dd") + " 23:59:59";
var sqlWhere = "";
if (!string.IsNullOrEmpty(projectCode)) sqlWhere = $"and t1.projectCode='{projectCode}'";
var sql = GetAlarmSql(sqlWhere, startTime, endTime);
var whereSql = "";
if (!string.IsNullOrEmpty(equipmentCode))
{
whereSql = $@"where t1.EquipmentCode = '{equipmentCode}'";
}
sql = sql + @"
select COUNT(*) as alarmCount, CAST(FORMAT(t1.CreateTime , 'HH') AS INT) as day_hour
from #tempdbRate t1 {0}
group by CAST(FORMAT(t1.CreateTime , 'HH') AS INT)
order by CAST(FORMAT(t1.CreateTime , 'HH') AS INT);
select * from #tempdbRate t1 {0}
select sumVal= sum(ErrorDuration) from #tempdbRate t1 {0} ";
sql = string.Format(sql, whereSql);
DataSet ds = Context.Ado.GetDataSetAll(sql);
List<EquipmentAlarmCountTimeEntity> list = new List<EquipmentAlarmCountTimeEntity>();
var result = ds.Tables[1];
foreach (DataRow dr in result.Rows)
{
int hour = (int)dr["day_hour"];
EquipmentAlarmCountTimeEntity entity = new EquipmentAlarmCountTimeEntity();
entity.AlarmCount = (int)dr["alarmCount"];
entity.TimePeriod = hour.ToString();
entity.AlarmListData = ds.Tables[2].AsEnumerable().Where(x => x.Field<DateTime>("CreateTime").Hour == hour).CopyToDataTable();
list.Add(entity);
}
response.data = list;
response.count = ds.Tables[2].Rows.Count;
response.message = list.Count == 0 ? " " : "故障次数天每小时对比,总次数:" + ds.Tables[2].Rows.Count + ",总故障分钟数:" + ds.Tables[3].Rows[0]["sumVal"].ToString();
return response;
});
}
/// <summary>
/// 故障次数
/// </summary>
/// <param name="projectCode"></param>
/// <param name="startTime"></param>
/// <param name="endTime"></param>
/// <returns></returns>
public dynamic GetFailureAlarmCount(string projectCode, DateTime startTime, DateTime endTime)
{
var response = new ResponseNew();
return ExceptionsHelp.Instance.ExecuteT(() =>
{
var begin = startTime;
var end = DateTime.Parse(endTime.ToString("yyyy-MM-dd") + " 23:59:59");
var data = Context.Queryable<daq_equipment_alarm_record, base_equipment_type>((x, y) => x.EquipmentTypeCode == y.code)
.Where((x, y) => (!SystemVariable.IotNotContainDevice.Contains(x.EquipmentTypeCode)) && x.ProjectCode == projectCode && x.createTime >= begin && x.createTime <= end)
.Select((x, y) => new
{
x.equipmentCode,
x.equipmentName,
//errorduration = x.errorduration > 0 ? Math.Round(x.errorduration / 60.0, 2) : 0,
x.EquipmentTypeCode,
EquipmentTypeName = y.name,
x.alarmMessage,
x.remark,
x.createTime,
x.updateTime
})
.ToList();
//设备故障分组
var res = data.GroupBy(x => new { x.equipmentCode, x.equipmentName, x.EquipmentTypeName, x.alarmMessage })
.Select(x => new
{
equipmentCode = x.Key.equipmentCode.ToString(),
equipmentName = x.Key.equipmentName.ToString(),
equipmentTypeName = x.Key.EquipmentTypeName,
alarmMessage = x.Key.alarmMessage,
alarmCount = x.Count()
})
.OrderBy(x => x.equipmentCode)
.ToList();
//故障次数分组
var alarmRes = data.GroupBy(x => new { x.alarmMessage })
.Select(x => new
{
alarmMessage = x.Key.alarmMessage,
alarmCount = x.Count()
})
.OrderByDescending(x => x.alarmCount)
.ToList();
response.data = new
{
res = res,
alarmRes = alarmRes
};
response.count = res.Count;
return response;
});
}
/// <summary>
/// 查询项目列表
/// </summary>
/// <param name="agvTag"></param>
/// <returns></returns>
public dynamic GetProjects(bool agvTag)
{
var response = new ResponseNew();
return ExceptionsHelp.Instance.ExecuteT(() =>
{
var expression = GetProjectsWhere();
var result = Context.Queryable<base_project>()
.Where(expression)
.OrderBy(x => x.createTime)
.Select(x => new { x.projectCode, x.projectName, x.createTime })
.ToList();
//agvTag标记true,只查询含agv设备的项目
if (agvTag)
{
var expressionAgv = GetProjectsAgvWhere();
result = Context.Queryable<base_project, base_equipment>((x, y) => x.keys == y.projectKeys)
.Where(expressionAgv)
.OrderBy((x, y) => x.createTime)
.Select((x, y) => new { x.projectCode, x.projectName, x.createTime })
.Distinct()
.ToList();
}
response.data = result;
response.count = result.Count;
return response;
});
}
public Expression<Func<base_project, bool>> GetProjectsWhere()
{
try
{
var exp = Expressionable.Create<base_project>();
//非管理员,查询登陆用户绑定客户管理的项目
string currentUser = sysUserApiAccount;
if (currentUser != SystemVariable.DefaultCreated)
{
var projectRoleKeys = GetProjectRoleKeys(currentUser);
exp.And(x => SqlFunc.Subqueryable<sys_role_projects_rel>().Where(c => projectRoleKeys.Contains(c.project_roles_key) && c.project_key == x.keys).Any());
}
return exp.ToExpression();//拼接表达式
}
catch (Exception ex)
{
throw new Exception($"{ex.Message}");
}
}
public Expression<Func<base_project, base_equipment, bool>> GetProjectsAgvWhere()
{
try
{
var exp = Expressionable.Create<base_project, base_equipment>();
//非管理员,查询登陆用户绑定客户管理的项目
string currentUser = sysUserApiAccount;
if (currentUser != SystemVariable.DefaultCreated)
{
var projectRoleKeys = GetProjectRoleKeys(currentUser);
exp.And((x, y) => SqlFunc.Subqueryable<sys_role_projects_rel>().Where(c => projectRoleKeys.Contains(c.project_roles_key) && c.project_key == x.keys).Any());
}
exp.And((x, y) => SystemVariable.IotAGVContainDevice.Contains(y.equipmentTypeCode));
return exp.ToExpression();//拼接表达式
}
catch (Exception ex)
{
throw new Exception($"{ex.Message}");
}
}
/// <summary>
///公共方法: 项目查询设备
/// </summary>
/// <param name="projectCode"></param>
/// <param name="agvTag"></param>
/// <returns></returns>
public dynamic GetEquipmentsByProject(string projectCode, bool agvTag)
{
var response = new ResponseNew();
return ExceptionsHelp.Instance.ExecuteT(() =>
{
var result = Context.Queryable<base_equipment, base_project>((x, y) => x.projectKeys == y.keys)
.Where((x, y) => y.projectCode == projectCode
&& !SystemVariable.IotNotContainDevice.Contains(x.equipmentTypeCode))
.OrderBy((x, y) => x.equipmentCode)
.Select((x, y) => new { x.equipmentCode, x.equipmentName, x.equipmentTypeCode })
.ToList();
//agvTag标记true,只查询agv设备
if (agvTag)
{
result = result.AsEnumerable().Where(x => SystemVariable.IotAGVContainDevice.Contains(x.equipmentTypeCode)).ToList();
}
response.data = result;
response.count = result.Count;
return response;
});
}
#endregion
#region AGV设备报表相关
/// <summary>
/// 公共方法:AGV报警列表
/// </summary>
/// <returns></returns>
public dynamic GetAGVAlarmList(string projectCode, string equipmentCode)
{
var response = new ResponseNew();
return ExceptionsHelp.Instance.ExecuteT(() =>
{
var result = Context.Queryable<daq_equipment_alarm_record>()
.Where(x => SystemVariable.IotAGVContainDevice.Contains(x.EquipmentTypeCode))
.Where(x => string.IsNullOrEmpty(projectCode) || x.ProjectCode == projectCode)
.Where(x => string.IsNullOrEmpty(equipmentCode) || x.equipmentCode == equipmentCode)
.Select(x => new
{
key = x.alarmMessage,
value = x.alarmMessage
})
.Distinct().ToList();
response.data = result;
response.count = result.Count;
return response;
});
}
/// <summary>
/// AGV设备异常分析(点位维度)
/// </summary>
/// <returns></returns>
public dynamic GetAGVCodePointAlarmRecord(string startTime, string endTime, string projectCode, string equipmentCode, string alarmMsg)
{
var response = new ResponseNew();
return ExceptionsHelp.Instance.ExecuteT(() =>
{
DataSet ds = new DataSet();
var startDate = startTime + " 00:00:00";
var endDate = endTime + " 23:59:59";
var sqlWhere = $" and t1.EquipmentTypeCode in ('{SystemVariable.IotAGVContainDevice}')";
if (!string.IsNullOrEmpty(projectCode)) sqlWhere += $" and t1.ProjectCode = '{projectCode}' ";
if (!string.IsNullOrEmpty(equipmentCode)) sqlWhere += $" and t1.EquipmentCode = '{equipmentCode}' ";
if (!string.IsNullOrEmpty(alarmMsg)) sqlWhere += $" and t1.AlarmMessage = '{alarmMsg}' ";
var sql = GetAlarmSql(sqlWhere, startDate, endDate) + GetAGVCodePointAlarmRecordSql(projectCode, alarmMsg);
ds = Context.Ado.GetDataSetAll(sql);
DataTable resDt = ds.Tables[2];//故障数据
DataTable barCodeDt = ds.Tables[1];//所有点位基础数据
//查询项目所有设备
if (!string.IsNullOrEmpty(projectCode) && string.IsNullOrEmpty(equipmentCode))
{
var equipmentList = Context.Queryable<base_equipment, base_project>((x, y) => x.projectKeys == y.keys)
.Where((x, y) => y.projectCode == projectCode && x.equipmentTypeCode.Contains("AGV"))
.Select((x, y) => new { x.equipmentCode, x.equipmentName, y.projectName })
.ToList();
if (resDt != null && resDt.Rows.Count > 0)
{
foreach (var i in equipmentList)
{
bool exists = resDt.AsEnumerable().Any(r => r.Field<string>("EquipmentName") == i.equipmentName);
if (!exists)
{
resDt.Rows.Add(0, i.equipmentCode, i.equipmentName, resDt.Rows[0]["CodePoint"]);
}
}
}
else
{
bool isHaveBarCode = barCodeDt.Rows.Count > 0;
var defaultBarCode = "0";
foreach (var i in equipmentList)
{
if (isHaveBarCode) defaultBarCode = barCodeDt.Rows[0]["BarCode"].ToString();
resDt.Rows.Add(0, i.equipmentCode, i.equipmentName, defaultBarCode);
}
}
}
response.data = new
{
codepoints = ds.Tables[1],//该项目所有点位
result = resDt,//有报警的点位以及信息
};
response.count = resDt.Rows.Count;
return response;
});
}
/// <summary>
/// AGV点位维度异常分析
/// </summary>
/// <param name="alarmMsg"></param>
/// <returns></returns>
public string GetAGVCodePointAlarmRecordSql(string projectCode, string alarmMsg)
{
var sql = $"select distinct ProjectCode,BarCode from daq_agv_point where ProjectCode='{projectCode}' order by BarCode;";
if (!string.IsNullOrEmpty(alarmMsg))
{
sql += @"select COUNT(*) as count,
EquipmentCode,EquipmentName,
CodePoint,
AlarmMessage
from
#tempdbRate t
group by
EquipmentCode,EquipmentName,
CodePoint,
AlarmMessage";
}
else
{
sql += @"select COUNT(*) as count,
EquipmentCode,EquipmentName,
CodePoint
from
#tempdbRate t
group by
EquipmentCode,EquipmentName,
CodePoint";
}
return sql;
}
/// <summary>
/// AGV设备异常分析(时间维度)
/// </summary>
/// <param name="startTime"></param>
/// <param name="endTime"></param>
/// <param name="projectCode"></param>
/// <param name="equipmentCode"></param>
/// <param name="alarmMsg"></param>
/// <returns></returns>
public dynamic GetAGVAbnormalRecord(string startTime, string endTime, string projectCode, string equipmentCode, string alarmMsg)
{
var response = new ResponseNew();
return ExceptionsHelp.Instance.ExecuteT(() =>
{
DataSet ds = new DataSet();
var startDate = startTime + " 00:00:00";
var endDate = endTime + " 23:59:59";
var sqlWhere = $" and t1.EquipmentTypeCode in ('{SystemVariable.IotAGVContainDevice}')";
if (!string.IsNullOrEmpty(projectCode)) sqlWhere += $" and t1.ProjectCode = '{projectCode}' ";
if (!string.IsNullOrEmpty(equipmentCode)) sqlWhere += $" and t1.EquipmentCode = '{equipmentCode}' ";
if (!string.IsNullOrEmpty(alarmMsg)) sqlWhere += $" and t1.AlarmMessage = '{alarmMsg}' ";
var sql = GetAlarmSql(sqlWhere, startDate, endDate) + GetAGVAbnormalRecordSql(alarmMsg);
ds = Context.Ado.GetDataSetAll(sql);
var resDt = ds.Tables[1];
//查询项目所有设备
if (!string.IsNullOrEmpty(projectCode) && string.IsNullOrEmpty(equipmentCode) && resDt.Rows.Count > 0)
{
var equipmentList = Context.Queryable<base_equipment, base_project>((x, y) => x.projectKeys == y.keys)
.Where((x, y) => y.projectCode == projectCode && x.equipmentTypeCode.Contains("AGV"))
.Select((x, y) => new { x.equipmentCode, x.equipmentName, y.projectName })
.ToList();
foreach (var i in equipmentList)
{
bool exists = resDt.AsEnumerable().Any(r => r.Field<string>("EquipmentName") == i.equipmentName);
if (!exists)
{
resDt.Rows.Add(0, i.equipmentCode, i.equipmentName, startTime);
}
}
}
response.data = resDt;
response.count = ds.Tables[1].Rows.Count;
return response;
});
}
public string GetAGVAbnormalRecordSql(string alarmMsg)
{
var sql = "";
if (!string.IsNullOrEmpty(alarmMsg))
{
sql += @"select COUNT(*) as count,
EquipmentCode,EquipmentName,
CONVERT(varchar,created,23) as date,
AlarmMessage
from
#tempdbRate t
group by
EquipmentCode,EquipmentName,
CONVERT(varchar,created,23),
AlarmMessage";
}
else
{
sql += @"select COUNT(*) as count,
EquipmentCode,EquipmentName,
CONVERT(varchar,created,23) as date
from
#tempdbRate t
group by
EquipmentCode,EquipmentName,
CONVERT(varchar,created,23)";
}
return sql;
}
/// <summary>
/// AGV故障任务妥善率
/// </summary>
/// <param name="startTime"></param>
/// <param name="endTime"></param>
/// <param name="yearOrdaySelectVal"></param>
/// <param name="timeFlag"></param>
/// <param name="projectCode"></param>
/// <param name="equipmentCode"></param>
/// <returns></returns>
public dynamic GetAGVProperRate(string startTime, string endTime, string yearOrdaySelectVal, string timeFlag, string projectCode, string equipmentCode)
{
var response = new ResponseNew();
return ExceptionsHelp.Instance.ExecuteT(() =>
{
//时间段筛选
if (timeFlag == "year")
{
startTime = yearOrdaySelectVal + "-01-01";
endTime = yearOrdaySelectVal + "-12-31";
}
else if (timeFlag == "day")
{
startTime = yearOrdaySelectVal;
endTime = yearOrdaySelectVal;
}
string startDate = startTime;
startTime = startTime + " 00:00:00";
endTime = endTime + " 23:59:59";
//故障次数
var sqlWhere = $" and t1.EquipmentTypeCode in ('{SystemVariable.IotAGVContainDevice}')";
if (!string.IsNullOrEmpty(projectCode)) sqlWhere += $" and t1.ProjectCode = '{projectCode}' ";
if (!string.IsNullOrEmpty(equipmentCode)) sqlWhere += $" and t1.EquipmentCode = '{equipmentCode}' ";
var sql = GetAlarmSql(sqlWhere, startTime, endTime) + GetAGVProperRateSql(timeFlag, startTime, endTime, projectCode);
var ds = Context.Ado.GetDataSetAll(sql);
var resDt = ds.Tables[1];
//查询项目所有设备
if (!string.IsNullOrEmpty(projectCode) && string.IsNullOrEmpty(equipmentCode))
{
var equipmentList = Context.Queryable<base_equipment, base_project>((x, y) => x.projectKeys == y.keys)
.Where((x, y) => y.projectCode == projectCode && x.equipmentTypeCode.Contains("AGV"))
.Select((x, y) => new { x.equipmentCode, x.equipmentName, y.projectName })
.ToList();
foreach (var i in equipmentList)
{
bool exists = resDt.AsEnumerable().Any(r => r.Field<string>("EquipmentName") == i.equipmentName);
if (!exists)
{
resDt.Rows.Add(i.equipmentCode, i.equipmentName, startDate, 0, 0);
}
}
}
resDt.Columns.Add("Rate", typeof(string));
foreach (DataRow row in resDt.Rows)
{
if ((decimal)row["TotalTask"] == 0)
{
row["Rate"] = "100%";
}
else
{
decimal result = Math.Round((int)row["counts"] / (decimal)row["TotalTask"], 2);
var rate = (1 - result).ToString("P2");
row["Rate"] = rate;
}
}
response.data = resDt;
response.count = resDt.Rows.Count;
return response;
});
}
public string GetAGVProperRateSql(string timeFlag, string startTime, string endTime, string projectCode)
{
var sql = @"IF OBJECT_ID('Tempdb..#tempdbAlarmCount') IS NOT NULL
DROP TABLE #tempdbAlarmCount;
SELECT *
INTO #tempdbAlarmCount
FROM
(
select COUNT(*) as counts,
EquipmentCode,EquipmentName,
{0} as dateVal
from #tempdbRate
group by {0},
EquipmentCode,EquipmentName
)t;
select
task.*,
temp.counts
from
#tempdbAlarmCount temp join (
select
t.EquipmentCode,t.EquipmentName,
t.dateVal,
sum(d.TotalTask) as TotalTask
from
#tempdbAlarmCount t join daq_equipment_task d
on t.EquipmentCode = d.EquipmentCode
and t.dateVal = {0}
group by
t.EquipmentCode,t.EquipmentName,
t.dateVal
) as task on task.EquipmentCode = temp.EquipmentCode
and task.dateVal = temp.dateVal
order by task.EquipmentCode";
if (timeFlag == "year")
{
sql = string.Format(sql, "CONVERT(varchar(7),created,120)");
}
else
{
sql = string.Format(sql, "CONVERT(varchar,created,23)");
}
return sql;
}
/// <summary>
/// 公共方法:查询对应条件的故障(过滤同设备同年月日时分的数据) 临时表 #tempdbRate
/// </summary>
/// <param name="sqlWhere"></param>
/// <returns></returns>
public string GetAlarmSql(string sqlWhere, string begin, string end, Guid[] projectKeys = null)
{
string sql = @" -----------------数据源--------------------------------------------
IF OBJECT_ID('Tempdb..#tempdbRate') IS NOT NULL
DROP TABLE #tempdbRate;
SELECT *
INTO #tempdbRate
FROM
(
SELECT t1.CreateTime AS created,
t1.UpdateTime AS updated,
t1.CreateTime,t1.UpdateTime,
ErrorDuration = CAST(t1.ErrorDuration/60.0 as DECIMAL(10, 2)),
t1.EquipmentCode,t1.EquipmentName,t1.EquipmentPropName,t1.Id AS EquipmentAlarmId,
t1.AlarmMessage,t1.AlarmMessage +';'+ ISNULL(t1.Remark,'') AS Alarm, ISNULL(t1.Remark,'') AS Remark,
t1.ProjectCode,t1.EquipmentTypeCode,p.projectName AS ProjectName,
t.name AS EquipmentTypeName,t1.Points as CodePoint,e.sequence,
h.HandleInfo,h.HandleUser,h.Reason, t1.HandleTime,t1.UserHandleTime
FROM dbo.daq_equipment_alarm_record t1 with(nolock)
LEFT JOIN dbo.bus_equipment_alarm_handle h
ON h.EquipmentAlarmRecordId=t1.Id
LEFT JOIN dbo.base_equipment_type t
ON t.code = t1.EquipmentTypeCode
LEFT JOIN dbo.base_project p
ON p.projectCode = t1.ProjectCode
LEFT JOIN dbo.base_equipment e
ON e.equipmentCode = t1.EquipmentCode
WHERE 1=1 {0}
AND t1.CreateTime >= '{1}'
AND t1.CreateTime <= '{2}'
AND t1.EquipmentTypeCode not in ('{3}')
{4}
) t;
----------------tempdbRate 处理相同设备在同年月日时分数据>----------------
WITH CTE
AS (SELECT ROW_NUMBER() OVER (PARTITION BY e.EquipmentCode,
SUBSTRING(CONVERT(VARCHAR(50), e.Created, 120), 1, 16),
SUBSTRING(CONVERT(VARCHAR(50), e.updated, 120), 1, 16)
ORDER BY EquipmentCode
) AS rownumber,
*
FROM #tempdbRate e)
DELETE FROM CTE WHERE rownumber > 1;
SELECT*FROM #tempdbRate ORDER BY CreateTime desc;";
var wh = "";
if (projectKeys != null)
{
wh = $" and p.keys in('{string.Join("','", projectKeys)}')";
}
sql = string.Format(sql, sqlWhere, begin, end, SystemVariable.IotNotContainDevice, wh);
return sql;
}
private DataTable HandleDt(DataTable resDt, string projectCode, string startDate)
{
if (!string.IsNullOrEmpty(projectCode))
{
var equipmentList = Context.Queryable<base_equipment, base_project>((x, y) => x.projectKeys == y.keys)
.Where((x, y) => y.projectCode == projectCode)
.Select((x, y) => new { x.equipmentCode, x.equipmentName, y.projectName, x.sequence })
.ToList();
foreach (var i in equipmentList)
{
bool exists = resDt.AsEnumerable().Any(r => r.Field<string>("EquipmentName") == i.equipmentName);
if (!exists)
{
resDt.Rows.Add(startDate, 0, i.projectName, i.equipmentCode, i.equipmentName, i.sequence);
}
}
}
DataView dv = new DataView(resDt);
dv.Sort = "Sequence";
resDt = dv.ToTable();
return resDt;
}
#endregion
/// <summary>
/// 获取保养报告
/// </summary>
/// <param name="projectKeys"></param>
/// <param name="equipmentCode"></param>
/// <param name="month"></param>
/// <returns></returns>
public dynamic GetEqMaintainReport(string projectCode, string equipmentCode, string yearMonth, bool thisMonth)
{
var response = new ResponseNew();
return ExceptionsHelp.Instance.ExecuteT(() =>
{
var day = GetTime(yearMonth, false);
if (thisMonth)
{
day = GetTime(yearMonth, true);//只获取当月的汇总
}
string projectKeys = Context.Queryable<base_project>().Where(x => x.projectCode == projectCode).Select(x => x.keys).First().ToString();
List<bus_equipment_maintain_record_detail> detailList = GetEqMaintainInfo(projectKeys, equipmentCode, day.Item1, day.Item2);
var maintainCountDts = detailList.AsEnumerable()
.GroupBy(x => new
{
EquipmentCode = x.equipmentCode,
x.EquipmentName,
x.RealStatus,
Year = x.RealTime.Year,
Month = x.RealTime.Month
})
.Select(x => new
{
Count = x.Count(),
x.Key.EquipmentName,
x.Key.EquipmentCode,
x.Key.RealStatus,
YearMonth = x.Key.Year + "-" + x.Key.Month.ToString("D2")
})
.OrderBy(x => x.EquipmentCode)
.ThenBy(x => x.YearMonth).ToList();
//--start处理数据--
var equipmentList = Context.Queryable<base_equipment>()
.Where(x => x.projectKeys == Guid.Parse(projectKeys))
.Select(x => new
{
x.equipmentCode,
x.equipmentName
})
.OrderBy(x => x.equipmentCode)
.ToList();//设备集合
if (!string.IsNullOrEmpty(equipmentCode))
{
equipmentList = Context.Queryable<base_equipment>()
.Where(x => x.projectKeys == Guid.Parse(projectKeys) && x.equipmentCode == equipmentCode)
.Select(x => new
{
x.equipmentCode,
x.equipmentName
}).ToList();
}
List<string> realStatusList = new List<string>() { "未保养", "已保养", "逾期" };//状态集合
List<string> monthList = day.Item3;//年月集合
// 使用 LINQ 来简化嵌套循环
List<EquipmentMaintainStatusDto> equipmentMaintainStatusDtos = equipmentList
.SelectMany(equipment => monthList,
(equipment, month) => new { equipment, month })
.SelectMany(em => realStatusList,
(em, status) => new EquipmentMaintainStatusDto
{
EquipmentCode = em.equipment.equipmentCode,
EquipmentName = em.equipment.equipmentName,
Count = 0,
YearMonth = em.month,
RealStatus = status
})
.ToList();
// 更新 DTO 列表中的 Count 值
foreach (var dto in equipmentMaintainStatusDtos)
{
var matchingRecord = maintainCountDts.FirstOrDefault(m =>
m.EquipmentCode == dto.EquipmentCode &&
m.YearMonth == dto.YearMonth &&
m.RealStatus == dto.RealStatus);
if (matchingRecord != null)
{
dto.Count = matchingRecord.Count; // 替换为实际的 Count 值
}
}
//--end 处理数据--
//var maintainCountDt = new EquipmentMaintainVM() { EquipmentMaintainStatus = equipmentMaintainStatusDtos };
var res = new
{
maintainCountDt = equipmentMaintainStatusDtos,
detailList
};
response.data = res;
response.count = res.detailList.Count;
return response;
});
}
/// <summary>
/// 获取所选时间、项目、设备下的保养状态详情数据
/// </summary>
/// <param name="projectKeys"></param>
/// <param name="equipmentCode"></param>
/// <param name="startTime"></param>
/// <param name="endTime"></param>
/// <returns></returns>
public List<bus_equipment_maintain_record_detail> GetEqMaintainInfo(string projectKeys, string equipmentCode, DateTime startTime, DateTime endTime)
{
var sql = string.Format($@"select
e.equipmentName,t.*
from
(
--未保养:下次保养时间+状态
select'未保养' as RealStatus,NextMaintainTime as RealTime,* from bus_equipment_maintain_record_detail where Status='10' and NextMaintainTime>GETDATE()
union
--已保养:保养时间+状态
select '已保养' as RealStatus,MaintainTime as RealTime,*from bus_equipment_maintain_record_detail where Status='20'
union
--逾期:下次保养时间+跟当前时间比对
select '逾期' as RealStatus,NextMaintainTime as RealTime,*from bus_equipment_maintain_record_detail where Status='10' and NextMaintainTime<=GETDATE()
)t inner join base_equipment e on t.EquipmentCode=e.equipmentCode
where t.ProjectKeys='{projectKeys}' and t.RealTime>='{startTime}' and t.RealTime<='{endTime}' ");
if (!string.IsNullOrEmpty(equipmentCode))
{
sql += $" and t.equipmentCode='{equipmentCode}' ";
}
//sql += " order by t.EquipmentCode,t.RealTime";
var res = Context.SqlQueryable<bus_equipment_maintain_record_detail>(sql);
List<bus_equipment_maintain_record_detail> resList = new List<bus_equipment_maintain_record_detail>();
if (res != null)
{
resList = res.ToList();
foreach (var x in resList)
{
//保养操作档案附件
x.OperationFileUrl = string.Join(',', Context.Queryable<Sys_File>()
.Where(t => SqlFunc.Subqueryable<base_equipment_part>()
.Where(s => s.partCode == x.partCode && s.id == t.targetId).Any()
&& t.targetTableName == nameof(base_equipment_part))
.Select(t => t.url)
.ToList());
//确认保养附件
x.ConfirmFileUrl = string.Join(',', Context.Queryable<Sys_File>()
.Where(t => SqlFunc.Subqueryable<bus_equipment_maintain_record_detail>()
.Where(s => s.partCode == x.partCode && s.id == t.targetId).Any()
&& t.targetTableName == nameof(bus_equipment_maintain_record_detail))
.Select(t => t.url)
.ToList());
//保养等级
x.maintainLevel = Context.Queryable<sys_dict_data>()
.Where(t => t.dictType == "MaintainLevel" && t.dictValue == x.maintainLevel)
.Select(t => t.dictLabel).First();
//推送状态
x.PushStatus = Enum.GetName(typeof(EnumMaintainPushStatus), x.pushStatus);
}
}
return resList;
}
/// <summary>
/// 获取每月所有设备保养次数总数
/// </summary>
/// <param name="projectkeys">项目keys</param>
/// <param name="yearMonth">年月</param>
/// <returns></returns>
public dynamic GetEqMaintainCount(string projectCode, string yearMonth)
{
var response = new ResponseNew();
return ExceptionsHelp.Instance.ExecuteT(() =>
{
var dateTime = GetTime(yearMonth, false);
string projectKeys = Context.Queryable<base_project>().Where(x => x.projectCode == projectCode).Select(x => x.keys).First().ToString();
var dt = Context.Queryable<bus_equipment_maintain_record_detail>()
.Where(x => x.maintainTime >= dateTime.Item1 && x.maintainTime <= dateTime.Item2 && x.projectKeys.Equals(projectKeys))
.ToList();
var resDt = dt.GroupBy(x => new
{
Year = x.maintainTime.Value.Year,
Month = x.maintainTime.Value.Month
})
.Select(x => new
{
YearMonth = x.Key.Year + "-" + x.Key.Month.ToString("D2"),
Count = x.Count()//,
//Records = x.ToList()
})
.OrderBy(x => x.YearMonth);
response.data = resDt;
return response;
});
}
/// <summary>
/// 公共方法:根据所传年月获取最近三个月的时间段
/// </summary>
/// <param name="yearMonth"></param>
/// <returns></returns>
public (DateTime, DateTime, List<string>) GetTime(string yearMonth, bool thisMonth)
{
//1、获取包含本月在内的三个月数据
var yearMonthParts = yearMonth.Split('-');
int year = int.Parse(yearMonthParts[0]);
int month = int.Parse(yearMonthParts[1]);
DateTime currentDate = new DateTime(year, month, 1);//选择月份
// 计算三个月前的开始日期
DateTime startDate = new DateTime(currentDate.Year, currentDate.Month, 1).AddMonths(-2);
// 2、计算当前月份的结束日期
DateTime endDate = new DateTime(currentDate.Year, currentDate.Month, 1).AddMonths(1).AddDays(-1);
if (thisMonth)
{
startDate = new DateTime(currentDate.Year, currentDate.Month, 1);
endDate = new DateTime(currentDate.Year, currentDate.Month, DateTime.DaysInMonth(year, month));
}
endDate = DateTime.Parse(endDate.ToString("yyyy-MM-dd") + " 23:59:59");//最后一天统一到23:59:59秒
//3、得出日期范围内所有年月份组合
List<string> months = new List<string>();
// 确保开始日期在结束日期之前
if (startDate > endDate)
{
throw new ArgumentException("Start date must be earlier than end date.");
}
// 从开始日期开始,逐月增加
DateTime current = new DateTime(startDate.Year, startDate.Month, 1);
while (current <= endDate)
{
months.Add(current.ToString("yyyy-MM")); // 格式化为 YYYY-MM
current = current.AddMonths(1); // 增加一个月
}
return (startDate, endDate, months);
}
public dynamic GetEquipmentMaintainStatus(string projectCode, DateTime date, string equipmentCode, EquipmentVisualService visualService)
{
var response = new ResponseNew();
return ExceptionsHelp.Instance.ExecuteT(() =>
{
List<base_equipment> eqList = new List<base_equipment>();
if (!string.IsNullOrEmpty(equipmentCode))
{
var eq = Context.Queryable<base_equipment>().Where(x => x.equipmentCode == equipmentCode).First();//查询外部编码才能匹配查询daq相关表数据
eqList.Add(eq);
}
else
{
var projectKeys = Context.Queryable<base_project>().Where(x => x.projectCode == projectCode).Select(x => x.keys).First();
eqList = Context.Queryable<base_equipment>().Where(x => x.projectKeys == projectKeys).OrderBy(x => x.equipmentCode).ToList();
}
//查询状态数据
List<EquipmentHealthVM> resList = new List<EquipmentHealthVM>();
foreach (var eq in eqList)
{
var equipmentHealthVM = visualService.GetEquipmentHealth(eq, date);
resList.Add(equipmentHealthVM.vm);
}
response.data = resList;
return response;
});
}
}
}