Vda5050ProtocolService.cs 83.2 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 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114
using System;
using System.Linq;
using System.Text.Json;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Rcs.Application.Common;
using Rcs.Application.Services;
using Rcs.Application.Services.PathFind;
using Rcs.Application.Services.PathFind.Models;
using Rcs.Application.Services.Protocol;
using Rcs.Application.Shared;
using Rcs.Domain.Entities;
using Rcs.Domain.Enums;
using Rcs.Domain.Models.VDA5050;
using Rcs.Domain.Repositories;
using Rcs.Domain.Settings;
using Rcs.Domain.ValueObjects;
using Rcs.Infrastructure.PathFinding.Services;
using StackExchange.Redis;

namespace Rcs.Infrastructure.Services.Protocol;

/// <summary>
/// 通过MQTT与机器人通信
/// @author zzy
/// </summary>
public class Vda5050ProtocolService : IProtocolService
{
    private readonly ILogger<Vda5050ProtocolService> _logger;
    private readonly IMqttClientService _mqttClientService;
    private readonly IAgvPathService _agvPathService;
    private readonly IConnectionMultiplexer _redis;
    private readonly IRobotSubTaskRepository _subTaskRepository;
    private readonly IRobotTaskRepository _taskRepository;
    private readonly IRobotRepository _robotRepository;
    private readonly IUnifiedTrafficControlService  _unifiedTrafficControlService;
    private readonly ITaskTemplateRepository _taskTemplateRepository;
    private readonly INetActionPropertysRepository _netActionPropertysRepository;
    private readonly INetActionExecutionService _netActionExecutionService;
    private readonly AppSettings _settings;

    /// <summary>
    /// 需要进行切割的资源类型集合
    /// 排除: markedArea, waitingArea, other
    /// </summary>
    private static readonly HashSet<int> CuttingResourceTypes = new()
    {
        (int)MapResourcesTYPE.dock,
        (int)MapResourcesTYPE.charger,
        (int)MapResourcesTYPE.elevator,
        (int)MapResourcesTYPE.airlock,
        (int)MapResourcesTYPE.conveyor,
        (int)MapResourcesTYPE.storage
    };

    public Vda5050ProtocolService(
        ILogger<Vda5050ProtocolService> logger,
        IMqttClientService mqttClientService,
        IAgvPathService agvPathService,
        IConnectionMultiplexer redis,
        IRobotSubTaskRepository subTaskRepository,
        IRobotTaskRepository taskRepository,
        IRobotRepository robotRepository,
        IOptions<AppSettings> settings,
        IUnifiedTrafficControlService  unifiedTrafficControlService,
        ITaskTemplateRepository taskTemplateRepository,
        INetActionPropertysRepository netActionPropertysRepository,
        INetActionExecutionService netActionExecutionService)
    {
        _logger = logger;
        _mqttClientService = mqttClientService;
        _agvPathService = agvPathService;
        _redis = redis;
        _subTaskRepository = subTaskRepository;
        _taskRepository = taskRepository;
        _robotRepository = robotRepository;
        _settings = settings.Value;
        _unifiedTrafficControlService = unifiedTrafficControlService;
        _taskTemplateRepository = taskTemplateRepository;
        _netActionPropertysRepository = netActionPropertysRepository;
        _netActionExecutionService = netActionExecutionService;
    }

    /// <summary>
    /// 
    /// </summary>
    public ProtocolType ProtocolType => ProtocolType.VDA;

    /// <summary>
    /// 根据任务规划路径并发送VDA5050订单。
    /// </summary>
    /// <remarks>
    /// 流程:校验输入 -> 路径规划 -> 资源/路口分段 -> 缓存分段路径 -> 发送首段订单。
    /// </remarks>
    public async Task<ApiResponse> SendOrderAsync(Robot robot, RobotTask task, CancellationToken ct = default)
    {
        _logger.LogInformation("VDA5050 - 发送Order,机器人: {SerialNumber}, 订单: {OrderId}",
            robot.RobotSerialNumber, task.TaskCode);

        if (!robot.CurrentNodeId.HasValue)
        {
            return ApiResponse.Failed("VDA5050 - 机器人当前节点为空,无法规划路径");
        }

        var beginMapId = task.BeginLocation?.MapNode?.MapId;
        if (!beginMapId.HasValue)
        {
            return ApiResponse.Failed("VDA5050 - 起点地图未找到,无法规划路径");
        }

        if (!task.EndLocation?.MapNodeId.HasValue ?? true)
        {
            return ApiResponse.Failed("VDA5050 - 终点节点为空,无法规划路径");
        }
        // 获取当前执行或要执行的子任务
        var currentSubTask = task.SubTasks.OrderBy(s => s.Sequence).FirstOrDefault(st => st.Status == Rcs.Domain.Entities.TaskStatus.Pending || st.Status == Rcs.Domain.Entities.TaskStatus.Assigned);
        if (currentSubTask == null)
        {
            return ApiResponse.Failed("不存在待执行的子任务"); 
        }
        _logger.LogInformation("VDA5050 - 找到子任务: {SubTaskId}, 执行次数: {ExecutionCount}",
            currentSubTask.SubTaskId, currentSubTask.ExecutionCount);
        
        var mapId = beginMapId.Value;
        var forkAngleOffsetsRad = robot.ForkRadOffset;
        var requiredEndRad = currentSubTask.EndNode?.Theta;

        PathRequest request = new PathRequest
        {
            RobotId = robot.RobotId,
            MapId = mapId,
            StartNodeId = robot.CurrentNodeId.Value,
            EndNodeId = currentSubTask.EndNodeId,
            CurrentTheta = robot.CurrentTheta ?? 0,
            IsLoaded = !string.IsNullOrEmpty(task.ShelfCode),
            Priority = task.Priority,
            BatteryLevel = robot.BatteryLevel ?? 100,
            ForkRadOffsets = forkAngleOffsetsRad,
            RequiredEndRad = requiredEndRad
        };

        var pathResult = await _agvPathService.CalculatePathAsync(request, ct);
        if (!pathResult.Success)
        {
            return ApiResponse.Failed($"VDA5050 - 路径规划失败: {pathResult.ErrorMessage}");
        }

        var graph = await _agvPathService.GetOrBuildGraphAsync(mapId);
        if (graph == null)
        {
            return ApiResponse.Failed("VDA5050 - 地图图结构加载失败");
        }

        var segmentsWithCode = _agvPathService.EnrichSegmentsWithCode(pathResult.Segments, graph);

        // 获取任务模板步骤(用于模板切割)
        var taskStep = await GetTaskStepForSubTaskAsync(task.TaskTemplateId, currentSubTask.Sequence, ct);

        var segmentedPath = SplitSegmentsByBoundary(segmentsWithCode, graph, taskStep);
        if (segmentedPath.Count == 0)
        {
            return ApiResponse.Failed("VDA5050 - 路径分段失败");
        }

        // 检查并补充虚拟原地路径(用于支持 Apply 类型前置动作)
        EnsureVirtualSegmentForApplyActions(segmentedPath, taskStep, request,graph);

        // 将任务模板动作装载到对应的路径段(包括网络动作和资源网络动作)
        LoadActionsToSegments(segmentedPath, taskStep, graph);

        await SaveSegmentedPathAsync(robot, task, currentSubTask.SubTaskId, mapId, graph.MapCode, segmentedPath, ct);

        return await SendNextSegmentAsync(robot, currentSubTask, ct);

    }

    /// <summary>
    /// 取消指定订单(通过发送cancelOrder即时动作)
    /// </summary>
    public async Task CancelOrderAsync(Robot robot, string? orderId, CancellationToken ct = default)
    {
        _logger.LogInformation("VDA5050 - 取消订单,机器人: {SerialNumber}, 订单: {OrderId}",
            robot.RobotSerialNumber, orderId);

        var instantAction = CreateInstantAction(robot, "cancelOrder");
        await SendInstantActionAsync(robot, instantAction, ct);

        // 删除Redis中该任务的VDA路径缓存数据
        if (!string.IsNullOrEmpty(orderId))
        {
            await ClearVdaPathCacheAsync(robot.RobotId, orderId);
        }
    }

    /// <summary>
    /// 取消机器人所有任务
    /// @author zzy
    /// </summary>
    public async Task CancelRobotTasksAsync(Robot robot, CancellationToken ct = default)
    {
        _logger.LogInformation("VDA5050 - 取消所有任务,机器人 {SerialNumber}", robot.RobotSerialNumber);

        var instantAction = CreateInstantAction(robot, "cancelOrder");
        await SendInstantActionAsync(robot, instantAction, ct);

        // 删除Redis中该机器人所有任务的VDA路径缓存数据
        await ClearAllVdaPathCacheAsync(robot.RobotId);

        // 释放该机器人的所有路径锁
        var releasedLockCount = await _unifiedTrafficControlService.ReleaseAllRobotLocksAsync(robot.RobotId);

    }

    /// <summary>
    /// 发送即时动作指令   /// </summary>
    public async Task SendInstantActionAsync(Robot robot, InstantAction actions, CancellationToken ct = default)
    {
        _logger.LogInformation("VDA5050 - 发送InstantAction,机器人: {SerialNumber}, 动作数: {Count}",
            robot.RobotSerialNumber, actions.Actions.Count);

        var payload = JsonSerializer.Serialize(actions);
        await _mqttClientService.PublishInstantActionsAsync(
            robot.ProtocolName,
            robot.ProtocolVersion,
            robot.RobotManufacturer,
            robot.RobotSerialNumber,
            payload,
            ct: ct);
    }

    /// <summary>
    /// 复位机器人(通过发送stateRequest即时动作   /// </summary>
    public async Task ResetRobotAsync(Robot robot, CancellationToken ct = default)
    {
        _logger.LogInformation("VDA5050 - 复位机器人 {SerialNumber}", robot.RobotSerialNumber);

        var instantAction = CreateInstantAction(robot, "stateRequest");
        await SendInstantActionAsync(robot, instantAction, ct);
    }

    /// <summary>
    /// 
    /// </summary>
    public Task ConfirmExceptionAsync(Robot robot, CancellationToken ct = default)
    {
        _logger.LogInformation("VDA5050 - 不存在确认工况动作 {SerialNumber}", robot.RobotSerialNumber);
        return Task.CompletedTask;
    }

