Vda5050ProtocolService.cs 206 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 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386
using System;
using System.Globalization;
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.PathFind.Realtime;
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
{
    /// <summary>
    /// 正常模式编码。
    /// </summary>
    private const string RouteModeNormal = RouteModeCodes.Normal;

    /// <summary>
    /// 等待模式编码。
    /// </summary>
    private const string RouteModeHold = RouteModeCodes.HoldingAtWaitNode;

    /// <summary>
    /// 排队模式编码。
    /// </summary>
    private const string RouteModeQueue = RouteModeCodes.QueueingForJunction;

    /// <summary>
    /// 占用路口模式编码。
    /// </summary>
    private const string RouteModeOccupying = RouteModeCodes.OccupyingJunction;

    /// <summary>
    /// 绕行模式编码。
    /// </summary>
    private const string RouteModeDetouring = RouteModeCodes.Detouring;

    /// <summary>
    /// 回归模式编码。
    /// </summary>
    private const string RouteModeRejoining = RouteModeCodes.Rejoining;

    /// <summary>
    /// 重规划待执行模式编码。
    /// </summary>
    private const string RouteModeReplanPending = RouteModeCodes.ReplanPending;

    /// <summary>
    /// 阻塞保护模式编码。
    /// </summary>
    private const string RouteModeBlocked = RouteModeCodes.Blocked;

    /// <summary>
    /// 订单首节点允许偏移量(米)。
    /// </summary>
    private const double FirstOrderNodeAllowedDeviationXY = 0.2;

    /// <summary>
    /// 单次下发路径的最小节点数限制(至少包含起点和终点)。
    /// </summary>
    private const int MinDispatchNodeCount = 2;

    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 IChargingPileRepository _chargingPileRepository;
    private readonly ITaskTemplateRepository _taskTemplateRepository;
    private readonly INetActionPropertysRepository _netActionPropertysRepository;
    private readonly INetActionExecutionService _netActionExecutionService;
    private readonly IActionConfigurationRepository _actionConfigurationRepository;
    private readonly IRobotCacheService _robotCacheService;

    /// <summary>
    /// 全局导航协调器。
    /// </summary>
    private readonly IGlobalNavigationCoordinator _globalNavigationCoordinator;

    /// <summary>
    /// 等待恢复调度器。
    /// </summary>
    private readonly IGlobalNavigationResumeScheduler _globalNavigationResumeScheduler;

    /// <summary>
    /// 尾段补丁应用器。
    /// </summary>
    private readonly ITailPatchApplier _tailPatchApplier;

    /// <summary>
    /// 应用配置监视器(用于动态刷新CAS参数)。
    /// </summary>
    private readonly IOptionsMonitor<AppSettings> _settingsMonitor;
    private readonly AppSettings _settings;

    /// <summary>
    /// 路径CAS运行配置快照。
    /// </summary>
    private GlobalPathCasSettings _pathCasSettings = new();

    /// <summary>
    /// CAS直接提交尝试次数。
    /// </summary>
    private long _pathCasDirectAttemptCount;

    /// <summary>
    /// CAS直接提交成功次数。
    /// </summary>
    private long _pathCasDirectSuccessCount;

    /// <summary>
    /// CAS直接提交冲突次数。
    /// </summary>
    private long _pathCasConflictCount;

    /// <summary>
    /// CAS回退提交尝试次数。
    /// </summary>
    private long _pathCasFallbackAttemptCount;

    /// <summary>
    /// CAS回退提交成功次数。
    /// </summary>
    private long _pathCasFallbackSuccessCount;

    /// <summary>
    /// CAS最终失败次数。
    /// </summary>
    private long _pathCasFailureCount;

    /// <summary>
    /// 上次输出CAS指标日志时间。
    /// </summary>
    private DateTime _lastPathCasMetricsLogUtc = DateTime.Now;

    /// <summary>
    /// CAS指标日志输出间隔。
    /// </summary>
    private TimeSpan _pathCasMetricsInterval;

    /// <summary>
    /// CAS窗口统计锁。
    /// </summary>
    private readonly object _pathCasWindowLock = new();

    /// <summary>
    /// CAS统计窗口起始时间。
    /// </summary>
    private DateTime _pathCasWindowStartedUtc = DateTime.Now;

    /// <summary>
    /// 当前窗口CAS尝试次数。
    /// </summary>
    private long _pathCasWindowAttemptCount;

    /// <summary>
    /// 当前窗口CAS冲突次数。
    /// </summary>
    private long _pathCasWindowConflictCount;

    /// <summary>
    /// 当前窗口CAS失败次数。
    /// </summary>
    private long _pathCasWindowFailureCount;

    /// <summary>
    /// CAS统计窗口时长。
    /// </summary>
    private TimeSpan _pathCasWindowDuration;

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

    /// <summary>
    /// 初始化 VDA5050 协议服务。
    /// </summary>
    public Vda5050ProtocolService(
        ILogger<Vda5050ProtocolService> logger,
        IMqttClientService mqttClientService,
        IAgvPathService agvPathService,
        IConnectionMultiplexer redis,
        IRobotSubTaskRepository subTaskRepository,
        IRobotTaskRepository taskRepository,
        IRobotRepository robotRepository,
        IChargingPileRepository chargingPileRepository,
        IOptionsMonitor<AppSettings> settings,
        ITaskTemplateRepository taskTemplateRepository,
        INetActionPropertysRepository netActionPropertysRepository,
        INetActionExecutionService netActionExecutionService,
        IActionConfigurationRepository actionConfigurationRepository,
        IRobotCacheService robotCacheService,
        IGlobalNavigationCoordinator globalNavigationCoordinator,
        IGlobalNavigationResumeScheduler globalNavigationResumeScheduler,
        ITailPatchApplier tailPatchApplier)
    {
        _logger = logger;
        _mqttClientService = mqttClientService;
        _agvPathService = agvPathService;
        _redis = redis;
        _subTaskRepository = subTaskRepository;
        _taskRepository = taskRepository;
        _robotRepository = robotRepository;
        _chargingPileRepository = chargingPileRepository;
        _settingsMonitor = settings;
        _settings = settings.CurrentValue;
        ApplyPathCasSettings(_settings);
        _taskTemplateRepository = taskTemplateRepository;
        _netActionPropertysRepository = netActionPropertysRepository;
        _netActionExecutionService = netActionExecutionService;
        _actionConfigurationRepository = actionConfigurationRepository;
        _robotCacheService = robotCacheService;
        _globalNavigationCoordinator = globalNavigationCoordinator;
        _globalNavigationResumeScheduler = globalNavigationResumeScheduler;
        _tailPatchApplier = tailPatchApplier;
    }

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

    /// <summary>
    /// 根据任务执行上下文做校验并准备发送订单参数。
    /// </summary>
    public async Task<ApiResponse> PrepareSendOrderAsync(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 currentSubTask = task.GetNextExecutableSubTask();
        if (currentSubTask == null)
        {
            return ApiResponse.Failed("不存在待执行的子任务"); 
        }

        var mapId = task.BeginLocation?.MapNode?.MapId
                    ?? currentSubTask.BeginNode?.MapId
                    ?? currentSubTask.EndNode?.MapId
                    ?? robot.CurrentMapCodeId;

        if (!mapId.HasValue)
        {
            return ApiResponse.Failed("VDA5050 - 起点地图未找到,无法规划路径");
        }

        if (currentSubTask.EndNodeId == Guid.Empty)
        {
            return ApiResponse.Failed("VDA5050 - 终点节点为空,无法规划路径");
        }

        _logger.LogInformation("VDA5050 - 找到子任务: {SubTaskId}, 执行次数: {ExecutionCount}",
            currentSubTask.SubTaskId, currentSubTask.ExecutionCount);

        return await SendOrderWithTaskContextAsync(
            robot,
            priority: task.Priority,
            endNodeId: currentSubTask.EndNodeId,
            containerId: task.ContainerID,
            taskId: task.TaskId,
            subTaskId: currentSubTask.SubTaskId,
            taskTemplateId: task.TaskTemplateId,
            subTaskSequence: currentSubTask.Sequence,
            taskCode: task.TaskCode,
            mapId: mapId.Value,
            ct: ct);
    }

    /// <summary>
    /// 直接发送VDA5050订单(无任务上下文)。
    /// </summary>
    public async Task<ApiResponse> SendOrderAsync(
        Robot robot,
        int priority,
        Guid endNodeId,
        string? containerId,
        CancellationToken ct = default)
    {
        return await SendOrderWithTaskContextAsync(
            robot,
            priority,
            endNodeId,
            containerId,
            taskId: null,
            subTaskId: null,
            taskTemplateId: null,
            subTaskSequence: null,
            taskCode: null,
            mapId: robot.CurrentMapCodeId,
            ct: ct);
    }

    /// <summary>
    /// 基于任务上下文发送VDA5050订单(支持仅传递上下文ID,ID可为空)。
    /// </summary>
    public async Task<ApiResponse> SendOrderWithTaskContextAsync(
        Robot robot,
        int priority,
        Guid endNodeId,
        string? containerId,
        Guid? taskId = null,
        Guid? subTaskId = null,
        Guid? taskTemplateId = null,
        int? subTaskSequence = null,
        string? taskCode = null,
        Guid? mapId = null,
        CancellationToken ct = default)
    {
        if (!robot.CurrentNodeId.HasValue)
        {
            return ApiResponse.Failed("VDA5050 - 机器人当前节点为空,无法规划路径");
        }

        if (endNodeId == Guid.Empty)
        {
            return ApiResponse.Failed("VDA5050 - 终点节点为空,无法规划路径");
        }

        var resolvedMapId = mapId ?? robot.CurrentMapCodeId;
        if (!resolvedMapId.HasValue)
        {
            return ApiResponse.Failed("VDA5050 - 机器人当前地图为空,无法规划路径");
        }

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

        if (!graph.Nodes.TryGetValue(endNodeId, out var endNode))
        {
            return ApiResponse.Failed("VDA5050 - 终点节点不在当前地图中,无法规划路径");
        }

        PathRequest request = new PathRequest
        {
            RobotId = robot.RobotId,
            MapId = resolvedMapId.Value,
            StartNodeId = robot.CurrentNodeId.Value,
            EndNodeId = endNodeId,
            CurrentTheta = robot.CurrentTheta ?? 0,
            IsLoaded = !string.IsNullOrWhiteSpace(containerId),
            Priority = priority,
            BatteryLevel = robot.BatteryLevel ?? 100,
            MovementType = robot.MovementType,
            ForkRadOffsets = robot.ForkRadOffset,
            RequiredEndRad = endNode.Theta
        };

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

        var segmentsWithCode = _agvPathService.EnrichSegmentsWithCode(pathResult.Segments, graph);
        if (segmentsWithCode.Count == 0)
        {
            return ApiResponse.Failed("VDA5050 - 路径为空,无法发送订单");
        }

        var resolvedTaskId = taskId.HasValue && taskId.Value != Guid.Empty
            ? taskId.Value
            : Guid.NewGuid();
        var resolvedSubTaskId = subTaskId.HasValue && subTaskId.Value != Guid.Empty
            ? subTaskId.Value
            : Guid.NewGuid();
        var resolvedSubTaskSequence = subTaskSequence.GetValueOrDefault(1);
        if (resolvedSubTaskSequence <= 0)
        {
            resolvedSubTaskSequence = 1;
        }

        var resolvedTaskCode = string.IsNullOrWhiteSpace(taskCode)
            ? resolvedSubTaskId.ToString()
            : taskCode.Trim();

        var dispatchSubTask = CreateDispatchSubTask(
            robot,
            resolvedTaskId,
            resolvedSubTaskId,
            endNodeId,
            resolvedSubTaskSequence);

        // 获取任务模板步骤(用于动作装载)
        var taskStep = await GetTaskStepForSubTaskAsync(taskTemplateId, resolvedSubTaskSequence, ct);
        var terminalActionContext = await ResolveTerminalLocationActionContextAsync(
            resolvedSubTaskId,
            resolvedSubTaskSequence,
            ct);

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

        // 检查并补充虚拟原地路径(用于支持 Apply 类型前置动作)
        if (!EnsureVirtualSegmentForApplyActions(segmentedPath, request, graph, terminalActionContext))
        {
            // 具体失败原因会在 EnsureVirtualSegmentForApplyActions 内记录告警日志。
            return ApiResponse.Failed("VDA5050 - 补充虚拟路径失败");
        }

        // 将任务模板动作装载到对应的路径段(包括网络动作和资源网络动作)
        if (!await LoadActionsToSegmentsAsync(
                segmentedPath,
                taskStep,
                graph,
                robot,
                addStopChargingActionAtStart: robot.Charging,
                terminalActionContext: terminalActionContext))
        {
            return ApiResponse.Failed("VDA5050 - 动作装载失败");
        }

        if (!await SaveSegmentedPathAsync(
                robot,
                resolvedTaskId,
                resolvedTaskCode,
                resolvedSubTaskId,
                resolvedMapId.Value,
                graph.MapCode,
                segmentedPath,
                graph,
                ct))
        {
            return ApiResponse.Failed("VDA5050 - 路径缓存保存失败");
        }
        
        return await SendNextSegmentAsync(robot, dispatchSubTask, ct);

    }

    /// <summary>
    /// 基于上下文ID构建一次下发所需的临时子任务对象(可用于未落库场景)。
    /// </summary>
    private static RobotSubTask CreateDispatchSubTask(
        Robot robot,
        Guid taskId,
        Guid subTaskId,
        Guid endNodeId,
        int sequence)
    {
        return new RobotSubTask
        {
            SubTaskId = subTaskId,
            TaskId = taskId,
            RobotId = robot.RobotId,
            BeginNodeId = robot.CurrentNodeId ?? Guid.Empty,
            EndNodeId = endNodeId,
            Sequence = sequence,
            Status = Rcs.Domain.Entities.TaskStatus.Pending,
            ExecutionCount = 0,
            CreatedAt = DateTime.Now,
            UpdatedAt = DateTime.Now
        };
    }

    /// <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);
        // 清理缓存中的Path路径数据
        await _robotCacheService.SetLocationValueAsync(
            robot.RobotManufacturer, robot.RobotSerialNumber, "Path", "");
        // 释放该机器人的所有路径锁
        await _agvPathService.ReleaseAllLocksAsync(robot.RobotId);

        await Task.Delay(TimeSpan.FromSeconds(2), ct); // 等待2秒,确保机器人收到取消指令并处理

    }

    /// <summary>
    /// 发送即时动作指令,发送后递增持久化 HeaderId
    /// @author zzy
    /// 2026-02-11 更新:发送后持久化 HeaderId
    /// </summary>
    public async Task SendInstantActionAsync(Robot robot, InstantAction actions, CancellationToken ct = default)
    {
        await _mqttClientService.PublishInstantActionsAsync(
            robot.ProtocolName,
            robot.ProtocolVersion,
            robot.RobotManufacturer,
            robot.RobotSerialNumber,
            actions,
            ct: ct);

        // 持久化递增后的 HeaderId
        await _robotRepository.UpdateAsync(robot, ct);
        await _robotRepository.SaveChangesAsync(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;
    }

    public async Task<ApiResponse> StartChargingAsync(Robot robot, string actionName, CancellationToken ct = default)
    {
        var finalActionName = string.IsNullOrWhiteSpace(actionName) ? "startCharging" : actionName.Trim();
        _logger.LogInformation(
            "VDA5050 - 发送开始充电即时动作。机器人={SerialNumber}, 动作={ActionName}",
            robot.RobotSerialNumber,
            finalActionName);

        var instantAction = CreateInstantAction(robot, finalActionName);
        await SendInstantActionAsync(robot, instantAction, ct);
        return ApiResponse.Successful();
    }

    public async Task<ApiResponse> StopChargingAsync(Robot robot, CancellationToken ct = default)
    {
        const string stopChargingActionName = "stopCharging";
        _logger.LogInformation(
            "VDA5050 - 发送停止充电即时动作。机器人={SerialNumber}, 动作={ActionName}",
            robot.RobotSerialNumber,
            stopChargingActionName);

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

        var chargingPile = await _chargingPileRepository.FirstOrDefaultAsync(
            p => p.CurrentChargingRobotId.HasValue && p.CurrentChargingRobotId.Value == robot.RobotId,
            ct);

        if (chargingPile == null)
        {
            _logger.LogDebug(
                "VDA5050 - 停止充电后未找到已绑定的充电桩。机器人={RobotCode}",
                robot.RobotCode);
            return ApiResponse.Successful();
        }

        chargingPile.CurrentChargingRobotId = null;
        chargingPile.UpdatedAt = DateTime.Now;

        await _chargingPileRepository.UpdateAsync(chargingPile, ct);
        await _chargingPileRepository.SaveChangesAsync(ct);

        _logger.LogInformation(
            "VDA5050 - 停止充电成功后已解绑充电桩。机器人={RobotCode}, 充电桩={PileCode}",
            robot.RobotCode,
            chargingPile.PileCode);

        return ApiResponse.Successful();
    }

    /// <summary>
    /// 构建VDA5050订单基础结构(Header/基础字段/空节点与边列表)。
    /// 每次构建时递增 robot.HeaderId
    /// @author zzy
    /// 2026-02-11 更新:递增 HeaderId
    /// </summary>
    private Domain.Models.VDA5050.Order BuildVdaOrder(Robot robot, RobotSubTask subTask)
    {
        var orderUpdateId = subTask?.ExecutionCount ?? 0;
        robot.HeaderId++;

        return new Domain.Models.VDA5050.Order
        {
            HeaderId = (int)robot.HeaderId,
            Timestamp = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss.fffzzz"),
            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并填充到订单中。
    /// @author zzy
    /// 2026-02-09 更新:改为异步方法,查询数据库获取动作参数
    /// 2026-02-25 更新:增加 startSequenceId 参数,支持分段发送时延续已发送的 sequenceId
    /// </summary>
    /// <param name="order">待填充的VDA5050订单</param>
    /// <param name="segments">路径段列表</param>
    /// <param name="graph">地图图结构</param>
    /// <param name="robot">机器人实体</param>
    /// <param name="subTask">子任务实体</param>
    /// <param name="startSequenceId">起始 sequenceId,后续段需延续上一次发送的值</param>
    /// <param name="ct">取消令牌</param>
    /// <param name="temporaryNextSegment">临时追加的下一段首条路径(仅用于Released=false预告)</param>
    /// <returns>本次填充后的最大 sequenceId</returns>
    private async Task<int> FillOrderWithSegmentsAsync(
        Domain.Models.VDA5050.Order order,
        List<PathSegmentWithCode> segments,
        PathGraph graph,
        Robot robot,
        RobotSubTask subTask,
        int startSequenceId = 0,
        CancellationToken ct = default,
        PathSegmentWithCode? temporaryNextSegment = null)
    {
        if (segments.Count == 0) return startSequenceId;

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

        // 构建上下文对象,用于参数解析
        var context = new ParameterResolveContext
        {
            Robot = robot,
            SubTask = subTask
        };

        var sequenceId = startSequenceId;
        var firstSeg = segments[0];

        // 构建第一个节点,填充第一个segment的StartNodeActions
        var firstNode = BuildNode(firstSeg.FromNodeId, firstSeg.FromNodeCode, nodeLookup, mapCode, sequenceId, robot.CoordinateScale, firstSeg.StartTheta);
        if (firstNode.NodePosition != null && order.OrderUpdateId == 0)
        {
            firstNode.NodePosition.AllowedDeviationXY = FirstOrderNodeAllowedDeviationXY;
        }

        if (firstSeg.StartNodeActions.Count > 0)
        {
            firstNode.Actions = await ConvertStepActionsToVdaActionsAsync(firstSeg.StartNodeActions, context, ct);
        }
        order.Nodes.Add(firstNode);

        foreach (var seg in segments)
        {
            var edgeSequenceId = sequenceId + 1;
            var nodeSequenceId = sequenceId + 2;

            var startNodeCode = seg.FromNodeCode;
            string? edgeCodeOverride = null;

            if (string.Equals(seg.FromNodeCode, seg.ToNodeCode, StringComparison.Ordinal))
            {
                startNodeCode = AppendTempSuffix(seg.FromNodeCode);
                edgeCodeOverride = string.IsNullOrEmpty(seg.EdgeCode)
                    ? string.Concat(startNodeCode, seg.ToNodeCode)
                    : seg.EdgeCode;

                if (order.Nodes.Count > 0 && string.Equals(order.Nodes[^1].NodeId, seg.FromNodeCode, StringComparison.Ordinal))
                {
                    order.Nodes[^1].NodeId = startNodeCode;
                }
            }

            graph.Edges.TryGetValue(seg.EdgeId, out var graphEdge);
            var edge = BuildEdge(
                seg,
                edgeSequenceId,
                graphEdge,
                robot.CoordinateScale,
                startNodeCode,
                edgeCodeOverride);
            var node = BuildNode(seg.ToNodeId, seg.ToNodeCode, nodeLookup, mapCode, nodeSequenceId, robot.CoordinateScale, seg.EndTheta);

            if (seg.EndNodeActions.Count > 0)
            {
                node.Actions = await ConvertStepActionsToVdaActionsAsync(seg.EndNodeActions, context, ct);
            }
            order.Edges.Add(edge);
            order.Nodes.Add(node);
            sequenceId = nodeSequenceId;
        }

        // 临时预告下一个节点路径:仅追加一条边和终点节点,Released=false,不影响已发送序列号延续。
        if (temporaryNextSegment != null)
        {
            var tempEdgeSequenceId = sequenceId + 1;
            var tempNodeSequenceId = sequenceId + 2;

            graph.Edges.TryGetValue(temporaryNextSegment.EdgeId, out var tempGraphEdge);
            var tempEdge = BuildEdge(
                temporaryNextSegment,
                tempEdgeSequenceId,
                tempGraphEdge,
                robot.CoordinateScale);
            var tempNode = BuildNode(
                temporaryNextSegment.ToNodeId,
                temporaryNextSegment.ToNodeCode,
                nodeLookup,
                mapCode,
                tempNodeSequenceId,
                robot.CoordinateScale,
                temporaryNextSegment.EndTheta);

            tempEdge.Released = false;
            tempNode.Released = false;

            order.Edges.Add(tempEdge);
            order.Nodes.Add(tempNode);
        }

        return sequenceId;
    }

    /// <summary>
    /// 为编码追加临时后缀,避免与正式编码冲突。
    /// </summary>
    private static string AppendTempSuffix(string code)
    {
        if (string.IsNullOrEmpty(code))
        {
            return code;
        }

        return code.EndsWith("-temp", StringComparison.Ordinal)
            ? code
            : string.Concat(code, "-temp");
    }

    /// <summary>
    /// 参数解析上下文
    /// @author zzy
    /// 2026-02-09 创建
    /// </summary>
    private class ParameterResolveContext
    {
        public Robot Robot { get; set; } = null!;
        public RobotSubTask SubTask { get; set; } = null!;
        public VdaSegmentedPathCache? PathCache { get; set; }
    }

    /// <summary>
    /// 将 StepAction 列表转换为 VDA5050 Action 列表
    /// @author zzy
    /// 2026-02-09 更新:查询数据库获取参数,使用 Action 构造函数
    /// 2026-02-09 更新:支持 ParameterSourceType 通过反射解析参数值
    /// </summary>
    private async Task<List<Domain.Models.VDA5050.Action>> ConvertStepActionsToVdaActionsAsync(
        List<StepAction> stepActions, 
        ParameterResolveContext context,
        CancellationToken ct = default)
    {
        var actions = new List<Domain.Models.VDA5050.Action>();
        
        foreach (var stepAction in stepActions.OrderBy(a => a.Order))
        {
            if (!stepAction.ActionConfigId.HasValue)
            {
                continue;
            }
            // 查询 ActionConfiguration 获取参数定义
            var config = await _actionConfigurationRepository.GetFullByIdAsync(stepAction.ActionConfigId.Value);
            if (config == null)
            {
                _logger.LogWarning("未找到动作配置,ActionConfigId: {ActionConfigId}", stepAction.ActionConfigId);
                continue;
            }
            // 构建参数列表
            var parameters = new List<(string Key, object Value)>();
            if (config?.Parameters != null)
            {
                foreach (var paramDef in config.Parameters.OrderBy(p => p.SortOrder))
                {
                    // 根据 ParameterSourceType 解析参数值
                    object paramValue = await ResolveParameterValueAsync(paramDef, context, ct);
                    paramValue = ApplyValueConstraint(paramValue, paramDef);
                    parameters.Add((paramDef.ParameterName, paramValue));
                }
            }

            // 使用构造函数创建 Action,传入参数
            var vdaAction = new Domain.Models.VDA5050.Action(
                actionType: config.ActionName ?? string.Empty,
                par: parameters,
                actionId: stepAction.ActionId.ToString(),
                blockingType: stepAction.BlockingType.ToString().ToUpper(),
                description: stepAction.Description ?? config.ActionName ?? string.Empty
            );

            // 设置描述
            vdaAction.ActionDescription = stepAction.Description ?? stepAction.ActionName ?? string.Empty;

            actions.Add(vdaAction);
        }
        
        return actions;
    }

    /// <summary>
    /// 解析参数值为对应类型
    /// @author zzy
    /// 2026-02-09 创建
    /// </summary>
    private static object ParseParameterValue(string? defaultValue, ParameterValueType valueType)
    {
        if (string.IsNullOrEmpty(defaultValue))
        {
            return valueType switch
            {
                ParameterValueType.Int => 0,
                ParameterValueType.Float => 0.0,
                ParameterValueType.Bool => false,
                _ => string.Empty
            };
        }

        try
        {
            return valueType switch
            {
                ParameterValueType.Int => int.Parse(defaultValue),
                ParameterValueType.Float => double.Parse(defaultValue),
                ParameterValueType.Bool => bool.Parse(defaultValue),
                _ => defaultValue
            };
        }
        catch
        {
            return valueType switch
            {
                ParameterValueType.Int => 0,
                ParameterValueType.Float => 0.0,
                ParameterValueType.Bool => false,
                _ => defaultValue
            };
        }
    }

    /// <summary>
    /// 根据 ParameterSourceType 解析参数值
    /// - 如果 ParameterSourceType 为 null,使用默认值
    /// - 如果不为 null,通过反射从对应对象获取值
    /// @author zzy
    /// 2026-02-09 创建
    /// 2026-03-03 更新:添加 PathCache 支持,从 Redis 路径缓存获取参数
    /// </summary>
    private async Task<object> ResolveParameterValueAsync(
        Domain.Entities.ActionParameterDefinition paramDef,
        ParameterResolveContext context,
        CancellationToken ct)
    {
        // 如果 ParameterSourceType 为 null,使用默认值
        if (paramDef.ParameterSourceType == null)
        {
            return ParseParameterValue(paramDef.DefaultValue, paramDef.ParameterValueType);
        }

        // 根据 ParameterSourceType 获取源对象
        object? sourceObject = paramDef.ParameterSourceType switch
        {
            ParameterSourceType.SubTask => context.SubTask,
            ParameterSourceType.Robot => context.Robot,
            ParameterSourceType.PathCache => await GetPathCacheAsync(context.Robot.RobotId, context.SubTask.TaskId, context.SubTask.SubTaskId),
            _ => null
        };

        // 如果源对象不存在,使用默认值
        if (sourceObject == null || string.IsNullOrEmpty(paramDef.ParameterSourcePath))
        {
            return ParseParameterValue(paramDef.DefaultValue, paramDef.ParameterValueType);
        }

        try
        {
            // 通过反射获取属性值(应用 FieldPathConfigurationService 的递归规则)
            var value = GetPropertyValueByPath(sourceObject, paramDef.ParameterSourcePath, 0, null);

            // 如果值为 null,使用默认值
            if (value == null)
            {
                return ParseParameterValue(paramDef.DefaultValue, paramDef.ParameterValueType);
            }

            // 转换为目标类型
            return ConvertToParameterValueType(value, paramDef.ParameterValueType);
        }
        catch (Exception ex)
        {
            _logger.LogWarning(ex, "解析参数值失败: {ParameterName}, SourceType: {SourceType}, Path: {SourcePath}",
                paramDef.ParameterName, paramDef.ParameterSourceType, paramDef.ParameterSourcePath);
            return ParseParameterValue(paramDef.DefaultValue, paramDef.ParameterValueType);
        }
    }

    private object ApplyValueConstraint(object resolvedValue, Domain.Entities.ActionParameterDefinition paramDef)
    {
        if (string.IsNullOrWhiteSpace(paramDef.ValueConstraints))
        {
            return ConvertToParameterValueType(resolvedValue, paramDef.ParameterValueType);
        }

        var constraintValue = paramDef.ValueConstraints.Trim();

        try
        {
            return paramDef.ParameterValueType switch
            {
                ParameterValueType.String => (resolvedValue?.ToString() ?? string.Empty) + constraintValue,
                ParameterValueType.Int => Convert.ToInt32(ConvertToParameterValueType(resolvedValue, ParameterValueType.Int)) +
                                          ParseConstraintInt(constraintValue),
                ParameterValueType.Float => Convert.ToDouble(ConvertToParameterValueType(resolvedValue, ParameterValueType.Float), CultureInfo.InvariantCulture) +
                                            ParseConstraintDouble(constraintValue),
                _ => ConvertToParameterValueType(resolvedValue, paramDef.ParameterValueType)
            };
        }
        catch (Exception ex)
        {
            _logger.LogWarning(ex,
                "参数约束值运算失败: {ParameterName}, ValueType: {ValueType}, Constraint: {Constraint}",
                paramDef.ParameterName, paramDef.ParameterValueType, paramDef.ValueConstraints);
            return ConvertToParameterValueType(resolvedValue, paramDef.ParameterValueType);
        }
    }

    private static int ParseConstraintInt(string constraintValue)
    {
        try        
        {
            if (int.TryParse(constraintValue, NumberStyles.Integer, CultureInfo.InvariantCulture, out var value) ||
            int.TryParse(constraintValue, NumberStyles.Integer, CultureInfo.CurrentCulture, out value))
            {
                return value;
            }
            return 0;
        }
        catch
        {
            
            return 0;
        }
    }

    private static double ParseConstraintDouble(string constraintValue)
    {
    try
        {
            if (double.TryParse(constraintValue, NumberStyles.Float | NumberStyles.AllowThousands,
                CultureInfo.InvariantCulture, out var value) ||
            double.TryParse(constraintValue, NumberStyles.Float | NumberStyles.AllowThousands,
                CultureInfo.CurrentCulture, out value))
            {
                return value;
            }
            return 0.0;
        }
        catch
        {
            return 0.0;
        }
    }

    /// <summary>
    /// 从 Redis 获取路径缓存
    /// @author zzy
    /// 2026-03-03 创建
    /// </summary>
    private async Task<VdaSegmentedPathCache?> GetPathCacheAsync(Guid robotId, Guid taskId, Guid subTaskId)
    {
        var key = $"{_settings.Redis.KeyPrefixes.VdaPath}:{robotId}:{taskId}:{subTaskId}";
        var cacheData = await _redis.GetDatabase().StringGetAsync(key);

        if (!cacheData.HasValue) return null;

        try
        {
            return JsonSerializer.Deserialize<VdaSegmentedPathCache>(cacheData.ToString());
        }
        catch (Exception ex)
        {
            _logger.LogWarning(ex, "路径缓存反序列化失败: RobotId={RobotId}, TaskId={TaskId}, SubTaskId={SubTaskId}",
                robotId, taskId, subTaskId);
            return null;
        }
    }

    // 最大递归深度,防止循环引用(与 FieldPathConfigurationService 保持一致)
    private const int MaxParameterResolveDepth = 5;

    // 排除的属性列表(与 FieldPathConfigurationService 保持一致)
    private static readonly HashSet<string> ExcludedParameterProperties = new(StringComparer.OrdinalIgnoreCase)
    {
        "DomainEvents", "NodeStates", "EdgeStates"
    };

    // 支持的嵌套导航属性(与 FieldPathConfigurationService 保持一致)
    private static readonly Dictionary<string, Type> SupportedParameterNavigationProperties = new(StringComparer.OrdinalIgnoreCase)
    {
        // Robot 相关
        { "Map", typeof(Domain.Entities.Map) },
        { "MapNode", typeof(MapNode) },
        // SubTask 相关
        { "Robot", typeof(Robot) },
        { "BeginLocation", typeof(StorageLocation) },
        { "EndLocation", typeof(StorageLocation) },
        { "TaskTemplate", typeof(TaskTemplate) },
        // Node 相关
        { "StorageLocationType", typeof(StorageLocationType) },
        // Edge 相关
        { "StartNode", typeof(MapNode) },
        { "EndNode", typeof(MapNode) }
    };

    /// <summary>
    /// 通过属性路径获取对象值(支持嵌套属性,如 "LoadType" 或 "EndLocation.LocationCode")
    /// 按照 FieldPathConfigurationService 的规则进行递归查询:
    /// - 最大递归深度限制
    /// - 排除特定属性
    /// - 只展开支持的导航属性
    /// @author zzy
    /// 2026-02-09 创建
    /// 2026-02-09 更新:应用 FieldPathConfigurationService 的递归规则
    /// </summary>
    private static object? GetPropertyValueByPath(object obj, string propertyPath, int currentDepth = 0, HashSet<Type>? visitedTypes = null)
    {
        if (currentDepth > MaxParameterResolveDepth)
        {
            return null;
        }

        visitedTypes ??= new HashSet<Type>();
        var currentObj = obj;
        var properties = propertyPath.Split('.');

        foreach (var propName in properties)
        {
            if (currentObj == null)
            {
                return null;
            }

            // 检查是否达到最大深度
            if (currentDepth >= MaxParameterResolveDepth)
            {
                return null;
            }

            // 处理集合索引,如 "Items[0]"
            var propNameClean = propName;
            int? index = null;
            if (propName.Contains('[') && propName.EndsWith(']'))
            {
                var startIdx = propName.IndexOf('[');
                var endIdx = propName.IndexOf(']');
                if (startIdx > 0 && endIdx > startIdx)
                {
                    propNameClean = propName.Substring(0, startIdx);
                    if (int.TryParse(propName.Substring(startIdx + 1, endIdx - startIdx - 1), out var idx))
                    {
                        index = idx;
                    }
                }
            }

            // 检查是否为排除的属性
            if (ExcludedParameterProperties.Contains(propNameClean))
            {
                return null;
            }

            // 获取属性值
            var prop = currentObj.GetType().GetProperty(propNameClean, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
            if (prop == null)
            {
                return null;
            }

            // 检查是否为支持的导航属性或普通属性
            var propType = prop.PropertyType;
            var underlyingType = Nullable.GetUnderlyingType(propType) ?? propType;

            // 如果是导航属性,检查是否在支持列表中
            if (IsParameterNavigationProperty(prop, out var navType))
            {
                // 检查类型是否已访问过(防止循环引用)
                if (navType != null && visitedTypes.Contains(navType))
                {
                    return null;
                }

                // 标记为已访问
                if (navType != null)
                {
                    visitedTypes.Add(navType);
                }
            }
            // 如果是集合类型,跳过(不支持的集合类型)
            else if (IsParameterCollectionType(propType))
            {
                return null;
            }

            currentObj = prop.GetValue(currentObj);

            // 如果存在索引,获取集合元素
            if (index.HasValue && currentObj != null)
            {
                if (currentObj is System.Collections.IList list && index.Value < list.Count)
                {
                    currentObj = list[index.Value];
                }
                else
                {
                    return null;
                }
            }

            currentDepth++;
        }

        return currentObj;
    }

    /// <summary>
    /// 检查属性是否为导航属性(与 FieldPathConfigurationService 规则一致)
    /// @author zzy
    /// 2026-02-09 创建
    /// </summary>
    private static bool IsParameterNavigationProperty(System.Reflection.PropertyInfo property, out Type? navigationType)
    {
        navigationType = null;

        // 检查是否在支持的导航属性列表中
        if (SupportedParameterNavigationProperties.TryGetValue(property.Name, out var supportedType))
        {
            navigationType = supportedType;
            return true;
        }

        // 检查是否有 ForeignKey 特性
        var foreignKeyAttr = System.Reflection.CustomAttributeExtensions.GetCustomAttribute<System.ComponentModel.DataAnnotations.Schema.ForeignKeyAttribute>(property, false);
        if (foreignKeyAttr != null)
        {
            navigationType = property.PropertyType;
            return true;
        }

        // 检查是否为虚拟导航属性(EF Core 导航属性通常标记为 virtual)
        if (property.GetMethod?.IsVirtual == true)
        {
            // 确保不是集合类型
            if (!IsParameterCollectionType(property.PropertyType))
            {
                navigationType = property.PropertyType;
                return true;
            }
        }

        return false;
    }

    /// <summary>
    /// 检查是否为集合类型(与 FieldPathConfigurationService 规则一致)
    /// @author zzy
    /// 2026-02-09 创建
    /// </summary>
    private static bool IsParameterCollectionType(Type type)
    {
        if (type == typeof(string))
            return false;

        return typeof(System.Collections.IEnumerable).IsAssignableFrom(type)
               && type.IsGenericType
               && type.GetGenericTypeDefinition() != typeof(Nullable<>);
    }

    /// <summary>
    /// 将值转换为 ParameterValueType 对应的类型
    /// @author zzy
    /// 2026-02-09 创建
    /// </summary>
    private static object ConvertToParameterValueType(object value, ParameterValueType targetType)
    {
        try
        {
            return targetType switch
            {
                ParameterValueType.Int => Convert.ToInt32(value),
                ParameterValueType.Float => Convert.ToDouble(value),
                ParameterValueType.Bool => Convert.ToBoolean(value),
                ParameterValueType.String => value.ToString() ?? string.Empty,
                _ => value.ToString() ?? string.Empty
            };
        }
        catch
        {
            return targetType switch
            {
                ParameterValueType.Int => 0,
                ParameterValueType.Float => 0.0,
                ParameterValueType.Bool => false,
                _ => string.Empty
            };
        }
    }

    /// <summary>
    /// 根据节点缓存构建VDA5050节点信息。
    /// 使用图结构的节点数据。
    /// </summary>
    private static Node BuildNode(Guid nodeId, string nodeCode, IReadOnlyDictionary<Guid, PathNode> lookup, string mapCode, int sequenceId, double coordinateScale, double theta)
    {
        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 / coordinateScale,
                Y = pathNode.Y / coordinateScale,
                Theta = theta,
                MapId = mapCode,
                AllowedDeviationXY = pathNode.MaxCoordinateOffset ?? (PositionConstants.AllowedDeviationPosition / coordinateScale)
            };
        }

        return node;
    }

    /// <summary>
    /// 根据路径段构建VDA5050边信息。
    /// </summary>
    private static Edge BuildEdge(
        PathSegmentWithCode seg,
        int sequenceId,
        PathEdge? graphEdge = null,
        double coordinateScale = 1,
        string? startNodeCodeOverride = null,
        string? edgeCodeOverride = null)
    {
        var edgeCode = edgeCodeOverride ?? (string.IsNullOrEmpty(seg.EdgeCode) ? seg.EdgeId.ToString() : seg.EdgeCode);

        var edge = new Edge()
        {
            EdgeId = edgeCode,
            SequenceId = sequenceId,
            Released = true,
            StartNodeId = startNodeCodeOverride ?? seg.FromNodeCode,
            EndNodeId = seg.ToNodeCode,
            MaxSpeed = seg.MaxSpeed,
            Orientation = seg.Angle
        };

        if (graphEdge?.CurveType == MapEdgeCurveType.Nurbs)
        {
            var trajectory = BuildNurbsTrajectory(graphEdge, coordinateScale);
            if (trajectory != null)
            {
                edge.Trajectory = trajectory;
            }
        }

        return edge;
    }

    /// <summary>
    /// 从路径边几何信息构建 VDA5050 NURBS 轨迹。
    /// </summary>
    private static Trajectory? BuildNurbsTrajectory(PathEdge edge, double coordinateScale)
    {
        var controlPoints = edge.ControlPoints;
        if (controlPoints == null || controlPoints.Count < 2)
        {
            return null;
        }

        var normalizedScale = Math.Abs(coordinateScale) < double.Epsilon ? 1 : coordinateScale;
        var weights = edge.Weights;
        var vdaControlPoints = new List<ControlPoint>(controlPoints.Count);
        for (var i = 0; i < controlPoints.Count; i++)
        {
            var cp = controlPoints[i];
            var weight = weights != null && i < weights.Count ? weights[i] : 1d;
            vdaControlPoints.Add(new ControlPoint
            {
                X = cp.X / normalizedScale,
                Y = cp.Y / normalizedScale,
                Weight = weight
            });
        }

        var n = controlPoints.Count - 1;
        var degree = Math.Clamp(edge.Degree ?? Math.Min(3, n), 1, n);
        var knotVector = edge.Knots != null && edge.Knots.Count > 0
            ? edge.Knots.ToList()
            : BuildOpenUniformKnotVector(controlPoints.Count, degree);

        return new Trajectory
        {
            Degree = degree,
            KnotVector = knotVector,
            ControlPoints = vdaControlPoints
        };
    }

    /// <summary>
    /// 构建开区间均匀节点向量(open-uniform knot vector)。
    /// </summary>
    private static List<double> BuildOpenUniformKnotVector(int controlPointCount, int degree)
    {
        var n = controlPointCount - 1;
        var knotCount = n + degree + 2;
        var knots = new List<double>(knotCount);
        for (var i = 0; i < knotCount; i++)
        {
            if (i <= degree)
            {
                knots.Add(0d);
                continue;
            }

            if (i >= knotCount - degree - 1)
            {
                knots.Add(1d);
                continue;
            }

            var denominator = n - degree + 1;
            knots.Add(denominator <= 0 ? 0d : (double)(i - degree) / denominator);
        }

        return knots;
    }

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

            var cache = new VdaSegmentedPathCache
            {
                TaskId = taskId,
                TaskCode = string.IsNullOrWhiteSpace(taskCode) ? subTaskId.ToString() : taskCode,
                RobotId = robot.RobotId,
                MapId = mapId,
                MapCode = mapCode ?? string.Empty,
                CreatedAt = DateTime.Now,
                CurrentJunctionIndex = 0,
                CurrentResourceIndex = 0,
                JunctionSegments = junctionSegments,
                PlanVersion = 1,
                RouteMode = "Normal",
                OriginalGoalNodeCode = segmentedPath.LastOrDefault()?
                    .LastOrDefault()?
                    .LastOrDefault()?
                    .ToNodeCode
            };

            // 提取最后一个路径段的货叉夹角信息并填充到姿态信息中
            // @author zzy
            // 2026-03-03 新增:从路径终点提取货叉与车头的夹角
            var lastJunction = segmentedPath.LastOrDefault();
            var lastResource = lastJunction?.LastOrDefault();
            var lastSegment = lastResource?.LastOrDefault();
            if (lastSegment?.ForkAngleOffset.HasValue == true)
            {
                cache.PoseInfo = new VdaPoseInfo
                {
                    EndForkAngleOffset = lastSegment.ForkAngleOffset.Value
                };
            }

            var key = $"{_settings.Redis.KeyPrefixes.VdaPath}:{robot.RobotId}:{taskId}:{subTaskId}";
            var payload = JsonSerializer.Serialize(cache);
            var db = _redis.GetDatabase();
            var tx = db.CreateTransaction();
            _ = tx.StringSetAsync(key, payload);
            _ = tx.StringSetAsync(BuildPathPlanVersionKey(key), cache.PlanVersion.ToString());
            var result = await tx.ExecuteAsync();
            if (!result)
            {
                _logger.LogError("VDA5050 - 路径缓存写入Redis失败,机器人: {RobotId}, 任务: {TaskId}", robot.RobotId, taskId);
                return false;
            }

            // 异步写入机器人路径坐标到位置缓存(不等待,fire-and-forget)
            // @author zzy
            _ = SavePathToRobotLocationAsync(robot, segmentedPath, graph);

            return true;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "VDA5050 - 保存路径缓存异常,机器人: {RobotId}, 任务: {TaskId}", robot.RobotId, taskId);
            return false;
        }
    }

    /// <summary>
    /// 从分段路径中提取所有节点坐标,写入机器人位置缓存的Path字段
    /// 格式: List&lt;List&lt;double&gt;&gt;,外层为点位集合,内层为每个点的 [x, y]
    /// @author zzy
    /// </summary>
    /// <param name="robot">机器人实体</param>
    /// <param name="segmentedPath">分段路径(三层嵌套结构)</param>
    /// <param name="graph">路径图结构(包含节点坐标信息)</param>
    private async Task SavePathToRobotLocationAsync(
        Robot robot,
        List<List<List<PathSegmentWithCode>>> segmentedPath,
        PathGraph graph)
    {
        try
        {
            // 按顺序收集所有路径节点ID(去重保持顺序)
            var orderedNodeIds = new List<Guid>();
            foreach (var junctionGroup in segmentedPath)
            {
                foreach (var resourceGroup in junctionGroup)
                {
                    foreach (var segment in resourceGroup)
                    {
                        // 添加起始节点(避免重复添加与上一段终点相同的节点)
                        if (orderedNodeIds.Count == 0 || orderedNodeIds[^1] != segment.FromNodeId)
                        {
                            orderedNodeIds.Add(segment.FromNodeId);
                        }
                        // 添加终止节点
                        orderedNodeIds.Add(segment.ToNodeId);
                    }
                }
            }

            // 将节点ID转换为 [x, y] 坐标列表
            var path = new List<List<double>>();
            foreach (var nodeId in orderedNodeIds)
            {
                if (graph.Nodes.TryGetValue(nodeId, out var node))
                {
                    path.Add(new List<double> { node.X, node.Y });
                }
            }

            if (path.Count > 0)
            {
                var pathJson = JsonSerializer.Serialize(path);
                await _robotCacheService.SetLocationValueAsync(
                    robot.RobotManufacturer, robot.RobotSerialNumber, "Path", pathJson);
            }
        }
        catch (Exception ex)
        {
            _logger.LogWarning(ex, "VDA5050 - 写入机器人路径坐标到位置缓存失败,机器人: {RobotId}", robot.RobotId);
        }
    }


    /// <summary>
    /// 按两层结构切割路径:
    /// 第一层:路口切割(用于节点锁/路径锁管理)
    /// 第二层:资源边界切割
    /// </summary>
    /// <remarks>
    /// 返回结构:List&lt;List&lt;List&lt;PathSegmentWithCode&gt;&gt;&gt;
    /// - 外层:路口切割后的段落(一级列表)
    /// - 中层:资源边界切割后的子段落(二级列表)
    /// - 内层:路径片段列表
    ///
    /// 注意:资源边界切割节点基于**整个原始路径**预计算,
    /// 而不是每个切割后的子段局部判断。
    ///
    /// 资源边界切割特殊规则:
    /// - 当资源边界切割点落在路口节点时,切割位置前移到路口前一个非路口节点
    /// - 预计算由 GetResourceBoundaryCutNodes 完成
    ///
    /// @author zzy
    /// 2026-02-05 重构为两层切割架构
    /// 2026-03-28 更新:移除模板切割,仅保留资源边界切割
    /// 2026-02-26 更新:资源边界切割改为基于完整路径预计算,路口前移
    /// </remarks>
    private List<List<List<PathSegmentWithCode>>> SplitSegmentsByBoundary(
        List<PathSegmentWithCode> segments,
        PathGraph graph,
        Robot robot,
        TerminalLocationActionContext? terminalActionContext)
    {
        var result = new List<List<List<PathSegmentWithCode>>>();
        if (segments.Count == 0) return result;

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

        // 基于原始完整路径预计算资源边界切割节点(路口前移)
        var resourceBoundaryCutNodes = GetResourceBoundaryCutNodes(segments, graph, junctionNodes);

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

        // 第二层:对每个路口段进行资源边界切割
        foreach (var junctionGroup in junctionSegments)
        {
            var resourceSegments = SplitByResourceBoundary(junctionGroup, resourceBoundaryCutNodes);
            result.Add(resourceSegments);
        }

        // 终点库位存在申请/完成事件时,确保真实终点段独立,便于后续虚拟段追加与动作挂载。
        if (terminalActionContext is { HasAnyAction: true })
        {
            EnsureTerminalSegmentIsolated(result);
        }

        var maxDispatchNodeCount = GetMaxDispatchNodeCount();
        return EnforceMaxDispatchNodeCount(result, maxDispatchNodeCount);
    }

    /// <summary>
    /// 获取单次下发路径允许的最大节点数。
    /// </summary>
    private int GetMaxDispatchNodeCount()
    {
        var configuredCount = _settingsMonitor.CurrentValue.Vda5050.MaxDispatchNodeCount;
        return Math.Max(MinDispatchNodeCount, configuredCount);
    }

    /// <summary>
    /// 将每个资源段按最大节点数强制切割,确保单次下发不会超过上限。
    /// </summary>
    private static List<List<List<PathSegmentWithCode>>> EnforceMaxDispatchNodeCount(
        List<List<List<PathSegmentWithCode>>> segmentedPath,
        int maxDispatchNodeCount)
    {
        if (segmentedPath.Count == 0)
        {
            return segmentedPath;
        }

        var maxSegmentsPerDispatch = Math.Max(1, maxDispatchNodeCount - 1);
        var normalized = new List<List<List<PathSegmentWithCode>>>(segmentedPath.Count);

        foreach (var junctionGroup in segmentedPath)
        {
            var normalizedResourceGroups = new List<List<PathSegmentWithCode>>();
            foreach (var resourceGroup in junctionGroup)
            {
                if (resourceGroup.Count <= maxSegmentsPerDispatch)
                {
                    normalizedResourceGroups.Add(resourceGroup);
                    continue;
                }

                for (var i = 0; i < resourceGroup.Count; i += maxSegmentsPerDispatch)
                {
                    normalizedResourceGroups.Add(resourceGroup.Skip(i).Take(maxSegmentsPerDispatch).ToList());
                }
            }

            if (normalizedResourceGroups.Count > 0)
            {
                normalized.Add(normalizedResourceGroups);
            }
        }

        return normalized;
    }

    /// <summary>
    /// 当终点库位存在申请/完成事件时,确保真实终点段独立成组,便于后续追加终点虚拟段并精确挂载动作。
    /// </summary>
    private static void EnsureTerminalSegmentIsolated(List<List<List<PathSegmentWithCode>>> segmentedPath)
    {
        if (segmentedPath.Count == 0) return;
        var lastJunctionGroup = segmentedPath[^1];
        if (lastJunctionGroup.Count == 0) return;

        var lastResourceGroup = lastJunctionGroup[^1];
        if (lastResourceGroup.Count <= 1) return;

        var terminalSegment = lastResourceGroup[^1];
        lastResourceGroup.RemoveAt(lastResourceGroup.Count - 1);
        lastJunctionGroup.Add(new List<PathSegmentWithCode> { terminalSegment });
    }
    /// <summary>
    /// 第一层切割:按路口节点切割(用于节点锁/路径锁管理)
    /// </summary>
    /// <remarks>
    /// 路口节点:在图中相邻节点数 >= 3 的节点。
    /// 分段规则:
    ///   1. 根据机器人尺寸(长宽)和转弯半径计算路口旋转范围
    ///   2. 在该旋转范围外沿路径向前的第一个点进行切割
    ///   3. 连续路口:在第一个路口处切割,后续连续路口不切割
    ///   4. 如果路口前没有可切割点(路径起点紧接路口或旋转范围覆盖起点),在路口边后切割(兜底)
    ///      例如:L00(路口)→N17 不切割;L00→中心路口→N17 分段为 [L00→中心路口], [中心路口→N17]
    /// 示例:P→A→B(路口)→C→D(路口)→E(路口)→F 分段为 [P→A], [A→B→C], [C→D→E→F]
    /// @author zzy
    /// 2026-02-26 修复:首个路口切割位置统一为路口前一个节点,与非首个路口一致
    /// 2026-03-05 优化:按机器人旋转范围向前回溯切割点
    /// </remarks>
    private static List<List<PathSegmentWithCode>> SplitByJunctions(
        List<PathSegmentWithCode> segments,
        PathGraph graph,
        Robot robot)
    {
        var result = new List<List<PathSegmentWithCode>>();
        if (segments.Count == 0) return result;

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

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

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

            if (isToJunction && !IsJunction(seg.FromNodeId))
            {
                var cutIndex = GetJunctionCutIndexByRotationRange(segments, graph, i, rotationRange);
                if (cutIndex.HasValue)
                {
                    cutIndices.Add(cutIndex.Value);
                }
                else if (i == 0 && i < segments.Count - 1)
                {
                    // 路径起点紧接路口时,兜底在路口边后切割
                    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>
    /// 计算路口旋转范围(米)。
    /// 旋转范围 = 转弯半径 + 车体外接圆半径(长宽对角线的一半)
    /// </summary>
    private static double CalculateJunctionRotationRange(Robot robot)
    {
        // var robotLength = Math.Max(robot.Length ?? 0d, 0d);
        // var robotWidth = Math.Max(robot.Width ?? 0d, 0d);
        var turningRadius = Math.Max(robot.Radius ?? 0d, 0d);

        //var bodyOuterRadius = Math.Sqrt((robotLength * robotLength) + (robotWidth * robotWidth)) / 2d;
        return turningRadius ;
    }

    /// <summary>
    /// 在路口前沿路径向前回溯,找到旋转范围外的第一个可切割点对应的边索引。
    /// 返回值表示“在哪条边后切割”;null 表示没有可用切割点。
    /// </summary>
    private static int? GetJunctionCutIndexByRotationRange(
        IReadOnlyList<PathSegmentWithCode> segments,
        PathGraph graph,
        int junctionEdgeIndex,
        double rotationRange)
    {
        if (junctionEdgeIndex <= 0)
        {
            return null;
        }

        if (rotationRange <= 0)
        {
            return junctionEdgeIndex - 1;
        }

        var accumulatedDistance = 0d;
        var totalBackDistance = 0d;
        for (var i = junctionEdgeIndex; i >= 0; i--)
        {
            var segmentLength = GetSegmentLengthForJunctionSplit(segments[i], graph);
            accumulatedDistance += segmentLength;
            totalBackDistance += segmentLength;

            // 当前 FromNode 到路口的路径距离已在旋转范围外,
            // 对应切割点是该 FromNode,等价于在前一条边后切割。
            if (accumulatedDistance > rotationRange)
            {
                if (i > 0)
                {
                    return i - 1;
                }

                // 路径起点就是范围外第一个点,无法在起点前切割。
                return null;
            }
        }

        // 地图边长缺失(全部为0)时,回退到原有策略:路口前一条边切割。
        if (totalBackDistance <= 0d)
        {
            return junctionEdgeIndex - 1;
        }

        return null;
    }

    /// <summary>
    /// 获取用于路口切割的段长(米)。
    /// 直接使用节点坐标欧氏距离。
    /// </summary>
    private static double GetSegmentLengthForJunctionSplit(PathSegmentWithCode segment, PathGraph graph)
    {
        if (graph.Nodes.TryGetValue(segment.FromNodeId, out var fromNode) &&
            graph.Nodes.TryGetValue(segment.ToNodeId, out var toNode))
        {
            var dx = toNode.X - fromNode.X;
            var dy = toNode.Y - fromNode.Y;
            var distance = Math.Sqrt((dx * dx) + (dy * dy));
            return Math.Max(distance, 0d);
        }

        return 0d;
    }

    /// <summary>
    /// 第二层切割:按资源边界切割
    /// </summary>
    /// <remarks>
    /// 切割规则:
    /// - ActionType.Apply(申请):需要实际切割
    /// - ActionType.Notify(通知):不需要切割,仅挂载动作
    ///
    /// 资源边界切割节点:由调用者基于完整路径预计算,路口前移已在预计算阶段处理
    ///
    /// @author zzy
    /// 2026-03-28 更新:移除模板切割
    /// 2026-02-26 重构:资源边界切割改为预计算模式,路口前移逻辑移至 GetResourceBoundaryCutNodes
    /// </remarks>
    private static List<List<PathSegmentWithCode>> SplitByResourceBoundary(
        List<PathSegmentWithCode> segments,
        HashSet<Guid> resourceBoundaryCutNodes)
    {
        var result = new List<List<PathSegmentWithCode>>();
        if (segments.Count == 0) return result;

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

        for (var i = 0; i < segments.Count; i++)
        {
            var seg = segments[i];
            var isResBoundaryCut = resourceBoundaryCutNodes.Contains(seg.ToNodeId);

            // 资源边界切割(路口前移已在预计算阶段处理)
            if (isResBoundaryCut)
            {
                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>
    /// 基于完整路径预计算资源边界切割节点
    /// </summary>
    /// <remarks>
    /// 遍历完整路径检测资源编码变化(进入/离开资源区域),根据资源的动作类型决定是否切割及切割位置:
    ///
    /// 进入资源(ToNode 在资源内,FromNode 不在):
    /// - Pre1(Apply)  → 切割点 = 进入前一个点(seg.FromNodeId)
    /// - Post1(Apply) → 切割点 = 进入后第一个点(seg.ToNodeId)
    ///
    /// 离开资源(FromNode 在资源内,ToNode 不在):
    /// - Pre2(Apply)  → 切割点 = 离开前一个点(seg.FromNodeId)
    /// - Post2(Apply) → 切割点 = 离开后第一个点(seg.ToNodeId)
    ///
    /// 非 Apply 类型(None/Notify/Charge)的动作不产生切割点。
    /// 当切割点落在路口节点时,沿路径向前搜索第一个非路口节点作为替代切割点。
    ///
    /// @author zzy
    /// 2026-02-26 创建
    /// 2026-02-26 更新:根据资源动作类型(Apply)决定切割点位置
    /// </remarks>
    private static HashSet<Guid> GetResourceBoundaryCutNodes(
        List<PathSegmentWithCode> segments,
        PathGraph graph,
        HashSet<Guid> junctionNodes)
    {
        var cutNodes = new HashSet<Guid>();
        if (segments.Count == 0) return cutNodes;

        var resourceLookup = BuildNodeResourceLookup(graph);

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

        // 将切割点加入集合,路口节点时向前搜索非路口节点
        void AddCutNode(Guid nodeId, int segIndex)
        {
            if (junctionNodes.Contains(nodeId))
            {
                // 沿路径向前找第一个非路口节点
                for (var j = segIndex; j >= 0; j--)
                {
                    var candidateId = segments[j].FromNodeId;
                    if (!junctionNodes.Contains(candidateId))
                    {
                        cutNodes.Add(candidateId);
                        return;
                    }
                }
                // 全是路口节点(极端情况),放弃该切割点
            }
            else
            {
                cutNodes.Add(nodeId);
            }
        }

        for (var i = 0; i < segments.Count; i++)
        {
            var seg = segments[i];
            var fromRes = resourceLookup.TryGetValue(seg.FromNodeId, out var fr) ? fr : new HashSet<string>();
            var toRes = resourceLookup.TryGetValue(seg.ToNodeId, out var tr) ? tr : new HashSet<string>();

            // 检测进入资源(ToNode 在资源内,FromNode 不在)
            var enteringResources = toRes.Except(fromRes);
            foreach (var resCode in enteringResources)
            {
                if (!resourceByCode.TryGetValue(resCode, out var resource)) continue;

                // Pre1(Apply) → 进入前一个点
                if ((resource.PreAction1Type ?? ActionType.None) == ActionType.Apply)
                {
                    AddCutNode(seg.FromNodeId, i > 0 ? i - 1 : i);
                }

                // Post1(Apply) → 进入后第一个点
                if ((resource.PostAction1Type ?? ActionType.None) == ActionType.Apply)
                {
                    AddCutNode(seg.ToNodeId, i);
                }
            }

            // 检测离开资源(FromNode 在资源内,ToNode 不在)
            var leavingResources = fromRes.Except(toRes);
            foreach (var resCode in leavingResources)
            {
                if (!resourceByCode.TryGetValue(resCode, out var resource)) continue;

                // Pre2(Apply) → 离开前一个点
                if ((resource.PreAction2Type ?? ActionType.None) == ActionType.Apply)
                {
                    AddCutNode(seg.FromNodeId, i > 0 ? i - 1 : i);
                }

                // Post2(Apply) → 离开后第一个点
                if ((resource.PostAction2Type ?? ActionType.None) == ActionType.Apply)
                {
                    AddCutNode(seg.ToNodeId, i);
                }
            }
        }

        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>
    /// 解析“子任务终点节点库位类型”对应的申请/完成事件上下文。
    /// 规则:
    /// - sequence=1(取货) -> PickupApplyRequestConfigId / PickupCompleteRequestConfigId
    /// - sequence=2(放货) -> DropApplyRequestConfigId / DropCompleteRequestConfigId
    /// - 其他 sequence 不处理
    /// </summary>
    private async Task<TerminalLocationActionContext?> ResolveTerminalLocationActionContextAsync(
        Guid subTaskId,
        int resolvedSubTaskSequence,
        CancellationToken ct)
    {
        if (subTaskId == Guid.Empty || (resolvedSubTaskSequence != 1 && resolvedSubTaskSequence != 2))
        {
            return null;
        }

        var subTask = await _subTaskRepository.GetByIdWithDetailsAsync(subTaskId, ct);
        var locationType = subTask?.EndNode?.StorageLocationType;
        if (locationType == null)
        {
            return null;
        }

        Guid? applyActionId;
        Guid? completeActionId;
        if (resolvedSubTaskSequence == 1)
        {
            // 取货任务:取货申请 / 取货完成
            applyActionId = locationType.PickupApplyRequestConfigId;
            completeActionId = locationType.PickupCompleteRequestConfigId;
        }
        else
        {
            // 放货任务:放货申请 / 放货完成
            applyActionId = locationType.DropApplyRequestConfigId;
            completeActionId = locationType.DropCompleteRequestConfigId;
        }

        if (!applyActionId.HasValue && !completeActionId.HasValue)
        {
            return null;
        }

        return new TerminalLocationActionContext(applyActionId, completeActionId);
    }

    /// <summary>
    /// 终点库位事件上下文(申请/完成)。
    /// </summary>
    private sealed class TerminalLocationActionContext
    {
        public TerminalLocationActionContext(Guid? applyActionId, Guid? completeActionId)
        {
            ApplyActionId = applyActionId;
            CompleteActionId = completeActionId;
        }

        /// <summary>
        /// 申请事件ID(取货申请或放货申请)。
        /// </summary>
        public Guid? ApplyActionId { get; }
        /// <summary>
        /// 完成事件ID(取货完成或放货完成)。
        /// </summary>
        public Guid? CompleteActionId { get; }
        /// <summary>
        /// 是否存在申请事件。
        /// </summary>
        public bool HasApplyAction => ApplyActionId.HasValue;
        /// <summary>
        /// 是否存在完成事件。
        /// </summary>
        public bool HasCompleteAction => CompleteActionId.HasValue;
        /// <summary>
        /// 是否至少存在一个终点库位事件(申请或完成)。
        /// </summary>
        public bool HasAnyAction => HasApplyAction || HasCompleteAction;
    }

    /// <summary>
    /// 检查并补充虚拟原地路径:
    /// 1. 保留资源边界首段 Pre-Apply 的起点虚拟段逻辑;
    /// 2. 按终点库位事件规则,在终点后补充 V1/V2 虚拟段并挂载申请/完成事件。
    ///
    /// 当首段存在资源边界 Pre-Apply 动作,且缺少“前一条原子路径”承载点时,
    /// 在路径起点生成一段虚拟原地路径作为独立的二级列表
    ///
    /// 生成规则(仅资源边界,不含任务模板):
    /// - 第一条原子路径发生资源边界切换,且存在以下任一动作时生成虚拟路径:
    ///   1. 进入资源时的 Pre1(Apply)
    ///   2. 离开资源时的 Pre2(Apply)
    ///
    /// 虚拟路径特征:
    /// - 作为独立的二级列表插入到第一个一级列表的开头
    /// - EdgeId = Guid.Empty(无实际边)
    /// - FromNodeId = ToNodeId = 起点节点ID
    /// - Length = 0
    ///
    /// @author zzy
    /// 2026-02-07 创建
    /// 2026-02-07 更新:虚拟路径作为独立二级列表插入
    /// 2026-03-28 更新:移除模板判断,改为资源边界 Pre-Apply 判断
    /// 2026-03-30 更新:新增终点库位事件矩阵(仅申请 / 仅完成 / 申请+完成)
    /// </summary>
    private bool EnsureVirtualSegmentForApplyActions(
        List<List<List<PathSegmentWithCode>>>? segmentedPath,
        PathRequest request,
        PathGraph graph,
        TerminalLocationActionContext? terminalActionContext)
    {

        if (segmentedPath == null || segmentedPath.Count == 0)
        {
            return true;
        }

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

        if (flatSegments.Count == 0)
        {
            return true;
        }

        // 资源边界首段虚拟路径:已存在时不重复插入
        var firstSegment = flatSegments[0];
        var hasStartVirtualSegment = firstSegment.EdgeId == Guid.Empty &&
                                     firstSegment.FromNodeId == firstSegment.ToNodeId;
        if (!hasStartVirtualSegment)
        {
            // 检查是否需要生成虚拟路径(仅资源边界 Pre-Apply)
            var needVirtualSegment = CheckNeedVirtualSegment(flatSegments, graph);
            if (needVirtualSegment)
            {
                if (!graph.Nodes.TryGetValue(request.StartNodeId, out var startNode) || startNode == null)
                {
                    _logger.LogWarning("VDA5050 - 补充虚拟路径失败,起点节点 {StartNodeId} 在图结构中不存在", request.StartNodeId);
                    return false;
                }

                // 创建独立的二级列表,只包含虚拟路径段
                var virtualResourceGroup = new List<PathSegmentWithCode>
                {
                    CreateInPlaceVirtualSegment(request.StartNodeId, startNode.NodeCode, theta: 0)
                };

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

        // 终点库位事件:统一在终点后补虚拟段并按规则挂载
        if (terminalActionContext is not { HasAnyAction: true })
        {
            return true;
        }

        flatSegments = segmentedPath
            .SelectMany(junction => junction.SelectMany(resource => resource))
            .ToList();
        if (flatSegments.Count == 0)
        {
            return true;
        }

        var terminalRealSegmentIndex = GetTerminalRealSegmentIndex(flatSegments);
        if (terminalRealSegmentIndex < 0 || terminalRealSegmentIndex >= flatSegments.Count)
        {
            return true;
        }

        var terminalRealSegment = flatSegments[terminalRealSegmentIndex];
        var terminalNodeId = terminalRealSegment.ToNodeId;
        if (!graph.Nodes.TryGetValue(terminalNodeId, out var terminalNode) || terminalNode == null)
        {
            _logger.LogWarning("VDA5050 - 补充终点虚拟路径失败,终点节点 {TerminalNodeId} 在图结构中不存在", terminalNodeId);
            return false;
        }

        // 申请事件固定挂在“真实终点段”。
        if (terminalActionContext.ApplyActionId.HasValue)
        {
            terminalRealSegment.EndNodeNetActionTypes[terminalActionContext.ApplyActionId.Value] = ActionType.Apply;
        }

        // 终点虚拟段数量规则:
        // - 仅申请:生成 1 段(V1)
        // - 仅完成:生成 1 段(V1)
        // - 申请+完成:生成 2 段(V1、V2)
        var requiredTrailingVirtualCount =
            (terminalActionContext.HasApplyAction ? 1 : 0) +
            (terminalActionContext.HasCompleteAction ? 1 : 0);

        var trailingVirtualCount = GetTrailingTerminalVirtualCount(flatSegments);
        while (trailingVirtualCount < requiredTrailingVirtualCount)
        {
            if (segmentedPath[^1].Count == 0)
            {
                segmentedPath[^1].Add(new List<PathSegmentWithCode>());
            }

            // 终点后追加原地虚拟段(From=To=终点),用于承载终点矩阵中的后续动作/事件。
            var virtualResourceGroup = new List<PathSegmentWithCode>
            {
                CreateInPlaceVirtualSegment(terminalNodeId, terminalNode.NodeCode, terminalRealSegment.EndTheta)
            };
            segmentedPath[^1].Add(virtualResourceGroup);
            trailingVirtualCount++;
        }

        if (terminalActionContext.CompleteActionId.HasValue)
        {
            flatSegments = segmentedPath
                .SelectMany(junction => junction.SelectMany(resource => resource))
                .ToList();

            terminalRealSegmentIndex = GetTerminalRealSegmentIndex(flatSegments);
            // 完成事件挂载矩阵:
            // - 仅完成:挂 V1(offset=1)
            // - 申请+完成:挂 V2(offset=2)
            var completeTargetOffset = terminalActionContext.HasApplyAction ? 2 : 1;
            var completeTargetIndex = terminalRealSegmentIndex + completeTargetOffset;
            if (completeTargetIndex < 0 || completeTargetIndex >= flatSegments.Count)
            {
                _logger.LogWarning(
                    "VDA5050 - 完成事件挂载失败,目标虚拟段不存在: TerminalIndex={TerminalIndex}, TargetIndex={TargetIndex}",
                    terminalRealSegmentIndex,
                    completeTargetIndex);
                return false;
            }

            flatSegments[completeTargetIndex].EndNodeNetActionTypes[terminalActionContext.CompleteActionId.Value] =
                ActionType.Apply;
        }

        return true;
    }

    /// <summary>
    /// 创建原地虚拟路径段(From=To,同节点)。
    /// </summary>
    private static PathSegmentWithCode CreateInPlaceVirtualSegment(Guid nodeId, string nodeCode, double theta)
    {
        return new PathSegmentWithCode
        {
            EdgeId = Guid.Empty,
            FromNodeId = nodeId,
            ToNodeId = nodeId,
            FromNodeCode = nodeCode,
            ToNodeCode = nodeCode,
            EdgeCode = string.Empty,
            Angle = 0,
            Length = 0,
            MaxSpeed = null,
            StartTheta = theta,
            EndTheta = theta
        };
    }

    /// <summary>
    /// 获取“真实终点段”在展平路径中的索引。
    /// 会跳过尾部已追加的终点原地虚拟段(V1/V2)。
    /// 特别约束:
    /// - 至少保留 1 条真实段,避免“原始路径本身就是原地段(N1->N1)”时被误判为虚拟段。
    /// </summary>
    private static int GetTerminalRealSegmentIndex(IReadOnlyList<PathSegmentWithCode> segments)
    {
        if (segments.Count == 0) return -1;

        var terminalNodeId = segments[^1].ToNodeId;
        var index = segments.Count - 1;
        // 只在 index > 0 时回退,保证至少留下第 0 条作为真实终点段。
        while (index > 0 && IsTerminalInPlaceVirtualSegment(segments[index], terminalNodeId))
        {
            index--;
        }

        return index >= 0 ? index : segments.Count - 1;
    }

    /// <summary>
    /// 统计尾部与终点同节点的原地虚拟段数量(V1/V2...)。
    /// 统计口径:总段数 - 真实终点段索引 - 1。
    /// 这样可以避免把“原始真实原地段(N1->N1)”计入虚拟段数量。
    /// </summary>
    private static int GetTrailingTerminalVirtualCount(IReadOnlyList<PathSegmentWithCode> segments)
    {
        if (segments.Count == 0)
        {
            return 0;
        }

        var terminalRealSegmentIndex = GetTerminalRealSegmentIndex(segments);
        if (terminalRealSegmentIndex < 0 || terminalRealSegmentIndex >= segments.Count)
        {
            return 0;
        }

        return Math.Max(0, segments.Count - terminalRealSegmentIndex - 1);
    }

    /// <summary>
    /// 判断是否为“终点原地虚拟段”(EdgeId=Empty 且 From/To 均为终点)。
    /// </summary>
    private static bool IsTerminalInPlaceVirtualSegment(PathSegmentWithCode segment, Guid terminalNodeId)
    {
        return segment.EdgeId == Guid.Empty &&
               segment.FromNodeId == terminalNodeId &&
               segment.ToNodeId == terminalNodeId;
    }

    /// <summary>
    /// 检查是否需要生成虚拟路径
    ///
    /// 判断规则(仅资源边界):
    /// 第一条原子路径发生资源边界切换,且包含 Pre1(Apply) 或 Pre2(Apply) 动作时,
    /// 需要生成虚拟路径作为“前一条路径”的承载位置。
    ///
    /// @author zzy
    /// 2026-02-07 创建
    /// 2026-03-28 更新:移除模板判断,改为首段资源边界 Pre-Apply 判断
    /// </summary>
    private static bool CheckNeedVirtualSegment(
        IReadOnlyList<PathSegmentWithCode> flatSegments,
        PathGraph graph)
    {
        if (flatSegments.Count == 0)
        {
            return false;
        }

        var firstSeg = flatSegments[0];
        var resourceLookup = BuildNodeResourceLookup(graph);
        var resourceByCode = graph.Resources
            .Where(r => CuttingResourceTypes.Contains(r.Type))
            .ToDictionary(r => r.ResourceCode, StringComparer.OrdinalIgnoreCase);

        var fromRes = resourceLookup.TryGetValue(firstSeg.FromNodeId, out var fr) ? fr : new HashSet<string>();
        var toRes = resourceLookup.TryGetValue(firstSeg.ToNodeId, out var tr) ? tr : new HashSet<string>();

        // 进入资源:检查 Pre1(Apply)
        foreach (var resCode in toRes.Except(fromRes))
        {
            if (!resourceByCode.TryGetValue(resCode, out var resource))
            {
                continue;
            }

            if ((resource.PreAction1Type ?? ActionType.None) == ActionType.Apply &&
                resource.PreNetActions1 is { Count: > 0 })
            {
                return true;
            }
        }

        // 离开资源:检查 Pre2(Apply)
        foreach (var resCode in fromRes.Except(toRes))
        {
            if (!resourceByCode.TryGetValue(resCode, out var resource))
            {
                continue;
            }

            if ((resource.PreAction2Type ?? ActionType.None) == ActionType.Apply &&
                resource.PreNetActions2 is { Count: > 0 })
            {
                return true;
            }
        }

        return false;
    }

    /// <summary>
    /// 将动作装载到路径段,分两轮处理:
    /// 第一轮:Notify 动作(基于原子路径挂载)
    /// 第二轮:Apply 动作(基于场景切割集合挂载)
    ///
    /// 【Notify(消息通知)】- 不需要等待响应
    ///   - 资源边界 Notify:挂载在切换场景时原子路径的起点/终点
    ///   - 任务步骤 Notify:挂载在整个原子路径的最后三个节点上
    ///     - Node: Pre1 → 倒数第二个节点, Post1 → 最后一个节点
    ///     - PreNode: Pre1 → 倒数第三个节点, Post1 → 倒数第二条原子路径终点,
    ///               Pre2 → 倒数第二个节点, Post2 → 最后一个节点
    ///
    /// 【Apply(动作申请)】- 需要等待响应,挂载在场景集合的边界位置
    ///   - Pre(进入/离开前):上一个场景集合最后一段路径的终点 (EndNode)
    ///   - Post(进入/离开后):切换场景时原子路径的终点 (EndNode)
    ///
    /// @author zzy
    /// 2026-02-09 重构:拆分为 Notify 轮 + Apply 轮,规则清晰、职责单一
    /// 2026-02-09 更新:任务步骤 Notify 改为基于整个原子路径的最后三个节点挂载
    /// </summary>
    private async Task<bool> LoadActionsToSegmentsAsync(
        List<List<List<PathSegmentWithCode>>> segmentedPath,
        TaskStep? taskStep,
        PathGraph graph,
        Robot robot,
        bool addStopChargingActionAtStart,
        TerminalLocationActionContext? terminalActionContext)
    {
        if (segmentedPath.Count == 0)
        {
            _logger.LogWarning("VDA5050 - 动作装载失败,路径分段为空");
            return false;
        }

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

        if (flatSegments.Count == 0)
        {
            _logger.LogWarning("VDA5050 - 动作装载失败,展平后路径为空");
            return false;
        }

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

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

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

        // 第三轮:挂载 StepAction 到最后一段的起点和终点
        await LoadStepActionsToLastSegmentAsync(
            flatSegments,
            taskStep,
            robot,
            addStopChargingActionAtStart,
            terminalActionContext);

        return true;
    }

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

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

        // 2. 任务步骤 Notify 动作
        if (taskStep != null)
        {
            LoadTaskStepNotifyActions(flatSegments, 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 类型动作
    ///
    /// 基于整个原子路径的最后三个节点挂载:
    /// - 倒数第三个节点 = flatSegments[^2].StartNode (即 flatSegments[^2].FromNodeId)
    /// - 倒数第二个节点 = flatSegments[^2].EndNode / flatSegments[^1].StartNode
    /// - 最后一个节点   = flatSegments[^1].EndNode (即 flatSegments[^1].ToNodeId)
    ///
    /// Node(路径终点):只有"进入"动作
    ///   - Pre1(Notify) → 倒数第二个节点 (flatSegments[^1].StartNode)
    ///   - Post1(Notify) → 最后一个节点 (flatSegments[^1].EndNode)
    ///
    /// PreNode(路径倒数第二个节点):有"进入"和"离开"两组动作
    ///   - Pre1(Notify) → 倒数第三个节点 (flatSegments[^2].StartNode)
    ///   - Post1(Notify) → 倒数第三个原子路径的终点 (flatSegments[^2].EndNode)
    ///   - Pre2(Notify) → 倒数第二个节点 (flatSegments[^1].StartNode)
    ///   - Post2(Notify) → 最后一个节点 (flatSegments[^1].EndNode)
    ///
    /// @author zzy
    /// 2026-02-09 创建
    /// 2026-02-09 更新:改为基于整个原子路径的最后三个节点挂载
    /// </summary>
    private void LoadTaskStepNotifyActions(
        List<PathSegmentWithCode> flatSegments,
        TaskStep taskStep)
    {
        if (flatSegments.Count == 0) return;

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

    /// <summary>
    /// 挂载 Node(路径终点)的 Notify 动作
    ///
    /// 基于整个原子路径的最后一条原子路径:
    /// - Pre1(Notify) → 倒数第二个节点 = flatSegments[^1].StartNode
    /// - Post1(Notify) → 最后一个节点 = flatSegments[^1].EndNode
    ///
    /// @author zzy
    /// 2026-02-09 创建
    /// 2026-02-09 更新:改为基于整个原子路径的最后节点挂载
    /// </summary>
    private void LoadNodeNotifyActions(
        List<PathSegmentWithCode> flatSegments,
        StepProperty prop)
    {
        if (flatSegments.Count < 1)
        {
            return;
        }

        // 最后一条原子路径
        var lastSegment = flatSegments[^1];

        // Pre1(进入前):Notify → 倒数第二个节点(最后一条原子路径的起点)
        if (HasNetActions(prop.PreNetActions1))
        {
            var type = prop.PreAction1Type ?? ActionType.None;
            if (type == ActionType.Notify)
            {
                foreach (var actionId in prop.PreNetActions1!)
                {
                    lastSegment.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!)
                {
                    lastSegment.EndNodeNetActionTypes[actionId] = type;
                }
            }
        }
    }

    /// <summary>
    /// 挂载 PreNode(路径倒数第二个节点)的 Notify 动作
    ///
    /// 基于整个原子路径的最后两条原子路径(最后三个节点):
    /// - flatSegments[^2] = 倒数第二条原子路径
    /// - flatSegments[^1] = 最后一条原子路径
    ///
    /// 进入动作:
    /// - Pre1(Notify) → 倒数第三个节点 = flatSegments[^2].StartNode
    /// - Post1(Notify) → 倒数第三个原子路径的终点 = flatSegments[^2].EndNode
    ///
    /// 离开动作:
    /// - Pre2(Notify) → 倒数第二个节点 = flatSegments[^1].StartNode
    /// - Post2(Notify) → 最后一个节点 = flatSegments[^1].EndNode
    ///
    /// @author zzy
    /// 2026-02-09 创建
    /// 2026-02-09 更新:改为基于整个原子路径的最后三个节点挂载
    /// </summary>
    private void LoadPreNodeNotifyActions(
        List<PathSegmentWithCode> flatSegments,
        StepProperty prop)
    {
        if (flatSegments.Count < 2)
        {
            _logger.LogWarning("PreNode Notify动作装载失败:原子路径数不足,路径数: {SegmentCount}", flatSegments.Count);
            return;
        }

        // 倒数第二条原子路径(包含倒数第三个节点和倒数第二个节点)
        var secondLastSegment = flatSegments[^2];
        // 最后一条原子路径(包含倒数第二个节点和最后一个节点)
        var lastSegment = flatSegments[^1];

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

        // Pre1(进入前):Notify → 倒数第三个节点(倒数第二条原子路径的起点)
        if (HasNetActions(prop.PreNetActions1))
        {
            var type = prop.PreAction1Type ?? ActionType.None;
            if (type == ActionType.Notify)
            {
                foreach (var actionId in prop.PreNetActions1!)
                {
                    secondLastSegment.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!)
                {
                    secondLastSegment.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!)
                {
                    lastSegment.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!)
                {
                    lastSegment.EndNodeNetActionTypes[actionId] = type;
                }
            }
        }
    }

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

    // ==================== 第三轮:StepAction 动作挂载 ====================

    /// <summary>
    /// 第三轮:将 StepAction 挂载到原子路径最后一段的起点和终点
    /// 
    /// 挂载规则:
    /// - 所有 StepAction 都挂载到最后一段的起点和终点
    /// - 堵塞类型使用任务模板中 StepAction 对应的值
    /// - 其他值(ActionName 等)使用 ActionConfiguration 中的值
    /// - 参数使用 ActionConfiguration.Parameters 中的定义
    /// 
    /// @author zzy
    /// 2026-02-09 创建
    /// 2026-02-09 更新:使用 StepActionWithParams 携带参数
    /// </summary>
    private async Task LoadStepActionsToLastSegmentAsync(
        List<PathSegmentWithCode> flatSegments,
        TaskStep? taskStep,
        Robot robot,
        bool addStopChargingActionAtStart,
        TerminalLocationActionContext? terminalActionContext)
    {
        if (flatSegments.Count == 0)
        {
            return;
        }

        // 默认挂载目标为“真实终点段”;当申请+完成同时存在时,挂载到第一个终点虚拟段(V1)。
        var lastSegment = ResolveStepActionTargetSegment(flatSegments, terminalActionContext);
        var firstSegment = flatSegments[0];

        var preNodeProperties = taskStep?.Properties
            .Where(p => p.PropertyType == StepPropertyType.PreNode)
            .ToList() ?? new List<StepProperty>();

        // 按 PropertyType 分组获取 StepAction
        // PreNode(前置节点)动作 → 挂载到最后一段的起点
        // Node(节点)动作 → 挂载到最后一段的终点
        var preNodeActions = preNodeProperties
            .SelectMany(p => p.Actions)
            .OrderBy(a => a.Order)
            .ToList();

        var nodeActions = taskStep?.Properties
            .Where(p => p.PropertyType == StepPropertyType.Node)
            .SelectMany(p => p.Actions)
            .OrderBy(a => a.Order)
            .ToList() ?? new List<StepAction>();

        StepAction? stopChargingAction = null;
        if (addStopChargingActionAtStart)
        {
            var hasExistingStopChargingAction = preNodeActions.Any(a => a.Type == ActionCategory.StopCharging)
                                                || firstSegment.StartNodeActions.Any(a => a.Type == ActionCategory.StopCharging);
            if (!hasExistingStopChargingAction)
            {
                stopChargingAction = await BuildStopChargingPreActionAsync(
                    robot,
                    preNodeProperties.FirstOrDefault()?.PropertyId);
            }
        }

        if (preNodeActions.Count == 0 && nodeActions.Count == 0 && stopChargingAction == null)
        {
            return;
        }

        _logger.LogInformation(
            "开始挂载 StepAction 到最后一段,路径段数: {SegmentCount}, 前置点动作数: {PreNodeCount}, 节点动作数: {NodeCount}, 增加取消充电动作: {HasStopChargingAction}",
            flatSegments.Count, preNodeActions.Count, nodeActions.Count, stopChargingAction != null);

        if (stopChargingAction != null)
        {
            var firstNodeOrderOffset = 0;
            if (firstSegment.StartNodeActions.Count > 0)
            {
                var minOrder = firstSegment.StartNodeActions.Min(a => a.Order);
                firstNodeOrderOffset = Math.Max(0, 2 - minOrder);
            }

            if (firstNodeOrderOffset > 0)
            {
                foreach (var action in firstSegment.StartNodeActions)
                {
                    action.Order += firstNodeOrderOffset;
                }
            }

            firstSegment.StartNodeActions.Add(stopChargingAction);
        }

        // 前置点动作挂载到最后一段原子路径的起点
        foreach (var stepAction in preNodeActions)
        {
            var actionToAdd = new StepAction
            {
                ActionId = stepAction.ActionId,
                ActionConfigId = stepAction.ActionConfigId,
                PropertyId = stepAction.PropertyId,
                Type = stepAction.Type,
                ActionName = stepAction.ActionName ?? stepAction.Type.ToString(),
                Description = stepAction.Description,
                Order = stepAction.Order,
                BlockingType = stepAction.BlockingType,
                CreatedAt = stepAction.CreatedAt,
                UpdatedAt = stepAction.UpdatedAt
            };
            lastSegment.StartNodeActions.Add(actionToAdd);
        }

        // 节点动作挂载到最后一段原子路径的终点
        foreach (var stepAction in nodeActions)
        {
            var actionToAdd = new StepAction
            {
                ActionId = stepAction.ActionId,
                ActionConfigId = stepAction.ActionConfigId,
                PropertyId = stepAction.PropertyId,
                Type = stepAction.Type,
                ActionName = stepAction.ActionName ?? stepAction.Type.ToString(),
                Description = stepAction.Description,
                Order = stepAction.Order,
                BlockingType = stepAction.BlockingType,
                CreatedAt = stepAction.CreatedAt,
                UpdatedAt = stepAction.UpdatedAt
            };
            lastSegment.EndNodeActions.Add(actionToAdd);
        }
    }

    /// <summary>
    /// 解析 StepAction 的挂载目标段。
    /// 矩阵规则:
    /// - 仅申请:挂真实终点段
    /// - 仅完成:挂真实终点段
    /// - 申请+完成:挂第一个终点虚拟段(V1)
    /// </summary>
    private static PathSegmentWithCode ResolveStepActionTargetSegment(
        IReadOnlyList<PathSegmentWithCode> flatSegments,
        TerminalLocationActionContext? terminalActionContext)
    {
        if (flatSegments.Count == 0)
        {
            throw new InvalidOperationException("路径段集合为空,无法解析 StepAction 挂载目标");
        }

        var terminalRealSegmentIndex = GetTerminalRealSegmentIndex(flatSegments);
        if (terminalRealSegmentIndex < 0 || terminalRealSegmentIndex >= flatSegments.Count)
        {
            return flatSegments[^1];
        }

        // 矩阵规则:
        // 1) 仅申请    -> step_action 挂在真实终点
        // 2) 仅完成    -> step_action 挂在真实终点
        // 3) 申请+完成 -> step_action 挂在 V1
        if (terminalActionContext is { HasApplyAction: true, HasCompleteAction: true })
        {
            var v1Index = terminalRealSegmentIndex + 1;
            if (v1Index >= 0 && v1Index < flatSegments.Count)
            {
                return flatSegments[v1Index];
            }
        }

        return flatSegments[terminalRealSegmentIndex];
    }

    /// <summary>
    /// 构建“取消充电”前置动作(PreAction1)。
    /// 根据机器人供应商与类型筛选 StopCharging 动作配置。
    /// </summary>
    private async Task<StepAction?> BuildStopChargingPreActionAsync(Robot robot, Guid? propertyId)
    {
        var configs = await _actionConfigurationRepository.GetByManufacturerAndTypeAsync(
            robot.RobotManufacturer,
            robot.RobotType,
            ActionCategory.StopCharging);

        var config = configs
            .Where(c => c.IsEnabled && !string.IsNullOrWhiteSpace(c.ActionName))
            .OrderBy(c => c.SortOrder)
            .ThenBy(c => c.ActionName)
            .FirstOrDefault();

        if (config == null)
        {
            _logger.LogWarning(
                "未找到可用的停止充电动作配置,无法添加取消充电动作: Manufacturer={Manufacturer}, RobotType={RobotType}",
                robot.RobotManufacturer,
                robot.RobotType);
            return null;
        }

        return new StepAction
        {
            ActionId = Guid.NewGuid(),
            ActionConfigId = config.ActionConfigId,
            PropertyId = propertyId ?? Guid.Empty,
            Type = config.ActionCategory,
            ActionName = config.ActionName,
            Description = string.IsNullOrWhiteSpace(config.ActionDescription) ? "取消充电" : config.ActionDescription,
            Order = 1,
            BlockingType = config.BlockingType,
            CreatedAt = DateTime.Now,
            UpdatedAt = DateTime.Now
        };
    }

    /// <summary>
    /// 根据 StepAction 列表获取对应的 ActionConfiguration
    /// </summary>
    private async Task<List<ActionConfiguration>> GetActionConfigurationsAsync(List<StepAction> stepActions)
    {
        var configs = new List<ActionConfiguration>();
        var distinctIds = stepActions.Select(a => a.ActionConfigId).Distinct().ToList();

        foreach (var distinctId in distinctIds)
        {
            // 尝试通过动作名称查找
            var config = await _actionConfigurationRepository.GetByIdAsync(distinctId);
            if (config != null)
            {
                configs.Add(config);
                continue;
            }
        }

        return configs;
    }

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

    private List<PathSegmentWithCode> BuildSweptLockCandidates(
        List<PathSegmentWithCode> baseSegments,
        PathGraph graph,
        Robot robot)
    {
        if (baseSegments.Count == 0)
        {
            return baseSegments;
        }

        var nodeLookup = SweptAreaCoverageResolver.BuildNodeLookup(graph);
        var edgePolylineLookup = SweptAreaCoverageResolver.BuildEdgePolylineLookup(graph);
        var centerLine = SweptAreaCoverageResolver.BuildPolylineFromSegments(
            baseSegments,
            nodeLookup,
            edgePolylineLookup);
        if (centerLine.Count == 0)
        {
            return baseSegments;
        }

        var dimensions = SweptAreaCoverageResolver.ResolveDimensions(
            robot.Width,
            robot.Length,
            robot.SafetyDistance,
            robot.CoordinateScale);
        var radius = SweptAreaCoverageResolver.CalculateSweepRadius(
            dimensions.Length,
            dimensions.Width,
            dimensions.SafetyDistance);
        var coverage = SweptAreaCoverageResolver.ExpandFromGraph(graph, centerLine, radius);
        return MergeCoverageIntoLockSegments(baseSegments, graph, coverage);
    }

    private static List<PathSegmentWithCode> MergeCoverageIntoLockSegments(
        List<PathSegmentWithCode> baseSegments,
        PathGraph graph,
        SweptAreaCoverageResult coverage)
    {
        var result = new List<PathSegmentWithCode>(baseSegments);
        var nodeCodes = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
        var edgeCodes = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

        foreach (var segment in baseSegments)
        {
            if (!string.IsNullOrWhiteSpace(segment.FromNodeCode))
            {
                nodeCodes.Add(segment.FromNodeCode);
            }

            if (!string.IsNullOrWhiteSpace(segment.ToNodeCode))
            {
                nodeCodes.Add(segment.ToNodeCode);
            }

            if (!string.IsNullOrWhiteSpace(segment.EdgeCode))
            {
                edgeCodes.Add(segment.EdgeCode);
            }
        }

        var nodeByCode = graph.Nodes.Values
            .Where(n => !string.IsNullOrWhiteSpace(n.NodeCode))
            .GroupBy(n => n.NodeCode, StringComparer.OrdinalIgnoreCase)
            .ToDictionary(g => g.Key, g => g.First(), StringComparer.OrdinalIgnoreCase);

        var edgeByCode = graph.Edges.Values
            .Where(e => !string.IsNullOrWhiteSpace(e.EdgeCode))
            .GroupBy(e => e.EdgeCode, StringComparer.OrdinalIgnoreCase)
            .ToDictionary(g => g.Key, g => g.First(), StringComparer.OrdinalIgnoreCase);

        foreach (var edgeCode in coverage.EdgeCodes)
        {
            if (edgeCodes.Contains(edgeCode) || !edgeByCode.TryGetValue(edgeCode, out var edge))
            {
                continue;
            }

            result.Add(new PathSegmentWithCode
            {
                EdgeId = edge.EdgeId,
                EdgeCode = edge.EdgeCode,
                FromNodeId = edge.FromNodeId,
                ToNodeId = edge.ToNodeId,
                FromNodeCode = edge.FromNodeCode,
                ToNodeCode = edge.ToNodeCode
            });

            edgeCodes.Add(edgeCode);
            if (!string.IsNullOrWhiteSpace(edge.FromNodeCode))
            {
                nodeCodes.Add(edge.FromNodeCode);
            }

            if (!string.IsNullOrWhiteSpace(edge.ToNodeCode))
            {
                nodeCodes.Add(edge.ToNodeCode);
            }
        }

        foreach (var nodeCode in coverage.NodeCodes)
        {
            if (nodeCodes.Contains(nodeCode) || !nodeByCode.TryGetValue(nodeCode, out var node))
            {
                continue;
            }

            result.Add(new PathSegmentWithCode
            {
                EdgeId = Guid.Empty,
                EdgeCode = string.Empty,
                FromNodeId = node.NodeId,
                ToNodeId = node.NodeId,
                FromNodeCode = node.NodeCode,
                ToNodeCode = node.NodeCode
            });

            nodeCodes.Add(nodeCode);
        }

        return result;
    }

    /// <summary>
    /// 创建即时动作消息(无参数)
    /// 每次创建时递增 robot.HeaderId
    /// @author zzy
    /// 2026-02-11 更新:递增 HeaderId
    /// </summary>
    private InstantAction CreateInstantAction(Robot robot, string actionType)
    {
        var action = new Domain.Models.VDA5050.Action
        {
            ActionId = Guid.NewGuid().ToString(),
            ActionType = actionType,
            BlockingType = "HARD"
        };

        return CreateInstantAction(robot, new List<Domain.Models.VDA5050.Action> { action });
    }

    /// <summary>
    /// 创建即时动作消息(批量动作)
    /// </summary>
    private InstantAction CreateInstantAction(Robot robot, List<Domain.Models.VDA5050.Action> actions)
    {
        robot.HeaderId++;

        return new InstantAction(
            (int)robot.HeaderId,
            robot.ProtocolVersion,
            robot.RobotManufacturer,
            robot.RobotSerialNumber,
            actions);
    }

    /// <summary>
    /// 判断当前资源段是否为原地路径(无实际移动)
    /// </summary>
    private static bool IsInPlaceSegments(List<PathSegmentWithCode> segments)
    {
        if (segments.Count == 0)
        {
            return false;
        }

        return segments.All(seg =>
            seg.FromNodeId == seg.ToNodeId &&
            Math.Abs(seg.Length) < 0.000001);
    }

    /// <summary>
    /// 将原地路径段中的节点动作转换为即时动作
    /// </summary>
    private async Task<InstantAction?> BuildInstantActionFromInPlaceSegmentsAsync(
        Robot robot,
        RobotSubTask subTask,
        List<PathSegmentWithCode> segments,
        CancellationToken ct)
    {
        var orderedStepActions = new List<StepAction>();
        var actionIds = new HashSet<Guid>();

        var firstSegment = segments[0];
        foreach (var action in firstSegment.StartNodeActions.OrderBy(a => a.Order))
        {
            if (actionIds.Add(action.ActionId))
            {
                orderedStepActions.Add(action);
            }
        }

        foreach (var segment in segments)
        {
            foreach (var action in segment.EndNodeActions.OrderBy(a => a.Order))
            {
                if (actionIds.Add(action.ActionId))
                {
                    orderedStepActions.Add(action);
                }
            }
        }

        if (orderedStepActions.Count == 0)
        {
            return null;
        }

        var context = new ParameterResolveContext
        {
            Robot = robot,
            SubTask = subTask
        };
        var actions = await ConvertStepActionsToVdaActionsAsync(orderedStepActions, context, ct);
        if (actions.Count == 0)
        {
            return null;
        }

        return CreateInstantAction(robot, actions);
    }

    /// <summary>
    /// 机器人暂停控制(当前为占位实现)。
    /// </summary>
    public Task RobotPauseAsync(Robot robot, CancellationToken ct = default)
    {
        throw new NotImplementedException();
    }

    /// <summary>
    /// 机器人继续控制(当前为占位实现)。
    /// </summary>
    public Task RobotUnPauseAsync(Robot robot, CancellationToken ct = default)
    {
        throw new NotImplementedException();
    }

    /// <summary>
    /// 机器人重定位控制(当前为占位实现)。
    /// </summary>
    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 db = _redis.GetDatabase();
        var expectedPlanVersion = cache.PlanVersion;
        await EnsurePathPlanVersionKeyAsync(db, key, expectedPlanVersion);

        var inHoldWindow =
            (string.Equals(cache.RouteMode, RouteModeHold, StringComparison.Ordinal) ||
             string.Equals(cache.RouteMode, RouteModeQueue, StringComparison.Ordinal) ||
             string.Equals(cache.RouteMode, RouteModeOccupying, StringComparison.Ordinal) ||
             string.Equals(cache.RouteMode, RouteModeReplanPending, StringComparison.Ordinal) ||
             string.Equals(cache.RouteMode, RouteModeBlocked, StringComparison.Ordinal)) &&
            cache.HoldUntilUtc.HasValue &&
            cache.HoldUntilUtc.Value > DateTime.Now;

        if (!reExec && inHoldWindow)
        {
            await ScheduleResumeDispatchAsync(robot, currentSubTask, key, cache, expectedPlanVersion, ct);
            return ApiResponse.Successful("等待窗口未到,保持等待");
        }

        if (!reExec)
        {
            var status = await _robotCacheService.GetStatusAsync(
                robot.RobotManufacturer,
                robot.RobotSerialNumber);

            var decision = await _globalNavigationCoordinator.TryAdjustBeforeSendAsync(
                robot.RobotId,
                cache,
                status?.LastNode,
                status?.Driving ?? false,
                ct);

            cache.LastDecisionCode = string.IsNullOrWhiteSpace(decision.StrategyCode)
                ? decision.Action.ToString()
                : decision.StrategyCode;

            if (decision.Action == RouteAdjustmentAction.Hold)
            {
                if (decision.SuggestedHoldUntilUtc.HasValue)
                {
                    cache.HoldUntilUtc = decision.SuggestedHoldUntilUtc;
                }

                if (cache.PlanVersion <= expectedPlanVersion)
                {
                    cache.PlanVersion = expectedPlanVersion + 1;
                }

                if (!await TryPersistPathCacheCasWithFallbackAsync(db, key, cache, expectedPlanVersion, ct))
                {
                    _logger.LogWarning(
                        "VDA5050 - 持久化等待状态时发生并发冲突: RobotId={RobotId}, PlanVersion={PlanVersion}",
                        robot.RobotId, expectedPlanVersion);
                    return ApiResponse.Successful("路径状态并发更新,等待下次调度");
                }

                expectedPlanVersion = cache.PlanVersion;
                await ScheduleResumeDispatchAsync(robot, currentSubTask, key, cache, expectedPlanVersion, ct);

                _logger.LogInformation(
                    "VDA5050 - 全局协调器触发等待,暂停发送下一段: RobotId={RobotId}, Message={Message}, RouteMode={RouteMode}",
                    robot.RobotId, decision.Message, cache.RouteMode);
                return ApiResponse.Successful(string.IsNullOrWhiteSpace(decision.Message) ? "等待中" : decision.Message);
            }

            if (decision.Action == RouteAdjustmentAction.PatchTail ||
                decision.Action == RouteAdjustmentAction.ReplanTail)
            {
                if (decision.Patch == null)
                {
                    return ApiResponse.Failed("VDA5050 - 全局协调器返回补丁动作但补丁为空");
                }

                if (!_tailPatchApplier.TryApplyPatch(cache, decision.Patch, out var failureReason))
                {
                    _logger.LogWarning(
                        "VDA5050 - 尾段补丁应用失败: RobotId={RobotId}, PatchId={PatchId}, Reason={Reason}",
                        robot.RobotId, decision.Patch.PatchId, failureReason);
                    return ApiResponse.Successful($"尾段补丁应用失败,进入等待: {failureReason}");
                }

                cache.LastDecisionCode = $"{decision.Action}:{decision.Patch.StrategyCode}";
                if (!await TryPersistPathCacheCasWithFallbackAsync(db, key, cache, expectedPlanVersion, ct))
                {
                    _logger.LogWarning(
                        "VDA5050 - 持久化补丁结果时发生并发冲突: RobotId={RobotId}, ExpectedPlanVersion={PlanVersion}",
                        robot.RobotId, expectedPlanVersion);
                    return ApiResponse.Successful("路径状态并发更新,等待下次调度");
                }

                expectedPlanVersion = cache.PlanVersion;

                _logger.LogInformation(
                    "VDA5050 - 尾段补丁应用成功: RobotId={RobotId}, Action={Action}, PatchId={PatchId}, NewPlanVersion={PlanVersion}",
                    robot.RobotId, decision.Action, decision.Patch.PatchId, cache.PlanVersion);
            }
            else if (string.Equals(cache.RouteMode, RouteModeHold, StringComparison.Ordinal) ||
                     string.Equals(cache.RouteMode, RouteModeQueue, StringComparison.Ordinal) ||
                     string.Equals(cache.RouteMode, RouteModeOccupying, StringComparison.Ordinal) ||
                     string.Equals(cache.RouteMode, RouteModeDetouring, StringComparison.Ordinal) ||
                     string.Equals(cache.RouteMode, RouteModeReplanPending, StringComparison.Ordinal) ||
                     string.Equals(cache.RouteMode, RouteModeBlocked, StringComparison.Ordinal))
            {
                cache.RouteMode = RouteModeNormal;
                cache.HoldUntilUtc = null;
                cache.HoldNodeCode = null;
                cache.StablePassCount = 0;
                cache.ConsecutiveConflictFailCount = 0;
                cache.BlockedReason = null;
                cache.PlanVersion += 1;

                if (!await TryPersistPathCacheCasWithFallbackAsync(db, key, cache, expectedPlanVersion, ct))
                {
                    _logger.LogWarning(
                        "VDA5050 - 模式归一化时发生并发冲突: RobotId={RobotId}, ExpectedPlanVersion={PlanVersion}",
                        robot.RobotId, expectedPlanVersion);
                    return ApiResponse.Successful("路径状态并发更新,等待下次调度");
                }

                expectedPlanVersion = cache.PlanVersion;
            }
        }

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

        // 检查是否已完成所有段
        if (junctionIndex >= cache.JunctionSegments.Count)
        {
            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}");
            }

            // 网络动作状态可能已推进路径版本,避免后续CAS使用过期版本号
            expectedPlanVersion = cache.PlanVersion;
        }

        

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

        var segmentsToSend = new List<PathSegmentWithCode>(nextSegment);
        
        // 获取地图图结构(用于填充节点位置信息)
        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 lockCandidates = BuildSweptLockCandidates(allJunctionSegments, graph, robot);
            
            var lockResult = await _agvPathService.TryAcquireNextSegmentLockAsync(
                cache.MapCode,
                lockCandidates,
                robot.RobotId,
                30);
            
            if (!lockResult.Success)
            {
                cache.RouteMode = RouteModeHold;
                cache.HoldNodeCode = nextSegment.FirstOrDefault()?.FromNodeCode;
                cache.HoldUntilUtc = DateTime.Now.AddSeconds(2);
                cache.PlanVersion += 1;
                cache.LastDecisionCode = "LockAcquireFailedHold";
                await PublishLockConflictEventAsync(
                    robot.RobotId,
                    cache.MapCode,
                    nextSegment.FirstOrDefault()?.FromNodeCode,
                    nextSegment.FirstOrDefault()?.EdgeCode,
                    false,
                    lockResult.FailureReason,
                    ct);
                if (!await TryPersistPathCacheCasWithFallbackAsync(db, key, cache, expectedPlanVersion, ct))
                {
                    _logger.LogWarning(
                        "VDA5050 - 锁失败等待状态持久化冲突: RobotId={RobotId}, ExpectedPlanVersion={PlanVersion}",
                        robot.RobotId, expectedPlanVersion);
                    return ApiResponse.Successful("路径状态并发更新,等待下次调度");
                }

                expectedPlanVersion = cache.PlanVersion;
                await ScheduleResumeDispatchAsync(robot, currentSubTask, key, cache, expectedPlanVersion, ct);

                _logger.LogInformation("路口段锁定失败,等待下次尝试: RobotId={RobotId}, Reason={Reason}",
                    robot.RobotId, lockResult.FailureReason ?? "未知原因");
                return ApiResponse.Successful($"路口段锁定失败,进入等待: {lockResult.FailureReason ?? "未知原因"}");
            }

            // 检查是否存在逆向占用冲突
            if (lockResult.HasReverseConflict)
            {
                cache.RouteMode = RouteModeQueue;
                cache.HoldNodeCode = nextSegment.FirstOrDefault()?.FromNodeCode;
                cache.HoldUntilUtc = DateTime.Now.AddSeconds(3);
                cache.PlanVersion += 1;
                cache.LastDecisionCode = "ReverseConflictQueue";
                await PublishLockConflictEventAsync(
                    robot.RobotId,
                    cache.MapCode,
                    nextSegment.FirstOrDefault()?.FromNodeCode,
                    nextSegment.FirstOrDefault()?.EdgeCode,
                    true,
                    "获取下一路口锁时发生逆向边冲突",
                    ct);
                if (!await TryPersistPathCacheCasWithFallbackAsync(db, key, cache, expectedPlanVersion, ct))
                {
                    _logger.LogWarning(
                        "VDA5050 - 逆向冲突队列状态持久化冲突: RobotId={RobotId}, ExpectedPlanVersion={PlanVersion}",
                        robot.RobotId, expectedPlanVersion);
                    return ApiResponse.Successful("路径状态并发更新,等待下次调度");
                }

                expectedPlanVersion = cache.PlanVersion;
                await ScheduleResumeDispatchAsync(robot, currentSubTask, key, cache, expectedPlanVersion, ct);

                _logger.LogInformation("路口段存在逆向占用,暂停发送: RobotId={RobotId}", robot.RobotId);
                return ApiResponse.Successful("路口段存在逆向占用冲突,进入等待");
            }
            
            _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);
        }

        // 重新查询完整的 SubTask 信息(含导航属性)。
        // 兼容不落库的临时子任务:查不到时回退使用传入子任务继续下发。
        var fullSubTask = await _subTaskRepository.GetByIdWithDetailsAsync(currentSubTask.SubTaskId, ct);
        var canPersistSubTaskState = fullSubTask != null;
        if (fullSubTask == null)
        {
            fullSubTask = currentSubTask;
            _logger.LogDebug(
                "VDA5050 - 子任务未落库,使用内存子任务继续下发。RobotId={RobotId}, TaskId={TaskId}, SubTaskId={SubTaskId}",
                robot.RobotId,
                currentSubTask.TaskId,
                currentSubTask.SubTaskId);
        }

        var lastSeqId = cache.LastSentSequenceId;

        // if (IsInPlaceSegments(segmentsToSend))
        // {
        //     // 原地路径:不发送 Order,改为发送即时动作
        //     var instantAction = await BuildInstantActionFromInPlaceSegmentsAsync(robot, fullSubTask, segmentsToSend, ct);
        //     if (instantAction != null)
        //     {
        //         await _mqttClientService.PublishInstantActionsAsync(
        //             robot.ProtocolName,
        //             robot.ProtocolVersion,
        //             robot.RobotManufacturer,
        //             robot.RobotSerialNumber,
        //             instantAction,
        //             ct: ct);
        //
        //         _logger.LogInformation(
        //             "VDA5050 - 原地路径已改为即时动作发送,机器人: {SerialNumber}, 动作数: {ActionCount}",
        //             robot.RobotSerialNumber,
        //             instantAction.Actions.Count);
        //     }
        //     else
        //     {
        //         _logger.LogWarning(
        //             "VDA5050 - 原地路径未解析出有效动作,跳过即时动作发送,机器人: {SerialNumber}",
        //             robot.RobotSerialNumber);
        //     }
        // }
        // else
        // {
            // 构建订单并填充下一段路径
            // @author zzy
            // 2026-02-25 更新:分段发送时 sequenceId 延续已发送的值,prefix 段复用原始 sequenceId
            var order = BuildVdaOrder(robot, fullSubTask);
            var hasPrefixSegment = (junctionIndex > 0 || resourceIndex > 0);
            // 有 prefix 段时,从 LastSentSequenceId - 2 开始(prefix 的 FromNode 复用原始编号)
            // 无 prefix 段(首段)时,从 0 开始
            var startSeqId = hasPrefixSegment ? cache.LastSentSequenceId : 0;
            PathSegmentWithCode? temporaryNextSegment = null;
            if (resourceIndex + 1 < currentJunctionGroup.ResourceSegments.Count)
            {
                temporaryNextSegment = currentJunctionGroup.ResourceSegments[resourceIndex + 1].Segments.FirstOrDefault();
            }
            else if (junctionIndex + 1 < cache.JunctionSegments.Count)
            {
                temporaryNextSegment = cache.JunctionSegments[junctionIndex + 1]
                    .ResourceSegments
                    .FirstOrDefault()?
                    .Segments
                    .FirstOrDefault();
            }

            // 预告下一节点会额外增加一个 Released=false 节点,若超过上限则跳过预告。
            var maxDispatchNodeCount = GetMaxDispatchNodeCount();
            if (temporaryNextSegment != null && segmentsToSend.Count + 2 > maxDispatchNodeCount)
            {
                temporaryNextSegment = null;
            }

            await FillOrderWithSegmentsAsync(
                order,
                segmentsToSend,
                graph,
                robot,
                fullSubTask,
                startSeqId,
                ct,
                temporaryNextSegment);

            // 仅以 Released=true 的节点/边计算“已发送序列号”,避免预告段(Released=false)写入已发送队列。
            var lastReleasedNodeSeq = order.Nodes
                .Where(n => n.Released)
                .Select(n => n.SequenceId)
                .DefaultIfEmpty(startSeqId)
                .Max();
            var lastReleasedEdgeSeq = order.Edges
                .Where(e => e.Released)
                .Select(e => e.SequenceId)
                .DefaultIfEmpty(startSeqId)
                .Max();
            lastSeqId = Math.Max(lastReleasedNodeSeq, lastReleasedEdgeSeq);

            // 发送订单
            await _mqttClientService.PublishOrderAsync(
                robot.ProtocolName,
                robot.ProtocolVersion,
                robot.RobotManufacturer,
                robot.RobotSerialNumber,
                order,
                ct: ct);
        // }

        // 更新缓存:标记当前段为已发送,更新索引,记录最大 sequenceId
        currentJunctionGroup.ResourceSegments[resourceIndex].IsSent = true;
        cache.LastSentSequenceId = lastSeqId;

        if (string.Equals(cache.RouteMode, RouteModeRejoining, StringComparison.Ordinal))
        {
            cache.RouteMode = RouteModeNormal;
            cache.ActivePatchId = null;
            cache.HoldUntilUtc = null;
            cache.HoldNodeCode = null;
            cache.StablePassCount = 0;
            cache.ConsecutiveConflictFailCount = 0;
            cache.BlockedReason = null;
        }
        
        if (!reExec)
        {
            // 移动到下一个资源段
            resourceIndex++;
            if (resourceIndex >= currentJunctionGroup.ResourceSegments.Count)
            {
                // 当前路口段完成,移动到下一个路口段
                junctionIndex++;
                resourceIndex = 0;
            }
        }
        
        cache.CurrentJunctionIndex = junctionIndex;
        cache.CurrentResourceIndex = resourceIndex;

        if (cache.PlanVersion <= expectedPlanVersion)
        {
            cache.PlanVersion = expectedPlanVersion + 1;
        }
        
        if (!await TryPersistPathCacheCasWithFallbackAsync(db, key, cache, expectedPlanVersion, ct))
        {
            _logger.LogError(
                "路径段索引更新发生并发冲突: RobotId={RobotId}, ExpectedPlanVersion={PlanVersion}",
                robot.RobotId, expectedPlanVersion);
        }
        else
        {
            expectedPlanVersion = cache.PlanVersion;
        }
        // 递增执行次数
        fullSubTask.ExecutionCount++;

        _logger.LogInformation("VDA5050 - 子任务: {SubTaskId}, 执行次数递增为: {ExecutionCount}, 路口段: {JunctionIndex}, 资源段: {ResourceIndex}",
            fullSubTask.SubTaskId, fullSubTask.ExecutionCount, junctionIndex, resourceIndex);
        // 显式更新子任务实体(解决引用同步问题)
        fullSubTask.Start();
        if (canPersistSubTaskState)
        {
            // fullSubTask 由当前 DbContext 查询得到,已处于跟踪状态。
            // 仅提交变更,避免同键实体重复 Attach 导致跟踪冲突。
            await _subTaskRepository.SaveChangesAsync(ct);
        }
        else
        {
            _logger.LogDebug(
                "VDA5050 - 子任务未落库,跳过子任务状态持久化。RobotId={RobotId}, TaskId={TaskId}, SubTaskId={SubTaskId}",
                robot.RobotId,
                fullSubTask.TaskId,
                fullSubTask.SubTaskId);
        }

        // 持久化递增后的 HeaderId
        await _robotRepository.UpdateAsync(robot, ct);
        await _robotRepository.SaveChangesAsync(ct);

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

        return ApiResponse.Successful();
    }

    /// <summary>
    /// 根据制造商与序列号定位机器人并发送下一段路径。
    /// </summary>
    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);
                // 优先选择“存在执行中子任务”的执行中主任务,避免多InProgress主任务时选错上下文。
                var inProgressTaskWithRunningSubTask = tasks
                    .Where(t => t.Status == Rcs.Domain.Entities.TaskStatus.InProgress)
                    .Select(t => new
                    {
                        Task = t,
                        SubTask = t.SubTasks
                            .OrderBy(st => st.Sequence)
                            .FirstOrDefault(st => st.Status == Rcs.Domain.Entities.TaskStatus.InProgress)
                    })
                    .FirstOrDefault(x => x.SubTask != null);

                if (inProgressTaskWithRunningSubTask != null)
                {
                    _logger.LogDebug(
                        "[段发送] 选中执行中子任务上下文: RobotId={RobotId}, TaskId={TaskId}, SubTaskId={SubTaskId}",
                        robot.RobotId,
                        inProgressTaskWithRunningSubTask.Task.TaskId,
                        inProgressTaskWithRunningSubTask.SubTask!.SubTaskId);

                    return await SendNextSegmentInternalAsync(
                        robot,
                        inProgressTaskWithRunningSubTask.SubTask!,
                        ct,
                        reExec);
                }

                // 回退:如果没有执行中子任务,则沿用原逻辑从执行中主任务里找待执行子任务。
                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);
            var deleted1Plan = await db.KeyDeleteAsync(BuildPathPlanVersionKey(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 count1Plan = deleted1Plan ? 1 : 0;
            var totalDeleted = count1 + count1Plan + 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>
    public 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>
    /// 按当前等待信息调度一次延迟恢复发送。
    /// </summary>
    private async Task ScheduleResumeDispatchAsync(
        Robot robot,
        RobotSubTask currentSubTask,
        string pathCacheKey,
        VdaSegmentedPathCache cache,
        long expectedPlanVersion,
        CancellationToken ct)
    {
        try
        {
            var resumeAtUtc = cache.HoldUntilUtc ?? DateTime.Now.AddSeconds(1);
            await _globalNavigationResumeScheduler.ScheduleResumeAsync(new HoldResumeRequest
            {
                RobotId = robot.RobotId,
                RobotManufacturer = robot.RobotManufacturer,
                RobotSerialNumber = robot.RobotSerialNumber,
                TaskId = currentSubTask.TaskId,
                SubTaskId = currentSubTask.SubTaskId,
                PathCacheKey = pathCacheKey,
                ExpectedPlanVersion = expectedPlanVersion,
                HoldNodeCode = cache.HoldNodeCode,
                ResumeAtUtc = resumeAtUtc
            }, ct);
        }
        catch (Exception ex)
        {
            _logger.LogWarning(
                ex,
                "VDA5050 - 调度等待恢复触发失败: RobotId={RobotId}, TaskId={TaskId}, SubTaskId={SubTaskId}",
                robot.RobotId, currentSubTask.TaskId, currentSubTask.SubTaskId);
        }
    }

    /// <summary>
    /// 发布锁冲突事件给全局导航协调器。
    /// </summary>
    private async Task PublishLockConflictEventAsync(
        Guid robotId,
        string mapCode,
        string? nodeCode,
        string? edgeCode,
        bool hasReverseConflict,
        string? failureReason,
        CancellationToken ct)
    {
        try
        {
            await _globalNavigationCoordinator.PublishLockConflictEventAsync(new LockConflictNavigationEvent
            {
                RobotId = robotId,
                MapCode = mapCode,
                NodeCode = nodeCode,
                EdgeCode = edgeCode,
                HasReverseConflict = hasReverseConflict,
                FailureReason = failureReason,
                OccurredAtUtc = DateTime.Now
            }, ct);
        }
        catch (Exception ex)
        {
            _logger.LogDebug(
                ex,
                "VDA5050 - 发布锁冲突事件失败: RobotId={RobotId}, Node={NodeCode}, Edge={EdgeCode}",
                robotId,
                nodeCode,
                edgeCode);
        }
    }

    /// <summary>
    /// 刷新路径CAS动态配置。
    /// </summary>
    private void RefreshPathCasSettings()
    {
        var current = _settingsMonitor.CurrentValue;
        ApplyPathCasSettings(current);
    }

    /// <summary>
    /// 应用路径CAS配置并更新派生时间窗口参数。
    /// </summary>
    private void ApplyPathCasSettings(AppSettings appSettings)
    {
        _pathCasSettings = appSettings.GlobalNavigation?.PathCas ?? new GlobalPathCasSettings();
        _pathCasMetricsInterval = TimeSpan.FromSeconds(Math.Max(10, _pathCasSettings.MetricsIntervalSeconds));
        _pathCasWindowDuration = TimeSpan.FromSeconds(Math.Max(5, _pathCasSettings.WindowDurationSeconds));
    }

    /// <summary>
    /// 构建路径版本号Key。
    /// </summary>
    private static string BuildPathPlanVersionKey(string pathKey) => $"{pathKey}:planVersion";

    /// <summary>
    /// 确保路径版本号Key存在(仅首次写入)。
    /// </summary>
    private async Task EnsurePathPlanVersionKeyAsync(IDatabase db, string pathKey, long planVersion)
    {
        await db.StringSetAsync(BuildPathPlanVersionKey(pathKey), planVersion.ToString(), when: When.NotExists);
    }

    /// <summary>
    /// 按预期版本执行一次路径缓存CAS写入。
    /// </summary>
    private async Task<bool> TryPersistPathCacheCasAsync(
        IDatabase db,
        string pathKey,
        VdaSegmentedPathCache cache,
        long expectedPlanVersion,
        CancellationToken ct = default)
    {
        System.Threading.Interlocked.Increment(ref _pathCasDirectAttemptCount);
        RegisterPathCasWindowAttempt();
        var payload = JsonSerializer.Serialize(cache);
        var planVersionKey = BuildPathPlanVersionKey(pathKey);

        for (var attempt = 0; attempt < 2; attempt++)
        {
            ct.ThrowIfCancellationRequested();
            var tx = db.CreateTransaction();
            tx.AddCondition(Condition.StringEqual(planVersionKey, expectedPlanVersion.ToString()));
            _ = tx.StringSetAsync(pathKey, payload);
            _ = tx.StringSetAsync(planVersionKey, cache.PlanVersion.ToString());

            if (await tx.ExecuteAsync())
            {
                System.Threading.Interlocked.Increment(ref _pathCasDirectSuccessCount);
                MaybeLogPathCasMetrics();
                return true;
            }

            if (attempt == 0)
            {
                await db.StringSetAsync(planVersionKey, expectedPlanVersion.ToString(), when: When.NotExists);
            }
        }

        System.Threading.Interlocked.Increment(ref _pathCasConflictCount);
        RegisterPathCasWindowConflict();
        MaybeLogPathCasMetrics();
        return false;
    }

    /// <summary>
    /// 执行带回退机制的路径缓存CAS写入。
    /// </summary>
    private async Task<bool> TryPersistPathCacheCasWithFallbackAsync(
        IDatabase db,
        string pathKey,
        VdaSegmentedPathCache cache,
        long expectedPlanVersion,
        CancellationToken ct = default)
    {
        await ApplyPathCasBackpressureIfNeededAsync(ct);

        if (await TryPersistPathCacheCasAsync(db, pathKey, cache, expectedPlanVersion, ct))
        {
            return true;
        }

        System.Threading.Interlocked.Increment(ref _pathCasFallbackAttemptCount);
        var planVersionValue = await db.StringGetAsync(BuildPathPlanVersionKey(pathKey));
        if (planVersionValue.IsNullOrEmpty || !long.TryParse(planVersionValue.ToString(), out var latestVersion))
        {
            System.Threading.Interlocked.Increment(ref _pathCasFailureCount);
            RegisterPathCasWindowFailure();
            MaybeLogPathCasMetrics();
            return false;
        }

        if (cache.PlanVersion <= latestVersion)
        {
            cache.PlanVersion = latestVersion + 1;
        }

        var fallbackSuccess = await TryPersistPathCacheCasAsync(db, pathKey, cache, latestVersion, ct);
        if (fallbackSuccess)
        {
            System.Threading.Interlocked.Increment(ref _pathCasFallbackSuccessCount);
        }
        else
        {
            System.Threading.Interlocked.Increment(ref _pathCasFailureCount);
            RegisterPathCasWindowFailure();
        }

        MaybeLogPathCasMetrics();
        return fallbackSuccess;
    }

    /// <summary>
    /// 记录CAS窗口尝试计数。
    /// </summary>
    private void RegisterPathCasWindowAttempt()
    {
        lock (_pathCasWindowLock)
        {
            EnsurePathCasWindowUnlocked();
            _pathCasWindowAttemptCount++;
        }
    }

    /// <summary>
    /// 记录CAS窗口冲突计数。
    /// </summary>
    private void RegisterPathCasWindowConflict()
    {
        lock (_pathCasWindowLock)
        {
            EnsurePathCasWindowUnlocked();
            _pathCasWindowConflictCount++;
        }
    }

    /// <summary>
    /// 记录CAS窗口失败计数。
    /// </summary>
    private void RegisterPathCasWindowFailure()
    {
        lock (_pathCasWindowLock)
        {
            EnsurePathCasWindowUnlocked();
            _pathCasWindowFailureCount++;
        }
    }

    /// <summary>
    /// 在高冲突场景下应用随机退避,降低CAS冲突放大。
    /// </summary>
    private async Task ApplyPathCasBackpressureIfNeededAsync(CancellationToken ct)
    {
        RefreshPathCasSettings();

        if (!_pathCasSettings.EnableHighConflictBackoff)
        {
            return;
        }

        long attempts;
        long conflicts;

        lock (_pathCasWindowLock)
        {
            EnsurePathCasWindowUnlocked();
            attempts = _pathCasWindowAttemptCount;
            conflicts = _pathCasWindowConflictCount;
        }

        var minAttempts = Math.Max(1, _pathCasSettings.HighConflictMinAttempts);
        if (attempts < minAttempts)
        {
            return;
        }

        var conflictRatioThreshold = Math.Clamp(_pathCasSettings.HighConflictRatioThreshold, 0.01, 1.0);
        var conflictRatio = attempts == 0 ? 0 : (double)conflicts / attempts;
        if (conflictRatio < conflictRatioThreshold)
        {
            return;
        }

        var delayMinMs = Math.Max(1, _pathCasSettings.BackoffMinMs);
        var delayMaxMs = Math.Max(delayMinMs, _pathCasSettings.BackoffMaxMs);
        var delayMs = Random.Shared.Next(delayMinMs, delayMaxMs + 1);
        _logger.LogDebug(
            "[路径CAS] 高冲突退避: 尝试={Attempts}, 冲突={Conflicts}, 比例={Ratio:P2}, 延迟毫秒={DelayMs}",
            attempts, conflicts, conflictRatio, delayMs);
        await Task.Delay(delayMs, ct);
    }

    /// <summary>
    /// 若当前统计窗口过期则重置窗口计数。
    /// </summary>
    private void EnsurePathCasWindowUnlocked()
    {
        var now = DateTime.Now;
        if (now - _pathCasWindowStartedUtc < _pathCasWindowDuration)
        {
            return;
        }

        _pathCasWindowStartedUtc = now;
        _pathCasWindowAttemptCount = 0;
        _pathCasWindowConflictCount = 0;
        _pathCasWindowFailureCount = 0;
    }

    /// <summary>
    /// 按间隔输出路径CAS指标日志。
    /// </summary>
    private void MaybeLogPathCasMetrics()
    {
        RefreshPathCasSettings();
        var now = DateTime.Now;
        if (now - _lastPathCasMetricsLogUtc < _pathCasMetricsInterval)
        {
            return;
        }

        _lastPathCasMetricsLogUtc = now;
        var directAttempt = System.Threading.Interlocked.Read(ref _pathCasDirectAttemptCount);
        var directSuccess = System.Threading.Interlocked.Read(ref _pathCasDirectSuccessCount);
        var conflict = System.Threading.Interlocked.Read(ref _pathCasConflictCount);
        var fallbackAttempt = System.Threading.Interlocked.Read(ref _pathCasFallbackAttemptCount);
        var fallbackSuccess = System.Threading.Interlocked.Read(ref _pathCasFallbackSuccessCount);
        var failure = System.Threading.Interlocked.Read(ref _pathCasFailureCount);
        var conflictRatio = directAttempt == 0 ? 0 : (double)conflict / directAttempt;

        var minAttempts = Math.Max(1, _pathCasSettings.HighConflictMinAttempts);
        var conflictRatioThreshold = Math.Clamp(_pathCasSettings.HighConflictRatioThreshold, 0.01, 1.0);
        var logLevelIsWarning = directAttempt >= minAttempts &&
                                conflictRatio >= conflictRatioThreshold;

        if (logLevelIsWarning)
        {
            _logger.LogWarning(
                "[路径CAS] 指标告警: 直接尝试={DirectAttempt}, 直接成功={DirectSuccess}, 冲突={Conflict}, 冲突比={ConflictRatio:P2}, 回退尝试={FallbackAttempt}, 回退成功={FallbackSuccess}, 失败={Failure}",
                directAttempt, directSuccess, conflict, conflictRatio, fallbackAttempt, fallbackSuccess, failure);
            return;
        }

        _logger.LogInformation(
            "[路径CAS] 指标: 直接尝试={DirectAttempt}, 直接成功={DirectSuccess}, 冲突={Conflict}, 冲突比={ConflictRatio:P2}, 回退尝试={FallbackAttempt}, 回退成功={FallbackSuccess}, 失败={Failure}",
            directAttempt, directSuccess, conflict, conflictRatio, fallbackAttempt, fallbackSuccess, failure);
    }

    /// <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 lastSegment = resourceSegment.Segments.LastOrDefault();
        if (lastSegment == null)
        {
            return result;
        }

        // 批量执行网络动作
        var executeRequests = new List<NetActionExecuteRequest>();
        var resolvedTaskCode = string.IsNullOrWhiteSpace(cache.TaskCode)
            ? cache.TaskId.ToString()
            : cache.TaskCode;
        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 = resolvedTaskCode,
                SubTaskId = subTask.SubTaskId,
                NodeCode = lastSegment.ToNodeCode,
                NodeId = lastSegment.ToNodeId,
                EdgeId = lastSegment.EdgeId,
                EdgeCode = lastSegment.EdgeCode,
                JunctionIndex = prevJunctionIndex,
                ResourceIndex = prevResourceIndex
            });

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

        // 更新缓存状态
        var cacheKey = $"{_settings.Redis.KeyPrefixes.VdaPath}:{robot.RobotId}:{subTask.TaskId}:{subTask.SubTaskId}";
        var db = _redis.GetDatabase();
        var expectedPlanVersion = cache.PlanVersion;
        await EnsurePathPlanVersionKeyAsync(db, cacheKey, expectedPlanVersion);

        cache.NetActionStatus = NetActionExecutionStatus.Executing;
        cache.ActiveNetActionContextId = resourceSegment.EndNodeNetActionContextIds.FirstOrDefault();
        if (cache.PlanVersion <= expectedPlanVersion)
        {
            cache.PlanVersion = expectedPlanVersion + 1;
        }

        if (!await TryPersistPathCacheCasWithFallbackAsync(db, cacheKey, cache, expectedPlanVersion))
        {
            result.CanContinue = false;
            result.Message = "网络动作状态更新冲突,等待下次调度";
            return result;
        }

        expectedPlanVersion = cache.PlanVersion;

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

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

            // 更新缓存状态为失败
            cache.NetActionStatus = NetActionExecutionStatus.Failed;
            if (cache.PlanVersion <= expectedPlanVersion)
            {
                cache.PlanVersion = expectedPlanVersion + 1;
            }

            if (!await TryPersistPathCacheCasWithFallbackAsync(db, cacheKey, cache, expectedPlanVersion))
            {
                _logger.LogWarning("[网络动作检查] 失败状态写入冲突: RobotId={RobotId}", robot.RobotId);
            }
            else
            {
                expectedPlanVersion = cache.PlanVersion;
            }

            return result;
        }

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

            // 更新缓存状态为等待异步响应
            cache.NetActionStatus = NetActionExecutionStatus.WaitingAsyncResponse;
            if (cache.PlanVersion <= expectedPlanVersion)
            {
                cache.PlanVersion = expectedPlanVersion + 1;
            }

            if (!await TryPersistPathCacheCasWithFallbackAsync(db, cacheKey, cache, expectedPlanVersion))
            {
                _logger.LogWarning("[网络动作检查] 等待异步状态写入冲突: RobotId={RobotId}", robot.RobotId);
            }
            else
            {
                expectedPlanVersion = cache.PlanVersion;
            }

            return result;
        }

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

        // 更新缓存状态为成功
        cache.NetActionStatus = NetActionExecutionStatus.Success;
        cache.ActiveNetActionContextId = null;
        if (cache.PlanVersion <= expectedPlanVersion)
        {
            cache.PlanVersion = expectedPlanVersion + 1;
        }

        if (!await TryPersistPathCacheCasWithFallbackAsync(db, cacheKey, cache, expectedPlanVersion))
        {
            _logger.LogWarning("[网络动作检查] 成功状态写入冲突: RobotId={RobotId}", robot.RobotId);
        }
        else
        {
            expectedPlanVersion = cache.PlanVersion;
        }

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

    /// <summary>
    /// 判断指定机器人当前是否已在最后一段路径上(所有段已发送完毕)
    /// 通过Redis轻量读取VDA路径缓存,检查两层索引是否已越界
    /// @author zzy
    /// </summary>
    /// <param name="robotManufacturer">机器人制造商</param>
    /// <param name="robotSerialNumber">机器人序列号</param>
    /// <param name="ct">取消令牌</param>
    /// <returns>true表示所有段已发送完毕,false表示还有后续段或无法判断</returns>
    public async Task<bool> IsAllSegmentsSentAsync(string robotManufacturer, string robotSerialNumber, CancellationToken ct = default)
    {
        try
        {
            var robot = await _robotRepository.GetByManufacturerAndSerialNumberAsync(robotManufacturer, robotSerialNumber, ct);
            if (robot == null) return false;

            // 获取当前执行中的任务和子任务
            var tasks = await _taskRepository.GetByRobotIdAsync(robot.RobotId, ct);
            var inProgressTask = tasks.FirstOrDefault(t => t.Status == Domain.Entities.TaskStatus.InProgress);
            if (inProgressTask == null) return false;

            var currentSubTask = inProgressTask.SubTasks
                .OrderBy(st => st.Sequence)
                .FirstOrDefault(st => st.Status == Domain.Entities.TaskStatus.Pending
                    || st.Status == Domain.Entities.TaskStatus.InProgress);
            if (currentSubTask == null) return false;

            // 从Redis读取VDA路径缓存
            var cacheKey = $"{_settings.Redis.KeyPrefixes.VdaPath}:{robot.RobotId}:{currentSubTask.TaskId}:{currentSubTask.SubTaskId}";
            var cacheData = await _redis.GetDatabase().StringGetAsync(cacheKey);
            if (cacheData.IsNullOrEmpty) return false;

            var cache = JsonSerializer.Deserialize<VdaSegmentedPathCache>(cacheData.ToString());
            if (cache == null) return false;

            // 判断是否所有段都已发送完毕(与TryCompleteOrderFromStateAsync中相同的判断逻辑)
            var junctionIndex = cache.CurrentJunctionIndex;
            var resourceIndex = cache.CurrentResourceIndex;
            var totalJunctions = cache.JunctionSegments.Count;

            if (junctionIndex >= totalJunctions)
            {
                // 路口段索引已越界 = 全部发送完毕
                return true;
            }

            if (junctionIndex == totalJunctions - 1)
            {
                // 在最后一个路口段,检查资源段是否也全部发送
                var lastJunction = cache.JunctionSegments[junctionIndex];
                return resourceIndex >= lastJunction.ResourceSegments.Count;
            }

            return false;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "判断机器人 {Manufacturer}:{SerialNumber} 是否在最后一段路径失败",
                robotManufacturer, robotSerialNumber);
            // 异常时返回false,允许后续流程继续(SendNextSegmentAsync内部会再次判断)
            return false;
        }
    }

    /// <summary>
    /// 判断机器人当前是否行驶在已下发VDA路径的最后一个原子路径上
    /// 通过缓存获取机器人信息和VDA路径,结合机器人当前位置(最后经过的节点)进行判断
    /// 用于NewBaseRequest判断:只有当机器人在最后一段上时才发送下一段,否则跳过
    /// @author zzy
    /// 2026-02-25 重构:移除仓储查询,改用缓存直接获取VDA路径和机器人位置
    /// </summary>
    /// <param name="robotManufacturer">机器人制造商</param>
    /// <param name="robotSerialNumber">机器人序列号</param>
    /// <param name="ct">取消令牌</param>
    /// <returns>true表示当前正在已下发路径的最后一个原子路径上(可以发送下一段),false表示不在或无法判断(跳过发送)</returns>
    public async Task<bool> IsOnLastSentSegmentAsync(string robotManufacturer, string robotSerialNumber, CancellationToken ct = default)
    {
        try
        {
            // 从缓存获取机器人基础信息(获取RobotId)
            var basicCache = await _robotCacheService.GetBasicAsync(robotManufacturer, robotSerialNumber);
            if (basicCache == null)
            {
                _logger.LogWarning("IsOnLastSentSegmentAsync - 未找到机器人缓存: {Manufacturer}:{SerialNumber}",
                    robotManufacturer, robotSerialNumber);
                return false;
            }

            // 使用通配符查找该机器人VDA路径缓存Key(兼容历史残留/并发场景可能存在多个)
            var pattern = $"{_settings.Redis.KeyPrefixes.VdaPath}:{basicCache.RobotId}:*";
            var server = _redis.GetServer(_redis.GetEndPoints().First());
            var keys = server.Keys(pattern: pattern).ToArray();
            if (keys.Length == 0) return false;

            var db = _redis.GetDatabase();
            VdaSegmentedPathCache? cache = null;
            foreach (var key in keys)
            {
                var keyText = key.ToString();
                if (!IsVdaPathCachePayloadKey(keyText))
                {
                    continue;
                }

                var cacheData = await db.StringGetAsync(key);
                if (cacheData.IsNullOrEmpty)
                {
                    continue;
                }

                VdaSegmentedPathCache? candidate;
                try
                {
                    candidate = JsonSerializer.Deserialize<VdaSegmentedPathCache>(cacheData.ToString());
                }
                catch (Exception ex) when (ex is JsonException or NotSupportedException)
                {
                    _logger.LogDebug("IsOnLastSentSegmentAsync - 跳过无法反序列化的路径缓存Key: {CacheKey}", keyText);
                    continue;
                }

                if (candidate == null || candidate.JunctionSegments.Count == 0)
                {
                    continue;
                }

                if (cache == null || candidate.CreatedAt > cache.CreatedAt)
                {
                    cache = candidate;
                }
            }

            if (cache == null) return false;

            // 从缓存获取机器人最后经过的节点
            var statusCache = await _robotCacheService.GetStatusAsync(robotManufacturer, robotSerialNumber);
            if (statusCache?.LastNode == null) return false;

            // 从后往前遍历所有资源段,找到最后一个已发送的资源段
            VdaSegmentCacheItem? lastSentSegment = null;
            for (var j = cache.JunctionSegments.Count - 1; j >= 0 && lastSentSegment == null; j--)
            {
                var junction = cache.JunctionSegments[j];
                for (var r = junction.ResourceSegments.Count - 1; r >= 0; r--)
                {
                    if (junction.ResourceSegments[r].IsSent)
                    {
                        lastSentSegment = junction.ResourceSegments[r];
                        break;
                    }
                }
            }

            if (lastSentSegment == null || lastSentSegment.Segments.Count == 0) return false;

            // 获取最后一个已发送资源段中的最后一个原子路径
            var lastAtomicPath = lastSentSegment.Segments[^1];

            // 判断机器人最后经过的节点是否在最后一个原子路径上
            // FromNodeId: 机器人正在行驶该边 → 在最后一段上
            // ToNodeId: 机器人已到达该边终点 → 在最后一段上
            var lastPassedNode = statusCache?.LastNode;
            return lastPassedNode == lastAtomicPath.FromNodeCode || lastPassedNode == lastAtomicPath.ToNodeCode;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "判断机器人 {Manufacturer}:{SerialNumber} 是否在当前下发路径的最后一段失败",
                robotManufacturer, robotSerialNumber);
            // 异常时返回false,允许后续流程继续
            return false;
        }
    }

    /// <summary>
    /// 判断是否为VDA路径缓存主体Key(...:{robotId}:{taskId}:{subTaskId})。
    /// </summary>
    private static bool IsVdaPathCachePayloadKey(string keyText)
    {
        if (string.IsNullOrWhiteSpace(keyText))
        {
            return false;
        }

        var parts = keyText.Split(':', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
        if (parts.Length < 3)
        {
            return false;
        }

        return Guid.TryParse(parts[^3], out _) &&
               Guid.TryParse(parts[^2], out _) &&
               Guid.TryParse(parts[^1], out _);
    }

    /// <summary>
    /// 解析用于完成判断的目标子任务:
    /// 1. 优先使用 State.OrderId(SubTaskId)
    /// 2. 若 OrderId 缺失/无效/非当前执行子任务,则回退到机器人当前执行中的子任务
    /// </summary>
    private async Task<RobotSubTask?> ResolveSubTaskForCompletionAsync(
        Robot robot,
        string? stateOrderId,
        CancellationToken ct)
    {
        // 1) 优先尝试使用 State.OrderId
        if (!string.IsNullOrWhiteSpace(stateOrderId) && Guid.TryParse(stateOrderId, out var orderSubTaskId))
        {
            var orderSubTask = await _subTaskRepository.GetByIdWithDetailsAsync(orderSubTaskId, ct);
            if (orderSubTask != null
                && orderSubTask.RobotId == robot.RobotId
                && orderSubTask.Status == Domain.Entities.TaskStatus.InProgress)
            {
                return orderSubTask;
            }

            _logger.LogDebug(
                "[VDA完成判断] State.OrderId 对应子任务不可用,转为回退匹配: RobotId={RobotId}, StateOrderId={OrderId}",
                robot.RobotId,
                stateOrderId);
        }

        // 2) 回退:根据机器人当前执行任务定位子任务
        var tasks = await _taskRepository.GetByRobotIdAsync(robot.RobotId, ct);
        var inProgressTask = tasks.FirstOrDefault(t => t.Status == Domain.Entities.TaskStatus.InProgress);
        if (inProgressTask == null)
        {
            return null;
        }

        var inProgressSubTask = inProgressTask.SubTasks
            .OrderBy(st => st.Sequence)
            .FirstOrDefault(st => st.Status == Domain.Entities.TaskStatus.InProgress);
        if (inProgressSubTask == null)
        {
            return null;
        }

        return await _subTaskRepository.GetByIdWithDetailsAsync(inProgressSubTask.SubTaskId, ct);
    }

    /// <summary>
    /// 根据VDA5050 State消息判断并处理订单(子任务)完成
    /// 判断条件:未行驶 + NodeStates为空 + EdgeStates为空 + 所有动作完成 + 最后一段已发送
    /// 子任务识别:优先使用State.OrderId,失败时回退到当前执行子任务
    /// @author zzy
    /// </summary>
    /// <param name="robotManufacturer">机器人制造商</param>
    /// <param name="robotSerialNumber">机器人序列号</param>
    /// <param name="stateInfo">VDA5050 State消息数据</param>
    /// <param name="ct">取消令牌</param>
    /// <returns>是否成功触发了完成</returns>
    public async Task<bool> TryCompleteOrderFromStateAsync(
        string robotManufacturer, string robotSerialNumber,
        State stateInfo, CancellationToken ct = default)
    {
        // 机器人必须已停止行驶
        if (stateInfo.Driving)
        {
            return false;
        }

        // NodeStates和EdgeStates必须为空(所有路径已走完)
        if (stateInfo.NodeStates != null && stateInfo.NodeStates.Count > 0)
        {
            return false;
        }
        if (stateInfo.EdgeStates != null && stateInfo.EdgeStates.Count > 0)
        {
            return false;
        }

        // 所有动作必须已完成(不存在未完成的动作)
        if (stateInfo.ActionStates != null && stateInfo.ActionStates.Count > 0)
        {
            var hasUnfinishedAction = stateInfo.ActionStates.Any(a =>
                a.ActionStatus != "FINISHED");
            if (hasUnfinishedAction)
            {
                return false;
            }

            // // 存在FAILED动作时记录警告,但不阻止完成判断
            // var failedActions = stateInfo.ActionStates.Where(a => a.ActionStatus == "FAILED").ToList();
            // if (failedActions.Any())
            // {
            //     _logger.LogWarning(
            //         "[VDA完成判断] 存在失败的动作,但仍继续完成判断: Robot={Manufacturer}:{SerialNumber}, FailedActions={Actions}",
            //         robotManufacturer, robotSerialNumber,
            //         string.Join(",", failedActions.Select(a => $"{a.ActionId}:{a.ActionType}")));
            // }
        }

        var robot = await _robotRepository.GetByManufacturerAndSerialNumberAsync(robotManufacturer, robotSerialNumber, ct);
        if (robot == null)
        {
            _logger.LogWarning("[VDA完成判断] 机器人不存在: {Manufacturer}:{SerialNumber}",
                robotManufacturer, robotSerialNumber);
            return false;
        }

        // 查找对应的子任务:优先使用State.OrderId,失败时回退当前执行子任务
        var subTask = await ResolveSubTaskForCompletionAsync(robot, stateInfo.OrderId, ct);
        var subTaskId = subTask?.SubTaskId;
        if (subTask != null)
        {
            
            if (subTask.Status == Domain.Entities.TaskStatus.Completed || subTask.Status != Domain.Entities.TaskStatus.InProgress)
            {
                return false;
            }
            // 最够经过的节点为任务终点
            if (string.IsNullOrEmpty(stateInfo.LastNodeId) || stateInfo.LastNodeId != subTask.EndNode?.NodeCode )
            {
                return false;
            }
        }


        // 检查VDA路径缓存,确认是最后一段已发送
        var cacheKey = $"{_settings.Redis.KeyPrefixes.VdaPath}:{robot.RobotId}:{subTask?.TaskId ?? Guid.Empty}:{subTaskId ?? Guid.Empty}";
        var cacheData = await _redis.GetDatabase().StringGetAsync(cacheKey);
        VdaSegmentedPathCache? pathCache = null;

        if (!cacheData.IsNullOrEmpty)
        {
            var cache = JsonSerializer.Deserialize<VdaSegmentedPathCache>(cacheData.ToString());
            if (cache != null)
            {
                pathCache = cache;
                // 判断是否所有段都已发送完毕(两层索引都必须越界)
                // 情况1:CurrentJunctionIndex 已超出路口段总数(最后一个路口段的最后一个资源段发送后递增越界)
                // 情况2:CurrentJunctionIndex 在最后一个路口段,但 CurrentResourceIndex 已超出该路口段的资源段总数
                var junctionIndex = cache.CurrentJunctionIndex;
                var resourceIndex = cache.CurrentResourceIndex;
                var totalJunctions = cache.JunctionSegments.Count;

                bool isAllSegmentsSent;
                if (junctionIndex >= totalJunctions)
                {
                    // 路口段索引已越界 = 全部发送完毕
                    isAllSegmentsSent = true;
                }
                else if (junctionIndex == totalJunctions - 1)
                {
                    // 在最后一个路口段,检查资源段是否也全部发送
                    var lastJunction = cache.JunctionSegments[junctionIndex];
                    isAllSegmentsSent = resourceIndex >= lastJunction.ResourceSegments.Count;
                }
                else
                {
                    // 还有未到达的路口段
                    isAllSegmentsSent = false;
                }

                if (!isAllSegmentsSent)
                {
                    _logger.LogDebug(
                        "[VDA完成判断] 还有未发送的路径段: SubTaskId={SubTaskId}, JunctionIndex={JI}/{JTotal}, ResourceIndex={RI}",
                        subTaskId, junctionIndex, totalJunctions, resourceIndex);
                    return false;
                }
            }
        }

        // 使用分布式锁防止并发完成
        var completionLockKey = $"order_completion_lock:{subTaskId}";
        var lockAcquired = await _redis.GetDatabase().StringSetAsync(
            completionLockKey, "1", TimeSpan.FromSeconds(30), When.NotExists);

        if (!lockAcquired)
        {
            _logger.LogDebug("[VDA完成判断] 完成处理正在进行中,跳过: SubTaskId={SubTaskId}", subTaskId);
            return false;
        }

        try
        {
            // 末段补充:当所有路径段已发送完成时,仍需检查并触发“最后一段终点”的网络动作。
            // 现有机制是在发送下一段前检查上一段终点;末段没有“下一段”,需在完成判断阶段补一次检查。
            if (subTask != null && pathCache != null)
            {
                var tailNetActionCheck = await CheckAndExecuteNetActionsAsync(
                    robot,
                    subTask,
                    pathCache,
                    pathCache.CurrentJunctionIndex,
                    pathCache.CurrentResourceIndex);

                if (!tailNetActionCheck.CanContinue)
                {
                    _logger.LogInformation(
                        "[VDA完成判断] 末段终点网络动作拦截完成: SubTaskId={SubTaskId}, Message={Message}, WaitingAsync={WaitingAsync}",
                        subTask.SubTaskId,
                        tailNetActionCheck.Message,
                        tailNetActionCheck.IsWaitingAsync);
                    return false;
                }
            }

            _logger.LogInformation(
                "[VDA完成判断] 订单完成条件满足,触发子任务完成: Robot={Manufacturer}:{SerialNumber}, SubTaskId={SubTaskId}, TaskId={TaskId}",
                robotManufacturer, robotSerialNumber, subTaskId, subTask?.TaskId);

            // 触发子任务完成(会添加 SubTaskCompletedDomainEvent)
            if (subTask != null)
            {
                subTask.Complete();
                await _subTaskRepository.UpdateAsync(subTask, ct);
                await _subTaskRepository.SaveChangesAsync(ct);
            }
            else
            {
                // 兜底无任务取消VDA订单
                await CancelRobotTasksAsync(robot, ct);
            }

            return true;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "[VDA完成判断] 触发子任务完成失败: SubTaskId={SubTaskId}", subTaskId);
            return false;
        }
        finally
        {
            await _redis.GetDatabase().KeyDeleteAsync(completionLockKey);
        }
    }
}