Blame view

HHECS.DAQHandle/Program.cs 24 KB
唐召明 authored
1
2
using HHECS.BllModel;
using HHECS.DAQHandle;
唐召明 authored
3
using HHECS.DAQHandle.Common.Utils;
4
using HHECS.DAQHandle.Dto;
唐召明 authored
5
using HHECS.DAQHandle.EquipmentHandle;
唐召明 authored
6
7
using HHECS.DAQShared.Common.Enums;
using HHECS.DAQShared.Models;
唐召明 authored
8
using LinqKit;
唐召明 authored
9
10
11
using System.Configuration;
using System.Diagnostics;
唐召明 authored
12
internal class Program
唐召明 authored
13
{
14
    private static DateTime LastUploadTime = DateTime.MinValue;
唐召明 authored
15
    private static void Main(string[] args)
唐召明 authored
16
    {
唐召明 authored
17
        try
李璐瑶 authored
18
        {
唐召明 authored
19
20
            var appConfigResult = LoadAppConfig();
            if (!appConfigResult.Success)
李璐瑶 authored
21
            {
唐召明 authored
22
                SystemLog.PrintError($"加载配置文件信息失败:{appConfigResult.Msg}");
唐召明 authored
23
                return;
李璐瑶 authored
24
            }
唐召明 authored
25
            var appConfig = appConfigResult.Data;
唐召明 authored
26
唐召明 authored
27
28
            var result = ValidationConfig(appConfig);
            if (!result.Success)
李璐瑶 authored
29
            {
唐召明 authored
30
                SystemLog.PrintError($"配置信息校验失败:{result.Msg}");
唐召明 authored
31
                return;
李璐瑶 authored
32
            }
唐召明 authored
33
唐召明 authored
34
35
            var connectionString = ConfigurationManager.ConnectionStrings[appConfig.IsProductionEnvironment ? "Production" : "Development"].ConnectionString;
            GlobalVar.SetConnectionString(connectionString);
36
            UpdateClientStatus();
唐召明 authored
37
            Startup(appConfig);
唐召明 authored
38
39
40
        }
        catch (Exception ex)
        {
唐召明 authored
41
            SystemLog.PrintWarn($"程序启动出现异常:{ex.Message}");
唐召明 authored
42
43
        }
    }
44
唐召明 authored
45
    private static void Startup(AppConfig config)
唐召明 authored
46
    {
唐召明 authored
47
        var equipments = new List<EquipmentExtend>();
唐召明 authored
48
        var equipmentTypes = new List<EquipmentTypeExtend>();
唐召明 authored
49
        var equipmentTypeCodes = config.EquipmentTypeCodes;
唐召明 authored
50
        SystemLog.PrintInfo($"正在初始化数据...");
唐召明 authored
51
        while (true)
唐召明 authored
52
        {
唐召明 authored
53
            try
唐召明 authored
54
            {
唐召明 authored
55
56
                var result = InitialData(equipmentTypeCodes, ref equipments, ref equipmentTypes);
                if (!result.Success)
李璐瑶 authored
57
                {
唐召明 authored
58
59
                    SystemLog.PrintError($"初始化数据失败:{result.Msg}");
                    continue;
李璐瑶 authored
60
                }
唐召明 authored
61
62
63
64
65
66
                if (equipmentTypes.Count == 0)
                {
                    SystemLog.PrintError($"获取设备类型[{string.Join(',', equipmentTypeCodes)}]数据失败,数据为空!");
                    continue;
                }
                Stopwatch stopwatch = Stopwatch.StartNew();
唐召明 authored
67
68
69
70
71
                var freeSql = GlobalVar.FreeSql;

                //获取所有设备记录表名称,FreeSql的分表查询,时间跨天后不能获取到新表,这里使用自定义方式实现
                var tableNames = freeSql.Select<object>().WithSql("SELECT table_name FROM INFORMATION_SCHEMA.TABLES WHERE table_name LIKE 'daq_equipment_data_record%'").OrderBy(x => "table_name").ToList<string>();
唐召明 authored
72
                var tasks = new List<Task>();
唐召明 authored
73
                foreach (var currentEquipmentType in equipmentTypes)
唐召明 authored
74
                {
唐召明 authored
75
76
77
                    tasks.Add(Task.Run(() =>
                    {
                        Stopwatch stopwatch = Stopwatch.StartNew();
唐召明 authored
78
79
80
81
82
83
84
85
                        _ = Enum.TryParse<EquipmentTypeConst>(currentEquipmentType.Code, out var equipmentTypeCode);
                        var parameter = new AnalysisParameter
                        {
                            Equipments = equipments.Where(x => x.EquipmentTypeId == currentEquipmentType.Id).ToList(),
                            EquipmentType = currentEquipmentType,
                            AppConfig = config,
                            EquipmentTotalAlarmCode = equipmentTypeCode switch
                            {
86
87
88
89
90
91
                                EquipmentTypeConst.SingleForkSRM or
                                EquipmentTypeConst.SingleForkSRMV2 => SRMProps.TotalError.ToString(),
                                EquipmentTypeConst.DoubleForkSRM or
                                EquipmentTypeConst.DoubleForkSRMV2 => SRMProps.TotalError.ToString(),
                                EquipmentTypeConst.SingleForkSSRM or
                                EquipmentTypeConst.SingleForkSSRMV2 => SRMProps.TotalError.ToString(),
唐召明 authored
92
93
                                EquipmentTypeConst.SingleForkSSRMV132 => SRMProps.TotalError.ToString(),
                                EquipmentTypeConst.WeldRobot => RobotProp.Alarm.ToString(),
94
                                EquipmentTypeConst.WeldRobotV2 => RobotV2Prop.Alarm.ToString(),
95
                                EquipmentTypeConst.AGVForklift => AGVForkliftProp.Error.ToString(),
唐召明 authored
96
                                EquipmentTypeConst.RGVStation => RGVStationProps.Fault.ToString(),
唐召明 authored
97
98
                                EquipmentTypeConst.StationMonitor => StationProps.StationError.ToString(),
                                EquipmentTypeConst.Hoist => HoistProps.HoistStatus.ToString(),
唐召明 authored
99
                                EquipmentTypeConst.CNC => CNCProp.RedLight.ToString(),
唐召明 authored
100
                                EquipmentTypeConst.SingleForkRGV => SingleForkRGVProp.TotalError.ToString(),
唐召明 authored
101
102
103
                                _ => string.Empty,
                            }
                        };
唐召明 authored
104
105
                        IAnalysis handle = equipmentTypeCode switch
                        {
106
107
108
109
110
111
                            EquipmentTypeConst.SingleForkSRM or
                            EquipmentTypeConst.SingleForkSRMV2 => new SingleForkSRMAnalysis(parameter),
                            EquipmentTypeConst.DoubleForkSRM or
                            EquipmentTypeConst.DoubleForkSRMV2 => new DoubleForkSRMAnalysis(parameter),
                            EquipmentTypeConst.SingleForkSSRM or
                            EquipmentTypeConst.SingleForkSSRMV2 => new SingleForkSSRMAnalysis(parameter),
唐召明 authored
112
113
                            EquipmentTypeConst.SingleForkSSRMV132 => new SingleForkSSRMV132Analysis(parameter),
                            EquipmentTypeConst.WeldRobot => new WeldRobotAnalysis(parameter),
114
                            EquipmentTypeConst.WeldRobotV2 => new WeldRobotV2Analysis(parameter),
115
                            EquipmentTypeConst.AGVForklift => new AGVForkliftAnalysis(parameter),
唐召明 authored
116
                            EquipmentTypeConst.RGVStation => new RGVStationAnalysis(parameter),
唐召明 authored
117
                            EquipmentTypeConst.SingleForkRGV => new SingleForkRGVAnalysis(parameter),
唐召明 authored
118
119
                            EquipmentTypeConst.StationMonitor => new StationMonitorAnalysis(parameter),
                            EquipmentTypeConst.Hoist => new HoistAnalysis(parameter),
唐召明 authored
120
                            EquipmentTypeConst.CNC => new CNCAnalysis(parameter),
唐召明 authored
121
122
123
124
125
                            _ => null
                        };
                        //未知类型,则跳过
                        if (handle is null)
                        {
唐召明 authored
126
                            SystemLog.PrintWarn($"未实现设备类型[{currentEquipmentType.Code}]对应的处理方法");
唐召明 authored
127
128
                            return;
                        }
李璐瑶 authored
129
                        try
唐召明 authored
130
                        {
唐召明 authored
131
132
133
134
135
136
137
                            var limit = config.ProcessingDataVolume;
                            if (equipmentTypeCode == EquipmentTypeConst.StationMonitor)
                            {
                                //站台数据量比较大,目前不处理站台状态和报警,所以每次多取一些数据
                                limit *= 5;
                            }
唐召明 authored
138
                            using var equipmentDataRecordRepository = freeSql.GetRepository<EquipmentDataRecord>();
唐召明 authored
139
                            var equipmentCodes = equipments.Where(x => x.EquipmentTypeId == currentEquipmentType.Id).Select(x => x.Code).ToList();
唐召明 authored
140
141
142
                            //缓存有数据的表名称集合
                            var cacheTableNames = new List<string>();
唐召明 authored
143
144
145
146
147
148
149
150
151
                            var equipmentDataRecords = new List<EquipmentDataRecord>();
                            foreach (var tableName in tableNames)
                            {
                                //达到设定数量时停止往后查询
                                if (equipmentDataRecords.Count == limit)
                                {
                                    break;
                                }
唐召明 authored
152
153
154
155
156
157
158
159
                                var filter = PredicateBuilder.New<EquipmentDataRecord>(true);
                                filter = filter.And(x => equipmentCodes.Contains(x.EquipmentCode));
                                filter = filter.And(x => !x.IsHandle);
                                if (config.Version != 0)
                                {
                                    filter = filter.And(x => x.Version == config.Version);
                                }
唐召明 authored
160
161
162
                                //本次查询数量
                                var currentLimit = limit - equipmentDataRecords.Count;
                                var temps = freeSql.Queryable<EquipmentDataRecord>().AsTable((type, oldName) => tableName)
唐召明 authored
163
                                 .Where(filter)
唐召明 authored
164
                                 .OrderBy(x => x.Timestamp).Take(currentLimit).ToList();
165
166
167
168
169
                                if (temps.Count > 0)
                                {
                                    equipmentDataRecords.AddRange(temps);
                                    cacheTableNames.Add(tableName);
                                }
唐召明 authored
170
171
                            }
唐召明 authored
172
173
174
175
176
                            if (equipmentDataRecords.Count == 0)
                            {
                                SystemLog.PrintInfo($"设备类型[{currentEquipmentType.Code}]记录数据为空,跳过解析,耗时:{stopwatch.ElapsedMilliseconds}ms");
                                return;
                            }
李璐瑶 authored
177
178
179
180

                            var result = handle.Execute(equipmentDataRecords);
                            if (!result.Success)
                            {
唐召明 authored
181
                                SystemLog.PrintError($"设备类型[{currentEquipmentType.Code}]解析失败,{result.Msg},数量{equipmentDataRecords.Count},耗时:{stopwatch.ElapsedMilliseconds}ms");
李璐瑶 authored
182
183
                                return;
                            }
唐召明 authored
184
185
                            //删除数据
唐召明 authored
186
                            var ids = equipmentDataRecords.Select(x => x.Id).ToList();
187
188
189
190
                            foreach (var tableName in cacheTableNames)
                            {
                                freeSql.Delete<EquipmentDataRecord>().AsTable(tableName).Where(x => ids.Contains(x.Id)).CommandTimeout(300).ExecuteAffrows();
                            }
唐召明 authored
191
唐召明 authored
192
                            SystemLog.PrintSuccess($"设备类型[{currentEquipmentType.Code}]解析完成,数量{equipmentDataRecords.Count},耗时:{stopwatch.ElapsedMilliseconds}ms");
李璐瑶 authored
193
194
195
                        }
                        catch (Exception ex)
                        {
唐召明 authored
196
                            SystemLog.PrintError($"[{handle.GetType().Name}]线程数据解析出现异常:{ex.Message}");
唐召明 authored
197
                        }
唐召明 authored
198
                    }));
唐召明 authored
199
                }
唐召明 authored
200
                Task.WaitAll(tasks.ToArray());
唐召明 authored
201
                Thread.Sleep(1000);
唐召明 authored
202
203
                const string tempString = "——————————————————";
                Console.WriteLine($"{tempString}[总耗时:{stopwatch.Elapsed}]{tempString}");
唐召明 authored
204
205
206
            }
            catch (Exception ex)
            {
唐召明 authored
207
                SystemLog.PrintError($"程序异常:{ex.Message}");
唐召明 authored
208
            }
唐召明 authored
209
210
        }
    }
唐召明 authored
211
212
    /// <summary>
唐召明 authored
213
    /// 加载配置文件信息
214
    /// </summary>
唐召明 authored
215
216
    /// <returns></returns>
    private static BllResult<AppConfig> LoadAppConfig()
217
    {
唐召明 authored
218
219
220
221
222
223
224
225
        try
        {
            _ = int.TryParse(ConfigurationManager.AppSettings["DataTimeOut"], out int dataTimeOutValue);
            _ = int.TryParse(ConfigurationManager.AppSettings["ProcessingDataVolume"], out int processingDataVolumeValue);
            _ = int.TryParse(ConfigurationManager.AppSettings["DataRetentionDays"], out int dataRetentionDaysValue);
            _ = int.TryParse(ConfigurationManager.AppSettings["Version"], out var version);
            _ = bool.TryParse(ConfigurationManager.AppSettings["IsProductionEnvironment"], out var isProductionEnvironmentValue);
            _ = Guid.TryParse((ConfigurationManager.AppSettings["ClientId"]), out var clientIdValue);
唐召明 authored
226
227
            var equipmentTypeCodes = ConfigurationManager.AppSettings["EquipmentType"];
            var warehouseCode = ConfigurationManager.AppSettings["WarehouseCode"];
228
唐召明 authored
229
230
231
232
            if (processingDataVolumeValue <= 0)
            {
                processingDataVolumeValue = 100;
            }
233
唐召明 authored
234
            if (isProductionEnvironmentValue)
235
            {
唐召明 authored
236
237
238
239
240
241
242
243
244
                Console.Title = "IOT数据处理端";
            }
            else
            {
                Console.Title = "IOT数据处理端(测试版)";
            }
            var appConfig = new AppConfig
            {
                ClientId = clientIdValue,
唐召明 authored
245
                WarehouseCode = warehouseCode,
唐召明 authored
246
247
248
                DataTimeOut = dataTimeOutValue,
                IsProductionEnvironment = isProductionEnvironmentValue,
                ProcessingDataVolume = processingDataVolumeValue,
唐召明 authored
249
                EquipmentTypeCodes = equipmentTypeCodes?.Split(',').Where(x => !string.IsNullOrWhiteSpace(x)).ToList() ?? new List<string>(),
唐召明 authored
250
251
252
253
254
255
256
257
258
                Version = version
            };
            return BllResultFactory.Success(appConfig);
        }

        catch (Exception ex)
        {
            return BllResultFactory.Error<AppConfig>(ex.Message);
        }
259
260
261
    }

    /// <summary>
唐召明 authored
262
    /// 配置信息校验
263
    /// </summary>
唐召明 authored
264
    /// <param name="appConfig"></param>
265
    /// <returns></returns>
唐召明 authored
266
    private static BllResult ValidationConfig(AppConfig appConfig)
267
    {
唐召明 authored
268
269
270
271
272
273
        try
        {
            if (string.IsNullOrWhiteSpace(appConfig.WarehouseCode))
            {
                return BllResultFactory.Error($"仓库编号[{nameof(appConfig.WarehouseCode)}]未配置!");
            }
274
唐召明 authored
275
276
            if (appConfig.EquipmentTypeCodes == null || appConfig.EquipmentTypeCodes.Count == 0)
            {
唐召明 authored
277
                SystemLog.PrintWarn($"设备类型[{nameof(appConfig.EquipmentTypeCodes)}]未配置,将默认匹配所有设备");
唐召明 authored
278
            }
279
唐召明 authored
280
281
            if (appConfig.Version == 0)
            {
唐召明 authored
282
                SystemLog.PrintWarn($"程序版本[{nameof(appConfig.Version)}]未配置,将匹配所有版本设备记录");
唐召明 authored
283
284
285
286
            }
            return BllResultFactory.Success();
        }
        catch (Exception ex)
287
        {
唐召明 authored
288
            return BllResultFactory.Error(ex.Message);
289
290
        }
    }
李璐瑶 authored
291
唐召明 authored
292
293
294
295
296
297
    /// <summary>
    /// 初始化数据
    /// </summary>
    /// <param name="equipmentTypeCodes">设备类型编号</param>
    /// <param name="equipments">设备集合</param>
    /// <param name="equipmentTypes">设备类型集合</param>
298
299
300
    /// <param name="timeSpanHours">强制刷新超时时间,默认1小时</param>
    /// <remarks>在设备或设备属性数据总数发生变化或距离上次加载时间超过一小时,则刷新数据</remarks>
    private static BllResult InitialData(List<string> equipmentTypeCodes, ref List<EquipmentExtend> equipments, ref List<EquipmentTypeExtend> equipmentTypes, double timeSpanHours = 1)
李璐瑶 authored
301
302
303
    {
        try
        {
唐召明 authored
304
            using var freeSql = GlobalVar.FreeSql;
唐召明 authored
305
306
307
308
            var equipmentRepository = freeSql.GetRepository<EquipmentExtend>();
            var equipmentPropRepository = freeSql.GetRepository<EquipmentPropExtend>();
            var equipmentTypeRepository = freeSql.GetRepository<EquipmentTypeExtend>();
309
            if ((DateTime.Now.AddHours(-timeSpanHours) > LastUploadTime) || equipmentTypes.Count == 0)
唐召明 authored
310
            {
唐召明 authored
311
312
313
314
315
316
                var filter = PredicateBuilder.New<EquipmentTypeExtend>(true);
                if (equipmentTypeCodes.Count > 0)
                {
                    filter = filter.And(x => equipmentTypeCodes.Contains(x.Code));
                }
                equipmentTypes = equipmentTypeRepository.Where(filter).IncludeMany(x => x.EquipmentTypePropTemplates).ToList();
唐召明 authored
317
318
            }
            var equipmentTypeIds = equipmentTypes.Select(x => x.Id).ToList();
唐召明 authored
319
            var equipmentIds = equipmentRepository.Where(x => equipmentTypeIds.Contains(x.EquipmentTypeId)).ToList(x => x.Id);
唐召明 authored
320
            var equipmentTotal = equipmentIds.Count;
唐召明 authored
321
            var equipmentPropTotal = equipmentPropRepository.Where(x => equipmentIds.Contains(x.EquipmentId)).Count();
322
            if ((DateTime.Now.AddHours(-timeSpanHours) > LastUploadTime) || equipments.Count != equipmentTotal || equipments.SelectMany(x => x.EquipmentProps).Count() != equipmentPropTotal)
唐召明 authored
323
            {
唐召明 authored
324
                equipments = equipmentRepository.Where(x => equipmentTypeIds.Contains(x.EquipmentTypeId)).IncludeMany(x => x.EquipmentProps).ToList();
唐召明 authored
325
326
327
328
329
330
                foreach (var item in equipments)
                {
                    var equipmentType = equipmentTypes.Find(x => x.Id == item.EquipmentTypeId);
                    item.EquipmentType = equipmentType;
                    item.EquipmentProps.ForEach(x => x.EquipmentTypePropTemplate = equipmentType.EquipmentTypePropTemplates.Find(t => t.Id == x.EquipmentTypePropTemplateId));
                }
331
                LastUploadTime = DateTime.Now;
唐召明 authored
332
333
            }
            return BllResultFactory.Success();
李璐瑶 authored
334
335
336
        }
        catch (Exception ex)
        {
唐召明 authored
337
            return BllResultFactory.Error(ex.Message);
李璐瑶 authored
338
339
        }
    }
340
唐召明 authored
341
342
343
    /// <summary>
    /// 更新客户端状态
    /// </summary>
344
345
    private static void UpdateClientStatus()
    {
唐召明 authored
346
        Task.Run(async () =>
347
        {
李璐瑶 authored
348
            while (true)
349
            {
李璐瑶 authored
350
                try
351
                {
唐召明 authored
352
                    await Task.Delay(5000);
唐召明 authored
353
                    using var clientStatusRepository = GlobalVar.FreeSql.GetRepository<ClientStatus>();
李璐瑶 authored
354
355
356
                    //更新客户端状态
                    _ = Guid.TryParse(ConfigurationManager.AppSettings["ClientId"], out var clientId);
                    if (clientId != Guid.Empty)
357
                    {
唐召明 authored
358
                        var client = clientStatusRepository.Where(x => x.ClientKeys == clientId).First();
李璐瑶 authored
359
360
                        if (client != null)
                        {
唐召明 authored
361
                            clientStatusRepository.Attach(client);
李璐瑶 authored
362
                            client.LastSeenDate = DateTime.Now;
唐召明 authored
363
                            clientStatusRepository.Update(client);
李璐瑶 authored
364
                        }
365
366
                    }
                }
李璐瑶 authored
367
368
369
370
                catch (Exception ex)
                {
                    SystemLog.PrintError($"客户端状态更新线程异常:{ex.Message}");
                }
371
            }
李璐瑶 authored
372
        });
373
    }
唐召明 authored
374
375

    /// <summary>
唐召明 authored
376
    /// 修复数据设备报警和设备状态
唐召明 authored
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
    /// </summary>
    private static void FixData()
    {
        var freeSql = GlobalVar.FreeSql;
        using var equipmentAlarmRecordRepository = freeSql.GetRepository<EquipmentAlarmRecord>();
        using var equipmentStatusRecordHistoryRepository = freeSql.GetRepository<EquipmentStatusRecordHistory>();

        //历史报警
        var alarmStartTime = equipmentAlarmRecordRepository.Where(x => true).OrderBy(x => x.CreateTime).First(x => x.CreateTime).Date;
        var alarmTotalDays = (DateTime.Today - alarmStartTime).Days;
        var allAlarmRecords = equipmentAlarmRecordRepository.Where(x => x.UpdateTime < DateTime.Today).OrderBy(x => x.CreateTime).ToList();
        for (int i = 0; i < alarmTotalDays; i++)
        {
            var tempDate1 = alarmStartTime.AddDays(i);
            var tempDate2 = alarmStartTime.AddDays(i + 1);
            var records = allAlarmRecords.Where(x => x.CreateTime.Date == tempDate1 && x.UpdateTime.Date != tempDate1).ToList();
            if (records.Count > 0)
            {
                Console.WriteLine($"[报警]{tempDate1.ToShortDateString()}:{records.Count}条");
            }

            foreach (var item in records)
            {
                var days = (item.UpdateTime.Date - item.CreateTime.Date).Days;
                var addTemps = new List<EquipmentAlarmRecord>();
                for (int j = 1; j <= days; j++)
                {
                    var tempDate3 = tempDate1.AddDays(j);
                    var tempDate4 = tempDate3.Date == item.UpdateTime.Date ? item.UpdateTime : tempDate3.AddDays(1).AddSeconds(-1);
                    var addTemp = new EquipmentAlarmRecord
                    {
                        EquipmentCode = item.EquipmentCode,
                        EquipmentName = item.EquipmentName,
                        EquipmentPropCode = item.EquipmentPropCode,
                        EquipmentPropName = item.EquipmentPropName,
                        AlarmMessage = item.AlarmMessage,
                        EquipmentTypeCode = item.EquipmentTypeCode,
                        FactoryCode = item.FactoryCode,
                        ProjectCode = item.ProjectCode,
                        HandleTime = item.HandleTime,
                        IsEnd = item.IsEnd,
                        IsHandled = item.IsHandled,
                        Remark = item.Remark,
                        ErrorDuration = (tempDate4 - tempDate3).TotalSeconds,
                        CreateTime = tempDate3,
                        UpdateTime = tempDate4
                    };
                    if (addTemp.ErrorDuration > 0)
                    {
                        addTemps.Add(addTemp);
                    }
                };
                equipmentAlarmRecordRepository.Attach(item);
                item.UpdateTime = tempDate2.AddSeconds(-1);
                item.ErrorDuration = (item.UpdateTime - item.CreateTime).TotalSeconds;
                equipmentAlarmRecordRepository.Update(item);
                equipmentAlarmRecordRepository.Insert(addTemps);
            }
        }

        //历史状态
        var statusStartTime = equipmentStatusRecordHistoryRepository.Where(x => true).OrderBy(x => x.CreateTime).First(x => x.CreateTime).Date;
        var statusTotalDays = (DateTime.Today - statusStartTime).Days;
        var allStatusRecords = equipmentStatusRecordHistoryRepository.Where(x => x.UpdateTime < DateTime.Today).OrderBy(x => x.CreateTime).ToList();
        for (int i = 0; i < statusTotalDays; i++)
        {
            var tempDate1 = alarmStartTime.AddDays(i);
            var tempDate2 = alarmStartTime.AddDays(i + 1);
            var records = allStatusRecords.Where(x => x.CreateTime.Date == tempDate1 && x.UpdateTime.Date != tempDate1).ToList();
            if (records.Count > 0)
            {
                Console.WriteLine($"[状态]{tempDate1.ToShortDateString()}:{records.Count}条");
            }

            foreach (var item in records)
            {
                var days = (item.UpdateTime.Date - item.CreateTime.Date).Days;
                var addTemps = new List<EquipmentStatusRecordHistory>();
                for (int j = 1; j <= days; j++)
                {
                    var tempDate3 = tempDate1.AddDays(j);
                    var tempDate4 = tempDate3.Date == item.UpdateTime.Date ? item.UpdateTime : tempDate3.AddDays(1).AddSeconds(-1);
                    var addTemp = new EquipmentStatusRecordHistory
                    {
                        EquipmentCode = item.EquipmentCode,
                        EquipmentName = item.EquipmentName,
                        EquipmentTypeCode = item.EquipmentTypeCode,
                        FactoryCode = item.FactoryCode,
                        ProjectCode = item.ProjectCode,
                        HandleTime = item.HandleTime,
                        IsEnd = item.IsEnd,
                        Remark = item.Remark,
                        Status = item.Status,
                        StatusDuration = (tempDate4 - tempDate3).TotalSeconds,
                        CreateTime = tempDate3,
                        UpdateTime = tempDate4
                    };
                    if (addTemp.StatusDuration > 0)
                    {
                        addTemps.Add(addTemp);
                    }
                };
                equipmentStatusRecordHistoryRepository.Attach(item);
                item.UpdateTime = tempDate2.AddSeconds(-1);
                item.StatusDuration = (item.UpdateTime - item.CreateTime).TotalSeconds;
                equipmentStatusRecordHistoryRepository.Update(item);
                equipmentStatusRecordHistoryRepository.Insert(addTemps);
            }
        }
    }
唐召明 authored
487
}