    /// <summary>
    /// 构建VDA5050订单基础结构(Header/基础字段/空节点与边列表)。
    /// </summary>
    private Domain.Models.VDA5050.Order BuildVdaOrder(Robot robot, RobotSubTask subTask)
    {
        var orderUpdateId = subTask?.ExecutionCount ?? 0;

        return new Domain.Models.VDA5050.Order
        {
            HeaderId = (int)(robot.HeaderId + 1),
            Timestamp = DateTime.Now.ToString("O"),
            Version = robot.ProtocolVersion,
            Manufacturer = robot.RobotManufacturer,
            SerialNumber = robot.RobotSerialNumber,
            ZoneSetId = robot.CurrentMapCodeId.ToString(),
            OrderId = subTask.SubTaskId.ToString(),
            OrderUpdateId = orderUpdateId,
            Nodes = new List<Node>(),
            Edges = new List<Edge>()
        };
    }
    /// <summary>
    /// 将路径段转换为VDA5050的Nodes与Edges并填充到订单中。
    /// </summary>
    private void FillOrderWithSegments(Domain.Models.VDA5050.Order order, List<PathSegmentWithCode> segments, PathGraph graph)
    {
        if (segments.Count == 0) return;

        // 使用图结构中的节点数据进行节点位置填充。
        var nodeLookup = graph.Nodes;
        var mapCode = !string.IsNullOrWhiteSpace(graph.MapCode)
            ? graph.MapCode
            : graph.MapId.ToString();

        var sequenceId = 0;
        var firstSeg = segments[0];
        order.Nodes.Add(BuildNode(firstSeg.FromNodeId, firstSeg.FromNodeCode, nodeLookup, mapCode, sequenceId));

        foreach (var seg in segments)
        {
            order.Edges.Add(BuildEdge(seg,  sequenceId + 1));
            sequenceId += 2;
            order.Nodes.Add(BuildNode(seg.ToNodeId, seg.ToNodeCode, nodeLookup, mapCode, sequenceId));
        }
    }

    /// <summary>
    /// 根据节点缓存构建VDA5050节点信息。
    /// 使用图结构的节点数据。
    /// </summary>
    private static Node BuildNode(Guid nodeId, string nodeCode, IReadOnlyDictionary<Guid, PathNode> lookup, string mapCode, int sequenceId)
    {
        var node = new Node
        {
            NodeId = string.IsNullOrEmpty(nodeCode) ? nodeId.ToString() : nodeCode,
            SequenceId = sequenceId,
            Released = true
        };

        if (lookup.TryGetValue(nodeId, out var pathNode))
        {
            node.NodePosition = new NodePosition
            {
                X = pathNode.X,
                Y = pathNode.Y,
                Theta = pathNode.Theta,
                MapId = mapCode,
                AllowedDeviationXY = pathNode.MaxCoordinateOffset ?? PositionConstants.AllowedDeviationPosition
            };
        }

        return node;
    }

    /// <summary>
    /// 根据路径段构建VDA5050边信息。
    /// </summary>
    private static Edge BuildEdge(PathSegmentWithCode seg, int sequenceId)
    {
        return new Edge()
        {
            EdgeId = string.IsNullOrEmpty(seg.EdgeCode) ? seg.EdgeId.ToString() : seg.EdgeCode,
            SequenceId = sequenceId,
            Released = true,
            StartNodeId = seg.FromNodeCode,
            EndNodeId = seg.ToNodeCode,
            MaxSpeed = seg.MaxSpeed,
            Length = seg.Length,
            Orientation = seg.Angle
        };
    }

    /// <summary>
    /// 缓存分段后的路径,供后续分段下发或恢复使用。
    /// @author zzy
    /// 2026-02-05 更新:支持两层切割结构
    /// </summary>
    private async Task SaveSegmentedPathAsync(
        Robot robot,
        RobotTask task,
        Guid subTaskId,
        Guid mapId,
        string? mapCode,
        List<List<List<PathSegmentWithCode>>> segmentedPath,
        CancellationToken ct)
    {
        var junctionSegments = segmentedPath
            .Select(junctionGroup => new VdaJunctionSegmentCache
            {
                ResourceSegments = junctionGroup.Select(resourceGroup => new VdaSegmentCacheItem
                {
                    Segments = resourceGroup
                }).ToList()
            })
            .ToList();

        var cache = new VdaSegmentedPathCache
        {
            TaskId = subTaskId,
            TaskCode = task.TaskCode,
            RobotId = robot.RobotId,
            MapId = mapId,
            MapCode = mapCode ?? string.Empty,
            CreatedAt = DateTime.Now,
            CurrentJunctionIndex = 0,
            CurrentResourceIndex = 0,
            JunctionSegments = junctionSegments
        };

        var key = $"{_settings.Redis.KeyPrefixes.VdaPath}:{robot.RobotId}:{task.TaskId}:{subTaskId}";
        var payload = JsonSerializer.Serialize(cache);
        await _redis.GetDatabase().StringSetAsync(key, payload);
    }


    /// <summary>
    /// 按两层结构切割路径:
    /// 第一层:路口切割(用于节点锁/路径锁管理)
    /// 第二层:资源边界和任务模板切割
    /// </summary>
    /// <remarks>
    /// 返回结构:List&lt;List&lt;List&lt;PathSegmentWithCode&gt;&gt;&gt;
    /// - 外层:路口切割后的段落(一级列表)
    /// - 中层:资源/模板切割后的子段落(二级列表)
    /// - 内层:路径片段列表
    ///
    /// 注意:任务模板切割节点基于**整个原始路径**的最后两个节点计算,
    /// 而不是每个切割后的子段的最后两个节点。
    ///
    /// 任务模板切割特殊规则:
    /// - 当存在任务模板切割需求时,最后一段必须独立成为一个二级列表
    /// - 不受路口吸收规则影响,确保动作装载位置正确
    ///
    /// @author zzy
    /// 2026-02-05 重构为两层切割架构
    /// 2026-02-07 更新:任务模板切割时最后一段必须独立成为二级列表
    /// </remarks>
    private List<List<List<PathSegmentWithCode>>> SplitSegmentsByBoundary(
        List<PathSegmentWithCode> segments,
        PathGraph graph,
        TaskStep? taskStep = null)
    {
        var result = new List<List<List<PathSegmentWithCode>>>();
        if (segments.Count == 0) return result;

        // 获取路口节点集合(用于路口吸收规则)
        var junctionNodes = GetJunctionNodes(graph);

        // 基于原始完整路径计算模板切割节点(整个路径的最后两个节点)
        var templateCutNodes = GetTemplateCutNodes(segments, taskStep);

        // 第一层:路口切割
        var junctionSegments = SplitByJunctions(segments, graph);

        // 第二层:对每个路口段进行资源/模板切割
        foreach (var junctionGroup in junctionSegments)
        {
            var resourceSegments = SplitByResourceAndTemplate(junctionGroup, graph, templateCutNodes, junctionNodes);
            result.Add(resourceSegments);
        }

        return result;
    }
    /// <summary>
    /// 第一层切割:按路口节点切割(用于节点锁/路径锁管理)
    /// 逻辑与之前实现完全一致
    /// </summary>
    /// <remarks>
    /// 路口节点:在图中相邻节点数 >= 3 的节点。
    /// 分段规则:
    ///   1. 路口的前一个节点作为上一段的终点和下一段的起点
    ///   2. 连续路口:在第一个路口的前一个节点处切割,后续连续路口不切割
    ///   3. 如果路口前没有点(路径起点就是路口),则该路口作为第一段起点
    /// 示例:A→B(路口)→C→D(路口)→E(路口)→F 分段为 [A→B→C], [C→D→E→F]
    /// @author zzy
    /// </remarks>
    private static List<List<PathSegmentWithCode>> SplitByJunctions(
        List<PathSegmentWithCode> segments,
        PathGraph graph)
    {
        var result = new List<List<PathSegmentWithCode>>();
        if (segments.Count == 0) return result;

        var junctionNodes = GetJunctionNodes(graph);
        bool IsJunction(Guid nodeId) => junctionNodes.Contains(nodeId);

        // 收集切割点索引(在哪些边之后进行切割)
        var cutIndices = new List<int>();
        int? lastJunctionEdgeIndex = null;

        for (var i = 0; i < segments.Count; i++)
        {
            var seg = segments[i];
            var isToJunction = IsJunction(seg.ToNodeId);

            if (isToJunction)
            {
                if (lastJunctionEdgeIndex.HasValue)
                {
                    // 这不是第一个路口,检查路口之间是否有普通节点
                    if (!IsJunction(seg.FromNodeId))
                    {
                        // 路口之间有普通节点,在该普通节点所在的边后切割
                        cutIndices.Add(i - 1);
                    }
                    // 如果是连续路口(FromNode也是路口),不切割,归入同一段
                }
                lastJunctionEdgeIndex = i;
            }
        }

        // 根据切割点分割路径
        var startIndex = 0;
        foreach (var cutIndex in cutIndices)
        {
            if (cutIndex >= startIndex && cutIndex < segments.Count)
            {
                var segmentLength = cutIndex - startIndex + 1;
                if (segmentLength > 0)
                {
                    result.Add(segments.Skip(startIndex).Take(segmentLength).ToList());
                }
                startIndex = cutIndex + 1;
            }
        }

        // 添加最后一段
        if (startIndex < segments.Count)
        {
            result.Add(segments.Skip(startIndex).ToList());
        }

        // 如果没有切割点,整段作为一个子段
        if (result.Count == 0)
        {
            result.Add(segments.ToList());
        }

        return result;
    }

