ManageMapEntitiesCommandHandler.cs
30.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
using System.Security.AccessControl;
using System.Text.Json;
using AutoMapper;
using MassTransit;
using Microsoft.Extensions.Logging;
using Rcs.Application.Common;
using Rcs.Application.MessageBus.Commands;
using Rcs.Application.MessageBus.Responses;
using Rcs.Domain.Entities;
using Rcs.Domain.Repositories;
using Rcs.Application.DTOs;
using Rcs.Shared.Utils;
using Rcs.Domain.Extensions;
using MassTransit.Internals;
using Rcs.Domain.ValueObjects;
using Rcs.Domain.Enums;
namespace Rcs.Infrastructure.MessageBus.Handlers.Commands;
/// <summary>
/// 管理地图命令处理器(全量同步模式)
/// </summary>
public class ManageMapEntitiesCommandHandler : IConsumer<ManageMapCommand>
{
private readonly ILogger<ManageMapEntitiesCommandHandler> _logger;
private readonly IMapRepository _mapRepository;
private readonly IMapNodeRepository _mapNodeRepository;
private readonly IMapEdgeRepository _mapEdgeRepository;
private readonly IMapResourceRepository _mapResourceRepository;
private readonly IStorageLocationRepository _storageLocationRepository;
private readonly IStorageLocationTypeRepository _storageLocationTypeRepository;
private readonly IStorageAreaRepository _storageAreaRepository;
private readonly IMapper _mapper;
public ManageMapEntitiesCommandHandler(
ILogger<ManageMapEntitiesCommandHandler> logger,
IMapRepository mapRepository,
IMapNodeRepository mapNodeRepository,
IMapEdgeRepository mapEdgeRepository,
IMapResourceRepository mapResourceRepository,
IStorageLocationRepository storageLocationRepository,
IStorageLocationTypeRepository storageLocationTypeRepository,
IStorageAreaRepository storageAreaRepository,
IMapper mapper)
{
_logger = logger;
_mapRepository = mapRepository;
_mapNodeRepository = mapNodeRepository;
_mapEdgeRepository = mapEdgeRepository;
_mapResourceRepository = mapResourceRepository;
_storageLocationRepository = storageLocationRepository;
_storageLocationTypeRepository = storageLocationTypeRepository;
_storageAreaRepository = storageAreaRepository;
_mapper = mapper;
}
public async Task Consume(ConsumeContext<ManageMapCommand> context)
{
var command = context.Message;
try
{
Map? map = null;
var operationDetails = new OperationResult();
// 创建或更新地图并同步嵌套实体
// ap = await HandleCreateOrUpdateMapAsync(command, context.CancellationToken);
map = await _mapRepository.GetByIdAsync(
Guid.Parse(command.MapId),
context.CancellationToken);
if (map == null)
{
throw new InvalidOperationException($"地图id {command.MapId} 不存在");
}
if (Guid.TryParse(command.MapId, out Guid mapId)) {
// 全量同步嵌套实体
await SynchronizeNestedEntitiesAsync(mapId, command, operationDetails, context.CancellationToken);
}
await context.RespondAsync(ApiResponse.Successful());
}
catch (Exception ex)
{
await context.RespondAsync(ApiResponse.Failed(ex.Message));
}
}
/// <summary>
/// 处理创建或更新地图
/// </summary>
private async Task<Map> HandleCreateOrUpdateMapAsync(ManageMapCommand command, CancellationToken cancellationToken)
{
Map? map;
if(!Guid.TryParse(command.MapId, out Guid mapId))
{
// 检查地图编码是否已存在
var existingMap = await _mapRepository.GetByMapCodeAsync(
command.MapCode,
cancellationToken);
if (existingMap != null)
{
throw new InvalidOperationException($"地图编码 {command.MapCode} 已存在");
}
// 创建地图实体
map = Map.Create
(
command.MapCode,
command.MapName,
(MapTYPE)(command.MapType),
command.Version,
command.Description,
command.Active
);
// 保存地图到数据库
await _mapRepository.AddAsync(map, cancellationToken);
}
else
{
map = await _mapRepository.GetByIdAsync(
mapId,
cancellationToken);
if (map == null)
throw new InvalidOperationException($"未找到地图ID为 {mapId} 的地图");
map.Update
(
command.MapCode,
command.MapName,
(MapTYPE)command.MapType,
command.Version,
command.Description,
command.Active
);
await _mapRepository.UpdateAsync(map, cancellationToken);
}
return map;
}
/// <summary>
/// 处理删除地图
/// </summary>
private async Task<Map> HandleDeleteMapAsync(Guid mapId, CancellationToken cancellationToken)
{
var map = await _mapRepository.GetByIdAsync(mapId, cancellationToken);
if (map == null)
{
throw new InvalidOperationException($"地图ID {mapId} 不存在");
}
// 先删除所有嵌套实体
await DeleteAllNestedEntitiesAsync(mapId, cancellationToken);
// 删除地图
await _mapRepository.DeleteAsync(map, cancellationToken);
_logger.LogInformation("地图删除成功 - 地图ID: {MapId}, 地图编码: {MapCode}", map.MapId, map.MapCode);
return map;
}
/// <summary>
/// 全量同步嵌套实体
/// </summary>
private async Task SynchronizeNestedEntitiesAsync(Guid mapId, ManageMapCommand command, OperationResult operationDetails, CancellationToken cancellationToken)
{
_logger.LogInformation("开始全量同步地图嵌套实体 - 地图ID: {MapId}", mapId);
// var nodes = _mapper.Map<List<MapNode>>(command.MapNodes);
// 同步节点,返回 nodeCode -> MapNode 实体映射(用于后续使用导航属性)
var (nodeResult, nodeMap) = await SynchronizeNodesAsync(mapId, command.MapNodes, cancellationToken);
operationDetails.Nodes = nodeResult;
// 同步边,传入 nodeCode -> MapNode 实体映射(使用导航属性构建边)
operationDetails.Edges = await SynchronizeEdgesAsync(mapId, command.MapEdges, nodeMap, cancellationToken);
// 同步资源(手动映射,避免 AutoMapper 复杂类型转换问题)
operationDetails.Resources = await SynchronizeResourcesAsync(mapId, command.MapResources, cancellationToken);
_logger.LogInformation("地图嵌套实体同步完成 - 地图ID: {MapId}", mapId);
}
/// <summary>
/// 同步节点
/// </summary>
private async Task<(EntityOperationResult Result, Dictionary<string, MapNode> NodeMap)> SynchronizeNodesAsync(Guid mapId, List<MapNodeDto>? targetNodes, CancellationToken cancellationToken)
{
var result = new EntityOperationResult();
var nodeMap = new Dictionary<string, MapNode>();
// 获取现有节点
var existingNodes = (await _mapNodeRepository.GetByMapIdAsync(mapId, cancellationToken)).ToList();
var existingNodeDict = existingNodes.ToDictionary(n => n.NodeCode);
if (targetNodes == null || targetNodes.Count == 0)
{
// 删除所有现有节点
foreach (var node in existingNodes)
{
// 删除对应的库区(库区编码 = 节点编码)
var area = await _storageAreaRepository.GetByAreaCodeAsync(node.NodeCode, cancellationToken);
if (area != null)
{
await _storageAreaRepository.DeleteAsync(area, cancellationToken);
_logger.LogInformation("删除节点 {NodeCode} 对应的库区", node.NodeCode);
}
await _mapNodeRepository.DeleteAsync(node, cancellationToken);
result.DeletedCount++;
}
return (result, nodeMap);
}
var targetNodeDict = targetNodes.ToDictionary(n => n.NodeCode);
// 找出需要删除的节点(存在现有但不在目标中)
var nodesToDelete = existingNodes.Where(n => !targetNodeDict.ContainsKey(n.NodeCode)).ToList();
foreach (var node in nodesToDelete)
{
// 删除对应的库区(库区编码 = 节点编码)
var area = await _storageAreaRepository.GetByAreaCodeAsync(node.NodeCode, cancellationToken);
if (area != null)
{
await _storageAreaRepository.DeleteAsync(area, cancellationToken);
_logger.LogInformation("删除节点 {NodeCode} 对应的库区", node.NodeCode);
}
await _mapNodeRepository.DeleteAsync(node, cancellationToken);
result.DeletedCount++;
}
// 找出需要添加或更新的节点
foreach (var targetNode in targetNodes)
{
if ((MapNodeTYPE)targetNode.Type == MapNodeTYPE.store && string.IsNullOrEmpty(targetNode.StorageLocationTypeId))
throw new BusinessException($"{targetNode.NodeCode} 储位节点必须选择储位类型");
if (existingNodeDict.TryGetValue(targetNode.NodeCode, out var existingNode))
{
// 更新现有节点
existingNode.NodeName = targetNode.NodeName;
existingNode.Description = targetNode.Description;
existingNode.X = targetNode.X;
existingNode.Y = targetNode.Y;
existingNode.Theta = AngleConverter.ToCycleRadians(targetNode.Theta);
existingNode.IsReverseParking = targetNode.IsReverseParking;
existingNode.AllowRotate = targetNode.AllowRotate;
existingNode.MaxCoordinateOffset = targetNode.MaxCoordinateOffset;
existingNode.Type = (MapNodeTYPE)targetNode.Type;
existingNode.StorageLocationTypeId = string.IsNullOrEmpty(targetNode.StorageLocationTypeId)
? null
: Guid.Parse(targetNode.StorageLocationTypeId);
existingNode.Active = targetNode.Active;
await _mapNodeRepository.UpdateAsync(existingNode, cancellationToken);
result.UpdatedCount++;
nodeMap[existingNode.NodeCode] = existingNode;
// 如果是储位节点,同步储位
if (existingNode.Type == MapNodeTYPE.store && existingNode.StorageLocationTypeId.HasValue)
{
await SynchronizeStorageLocationsForNodeAsync(existingNode, cancellationToken);
}
}
else
{
// 添加新节点
var newNode = new MapNode
{
NodeId = Guid.NewGuid(),
MapId = mapId,
NodeCode = targetNode.NodeCode,
NodeName = targetNode.NodeName,
Description = targetNode.Description,
X = targetNode.X,
Y = targetNode.Y,
Theta = AngleConverter.ToCycleRadians(targetNode.Theta),
IsReverseParking = targetNode.IsReverseParking,
AllowRotate = targetNode.AllowRotate,
MaxCoordinateOffset = targetNode.MaxCoordinateOffset,
Type = (MapNodeTYPE)targetNode.Type,
StorageLocationTypeId = string.IsNullOrEmpty(targetNode.StorageLocationTypeId)
? null
: Guid.Parse(targetNode.StorageLocationTypeId),
Active = targetNode.Active,
CreatedAt = DateTime.Now
};
await _mapNodeRepository.AddAsync(newNode, cancellationToken);
result.AddedCount++;
nodeMap[newNode.NodeCode] = newNode;
// 如果是储位节点,同步储位
if (newNode.Type == MapNodeTYPE.store && newNode.StorageLocationTypeId.HasValue)
{
await SynchronizeStorageLocationsForNodeAsync(newNode, cancellationToken);
}
}
}
_logger.LogInformation("节点同步完成 - 添加: {Added}, 更新: {Updated}, 删除: {Deleted}",
result.AddedCount, result.UpdatedCount, result.DeletedCount);
return (result, nodeMap);
}
/// <summary>
/// 同步边
/// </summary>
private async Task<EntityOperationResult> SynchronizeEdgesAsync(Guid mapId, List<MapEdgeDto>? targetEdges, Dictionary<string,MapNode>
nodeCodeToIdMap, CancellationToken cancellationToken)
{
var result = new EntityOperationResult();
// 获取现有边
var existingEdges = (await _mapEdgeRepository.GetByMapIdAsync(mapId, cancellationToken)).ToList();
var existingEdgeDict = existingEdges.ToDictionary(e => e.EdgeCode);
if (targetEdges == null || targetEdges.Count == 0)
{
// 删除所有现有边
foreach (var edge in existingEdges)
{
await _mapEdgeRepository.DeleteAsync(edge, cancellationToken);
result.DeletedCount++;
}
return result;
}
var targetEdgeDict = targetEdges.ToDictionary(e => e.EdgeCode);
// 找出需要删除的边(存在现有但不在目标中)
var edgesToDelete = existingEdges.Where(e => !targetEdgeDict.ContainsKey(e.EdgeCode)).ToList();
foreach (var edge in edgesToDelete)
{
await _mapEdgeRepository.DeleteAsync(edge, cancellationToken);
result.DeletedCount++;
}
// 找出需要添加或更新的边
foreach (var targetEdge in targetEdges)
{
if (existingEdgeDict.TryGetValue(targetEdge.EdgeCode, out var existingEdge))
{
// 更新现有边
existingEdge.FromNode = nodeCodeToIdMap.GetValueOrDefault(targetEdge.FromNode)?.NodeId ?? Guid.Empty;
existingEdge.ToNode = nodeCodeToIdMap.GetValueOrDefault(targetEdge.ToNode)?.NodeId ?? Guid.Empty;
existingEdge.EdgeName = targetEdge.EdgeName;
existingEdge.Length = targetEdge.Length ?? 0d;
existingEdge.Cost = targetEdge.Cost;
existingEdge.IsCurve = targetEdge.IsCurve;
existingEdge.Radius = targetEdge.Radius;
existingEdge.CenterX = targetEdge.CenterX;
existingEdge.CenterY = targetEdge.CenterY;
existingEdge.Degree = targetEdge.Degree;
existingEdge.Weights = targetEdge.Weights;
existingEdge.Knots = targetEdge.Knots;
existingEdge.OrientationRads = targetEdge.OrientationAngles?.Select(a => (double)AngleConverter.ToCycleRadians(a)).ToList() ?? new List<double>{0,AngleConstants.Degrees180};
existingEdge.MaxCoordinateOffset = targetEdge.MaxCoordinateOffset;
existingEdge.MaxRadDeviation = AngleConverter.ToCycleRadians(targetEdge.MaxAngleDeviation);
existingEdge.MaxSpeed = targetEdge.MaxSpeed;
existingEdge.Active = targetEdge.Active;
if (targetEdge.IsCurve)
{
existingEdge.Degree = 2;
existingEdge.ControlPoints = new List<Point>() {
new Point(){
X = nodeCodeToIdMap.GetValueOrDefault(targetEdge.FromNode)?.X ?? 0d,
Y = nodeCodeToIdMap.GetValueOrDefault(targetEdge.FromNode)?.Y ?? 0d,
},
new Point(){
X = nodeCodeToIdMap.GetValueOrDefault(targetEdge.ToNode)?.X ?? 0d,
Y = nodeCodeToIdMap.GetValueOrDefault(targetEdge.ToNode)?.Y ?? 0d,
},
new Point(){
X = targetEdge.CenterX ?? 0d,
Y = targetEdge.CenterY ?? 0d
}
};
}
await _mapEdgeRepository.UpdateAsync(existingEdge, cancellationToken);
result.UpdatedCount++;
}
else
{
// 添加新边
var newEdge = new MapEdge
{
EdgeId = Guid.NewGuid(),
MapId = mapId,
EdgeCode = targetEdge.EdgeCode,
FromNode = nodeCodeToIdMap.GetValueOrDefault(targetEdge.FromNode)?.NodeId ?? Guid.Empty,
ToNode = nodeCodeToIdMap.GetValueOrDefault(targetEdge.ToNode)?.NodeId ?? Guid.Empty,
EdgeName = targetEdge.EdgeName,
Length = targetEdge.Length ?? 0d,
Cost = targetEdge.Cost,
IsCurve = targetEdge.IsCurve,
Radius = targetEdge.Radius,
CenterX = targetEdge.CenterX,
CenterY = targetEdge.CenterY,
Degree = targetEdge.Degree,
ControlPoints = targetEdge.ControlPoints,
Weights = targetEdge.Weights,
Knots = targetEdge.Knots,
OrientationRads = targetEdge.OrientationAngles?.Select(a => (double)AngleConverter.ToCycleRadians(a)).ToList() ?? new List<double>{0,AngleConstants.Degrees180},
MaxCoordinateOffset = targetEdge.MaxCoordinateOffset,
MaxRadDeviation = AngleConverter.ToCycleRadians(targetEdge.MaxAngleDeviation),
MaxSpeed = targetEdge.MaxSpeed,
Active = targetEdge.Active,
CreatedAt = DateTime.Now
};
if (newEdge.IsCurve)
{
newEdge.Degree = 2;
newEdge.ControlPoints = new List<Point>() {
new Point(){
X = nodeCodeToIdMap.GetValueOrDefault(targetEdge.FromNode)?.X ?? 0d,
Y = nodeCodeToIdMap.GetValueOrDefault(targetEdge.FromNode)?.Y ?? 0d,
},
new Point(){
X = nodeCodeToIdMap.GetValueOrDefault(targetEdge.ToNode)?.X ?? 0d,
Y = nodeCodeToIdMap.GetValueOrDefault(targetEdge.ToNode)?.Y ?? 0d,
},
new Point(){
X = targetEdge.CenterX ?? 0d,
Y = targetEdge.CenterY ?? 0d
}
};
}
await _mapEdgeRepository.AddAsync(newEdge, cancellationToken);
result.AddedCount++;
}
}
_logger.LogInformation("边同步完成 - 添加: {Added}, 更新: {Updated}, 删除: {Deleted}",
result.AddedCount, result.UpdatedCount, result.DeletedCount);
return result;
}
/// <summary>
/// 同步资源
/// </summary>
private async Task<EntityOperationResult> SynchronizeResourcesAsync(Guid mapId, List<MapResourceDto>? targetResourceDtos, CancellationToken cancellationToken)
{
var result = new EntityOperationResult();
// 获取现有资源
var existingResources = (await _mapResourceRepository.GetByMapIdAsync(mapId, cancellationToken)).ToList();
var existingResourceDict = existingResources.ToDictionary(r => r.ResourceCode);
if (targetResourceDtos == null || targetResourceDtos.Count == 0)
{
// 删除所有现有资源
foreach (var resource in existingResources)
{
await _mapResourceRepository.DeleteAsync(resource, cancellationToken);
result.DeletedCount++;
}
return result;
}
var targetResourceDict = targetResourceDtos
.Where(r => !string.IsNullOrEmpty(r.ResourceCode))
.ToDictionary(r => r.ResourceCode!);
// 找出需要删除的资源(存在现有但不在目标中)
var resourcesToDelete = existingResources.Where(r => !targetResourceDict.ContainsKey(r.ResourceCode)).ToList();
foreach (var resource in resourcesToDelete)
{
await _mapResourceRepository.DeleteAsync(resource, cancellationToken);
result.DeletedCount++;
}
// 找出需要添加或更新的资源
foreach (var dto in targetResourceDtos)
{
if (string.IsNullOrEmpty(dto.ResourceCode)) continue;
// 手动转换 LocationCoordinates
var polygon = dto.LocationCoordinates != null && dto.LocationCoordinates.Count >= 3
? PolygonConverter.ToPolygonFromXY(dto.LocationCoordinates.Select(p => new double[] { p.X, p.Y }))
: null;
if (existingResourceDict.TryGetValue(dto.ResourceCode, out var existingResource))
{
// 更新现有资源
existingResource.ResourceName = dto.ResourceName ?? "";
existingResource.Type = (MapResourcesTYPE)dto.Type;
existingResource.Capacity = dto.Capacity;
existingResource.MaxSpeed = dto.MaxSpeed;
existingResource.CanRotate = dto.CanRotate;
existingResource.LocationCoordinates = polygon;
existingResource.Active = dto.Active;
// 设置四对动作属性
existingResource.PreAction1Type = dto.PreAction1Type.HasValue ? (ActionType)dto.PreAction1Type.Value : null;
existingResource.PreNetActions1 = dto.PreNetActions1?.Where(n => Guid.TryParse(n, out _)).Select(n => Guid.Parse(n)).ToList();
existingResource.PostAction1Type = dto.PostAction1Type.HasValue ? (ActionType)dto.PostAction1Type.Value : null;
existingResource.PostNetActions1 = dto.PostNetActions1?.Where(n => Guid.TryParse(n, out _)).Select(n => Guid.Parse(n)).ToList();
existingResource.PreAction2Type = dto.PreAction2Type.HasValue ? (ActionType)dto.PreAction2Type.Value : null;
existingResource.PreNetActions2 = dto.PreNetActions2?.Where(n => Guid.TryParse(n, out _)).Select(n => Guid.Parse(n)).ToList();
existingResource.PostAction2Type = dto.PostAction2Type.HasValue ? (ActionType)dto.PostAction2Type.Value : null;
existingResource.PostNetActions2 = dto.PostNetActions2?.Where(n => Guid.TryParse(n, out _)).Select(n => Guid.Parse(n)).ToList();
await _mapResourceRepository.UpdateAsync(existingResource, cancellationToken);
result.UpdatedCount++;
}
else
{
// 添加新资源
var newResource = new MapResource
{
ResourceId = Guid.NewGuid(),
MapId = mapId,
ResourceCode = dto.ResourceCode,
ResourceName = dto.ResourceName,
Type = (MapResourcesTYPE)dto.Type,
Capacity = dto.Capacity,
MaxSpeed = dto.MaxSpeed,
CanRotate = dto.CanRotate,
LocationCoordinates = polygon,
// 设置四对动作属性
PreAction1Type = dto.PreAction1Type.HasValue ? (ActionType)dto.PreAction1Type.Value : null,
PreNetActions1 = dto.PreNetActions1?.Where(n => Guid.TryParse(n, out _)).Select(n => Guid.Parse(n)).ToList(),
PostAction1Type = dto.PostAction1Type.HasValue ? (ActionType)dto.PostAction1Type.Value : null,
PostNetActions1 = dto.PostNetActions1?.Where(n => Guid.TryParse(n, out _)).Select(n => Guid.Parse(n)).ToList(),
PreAction2Type = dto.PreAction2Type.HasValue ? (ActionType)dto.PreAction2Type.Value : null,
PreNetActions2 = dto.PreNetActions2?.Where(n => Guid.TryParse(n, out _)).Select(n => Guid.Parse(n)).ToList(),
PostAction2Type = dto.PostAction2Type.HasValue ? (ActionType)dto.PostAction2Type.Value : null,
PostNetActions2 = dto.PostNetActions2?.Where(n => Guid.TryParse(n, out _)).Select(n => Guid.Parse(n)).ToList(),
Active = dto.Active,
CreatedAt = DateTime.Now
};
await _mapResourceRepository.AddAsync(newResource, cancellationToken);
result.AddedCount++;
}
}
return result;
}
/// <summary>
/// 为节点同步储位(增量同步模式)
/// </summary>
/// <param name="node">地图节点</param>
/// <param name="cancellationToken">取消令牌</param>
/// <remarks>
/// @author zzy
/// 修改内容:储位改为增量同步,库区不更新
/// </remarks>
private async Task SynchronizeStorageLocationsForNodeAsync(MapNode node, CancellationToken cancellationToken)
{
// 如果节点不是储位类型或没有储位类型ID,删除所有关联的储位
if (node.Type != MapNodeTYPE.store || !node.StorageLocationTypeId.HasValue)
{
var delLocations = await _storageLocationRepository.GetByMapNodeIdAsync(node.NodeId, cancellationToken);
if (delLocations != null)
{
await _storageLocationRepository.DeleteRangeAsync(delLocations, cancellationToken);
_logger.LogInformation("删除节点 {NodeCode} 的储位", node.NodeCode);
}
return;
}
// 获取储位类型配置
var locationType = await _storageLocationTypeRepository.GetByIdAsync(node.StorageLocationTypeId.Value, cancellationToken);
if (locationType == null)
{
_logger.LogWarning("储位类型 {TypeId} 不存在,跳过储位同步", node.StorageLocationTypeId.Value);
return;
}
// 根据节点编码获取库区(仅获取,不更新库区)
var area = await _storageAreaRepository.GetByAreaCodeAsync(node.NodeCode, cancellationToken);
if (area == null)
{
_logger.LogWarning("节点 {NodeCode} 对应的库区不存在,无法同步储位", node.NodeCode);
return;
}
// 获取现有储位
var existingLocations = await _storageLocationRepository.GetByMapNodeIdAsync(node.NodeId, cancellationToken);
var existingLocationDict = existingLocations.ToDictionary(l => l.LocationCode);
// 生成目标储位列表
var targetLocations = new List<StorageLocation>();
int startNumber = locationType.LayerNumberStart;
for (int i = 0; i < locationType.LayerCount; i++)
{
var locationCode = $"{node.NodeCode}-{startNumber + i}";
targetLocations.Add(new StorageLocation
{
LocationId = Guid.NewGuid(),
AreaId = area.AreaId,
MapNodeId = node.NodeId,
LocationTypeId = locationType.TypeId,
LocationCode = locationCode,
LocationName = locationCode,
LayerNumber = i + 1,
Status = StorageLocationStatus.Empty,
CreatedAt = DateTime.Now
});
}
var targetLocationDict = targetLocations.ToDictionary(l => l.LocationCode);
// 1. 删除目标列表中不存在的储位
var locationsToDelete = existingLocations.Where(l => !targetLocationDict.ContainsKey(l.LocationCode)).ToList();
foreach (var location in locationsToDelete)
{
await _storageLocationRepository.DeleteAsync(location, cancellationToken);
_logger.LogInformation("删除储位 {LocationCode}", location.LocationCode);
}
// 2. 更新已存在的储位
foreach (var targetLocation in targetLocations)
{
if (existingLocationDict.TryGetValue(targetLocation.LocationCode, out var existingLocation))
{
// 更新现有储位(只更新可变更字段)
existingLocation.LocationName = targetLocation.LocationName;
existingLocation.LayerNumber = targetLocation.LayerNumber;
existingLocation.LocationTypeId = targetLocation.LocationTypeId;
existingLocation.AreaId = targetLocation.AreaId;
existingLocation.UpdatedAt = DateTime.Now;
await _storageLocationRepository.UpdateAsync(existingLocation, cancellationToken);
_logger.LogDebug("更新储位 {LocationCode}", targetLocation.LocationCode);
}
}
// 3. 添加新储位
var locationsToAdd = targetLocations.Where(l => !existingLocationDict.ContainsKey(l.LocationCode)).ToList();
if (locationsToAdd.Any())
{
await _storageLocationRepository.AddRangeAsync(locationsToAdd, cancellationToken);
foreach (var location in locationsToAdd)
{
_logger.LogInformation("新增储位 {LocationCode}", location.LocationCode);
}
}
_logger.LogInformation("储位同步完成 - 节点: {NodeCode}, 新增: {Added}, 更新: {Updated}, 删除: {Deleted}",
node.NodeCode, locationsToAdd.Count, targetLocations.Count - locationsToAdd.Count - locationsToDelete.Count, locationsToDelete.Count);
}
/// <summary>
/// 删除所有嵌套实体
/// </summary>
private async Task DeleteAllNestedEntitiesAsync(Guid mapId, CancellationToken cancellationToken)
{
// 删除资源
var resources = await _mapResourceRepository.GetByMapIdAsync(mapId, cancellationToken);
foreach (var resource in resources)
{
await _mapResourceRepository.DeleteAsync(resource, cancellationToken);
}
// 删除边
var edges = await _mapEdgeRepository.GetByMapIdAsync(mapId, cancellationToken);
foreach (var edge in edges)
{
await _mapEdgeRepository.DeleteAsync(edge, cancellationToken);
}
// 删除节点
var nodes = await _mapNodeRepository.GetByMapIdAsync(mapId, cancellationToken);
foreach (var node in nodes)
{
await _mapNodeRepository.DeleteAsync(node, cancellationToken);
}
_logger.LogInformation("删除地图的所有嵌套实体完成 - 地图ID: {MapId}", mapId);
}
}