ManageMapEntitiesCommandHandler.cs 19.7 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
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;

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 IMapper _mapper;

    public ManageMapEntitiesCommandHandler(
        ILogger<ManageMapEntitiesCommandHandler> logger,
        IMapRepository mapRepository,
        IMapNodeRepository mapNodeRepository,
        IMapEdgeRepository mapEdgeRepository,
        IMapResourceRepository mapResourceRepository,
        IMapper mapper)
    {
        _logger = logger;
        _mapRepository = mapRepository;
        _mapNodeRepository = mapNodeRepository;
        _mapEdgeRepository = mapEdgeRepository;
        _mapResourceRepository = mapResourceRepository;
        _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);
        var resources = _mapper.Map<List<MapResource>>(command.MapResources);
        // 同步资源
        operationDetails.Resources = await SynchronizeResourcesAsync(mapId, resources, 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)
            {
                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)
        {
            await _mapNodeRepository.DeleteAsync(node, cancellationToken);
            result.DeletedCount++;
        }

        // 找出需要添加或更新的节点
        foreach (var targetNode in targetNodes)
        {
            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 = targetNode.Theta;
                existingNode.IsReverseParking = targetNode.IsReverseParking;
                existingNode.AllowRotate = targetNode.AllowRotate;
                existingNode.MaxCoordinateOffset = targetNode.MaxCoordinateOffset;
                existingNode.Type = (MapNodeTYPE)targetNode.Type;
                existingNode.Active = targetNode.Active;

                await _mapNodeRepository.UpdateAsync(existingNode, cancellationToken);
                result.UpdatedCount++;
                nodeMap[existingNode.NodeCode] = existingNode;
            }
            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 = targetNode.Theta,
                    IsReverseParking = targetNode.IsReverseParking,
                    AllowRotate = targetNode.AllowRotate,
                    MaxCoordinateOffset = targetNode.MaxCoordinateOffset,
                    Type = (MapNodeTYPE)targetNode.Type,
                    Active = targetNode.Active,
                    CreatedAt = DateTime.Now
                };

                await _mapNodeRepository.AddAsync(newNode, cancellationToken);
                result.AddedCount++;
                nodeMap[newNode.NodeCode] = newNode;
            }
        }

        _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.Regress = targetEdge.Regress;
                existingEdge.MaxCoordinateOffset = targetEdge.MaxCoordinateOffset;
                existingEdge.MaxAngleDeviation = 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,
                    Regress = targetEdge.Regress,
                    MaxCoordinateOffset = targetEdge.MaxCoordinateOffset,
                    MaxAngleDeviation = 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<MapResource>? targetResources, CancellationToken cancellationToken)
    {
        var result = new EntityOperationResult();

        // 获取现有资源
        var existingResources = (await _mapResourceRepository.GetByMapIdAsync(mapId, cancellationToken)).ToList();
        var existingResourceDict = existingResources.ToDictionary(r => r.ResourceCode);

        if (targetResources == null || targetResources.Count == 0)
        {
            // 删除所有现有资源
            foreach (var resource in existingResources)
            {
                await _mapResourceRepository.DeleteAsync(resource, cancellationToken);
                result.DeletedCount++;
            }
            return result;
        }

        var targetResourceDict = targetResources.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 targetResource in targetResources)
        {
            if (existingResourceDict.TryGetValue(targetResource.ResourceCode, out var existingResource))
            {
                // 更新现有资源
                existingResource.ResourceName = targetResource.ResourceName;

                existingResource.Type = targetResource.Type;
                
                existingResource.LocationCoordinates = targetResource.LocationCoordinates;
                existingResource.Active = targetResource.Active;

                await _mapResourceRepository.UpdateAsync(existingResource, cancellationToken);
                result.UpdatedCount++;
            }
            else
            {
                // 添加新资源
                var newResource = new MapResource
                {
                    ResourceId = Guid.NewGuid(),
                    MapId = mapId,
                    ResourceCode = targetResource.ResourceCode,
                    ResourceName = targetResource.ResourceName,
                    Type =  targetResource.Type,
                    LocationCoordinates = targetResource.LocationCoordinates,
                    Active = targetResource.Active,
                    CreatedAt = DateTime.Now
                };

                await _mapResourceRepository.AddAsync(newResource, cancellationToken);
                result.AddedCount++;
            }
        }

        return result;
    }

    /// <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);
    }
}