    /// <summary>
    /// 第二层切割:按资源边界和任务模板步骤切割
    /// </summary>
    /// <remarks>
    /// 切割规则:
    /// - ActionType.Apply(申请):需要实际切割
    /// - ActionType.Notify(通知):不需要切割,仅挂载动作
    ///
    /// 资源边界判断:相邻节点的资源编码发生变化
    /// 模板切割节点:由调用者预先计算(基于整个原始路径)
    ///
    /// 路口吸收规则(仅适用于资源边界切割):
    /// - 当资源边界切割点是路口节点时,跳过切割
    /// - 路口节点由第一层切割处理,此处吸收到资源段中
    ///
    /// 任务模板切割规则(不受路口吸收规则影响):
    /// - 任务模板切割点必须独立切割,即使是路口节点也要切割
    /// - 确保最后一段(任务终点段)独立出来,用于动作装载
    ///
    /// @author zzy
    /// 2026-02-07 更新:任务模板切割不受路口吸收规则影响
    /// </remarks>
    private static List<List<PathSegmentWithCode>> SplitByResourceAndTemplate(
        List<PathSegmentWithCode> segments,
        PathGraph graph,
        HashSet<Guid> templateCutNodes,
        HashSet<Guid> junctionNodes)
    {
        var result = new List<List<PathSegmentWithCode>>();
        if (segments.Count == 0) return result;

        var resourceLookup = BuildNodeResourceLookup(graph);

        bool IsResourceBoundary(PathSegment seg)
        {
            var fromResources = resourceLookup.TryGetValue(seg.FromNodeId, out var fr) ? fr : new HashSet<string>();
            var toResources = resourceLookup.TryGetValue(seg.ToNodeId, out var tr) ? tr : new HashSet<string>();
            return !fromResources.SetEquals(toResources);
        }
        bool IsTemplateCutNode(Guid nodeId) => templateCutNodes.Contains(nodeId);
        bool IsJunction(Guid nodeId) => junctionNodes.Contains(nodeId);

        // 收集切割点索引
        var cutIndices = new List<int>();

        for (var i = 0; i < segments.Count; i++)
        {
            var seg = segments[i];
            var isResBoundary = IsResourceBoundary(seg);
            var isTemplateCut = IsTemplateCutNode(seg.ToNodeId);

            // 任务模板切割:不受路口吸收规则影响,必须独立切割
            if (isTemplateCut || isResBoundary)
            {
                // 路口吸收规则:如果切割点(ToNodeId)是路口,跳过切割
                // 路口已由第一层处理,此处吸收到资源段中
                if (IsJunction(seg.ToNodeId))
                {
                    continue;
                }
                cutIndices.Add(i);
            }
        }

        // 根据切割点分割路径
        var startIndex = 0;
        foreach (var cutIndex in cutIndices)
        {
            if (cutIndex >= startIndex && cutIndex < segments.Count)
            {
                var segmentLength = cutIndex - startIndex + 1;
                if (segmentLength > 0)
                {
                    result.Add(segments.Skip(startIndex).Take(segmentLength).ToList());
                }
                startIndex = cutIndex + 1;
            }
        }

        // 添加最后一段
        if (startIndex < segments.Count)
        {
            result.Add(segments.Skip(startIndex).ToList());
        }

        // 如果没有切割点,整段作为一个子段
        if (result.Count == 0)
        {
            result.Add(segments.ToList());
        }

        return result;
    }

    /// <summary>
    /// 根据任务步骤属性获取需要切割的节点ID集合
    /// Node = 终点 (最后一个segment的ToNodeId)
    /// PreNode = 终点前一个节点 (最后一个segment的FromNodeId)
    /// @author zzy
    /// </summary>
    private static HashSet<Guid> GetTemplateCutNodes(
        List<PathSegmentWithCode> segments,
        TaskStep? taskStep)
    {
        var cutNodes = new HashSet<Guid>();
        if (taskStep == null || segments.Count == 0) return cutNodes;

        // PreNode = 终点前一个节点 (最后一个segment的FromNodeId)
        var preNodeId = segments.Last().FromNodeId;

        foreach (var prop in taskStep.Properties)
        {
            // 检查是否有任一 ActionType 为 Apply(需要切割的类型)
            var hasApplyAction = prop.PreAction1Type == ActionType.Apply || 
                                 prop.PostAction1Type == ActionType.Apply ||
                                 prop.PreAction2Type == ActionType.Apply ||
                                 prop.PostAction2Type == ActionType.Apply;
            if (!hasApplyAction) continue;
            
            if (prop.PropertyType == StepPropertyType.PreNode)
                cutNodes.Add(preNodeId);
        }

        return cutNodes;
    }

    /// <summary>
    /// 根据子任务序号获取对应的任务模板步骤
    /// @author zzy
    /// </summary>
    private async Task<TaskStep?> GetTaskStepForSubTaskAsync(
        Guid? templateId,
        int sequence,
        CancellationToken ct)
    {
        if (!templateId.HasValue) return null;
        var template = await _taskTemplateRepository.GetWithFullDetailsAsync(templateId.Value, ct);
        return template?.TaskSteps?.OrderBy(s => s.Order).ElementAtOrDefault(sequence - 1);
    }

    /// <summary>
    /// 检查并补充虚拟原地路径,用于支持 Apply 类型前置动作
    ///
    /// 当路径太短导致"前一个二级列表"不存在时,在路径起点生成一段虚拟原地路径作为独立的二级列表
    ///
    /// 生成规则(基于二级列表数量判断):
    /// 1. 二级列表总数 == 1 且有 PreNode 类型属性包含 Apply 动作 → 生成虚拟路径
    /// 2. 二级列表总数 == 1 且 Node 类型属性有 Pre1(Apply) → 生成虚拟路径
    /// 3. 二级列表总数 == 2 且 PreNode 类型属性有 Pre1(Apply) → 生成虚拟路径
    ///
    /// 虚拟路径特征:
    /// - 作为独立的二级列表插入到第一个一级列表的开头
    /// - EdgeId = Guid.Empty(无实际边)
    /// - FromNodeId = ToNodeId = 起点节点ID
    /// - Length = 0
    ///
    /// @author zzy
    /// 2026-02-07 创建
    /// 2026-02-07 更新:虚拟路径作为独立二级列表插入
    /// </summary>
    private void EnsureVirtualSegmentForApplyActions(
        List<List<List<PathSegmentWithCode>>>? segmentedPath,
        TaskStep? taskStep,
        PathRequest request,
        PathGraph graph)
    {

        if (segmentedPath == null || segmentedPath.Count == 0)
        {
            segmentedPath = new List<List<List<PathSegmentWithCode>>>();
        }

        // 将二级列表展平为场景切割集合列表
        var flatSceneGroups = segmentedPath
            .SelectMany(junction => junction)
            .ToList();

        // 检查是否需要生成虚拟路径(基于二级列表数量)
        var needVirtualSegment = CheckNeedVirtualSegment(flatSceneGroups.Count, taskStep);

        if (!needVirtualSegment) return;
        if (graph.Nodes.TryGetValue(request.StartNodeId, out var startNode) && startNode != null)
        {
            // 创建虚拟原地路径段
            var virtualSegment = new PathSegmentWithCode
            {
                EdgeId = Guid.Empty,
                FromNodeId = request.StartNodeId,
                ToNodeId = request.StartNodeId,
                FromNodeCode = startNode.NodeCode,
                ToNodeCode = startNode.NodeCode,
                EdgeCode = string.Empty,
                Angle = 0,
                Length = 0,
                MaxSpeed = null
            };

            // 创建独立的二级列表,只包含虚拟路径段
            var virtualResourceGroup = new List<PathSegmentWithCode> { virtualSegment };

            // 将虚拟二级列表插入到第一个一级列表的开头
            segmentedPath[0].Insert(0, virtualResourceGroup);
        }
    }

    /// <summary>
    /// 检查是否需要生成虚拟路径
    ///
    /// 判断规则:
    /// 当二级列表总数 &lt;= 2 且 PreNode 类型属性存在任何 Apply 动作时,需要生成虚拟路径
    ///
    /// @author zzy
    /// 2026-02-07 创建
    /// 2026-02-07 更新:简化规则,二级列表总数 &lt;= 2 且 PreNode 有 Apply 动作即生成
    /// </summary>
    private static bool CheckNeedVirtualSegment(int totalResourceGroupCount, TaskStep? taskStep)
    {
        if (taskStep == null) return false;

        // 当二级列表总数 <= 2 时,检查 PreNode 是否存在 Apply 动作
        if (totalResourceGroupCount <= 2)
        {
                if (taskStep.Properties.Any(p => p.PreAction1Type == ActionType.Apply ||
                                                 p.PostAction1Type == ActionType.Apply ||
                                                 p.PreAction2Type == ActionType.Apply ||
                                                 p.PostAction2Type == ActionType.Apply))
                {
                    return true;
                }
        }

        return false;
    }

    /// <summary>
    /// 将动作装载到路径段,分两轮处理:
    /// 第一轮:Notify 动作(基于原子路径挂载)
    /// 第二轮:Apply 动作(基于场景切割集合挂载)
    ///
    /// 【Notify(消息通知)】- 不需要等待响应,挂载在切换场景时原子路径的起点/终点
    ///   - Pre(进入/离开前):切换场景时原子路径的起点 (StartNode)
    ///   - Post(进入/离开后):切换场景时原子路径的终点 (EndNode)
    ///
    /// 【Apply(动作申请)】- 需要等待响应,挂载在场景集合的边界位置
    ///   - Pre(进入/离开前):上一个场景集合最后一段路径的终点 (EndNode)
    ///   - Post(进入/离开后):切换场景时原子路径的终点 (EndNode)
    ///
    /// @author zzy
    /// 2026-02-09 重构:拆分为 Notify 轮 + Apply 轮,规则清晰、职责单一
    /// </summary>
    private void LoadActionsToSegments(
        List<List<List<PathSegmentWithCode>>> segmentedPath,
        TaskStep? taskStep,
        PathGraph graph)
    {
        if (segmentedPath.Count == 0) return;

        // 将三层结构展平为单层原子路径列表
        var flatSegments = segmentedPath
            .SelectMany(junction => junction.SelectMany(resource => resource))
            .ToList();

        if (flatSegments.Count == 0) return;

        // 将二级列表展平为场景切割集合列表
        var flatSceneGroups = segmentedPath
            .SelectMany(junction => junction)
            .ToList();

        // 第一轮:挂载所有 Notify 类型动作
        LoadNotifyActions(flatSegments, flatSceneGroups, taskStep, graph);

        // 第二轮:挂载所有 Apply 类型动作
        LoadApplyActions(flatSegments, flatSceneGroups, taskStep, graph);
    }

    // ==================== 第一轮:Notify 动作挂载 ====================

    /// <summary>
    /// 第一轮:挂载所有 Notify 类型动作
    /// 遍历每个场景切换边界,将 Notify 动作挂载到切换场景时原子路径的起点/终点
    ///
    /// Notify 规则:
    /// - Pre(进入/离开前):切换场景时原子路径的起点 (StartNode)
    /// - Post(进入/离开后):切换场景时原子路径的终点 (EndNode)
    ///
    /// @author zzy
    /// 2026-02-09 创建
    /// </summary>
    private void LoadNotifyActions(
        List<PathSegmentWithCode> flatSegments,
        List<List<PathSegmentWithCode>> flatSceneGroups,
        TaskStep? taskStep,
        PathGraph graph)
    {
        // 1. 资源边界 Notify 动作
        LoadResourceBoundaryNotifyActions(flatSegments, graph);

        // 2. 任务步骤 Notify 动作
        if (taskStep != null)
        {
            LoadTaskStepNotifyActions(flatSegments, flatSceneGroups, taskStep);
        }
    }

    /// <summary>
    /// 挂载资源边界 Notify 类型动作
    ///
    /// 当机器人跨越资源区域边界时:
    /// - 进入资源:ToNode在资源内,FromNode不在资源内
    ///   - Pre1(Notify) → 当前原子路径的起点 (StartNode)
    ///   - Post1(Notify) → 当前原子路径的终点 (EndNode)
    /// - 离开资源:FromNode在资源内,ToNode不在资源内
    ///   - Pre2(Notify) → 当前原子路径的起点 (StartNode)
    ///   - Post2(Notify) → 当前原子路径的终点 (EndNode)
    ///
    /// @author zzy
    /// 2026-02-09 创建:从 LoadResourceBoundaryNetActions 拆分
    /// </summary>
    private void LoadResourceBoundaryNotifyActions(
        List<PathSegmentWithCode> flatSegments,
        PathGraph graph)
    {
        if (flatSegments.Count == 0) return;

        // 建立资源编码到资源的映射
        var resourceByCode = graph.Resources
            .Where(r => CuttingResourceTypes.Contains(r.Type))
            .ToDictionary(r => r.ResourceCode, StringComparer.OrdinalIgnoreCase);

        // 构建节点到资源编码的查找表
        var resourceLookup = BuildNodeResourceLookup(graph);

        for (var i = 0; i < flatSegments.Count; i++)
        {
            var currentSeg = flatSegments[i];
            var fromResources = resourceLookup.TryGetValue(currentSeg.FromNodeId, out var fr) ? fr : new HashSet<string>();
            var toResources = resourceLookup.TryGetValue(currentSeg.ToNodeId, out var tr) ? tr : new HashSet<string>();

            // 检测进入资源(ToNode在资源内,FromNode不在)
            var enteringResources = toResources.Except(fromResources).ToList();
            foreach (var resCode in enteringResources)
            {
                if (resourceByCode.TryGetValue(resCode, out var resource))
                {
                    // Pre1(进入前):Notify → 当前原子路径的起点
                    if (HasNetActions(resource.PreNetActions1))
                    {
                        var type = resource.PreAction1Type ?? ActionType.None;
                        if (type == ActionType.Notify)
                        {
                            foreach (var actionId in resource.PreNetActions1!)
                            {
                                currentSeg.StartNodeNetActionTypes[actionId] = type;
                            }
                        }
                    }

                    // Post1(进入后):Notify → 当前原子路径的终点
                    if (HasNetActions(resource.PostNetActions1))
                    {
                        var type = resource.PostAction1Type ?? ActionType.None;
                        if (type == ActionType.Notify)
                        {
                            foreach (var actionId in resource.PostNetActions1!)
                            {
                                currentSeg.EndNodeNetActionTypes[actionId] = type;
                            }
                        }
                    }
                }
            }

            // 检测离开资源(FromNode在资源内,ToNode不在)
            var exitingResources = fromResources.Except(toResources).ToList();
            foreach (var resCode in exitingResources)
            {
                if (resourceByCode.TryGetValue(resCode, out var resource))
                {
                    // Pre2(离开前):Notify → 当前原子路径的起点
                    if (HasNetActions(resource.PreNetActions2))
                    {
                        var type = resource.PreAction2Type ?? ActionType.None;
                        if (type == ActionType.Notify)
                        {
                            foreach (var actionId in resource.PreNetActions2!)
                            {
                                currentSeg.StartNodeNetActionTypes[actionId] = type;
                            }
                        }
                    }

                    // Post2(离开后):Notify → 当前原子路径的终点
                    if (HasNetActions(resource.PostNetActions2))
                    {
                        var type = resource.PostAction2Type ?? ActionType.None;
                        if (type == ActionType.Notify)
                        {
                            foreach (var actionId in resource.PostNetActions2!)
                            {
                                currentSeg.EndNodeNetActionTypes[actionId] = type;
                            }
                        }
                    }
                }
            }
        }
    }

    /// <summary>
    /// 挂载任务步骤 Notify 类型动作
    ///
    /// Node(路径终点):只有"进入"动作
    ///   - 进入场景 = 最后一个场景切割集合
    ///   - 切换场景时原子路径 = 进入场景的第一条原子路径
    ///   - Pre1(Notify) → 切换原子路径的起点 (StartNode)
    ///   - Post1(Notify) → 切换原子路径的终点 (EndNode)
    ///
    /// PreNode(路径倒数第二个节点):有"进入"和"离开"两组动作
    ///   - 进入场景 = 倒数第二个场景切割集合
    ///   - 离开场景 = 最后一个场景切割集合
    ///   - 进入切换原子路径 = 进入场景的第一条原子路径
    ///   - 离开切换原子路径 = 离开场景的第一条原子路径
    ///
    /// @author zzy
    /// 2026-02-09 创建
    /// </summary>
    private void LoadTaskStepNotifyActions(
        List<PathSegmentWithCode> flatSegments,
        List<List<PathSegmentWithCode>> flatSceneGroups,
        TaskStep taskStep)
    {
        if (flatSegments.Count == 0 || flatSceneGroups.Count == 0) return;

        foreach (var prop in taskStep.Properties)
        {
            if (prop.PropertyType == StepPropertyType.Node)
            {
                LoadNodeNotifyActions(flatSceneGroups, prop);
            }
            else if (prop.PropertyType == StepPropertyType.PreNode)
            {
                LoadPreNodeNotifyActions(flatSegments, flatSceneGroups, prop);
            }
        }
    }

    /// <summary>
    /// 挂载 Node(路径终点)的 Notify 动作
    ///
    /// 切换场景时原子路径 = 最后一个场景切割集合的第一条原子路径
    /// - Pre1(Notify) → 切换原子路径的起点 (StartNode)
    /// - Post1(Notify) → 切换原子路径的终点 (EndNode)
    ///
    /// @author zzy
    /// 2026-02-09 创建
    /// </summary>
    private void LoadNodeNotifyActions(
        List<List<PathSegmentWithCode>> flatSceneGroups,
        StepProperty prop)
    {
        // 进入场景 = 最后一个场景切割集合
        var enterSceneGroup = flatSceneGroups[^1];
        // 切换场景时原子路径 = 进入场景的第一条原子路径
        var enterSegment = enterSceneGroup[0];

        // Pre1(进入前):Notify → 切换原子路径的起点
        if (HasNetActions(prop.PreNetActions1))
        {
            var type = prop.PreAction1Type ?? ActionType.None;
            if (type == ActionType.Notify)
            {
                foreach (var actionId in prop.PreNetActions1!)
                {
                    enterSegment.StartNodeNetActionTypes[actionId] = type;
                }
            }
        }

        // Post1(进入后):Notify → 切换原子路径的终点
        if (HasNetActions(prop.PostNetActions1))
        {
            var type = prop.PostAction1Type ?? ActionType.None;
            if (type == ActionType.Notify)
            {
                foreach (var actionId in prop.PostNetActions1!)
                {
                    enterSegment.EndNodeNetActionTypes[actionId] = type;
                }
            }
        }

        _logger.LogDebug("Node Notify动作装载完成,场景数: {SceneCount}, Pre1Type: {Pre1Type}, Post1Type: {Post1Type}",
            flatSceneGroups.Count, prop.PreAction1Type, prop.PostAction1Type);
    }

    /// <summary>
    /// 挂载 PreNode(路径倒数第二个节点)的 Notify 动作
    ///
    /// 进入切换原子路径 = 倒数第二个场景切割集合的第一条原子路径
    /// 离开切换原子路径 = 最后一个场景切割集合的第一条原子路径
    ///
    /// 进入动作:
    /// - Pre1(Notify) → 进入切换原子路径的起点 (StartNode)
    /// - Post1(Notify) → 进入切换原子路径的终点 (EndNode)
    ///
    /// 离开动作:
    /// - Pre2(Notify) → 离开切换原子路径的起点 (StartNode)
    /// - Post2(Notify) → 离开切换原子路径的终点 (EndNode)
    ///
    /// @author zzy
    /// 2026-02-09 创建
    /// </summary>
    private void LoadPreNodeNotifyActions(
        List<PathSegmentWithCode> flatSegments,
        List<List<PathSegmentWithCode>> flatSceneGroups,
        StepProperty prop)
    {
        if (flatSceneGroups.Count < 2 || flatSegments.Count < 2)
        {
            _logger.LogWarning("PreNode Notify动作装载失败:场景数或路径数不足,场景数: {SceneCount}, 路径数: {SegmentCount}",
                flatSceneGroups.Count, flatSegments.Count);
            return;
        }

        // 进入场景 = 倒数第二个场景切割集合
        var enterSceneGroup = flatSceneGroups[^2];
        // 离开场景 = 最后一个场景切割集合
        var exitSceneGroup = flatSceneGroups[^1];
        // 进入切换原子路径 = 进入场景的第一条原子路径
        var enterSegment = enterSceneGroup[0];
        // 离开切换原子路径 = 离开场景的第一条原子路径
        var exitSegment = exitSceneGroup[0];

        // ========== 进入动作(Pre1/Post1)==========

        // Pre1(进入前):Notify → 进入切换原子路径的起点
        if (HasNetActions(prop.PreNetActions1))
        {
            var type = prop.PreAction1Type ?? ActionType.None;
            if (type == ActionType.Notify)
            {
                foreach (var actionId in prop.PreNetActions1!)
                {
                    enterSegment.StartNodeNetActionTypes[actionId] = type;
                }
            }
        }

        // Post1(进入后):Notify → 进入切换原子路径的终点
        if (HasNetActions(prop.PostNetActions1))
        {
            var type = prop.PostAction1Type ?? ActionType.None;
            if (type == ActionType.Notify)
            {
                foreach (var actionId in prop.PostNetActions1!)
                {
                    enterSegment.EndNodeNetActionTypes[actionId] = type;
                }
            }
        }

        // ========== 离开动作(Pre2/Post2)==========

        // Pre2(离开前):Notify → 离开切换原子路径的起点
        if (HasNetActions(prop.PreNetActions2))
        {
            var type = prop.PreAction2Type ?? ActionType.None;
            if (type == ActionType.Notify)
            {
                foreach (var actionId in prop.PreNetActions2!)
                {
                    exitSegment.StartNodeNetActionTypes[actionId] = type;
                }
            }
        }

        // Post2(离开后):Notify → 离开切换原子路径的终点
        if (HasNetActions(prop.PostNetActions2))
        {
            var type = prop.PostAction2Type ?? ActionType.None;
            if (type == ActionType.Notify)
            {
                foreach (var actionId in prop.PostNetActions2!)
                {
                    exitSegment.EndNodeNetActionTypes[actionId] = type;
                }
            }
        }

        _logger.LogDebug("PreNode Notify动作装载完成,场景数: {SceneCount}, Pre1Type: {Pre1Type}, Post1Type: {Post1Type}, Pre2Type: {Pre2Type}, Post2Type: {Post2Type}",
            flatSceneGroups.Count, prop.PreAction1Type, prop.PostAction1Type, prop.PreAction2Type, prop.PostAction2Type);
    }

    /// <summary>
    /// 判断是否有网络动作配置
    /// </summary>
    private bool HasNetActions(List<Guid>? netActionIds)
    {
        return netActionIds != null && netActionIds.Count > 0;
    }

    // ==================== 第二轮:Apply 动作挂载 ====================

    /// <summary>
    /// 第二轮:挂载所有 Apply 类型动作
    /// 遍历每个场景切换边界,将 Apply 动作挂载到场景集合的边界位置
    ///
    /// Apply 规则:
    /// - Pre(进入/离开前):上一个场景集合最后一段路径的终点 (EndNode)
    /// - Post(进入/离开后):切换场景时原子路径的终点 (EndNode)
    ///
    /// @author zzy
    /// 2026-02-09 创建
    /// </summary>
    private void LoadApplyActions(
        List<PathSegmentWithCode> flatSegments,
        List<List<PathSegmentWithCode>> flatSceneGroups,
        TaskStep? taskStep,
        PathGraph graph)
    {
        // 1. 资源边界 Apply 动作
        LoadResourceBoundaryApplyActions(flatSegments, graph);

        // 2. 任务步骤 Apply 动作
        if (taskStep != null)
        {
            LoadTaskStepApplyActions(flatSegments, flatSceneGroups, taskStep);
        }
    }

    /// <summary>
    /// 挂载资源边界 Apply 类型动作
    ///
    /// 当机器人跨越资源区域边界时:
    /// - 进入资源:ToNode在资源内,FromNode不在资源内
    ///   - Pre1(Apply) → 前一条原子路径的终点 (seg[i-1].EndNode)
    ///   - Post1(Apply) → 当前原子路径的终点 (seg[i].EndNode)
    /// - 离开资源:FromNode在资源内,ToNode不在资源内
    ///   - Pre2(Apply) → 前一条原子路径的终点 (seg[i-1].EndNode)
    ///   - Post2(Apply) → 当前原子路径的终点 (seg[i].EndNode)
    ///
    /// @author zzy
    /// 2026-02-09 创建:从 LoadResourceBoundaryNetActions 拆分
    /// </summary>
    private void LoadResourceBoundaryApplyActions(
        List<PathSegmentWithCode> flatSegments,
        PathGraph graph)
    {
        if (flatSegments.Count == 0) return;

        // 建立资源编码到资源的映射
        var resourceByCode = graph.Resources
            .Where(r => CuttingResourceTypes.Contains(r.Type))
            .ToDictionary(r => r.ResourceCode, StringComparer.OrdinalIgnoreCase);

        // 构建节点到资源编码的查找表
        var resourceLookup = BuildNodeResourceLookup(graph);

        for (var i = 0; i < flatSegments.Count; i++)
        {
            var currentSeg = flatSegments[i];
            var fromResources = resourceLookup.TryGetValue(currentSeg.FromNodeId, out var fr) ? fr : new HashSet<string>();
            var toResources = resourceLookup.TryGetValue(currentSeg.ToNodeId, out var tr) ? tr : new HashSet<string>();
            var preSegment = i > 0 ? flatSegments[i - 1] : null;

            // 检测进入资源(ToNode在资源内,FromNode不在)
            var enteringResources = toResources.Except(fromResources).ToList();
            foreach (var resCode in enteringResources)
            {
                if (resourceByCode.TryGetValue(resCode, out var resource))
                {
                    // Pre1(进入前):Apply → 前一条原子路径的终点
                    if (HasNetActions(resource.PreNetActions1))
                    {
                        var type = resource.PreAction1Type ?? ActionType.None;
                        if (type == ActionType.Apply && preSegment != null)
                        {
                            foreach (var actionId in resource.PreNetActions1!)
                            {
                                preSegment.EndNodeNetActionTypes[actionId] = type;
                            }
                        }
                    }

                    // Post1(进入后):Apply → 当前原子路径的终点
                    if (HasNetActions(resource.PostNetActions1))
                    {
                        var type = resource.PostAction1Type ?? ActionType.None;
                        if (type == ActionType.Apply)
                        {
                            foreach (var actionId in resource.PostNetActions1!)
                            {
                                currentSeg.EndNodeNetActionTypes[actionId] = type;
                            }
                        }
                    }
                }
            }

            // 检测离开资源(FromNode在资源内,ToNode不在)
            var exitingResources = fromResources.Except(toResources).ToList();
            foreach (var resCode in exitingResources)
            {
                if (resourceByCode.TryGetValue(resCode, out var resource))
                {
                    // Pre2(离开前):Apply → 前一条原子路径的终点
                    if (HasNetActions(resource.PreNetActions2))
                    {
                        var type = resource.PreAction2Type ?? ActionType.None;
                        if (type == ActionType.Apply && preSegment != null)
                        {
                            foreach (var actionId in resource.PreNetActions2!)
                            {
                                preSegment.EndNodeNetActionTypes[actionId] = type;
                            }
                        }
                    }

                    // Post2(离开后):Apply → 当前原子路径的终点
                    if (HasNetActions(resource.PostNetActions2))
                    {
                        var type = resource.PostAction2Type ?? ActionType.None;
                        if (type == ActionType.Apply)
                        {
                            foreach (var actionId in resource.PostNetActions2!)
                            {
                                currentSeg.EndNodeNetActionTypes[actionId] = type;
                            }
                        }
                    }
                }
            }
        }
    }

    /// <summary>
    /// 挂载任务步骤 Apply 类型动作
    ///
    /// Node(路径终点):只有"进入"动作
    ///   - 进入场景 = 最后一个场景切割集合
    ///   - 前一个场景 = 倒数第二个场景切割集合
    ///   - Pre1(Apply) → 前一个场景最后一条原子路径的终点 (EndNode)
    ///   - Post1(Apply) → 进入场景第一条原子路径的终点 (EndNode)
    ///
    /// PreNode(路径倒数第二个节点):有"进入"和"离开"两组动作
    ///   - 进入前场景 = 倒数第三个场景切割集合
    ///   - 进入场景 = 倒数第二个场景切割集合
    ///   - 离开场景 = 最后一个场景切割集合
    ///   - Pre1(Apply) → 进入前场景最后一条原子路径的终点
    ///   - Post1(Apply) → 进入场景第一条原子路径的终点
    ///   - Pre2(Apply) → 进入场景最后一条原子路径的终点
    ///   - Post2(Apply) → 离开场景第一条原子路径的终点
    ///
    /// @author zzy
    /// 2026-02-09 创建
    /// </summary>
    private void LoadTaskStepApplyActions(
        List<PathSegmentWithCode> flatSegments,
        List<List<PathSegmentWithCode>> flatSceneGroups,
        TaskStep taskStep)
    {
        if (flatSegments.Count == 0 || flatSceneGroups.Count == 0) return;

        foreach (var prop in taskStep.Properties)
        {
            if (prop.PropertyType == StepPropertyType.Node)
            {
                LoadNodeApplyActions(flatSceneGroups, prop);
            }
            else if (prop.PropertyType == StepPropertyType.PreNode)
            {
                LoadPreNodeApplyActions(flatSegments, flatSceneGroups, prop);
            }
        }
    }

    /// <summary>
    /// 挂载 Node(路径终点)的 Apply 类型动作
    ///
    /// Node 只有"进入"动作(Pre1/Post1):
    /// - Pre1(Apply) → 前一个场景集合(倒数第二个)最后一条原子路径的终点
    /// - Post1(Apply) → 进入场景集合(最后一个)第一条原子路径的终点
    ///
    /// @author zzy
    /// 2026-02-09 创建
    /// </summary>
    private void LoadNodeApplyActions(
        List<List<PathSegmentWithCode>> flatSceneGroups,
        StepProperty prop)
    {
        // 进入场景 = 最后一个场景切割集合
        var enterSceneGroup = flatSceneGroups[^1];
        // 前一个场景 = 倒数第二个场景切割集合
        var prevSceneGroup = flatSceneGroups.Count >= 2 ? flatSceneGroups[^2] : null;

        // ========== Pre1(进入前):Apply → 前一个场景最后一条原子路径的终点 ==========
        if (HasNetActions(prop.PreNetActions1))
        {
            var type = prop.PreAction1Type ?? ActionType.None;
            if (type == ActionType.Apply && prevSceneGroup != null && prevSceneGroup.Count > 0)
            {
                var targetSegment = prevSceneGroup[^1];
                foreach (var actionId in prop.PreNetActions1!)
                {
                    targetSegment.EndNodeNetActionTypes[actionId] = type;
                }
            }
        }

        // ========== Post1(进入后):Apply → 进入场景第一条原子路径的终点 ==========
        if (HasNetActions(prop.PostNetActions1))
        {
            var type = prop.PostAction1Type ?? ActionType.None;
            if (type == ActionType.Apply && enterSceneGroup.Count > 0)
            {
                var targetSegment = enterSceneGroup[0];
                foreach (var actionId in prop.PostNetActions1!)
                {
                    targetSegment.EndNodeNetActionTypes[actionId] = type;
                }
            }
        }

        _logger.LogDebug("Node Apply动作装载完成,场景数: {SceneCount}, Pre1Type: {Pre1Type}, Post1Type: {Post1Type}",
            flatSceneGroups.Count, prop.PreAction1Type, prop.PostAction1Type);
    }

    /// <summary>
    /// 挂载 PreNode(路径倒数第二个节点)的 Apply 类型动作
    ///
    /// PreNode 有"进入"和"离开"两组动作:
    /// - Pre1(Apply) → 进入前场景(倒数第三个)最后一条原子路径的终点
    /// - Post1(Apply) → 进入场景(倒数第二个)第一条原子路径的终点
    /// - Pre2(Apply) → 进入场景(倒数第二个)最后一条原子路径的终点
    /// - Post2(Apply) → 离开场景(最后一个)第一条原子路径的终点
    ///
    /// @author zzy
    /// 2026-02-09 创建
    /// </summary>
    private void LoadPreNodeApplyActions(
        List<PathSegmentWithCode> flatSegments,
        List<List<PathSegmentWithCode>> flatSceneGroups,
        StepProperty prop)
    {
        if (flatSceneGroups.Count < 2 || flatSegments.Count < 2)
        {
            _logger.LogWarning("PreNode Apply动作装载失败:场景数或路径数不足,场景数: {SceneCount}, 路径数: {SegmentCount}",
                flatSceneGroups.Count, flatSegments.Count);
            return;
        }

        // 进入前场景 = 倒数第三个场景切割集合
        var preEnterSceneGroup = flatSceneGroups.Count >= 3 ? flatSceneGroups[^3] : null;
        // 进入场景 = 倒数第二个场景切割集合
        var enterSceneGroup = flatSceneGroups[^2];
        // 离开场景 = 最后一个场景切割集合
        var exitSceneGroup = flatSceneGroups[^1];

        // ========== 进入动作 ==========

        // Pre1(进入前):Apply → 进入前场景最后一条原子路径的终点
        if (HasNetActions(prop.PreNetActions1))
        {
            var type = prop.PreAction1Type ?? ActionType.None;
            if (type == ActionType.Apply && preEnterSceneGroup != null && preEnterSceneGroup.Count > 0)
            {
                var targetSegment = preEnterSceneGroup[^1];
                foreach (var actionId in prop.PreNetActions1!)
                {
                    targetSegment.EndNodeNetActionTypes[actionId] = type;
                }
            }
        }

        // Post1(进入后):Apply → 进入场景第一条原子路径的终点
        if (HasNetActions(prop.PostNetActions1))
        {
            var type = prop.PostAction1Type ?? ActionType.None;
            if (type == ActionType.Apply && enterSceneGroup.Count > 0)
            {
                var targetSegment = enterSceneGroup[0];
                foreach (var actionId in prop.PostNetActions1!)
                {
                    targetSegment.EndNodeNetActionTypes[actionId] = type;
                }
            }
        }

        // ========== 离开动作 ==========

        // Pre2(离开前):Apply → 进入场景最后一条原子路径的终点
        if (HasNetActions(prop.PreNetActions2))
        {
            var type = prop.PreAction2Type ?? ActionType.None;
            if (type == ActionType.Apply && enterSceneGroup.Count > 0)
            {
                var targetSegment = enterSceneGroup[^1];
                foreach (var actionId in prop.PreNetActions2!)
                {
                    targetSegment.EndNodeNetActionTypes[actionId] = type;
                }
            }
        }

        // Post2(离开后):Apply → 离开场景第一条原子路径的终点
        if (HasNetActions(prop.PostNetActions2))
        {
            var type = prop.PostAction2Type ?? ActionType.None;
            if (type == ActionType.Apply && exitSceneGroup.Count > 0)
            {
                var targetSegment = exitSceneGroup[0];
                foreach (var actionId in prop.PostNetActions2!)
                {
                    targetSegment.EndNodeNetActionTypes[actionId] = type;
                }
            }
        }

        _logger.LogDebug("PreNode Apply动作装载完成,场景数: {SceneCount}, Pre1Type: {Pre1Type}, Post1Type: {Post1Type}, Pre2Type: {Pre2Type}, Post2Type: {Post2Type}",
            flatSceneGroups.Count, prop.PreAction1Type, prop.PostAction1Type, prop.PreAction2Type, prop.PostAction2Type);
    }

    /// <summary>
    /// 根据图连通性识别路口节点(度数 >= 3)。
    /// </summary>
    private static HashSet<Guid> GetJunctionNodes(PathGraph graph)
    {
        var nodeNeighbors = new Dictionary<Guid, HashSet<Guid>>();
        var undirectedEdges = new HashSet<(Guid A, Guid B)>();

        foreach (var edge in graph.Edges.Values)
        {
            // 统计度数时将边视为无向边,逆向边只计一次。
            var a = edge.FromNodeId;
            var b = edge.ToNodeId;
            var key = a.CompareTo(b) <= 0 ? (a, b) : (b, a);
            if (!undirectedEdges.Add(key))
            {
                continue;
            }
            AddNeighbor(nodeNeighbors, edge.FromNodeId, edge.ToNodeId);
            AddNeighbor(nodeNeighbors, edge.ToNodeId, edge.FromNodeId);
        }

        return nodeNeighbors
            .Where(kv => kv.Value.Count >= 3)
            .Select(kv => kv.Key)
            .ToHashSet();
    }

    /// <summary>
    /// 为节点添加相邻关系,必要时初始化集合。
    /// </summary>
    private static void AddNeighbor(Dictionary<Guid, HashSet<Guid>> dict, Guid nodeId, Guid neighborId)
    {
        if (!dict.TryGetValue(nodeId, out var set))
        {
            set = new HashSet<Guid>();
            dict[nodeId] = set;
        }
        set.Add(neighborId);
    }

    /// <summary>
    /// 构建"节点 -> 资源编码集合"的查找表,用于资源边界判断。
    /// 使用几何点在多边形内判断来确定节点所属的资源区域。
    /// 节点可属于多个资源区域。
    /// @author zzy
    /// </summary>
    private static Dictionary<Guid, HashSet<string>> BuildNodeResourceLookup(PathGraph graph)
    {
        var lookup = new Dictionary<Guid, HashSet<string>>();
        
        // 过滤出需要进行切割判断的资源区域
        var cuttingResources = graph.Resources
            .Where(r => CuttingResourceTypes.Contains(r.Type) && r.LocationCoordinates != null && r.LocationCoordinates.Count >= 3)
            .ToList();
        
        foreach (var node in graph.Nodes.Values)
        {
            var resourceCodes = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
            
            foreach (var resource in cuttingResources)
            {
                if (IsPointInPolygon(node.X, node.Y, resource.LocationCoordinates!))
                {
                    resourceCodes.Add(resource.ResourceCode);
                }
            }
            
            if (resourceCodes.Count > 0)
            {
                lookup[node.NodeId] = resourceCodes;
            }
        }
        
        return lookup;
    }

    /// <summary>
    /// 判断点是否在多边形内(射线法)
    /// @author zzy
    /// </summary>
    /// <param name="x">点的X坐标</param>
    /// <param name="y">点的Y坐标</param>
    /// <param name="polygon">多边形顶点列表(按顺序组成封闭多边形)</param>
    /// <returns>点是否在多边形内</returns>
    private static bool IsPointInPolygon(double x, double y, List<PointCache> polygon)
    {
        if (polygon == null || polygon.Count < 3)
            return false;

        var inside = false;
        var j = polygon.Count - 1;

        for (var i = 0; i < polygon.Count; i++)
        {
            var xi = polygon[i].X;
            var yi = polygon[i].Y;
            var xj = polygon[j].X;
            var yj = polygon[j].Y;

            // 射线法:检查从点向右发出的水平射线与多边形边的交点数
            if (((yi > y) != (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi))
            {
                inside = !inside;
            }

            j = i;
        }

        return inside;
    }

    /// <summary>
    /// 创建即时动作消息
    /// </summary>
    private InstantAction CreateInstantAction(Robot robot, string actionType)
    {
        var action = new Domain.Models.VDA5050.Action
        {
            ActionId = Guid.NewGuid().ToString(),
            ActionType = actionType,
            BlockingType = "HARD"
        };

        return new InstantAction(
            (int)robot.HeaderId + 1,
            robot.ProtocolVersion,
            robot.RobotManufacturer,
            robot.RobotSerialNumber,
            new List<Domain.Models.VDA5050.Action> { action });
    }

    public Task RobotPauseAsync(Robot robot, CancellationToken ct = default)
    {
        throw new NotImplementedException();
    }

    public Task RobotUnPauseAsync(Robot robot, CancellationToken ct = default)
    {
        throw new NotImplementedException();
    }

    public async Task<ApiResponse> ReLocationAsync(Robot robot,string mapCode, double x, double y, double theta, CancellationToken ct = default)
    {
        return ApiResponse.Successful();
    }

    /// <summary>
    /// 发送下一段路径指令
    /// 从已缓存的分段路径中获取下一段并发送
    /// @author zzy
    /// 2026-02-05 更新:支持两层切割结构(路口段 + 资源段)
    /// 2026-02-06 更新:添加分布式锁防止并发重复发送
    /// </summary>
    /// <param name="robot">机器人实体</param>
    /// <param name="currentSubTask">子任务实体</param>
    /// <param name="ct">取消令牌</param>
    /// <param name="reExec">是否为重新执行</param>
    /// <returns>操作响应</returns>
    public async Task<ApiResponse> SendNextSegmentAsync(Robot robot, RobotSubTask currentSubTask, CancellationToken ct = default, bool reExec = false)
    {
        // 尝试获取分布式锁,防止并发重复发送
        var lockKey = $"send_segment_lock:{robot.RobotId}";
        var lockAcquired = await _redis.GetDatabase().StringSetAsync(
            lockKey, "1", TimeSpan.FromSeconds(10), When.NotExists);

        if (!lockAcquired)
        {
            _logger.LogInformation("[段发送] 其他进程正在发送路径段,跳过: RobotId={RobotId}", robot.RobotId);
            return ApiResponse.Failed("路径段发送正在进行中");
        }

        try
        {
            return await SendNextSegmentInternalAsync(robot, currentSubTask, ct, reExec);
        }
        finally
        {
            // 释放锁
            await _redis.GetDatabase().KeyDeleteAsync(lockKey);
        }
    }

    /// <summary>
    /// 发送下一段路径指令的内部实现(无锁版本,供 SendNextSegmentAsync 调用)
    /// @author zzy
    /// 2026-02-06 更新:添加网络动作执行检查
    /// </summary>
    private async Task<ApiResponse> SendNextSegmentInternalAsync(Robot robot, RobotSubTask currentSubTask, CancellationToken ct, bool reExec)
    {
        _logger.LogInformation("VDA5050 - 发送下一段路径,机器人: {SerialNumber}, 任务: {TaskCode}",
            robot.RobotSerialNumber, currentSubTask.SubTaskId);

        // 从 Redis 获取缓存的分段路径
        var key = $"{_settings.Redis.KeyPrefixes.VdaPath}:{robot.RobotId}:{currentSubTask.TaskId}:{currentSubTask.SubTaskId}";
        var cacheData = await _redis.GetDatabase().StringGetAsync(key);
        if (cacheData.IsNullOrEmpty)
        {
            return ApiResponse.Failed("VDA5050 - 未找到缓存的路径数据");
        }

        var cache = JsonSerializer.Deserialize<VdaSegmentedPathCache>(cacheData.ToString());
        if (cache == null)
        {
            return ApiResponse.Failed("VDA5050 - 路径缓存反序列化失败");
        }

        // 获取当前的两层索引
        var junctionIndex = cache.CurrentJunctionIndex;
        var resourceIndex = cache.CurrentResourceIndex;

        // 检查是否已完成所有段
        if (junctionIndex >= cache.JunctionSegments.Count && !reExec)
        {
            return ApiResponse.Failed("VDA5050 - 已是最后一段,无下一段路径可发送");
        }

        // 获取当前路口段
        var currentJunctionGroup = cache.JunctionSegments[junctionIndex];
        
        // 检查资源段索引是否有效
        if (resourceIndex >= currentJunctionGroup.ResourceSegments.Count && !reExec)
        {
            // 当前路口段的资源段已全部发送,移动到下一个路口段
            junctionIndex++;
            resourceIndex = 0;
            
            if (junctionIndex >= cache.JunctionSegments.Count)
            {
                return ApiResponse.Failed("VDA5050 - 已是最后一段,无下一段路径可发送");
            }
            currentJunctionGroup = cache.JunctionSegments[junctionIndex];
        }

        // 检查网络动作(仅在非reExec模式下检查)
        if (!reExec)
        {
            var netActionCheck = await CheckAndExecuteNetActionsAsync(robot, currentSubTask, cache, junctionIndex, resourceIndex);
            if (!netActionCheck.CanContinue)
            {
                return ApiResponse.Failed($"网络动作拦截: {netActionCheck.Message}");
            }
        }

        // 递增执行次数
        currentSubTask.ExecutionCount++;

        _logger.LogInformation("VDA5050 - 子任务: {SubTaskId}, 执行次数递增为: {ExecutionCount}, 路口段: {JunctionIndex}, 资源段: {ResourceIndex}",
            currentSubTask.SubTaskId, currentSubTask.ExecutionCount, junctionIndex, resourceIndex);

        // 获取下一段路径
        var nextSegment = currentJunctionGroup.ResourceSegments[resourceIndex].Segments;

        // 获取地图图结构(用于填充节点位置信息)
        var graph = await _agvPathService.GetOrBuildGraphAsync(cache.MapId);
        if (graph == null)
        {
            return ApiResponse.Failed("VDA5050 - 地图图结构加载失败");
        }

        // 锁定逻辑优化:
        // - 锁定单位:整个一级列表(路口切割后的段落)的所有路径和节点
        // - 发送一级列表的第一个二级列表时锁定整个一级列表
        // - 非第一个二级列表时跳过锁定(已锁定)
        if (resourceIndex == 0)
        {
            // 锁定整个一级列表的所有路径和节点
            var allJunctionSegments = currentJunctionGroup.ResourceSegments
                .SelectMany(r => r.Segments)
                .ToList();
            
            var lockResult = await _unifiedTrafficControlService.TryAcquireNextSegmentLockAsync(
                cache.MapCode,
                allJunctionSegments,
                robot.RobotId,
                30);
            
            if (!lockResult.Success)
            {
                _logger.LogInformation("路口段锁定失败,等待下次尝试: RobotId={RobotId}, Reason={Reason}",
                    robot.RobotId, lockResult.FailureReason ?? "未知原因");
                return ApiResponse.Failed($"路口段锁定失败: {lockResult.FailureReason ?? "未知原因"}");
            }

            // 检查是否存在逆向占用冲突
            if (lockResult.HasReverseConflict)
            {
                _logger.LogInformation("路口段存在逆向占用,暂停发送: RobotId={RobotId}", robot.RobotId);
                return ApiResponse.Failed("路口段存在逆向占用冲突,暂停发送");
            }
            
            _logger.LogInformation("VDA5050 - 锁定整个路口段成功,机器人: {RobotId}, 路口段: {JunctionIndex}, 锁定节点: {NodeCount}, 锁定边: {EdgeCount}",
                robot.RobotId, junctionIndex, lockResult.LockedNodeCodes.Count, lockResult.LockedEdgeCodes.Count);
        }
        else
        {
            // resourceIndex > 0:当前一级列表已锁定,跳过锁定请求
            _logger.LogDebug("VDA5050 - 当前路口段已锁定,跳过锁定请求,机器人: {RobotId}, 路口段: {JunctionIndex}, 资源段: {ResourceIndex}",
                robot.RobotId, junctionIndex, resourceIndex);
        }
        
        // 构建订单并填充下一段路径
        var order = BuildVdaOrder(robot, currentSubTask);
        FillOrderWithSegments(order, nextSegment, graph);

        // 发送订单
        var payload = JsonSerializer.Serialize(order);
        await _mqttClientService.PublishOrderAsync(
            robot.ProtocolName,
            robot.ProtocolVersion,
            robot.RobotManufacturer,
            robot.RobotSerialNumber,
            payload,
            ct: ct);

        // 更新缓存:标记当前段为已发送,更新索引
        currentJunctionGroup.ResourceSegments[resourceIndex].IsSent = true;
        
        if (!reExec)
        {
            // 移动到下一个资源段
            resourceIndex++;
            if (resourceIndex >= currentJunctionGroup.ResourceSegments.Count)
            {
                // 当前路口段完成,移动到下一个路口段
                junctionIndex++;
                resourceIndex = 0;
            }
        }
        
        cache.CurrentJunctionIndex = junctionIndex;
        cache.CurrentResourceIndex = resourceIndex;
        
        var updatedPayload = JsonSerializer.Serialize(cache);
        await _redis.GetDatabase().StringSetAsync(key, updatedPayload);

        // 显式更新子任务实体(解决引用同步问题)
        currentSubTask.Start();
        await _subTaskRepository.UpdateAsync(currentSubTask, ct);
        await _subTaskRepository.SaveChangesAsync(ct);

        _logger.LogInformation("VDA5050 - 下一段路径发送成功,机器人: {SerialNumber}, 路口段: {JunctionIndex}, 资源段: {ResourceIndex}",
            robot.RobotSerialNumber, cache.CurrentJunctionIndex, cache.CurrentResourceIndex);

        return ApiResponse.Successful();
    }

    public async Task<ApiResponse> SendNextSegmentAsync(string robotManufacturer, string robotSerialNumber, CancellationToken ct = default, bool reExec = false)
    {
        try
        {            
            var robot = await _robotRepository.GetByManufacturerAndSerialNumberAsync(robotManufacturer, robotSerialNumber, ct);
            if (robot == null)
                throw new Exception($"制造商:{robotManufacturer},序列号:{robotSerialNumber} 的机器人不存在");

            // 尝试获取分布式锁,防止并发重复发送
            var lockKey = $"send_segment_lock:{robot.RobotId}";
            var lockAcquired = await _redis.GetDatabase().StringSetAsync(
                lockKey, "1", TimeSpan.FromSeconds(10), When.NotExists);

            if (!lockAcquired)
            {
                _logger.LogInformation("[段发送] 其他进程正在发送路径段,跳过: RobotId={RobotId}", robot.RobotId);
                return ApiResponse.Failed("路径段发送正在进行中");
            }

            try
            {
                var tasks = await _taskRepository.GetByRobotIdAsync(robot.RobotId, ct);
                // 获取当前执行或要执行的子任务
                var currInProgressTask = tasks.FirstOrDefault(st => st.Status == Rcs.Domain.Entities.TaskStatus.InProgress);
                if (currInProgressTask != null)
                {
                    var currSubTask = currInProgressTask.SubTasks.OrderBy(st => st.Sequence).FirstOrDefault(st => st.Status == Rcs.Domain.Entities.TaskStatus.Pending
                            || st.Status == Rcs.Domain.Entities.TaskStatus.InProgress);
                    if (currSubTask == null)
                        throw new Exception($"任务号 {currInProgressTask.TaskCode} 不存在子任务");

                    return await SendNextSegmentInternalAsync(robot, currSubTask, ct, reExec);
                }
                
                var currPendingTask = tasks.FirstOrDefault(st => st.Status == Rcs.Domain.Entities.TaskStatus.Pending);
                if (currPendingTask != null)
                {
                    var currSubTask = currPendingTask.SubTasks.OrderBy(st => st.Sequence).FirstOrDefault(st => st.Status == Rcs.Domain.Entities.TaskStatus.Pending
                        || st.Status == Rcs.Domain.Entities.TaskStatus.InProgress);
                    if (currSubTask == null)
                        throw new Exception($"任务号 {currPendingTask.TaskCode} 不存在子任务");

                    return await SendNextSegmentInternalAsync(robot, currSubTask, ct, reExec);
                }

                throw new Exception($"机器人 {robot.RobotCode} 不存在执行中或待执行的任务");
            }
            finally
            {
                // 释放锁
                await _redis.GetDatabase().KeyDeleteAsync(lockKey);
            }
        }
        catch (Exception e)
        {
            return ApiResponse.Failed(e.Message);
        }
    }
    /// <summary>
    /// 删除指定任务的VDA路径缓存数据
    /// </summary>
    /// <param name="robotId">机器人ID</param>
    /// <param name="orderId">订单ID(任务编码)</param>
    private async Task ClearVdaPathCacheAsync(Guid robotId, string orderId)
    {
        try
        {
            var db = _redis.GetDatabase();

            // 尝试删除两种可能的Key格式
            // 格式1: {prefix}{robotId}:{taskId} (在SendNextSegmentAsync中使用)
            var key1 = $"{_settings.Redis.KeyPrefixes.VdaPath}:{robotId}:{orderId}";
            var deleted1 = await db.KeyDeleteAsync(key1);

            // 格式2: {prefix}{robotId}:{taskId}:{subTaskId} (在SaveSegmentedPathAsync中使用)
            // 使用KeyDeleteByPattern删除匹配模式的所有Key
            var pattern = $"{_settings.Redis.KeyPrefixes.VdaPath}:{robotId}:{orderId}:*";
            var deleted2 = await KeyDeleteByPatternAsync(pattern);

            // 将bool转换为数量进行统计
            var count1 = deleted1 ? 1 : 0;
            var totalDeleted = count1 + deleted2;
            _logger.LogInformation("VDA5050 - 删除VDA路径缓存,机器人: {RobotId}, 订单: {OrderId}, 删除数量: {Count}",
                robotId, orderId, totalDeleted);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "VDA5050 - 删除VDA路径缓存失败,机器人: {RobotId}, 订单: {OrderId}",
                robotId, orderId);
        }
    }

    /// <summary>
    /// 删除指定机器人所有任务的VDA路径缓存数据
    /// </summary>
    /// <param name="robotId">机器人ID</param>
    private async Task ClearAllVdaPathCacheAsync(Guid robotId)
    {
        try
        {
            var pattern = $"{_settings.Redis.KeyPrefixes.VdaPath}:{robotId}:*";
            var deletedCount = await KeyDeleteByPatternAsync(pattern);

            _logger.LogInformation("VDA5050 - 删除机器人所有VDA路径缓存,机器人: {RobotId}, 删除数量: {Count}",
                robotId, deletedCount);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "VDA5050 - 删除机器人所有VDA路径缓存失败,机器人: {RobotId}", robotId);
        }
    }

    /// <summary>
    /// 根据模式删除Redis Key
    /// </summary>
    /// <param name="pattern">Key匹配模式</param>
    /// <returns>删除的Key数量</returns>
    private async Task<int> KeyDeleteByPatternAsync(string pattern)
    {
        var server = _redis.GetServer(_redis.GetEndPoints().First());
        var keys = server.Keys(pattern: pattern).ToArray();

        if (keys.Length == 0)
        {
            return 0;
        }

        var db = _redis.GetDatabase();
        return (int)await db.KeyDeleteAsync(keys);
    }

    /// <summary>
    /// 检查并执行网络动作
    /// 在发送下一段路径之前调用,检查的是**上一个已发送段**的终点网络动作
    /// 核心逻辑:机器人到达当前段终点时,检查该终点是否有网络动作需要执行
    /// @author zzy
    /// 2026-02-06 创建
    /// 2026-02-07 修复:检查上一个已发送段的终点网络动作,而非即将发送段
    /// </summary>
    private async Task<SegmentNetActionCheckResult> CheckAndExecuteNetActionsAsync(
        Robot robot,
        RobotSubTask subTask,
        VdaSegmentedPathCache cache,
        int junctionIndex,
        int resourceIndex)
    {
        var result = new SegmentNetActionCheckResult
        {
            CanContinue = true
        };

        // 获取上一个已发送段的索引(机器人当前所在位置)
        var (prevJunctionIndex, prevResourceIndex) = GetPreviousSentSegmentIndex(cache, junctionIndex, resourceIndex);

        // 如果没有上一个已发送段(首次发送),直接返回可继续
        if (prevJunctionIndex < 0 || prevResourceIndex < 0)
        {
            return result;
        }

        // 检查索引有效性
        if (prevJunctionIndex >= cache.JunctionSegments.Count)
        {
            return result;
        }

        var junctionSegment = cache.JunctionSegments[prevJunctionIndex];
        if (prevResourceIndex >= junctionSegment.ResourceSegments.Count)
        {
            return result;
        }

        var resourceSegment = junctionSegment.ResourceSegments[prevResourceIndex];

        // 获取该段的终点网络动作ID列表(仅Apply类型)
        var netActionIds = resourceSegment.GetEndNodeNetActionIds();

        if (netActionIds.Count == 0)
        {
            // 没有网络动作,可以正常发送
            return result;
        }

        _logger.LogInformation("[网络动作检查] 发现{Count}个终点网络动作: RobotId={RobotId}, PrevJunctionIndex={PrevJunctionIndex}, PrevResourceIndex={PrevResourceIndex}",
            netActionIds.Count, robot.RobotId, prevJunctionIndex, prevResourceIndex);

        // 检查该段是否已经执行过网络动作
        if (resourceSegment.IsEndNodeNetActionExecuted)
        {
            _logger.LogDebug("[网络动作检查] 该段网络动作已执行过,继续发送: RobotId={RobotId}", robot.RobotId);
            return result;
        }

        // 检查是否有正在进行的网络动作
        var hasInProgress = await _netActionExecutionService.HasInProgressNetActionAsync(
            robot.RobotId, cache.TaskId, subTask.SubTaskId, prevJunctionIndex, prevResourceIndex);

        if (hasInProgress)
        {
            result.CanContinue = false;
            result.Message = "网络动作正在执行中";
            return result;
        }

        // 检查是否有等待异步响应的网络动作
        var hasWaitingAsync = await _netActionExecutionService.HasWaitingAsyncResponseAsync(
            robot.RobotId, cache.TaskId, subTask.SubTaskId);

        if (hasWaitingAsync)
        {
            result.CanContinue = false;
            result.IsWaitingAsync = true;
            result.Message = "等待异步响应中";
            return result;
        }

        // 获取任务信息用于构建执行请求
        var task = await _taskRepository.GetByIdAsync(subTask.TaskId);
        var taskCode = task?.TaskCode ?? subTask.TaskId.ToString();

        // 获取最后一段的终点节点信息
        var lastSegment = resourceSegment.Segments.LastOrDefault();
        if (lastSegment == null)
        {
            return result;
        }

        // 批量执行网络动作
        var executeRequests = new List<NetActionExecuteRequest>();
        foreach (var netActionId in netActionIds)
        {
            var contextId = $"{robot.RobotId}:{cache.TaskId}:{subTask.SubTaskId}:{prevJunctionIndex}:{prevResourceIndex}:{netActionId}:{Guid.NewGuid():N}";

            executeRequests.Add(new NetActionExecuteRequest
            {
                NetActionId = netActionId,
                ContextId = contextId,
                RobotId = robot.RobotId,
                RobotCode = robot.RobotCode,
                TaskId = cache.TaskId,
                TaskCode = taskCode,
                SubTaskId = subTask.SubTaskId,
                NodeCode = lastSegment.ToNodeCode,
                NodeId = lastSegment.ToNodeId
            });

            // 保存上下文ID到缓存
            resourceSegment.EndNodeNetActionContextIds.Add(contextId);
        }

        // 更新缓存状态
        var cacheKey = $"{_settings.Redis.KeyPrefixes.VdaPath}:{robot.RobotId}:{subTask.TaskId}:{subTask.SubTaskId}";
        cache.NetActionStatus = NetActionExecutionStatus.Executing;
        cache.ActiveNetActionContextId = resourceSegment.EndNodeNetActionContextIds.FirstOrDefault();
        await _redis.GetDatabase().StringSetAsync(cacheKey, JsonSerializer.Serialize(cache));

        // 执行网络动作
        var executeResult = await _netActionExecutionService.ExecuteNetActionsAsync(executeRequests);

        if (!executeResult.Success)
        {
            result.CanContinue = false;
            result.Message = $"网络动作执行失败: {executeResult.Message}";

            // 更新缓存状态为失败
            cache.NetActionStatus = NetActionExecutionStatus.Failed;
            await _redis.GetDatabase().StringSetAsync(cacheKey, JsonSerializer.Serialize(cache));

            return result;
        }

        // 如果是异步等待,设置等待状态
        if (executeResult.IsAsyncWaiting)
        {
            result.CanContinue = false;
            result.IsWaitingAsync = true;
            result.ContextId = executeResult.ContextId;
            result.Message = "网络动作请求已发送,等待异步回调";

            // 更新缓存状态为等待异步响应
            cache.NetActionStatus = NetActionExecutionStatus.WaitingAsyncResponse;
            await _redis.GetDatabase().StringSetAsync(cacheKey, JsonSerializer.Serialize(cache));

            return result;
        }

        // 网络动作执行成功,标记为已执行
        resourceSegment.IsEndNodeNetActionExecuted = true;

        // 更新缓存状态为成功
        cache.NetActionStatus = NetActionExecutionStatus.Success;
        cache.ActiveNetActionContextId = null;
        await _redis.GetDatabase().StringSetAsync(cacheKey, JsonSerializer.Serialize(cache));

        _logger.LogInformation("[网络动作检查] 网络动作执行成功,继续发送路径段: RobotId={RobotId}", robot.RobotId);

        return result;
    }

    /// <summary>
    /// 获取上一个已发送段的索引
    /// 用于确定机器人当前所在位置(已到达的段终点)
    /// @author zzy
    /// 2026-02-07
    /// </summary>
    /// <param name="cache">路径缓存</param>
    /// <param name="currentJunctionIndex">当前路口段索引</param>
    /// <param name="currentResourceIndex">当前资源段索引</param>
    /// <returns>上一个已发送段的索引,如果没有则返回(-1, -1)</returns>
    private static (int JunctionIndex, int ResourceIndex) GetPreviousSentSegmentIndex(
        VdaSegmentedPathCache cache,
        int currentJunctionIndex,
        int currentResourceIndex)
    {
        // 如果当前资源段索引大于0,上一段在同一路口段内
        if (currentResourceIndex > 0)
        {
            return (currentJunctionIndex, currentResourceIndex - 1);
        }

        // 如果当前资源段索引为0,需要查找上一个路口段的最后一个资源段
        if (currentJunctionIndex > 0)
        {
            var prevJunctionIndex = currentJunctionIndex - 1;
            var prevJunction = cache.JunctionSegments[prevJunctionIndex];
            var prevResourceIndex = prevJunction.ResourceSegments.Count - 1;
            return (prevJunctionIndex, prevResourceIndex);
        }

        // 没有上一段(首次发送)
        return (-1, -1);
    }
}