TaskDispatchBackgroundService.cs 93.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 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
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.EntityFrameworkCore;
using Rcs.Application.Services;
using Rcs.Application.Services.PathFind;
using Rcs.Application.Services.PathFind.Models;
using Rcs.Application.Shared;
using Rcs.Domain.Entities;
using Rcs.Domain.Enums;
using Rcs.Domain.Repositories;
using Rcs.Domain.Settings;
using Rcs.Infrastructure.DB.MsSql;
using StackExchange.Redis;
using TaskStatus = Rcs.Domain.Entities.TaskStatus;

namespace Rcs.Infrastructure.Services
{
    /// <summary>
    /// 后台任务调度服务 - 循环调度等待中的任务分配给空闲机器人
    /// @author zzy
    /// </summary>
    public class TaskDispatchBackgroundService : BackgroundService, ITaskDispatchService
    {
        private readonly ILogger<TaskDispatchBackgroundService> _logger;
        private readonly IServiceProvider _serviceProvider;
        private readonly IAgvPathService _agvPathService;
        private readonly IOptionsMonitor<AppSettings> _settingsMonitor;
        private readonly TimeSpan _dispatchInterval = TimeSpan.FromSeconds(2);
        private const int MaxPendingTasksPerCycle = 10;
        private const double EtaPrioritySlackMeters = 5d;
        private const double EtaWeight = 0.55d;
        private const double DetourWeight = 0.20d;
        private const double LoadWeight = 0.20d;
        private const double TaskCountWeight = 0.05d;
        private const string TaskExecutionStartedLatchKeySuffix = "task-exec-started";

        public TaskDispatchBackgroundService(
            ILogger<TaskDispatchBackgroundService> logger,
            IServiceProvider serviceProvider,
            IAgvPathService agvPathService,
            IOptionsMonitor<AppSettings> settingsMonitor)
        {
            _logger = logger;
            _serviceProvider = serviceProvider;
            _agvPathService = agvPathService;
            _settingsMonitor = settingsMonitor;
        }

        /// <summary>
        /// 后台服务执行入口
        /// @author zzy
        /// </summary>
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            _logger.LogInformation("[任务调度] 后台任务调度服务已启动");

            while (!stoppingToken.IsCancellationRequested)
            {
                try
                {
                    await DispatchAsync(stoppingToken);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "[任务调度] 调度过程发生异常");
                }

                await Task.Delay(_dispatchInterval, stoppingToken);
            }

            _logger.LogInformation("[任务调度] 后台任务调度服务已停止");
        }

        /// <summary>
        /// 执行一次任务调度
        /// @author zzy
        /// </summary>
        public async Task<TaskDispatchResult> DispatchAsync(CancellationToken cancellationToken = default)
        {
            using var scope = _serviceProvider.CreateScope();
            var taskRepo = scope.ServiceProvider.GetRequiredService<IRobotTaskRepository>();
            var robotRepo = scope.ServiceProvider.GetRequiredService<IRobotRepository>();
            var robotCache = scope.ServiceProvider.GetRequiredService<IRobotCacheService>();
            var templateRepo = scope.ServiceProvider.GetRequiredService<ITaskTemplateRepository>();
            var locationTypeRepo = scope.ServiceProvider.GetRequiredService<IStorageLocationTypeRepository>();
            var chargingPileRepo = scope.ServiceProvider.GetRequiredService<IChargingPileRepository>();
            var subTaskRepo = scope.ServiceProvider.GetRequiredService<IRobotSubTaskRepository>();
            var taskLeaseService = scope.ServiceProvider.GetRequiredService<ITaskLeaseService>();
            var dbContext = scope.ServiceProvider.GetRequiredService<AppDbContext>();
            var redis = scope.ServiceProvider.GetRequiredService<IConnectionMultiplexer>();

            await PreRecoverUnstartedAssignedTasksAsync(
                subTaskRepo,
                taskLeaseService,
                dbContext,
                redis,
                cancellationToken);

            var pendingTasks = (await taskRepo.GetByStatusAsync(TaskStatus.Pending, cancellationToken))
                .OrderByDescending(t => t.Priority)
                .ThenBy(t => GetCreatedAtMilliseconds(t.CreatedAt))
                .ThenBy(t => t.TaskId)
                .Take(MaxPendingTasksPerCycle)
                .ToList();
            if (!pendingTasks.Any())
            {
                return new TaskDispatchResult { Success = true, AssignedCount = 0, Message = "无待调度任务" };
            }

            var pendingTaskDetails = new List<RobotTask>(pendingTasks.Count);
            foreach (var pendingTask in pendingTasks)
            {
                var detail = await taskRepo.GetByIdWithDetailsAsync(pendingTask.TaskId, cancellationToken);
                if (detail != null)
                {
                    pendingTaskDetails.Add(detail);
                }
            }

            if (!pendingTaskDetails.Any())
            {
                return new TaskDispatchResult { Success = true, AssignedCount = 0, Message = "待调度任务详情缺失" };
            }

            var dispatchContexts = await BuildPendingTaskDispatchContextsAsync(
                pendingTaskDetails,
                robotCache,
                locationTypeRepo,
                chargingPileRepo,
                cancellationToken);
            if (!dispatchContexts.Any())
            {
                return new TaskDispatchResult { Success = true, AssignedCount = 0, Message = "无可调度任务上下文" };
            }

            var candidateRobotIds = dispatchContexts
                .SelectMany(c => c.CandidateRobotIds)
                .Distinct()
                .ToList();

            var liveRobotById = dispatchContexts
                .SelectMany(c => c.CandidateRobots)
                .GroupBy(r => r.RobotId)
                .ToDictionary(g => g.Key, g => g.First());

            var robotEntities = new List<Robot>(candidateRobotIds.Count);
            foreach (var robotId in candidateRobotIds)
            {
                var robot = await robotRepo.GetByIdFullDataAsync(robotId, cancellationToken);
                if (robot != null)
                {
                    robotEntities.Add(robot);
                }
            }

            if (!robotEntities.Any())
            {
                return new TaskDispatchResult { Success = true, AssignedCount = 0, Message = "无可用机器人" };
            }

            var assignedTasks = await taskRepo.GetByStatusAsync(TaskStatus.Assigned, cancellationToken);
            var inProgressTasks = await taskRepo.GetByStatusAsync(TaskStatus.InProgress, cancellationToken);
            var activeTaskIds = assignedTasks
                .Concat(inProgressTasks)
                .Where(t => t.RobotId.HasValue)
                .Select(t => t.TaskId)
                .Distinct()
                .ToList();

            var activeTasks = new List<RobotTask>(activeTaskIds.Count);
            foreach (var taskId in activeTaskIds)
            {
                var task = await taskRepo.GetByIdWithDetailsAsync(taskId, cancellationToken);
                if (task?.RobotId.HasValue == true)
                {
                    activeTasks.Add(task);
                }
            }

            var activeTasksByRobot = activeTasks
                .Where(t => t.RobotId.HasValue)
                .GroupBy(t => t.RobotId!.Value)
                .ToDictionary(g => g.Key, g => (IReadOnlyCollection<RobotTask>)g.ToList());

            int assignedCount = 0;
            var dispatchRoundRobotStates = new Dictionary<Guid, DispatchRoundRobotState>();
            var assignedTaskIdsThisRound = new HashSet<Guid>();
            var skippedTaskIdsThisRound = new HashSet<Guid>();
            var mapGraphCache = new Dictionary<Guid, PathGraph?>();
            var pathCostCache = new Dictionary<PathCostCacheKey, double>();

            foreach (var robot in robotEntities.OrderBy(r => r.RobotCode))
            {
                if (!liveRobotById.TryGetValue(robot.RobotId, out var liveRobot))
                {
                    continue;
                }

                activeTasksByRobot.TryGetValue(robot.RobotId, out var robotActiveTasks);
                var currentRobotActiveTasks = robotActiveTasks ?? Array.Empty<RobotTask>();
                var slots = BuildDistributableSlotsForRobot(robot);
                if (!slots.Any())
                {
                    continue;
                }

                var anchor = await ResolveDispatchAnchorAsync(
                    robot,
                    liveRobot,
                    currentRobotActiveTasks,
                    redis,
                    cancellationToken);
                if (!anchor.CanDispatch)
                {
                    continue;
                }

                foreach (var slot in slots)
                {
                    var candidates = new List<RobotDispatchTaskCandidate>();
                    foreach (var context in dispatchContexts)
                    {
                        var task = context.Task;
                        if (assignedTaskIdsThisRound.Contains(task.TaskId)
                            || skippedTaskIdsThisRound.Contains(task.TaskId))
                        {
                            continue;
                        }

                        if (task.Status != TaskStatus.Pending)
                        {
                            continue;
                        }

                        if (task.RobotId.HasValue && task.RobotId.Value != robot.RobotId)
                        {
                            continue;
                        }

                        if (!context.CandidateRobotIds.Contains(robot.RobotId))
                        {
                            continue;
                        }

                        if (!string.IsNullOrWhiteSpace(task.ShelfCode)
                            && !string.Equals(task.ShelfCode.Trim(), slot.Location.LocationCode, StringComparison.OrdinalIgnoreCase))
                        {
                            continue;
                        }

                        var mixedLineResult = await CanAssignMixedLineExclusiveTaskAsync(
                            task,
                            context.BeginLocationType,
                            liveRobot,
                            currentRobotActiveTasks,
                            locationTypeRepo,
                            new Dictionary<Guid, bool>
                            {
                                [context.BeginLocationType.TypeId] = context.BeginLocationType.IsMixedLineShelfTaskExclusive
                            },
                            cancellationToken);
                        if (!mixedLineResult.CanAssign)
                        {
                            if (mixedLineResult.IsMixedLineSoftConstraintFailure)
                            {
                                ExcludeRobotForSoftMixedLineFailure(
                                    liveRobot.RobotId,
                                    task.Priority,
                                    dispatchRoundRobotStates);
                            }

                            continue;
                        }

                        if (ShouldSkipRobotExcludedByHigherPrioritySoftMixedLineFailure(
                                task,
                                liveRobot.RobotId,
                                dispatchRoundRobotStates))
                        {
                            continue;
                        }

                        var cost = await CalculateDispatchCostAsync(
                            robot,
                            anchor,
                            task,
                            mapGraphCache,
                            pathCostCache,
                            cancellationToken);
                        if (double.IsNaN(cost) || double.IsInfinity(cost) || cost == double.MaxValue)
                        {
                            continue;
                        }

                        candidates.Add(new RobotDispatchTaskCandidate(task, context, cost));
                    }

                    var selected = candidates
                        .OrderByDescending(c => c.Task.Priority)
                        .ThenBy(c => c.Cost)
                        .ThenBy(c => GetCreatedAtMilliseconds(c.Task.CreatedAt))
                        .ThenBy(c => c.Task.TaskId)
                        .FirstOrDefault();

                    if (selected == null)
                    {
                        continue;
                    }

                    var assigned = await TryAssignTaskToSlotAsync(
                        selected,
                        slot,
                        robot,
                        liveRobot,
                        taskRepo,
                        subTaskRepo,
                        templateRepo,
                        taskLeaseService,
                        dbContext,
                        cancellationToken);
                    if (!assigned)
                    {
                        skippedTaskIdsThisRound.Add(selected.Task.TaskId);
                        continue;
                    }

                    assignedTaskIdsThisRound.Add(selected.Task.TaskId);
                    assignedCount++;

                    _logger.LogInformation(
                        "[任务调度] 任务 {TaskCode} 已分配给机器人 {RobotCode},缓存位 {ShelfCode}",
                        selected.Task.TaskCode,
                        robot.RobotCode,
                        slot.Location.LocationCode);
                }
            }

            return new TaskDispatchResult
            {
                Success = true,
                AssignedCount = assignedCount,
                Message = $"本次调度完成,已分配 {assignedCount} 个任务"
            };
        }

        private static void ExcludeRobotForSoftMixedLineFailure(
            Guid robotId,
            int taskPriority,
            IDictionary<Guid, DispatchRoundRobotState> dispatchRoundRobotStates)
        {
            if (!dispatchRoundRobotStates.TryGetValue(robotId, out var robotState))
            {
                robotState = new DispatchRoundRobotState();
                dispatchRoundRobotStates[robotId] = robotState;
            }

            if (!robotState.SoftMixedLineFailurePriority.HasValue
                || taskPriority > robotState.SoftMixedLineFailurePriority.Value)
            {
                robotState.SoftMixedLineFailurePriority = taskPriority;
            }
        }

        private static long GetCreatedAtMilliseconds(DateTime createdAt)
        {
            return createdAt.Ticks / TimeSpan.TicksPerMillisecond;
        }

        private async Task<List<PendingTaskDispatchContext>> BuildPendingTaskDispatchContextsAsync(
            IReadOnlyCollection<RobotTask> pendingTaskDetails,
            IRobotCacheService robotCache,
            IStorageLocationTypeRepository locationTypeRepo,
            IChargingPileRepository chargingPileRepo,
            CancellationToken cancellationToken)
        {
            var result = new List<PendingTaskDispatchContext>(pendingTaskDetails.Count);
            foreach (var task in pendingTaskDetails)
            {
                var context = await GetStaticDispatchContextAsync(
                    task,
                    robotCache,
                    locationTypeRepo,
                    chargingPileRepo,
                    cancellationToken);
                if (!context.HasValue)
                {
                    continue;
                }

                var candidateRobots = context.Value.CandidateRobots;
                if (!candidateRobots.Any())
                {
                    continue;
                }

                result.Add(new PendingTaskDispatchContext(
                    task,
                    context.Value.BeginLocationType,
                    context.Value.EndLocationType,
                    candidateRobots,
                    candidateRobots.Select(r => r.RobotId).ToHashSet()));
            }

            return result;
        }

        private async Task PreRecoverUnstartedAssignedTasksAsync(
            IRobotSubTaskRepository subTaskRepo,
            ITaskLeaseService taskLeaseService,
            AppDbContext dbContext,
            IConnectionMultiplexer redis,
            CancellationToken cancellationToken)
        {
            var redisDb = redis.GetDatabase();
            var assignedTaskSnapshots = await dbContext.Set<RobotTask>()
                .AsNoTracking()
                .Where(t => t.Status == TaskStatus.Assigned)
                .Select(t => new PreRecoverTaskSnapshot(t.TaskId, t.TaskCode, t.RobotId))
                .ToListAsync(cancellationToken);
            if (!assignedTaskSnapshots.Any())
            {
                return;
            }

            foreach (var snapshot in assignedTaskSnapshots)
            {
                var executionLatchKey = BuildExecutionStartedLatchKey(snapshot.TaskId);
                if (await redisDb.KeyExistsAsync(executionLatchKey))
                {
                    _logger.LogDebug(
                        "[任务调度] 预恢复跳过(存在执行开始门闩): TaskCode={TaskCode}, TaskId={TaskId}",
                        snapshot.TaskCode,
                        snapshot.TaskId);
                    continue;
                }

                var leaseAcquireResult = await taskLeaseService.TryAcquireAsync(
                    snapshot.TaskId,
                    snapshot.RobotId,
                    "dispatch-pre-restore",
                    cancellationToken);
                if (!leaseAcquireResult.Success || leaseAcquireResult.Lease == null)
                {
                    _logger.LogDebug(
                        "[任务调度] 预恢复跳过(存在执行门闩锁或并发冲突): TaskCode={TaskCode}, TaskId={TaskId}",
                        snapshot.TaskCode,
                        snapshot.TaskId);
                    continue;
                }

                await using var lease = leaseAcquireResult.Lease;
                await using var tx = await dbContext.Database.BeginTransactionAsync(cancellationToken);

                var freshAssignedTask = await dbContext.Set<RobotTask>()
                    .Include(t => t.SubTasks)
                    .FirstOrDefaultAsync(t => t.TaskId == snapshot.TaskId, cancellationToken);
                if (freshAssignedTask == null
                    || freshAssignedTask.Status != TaskStatus.Assigned
                    || !IsTaskUnstarted(freshAssignedTask))
                {
                    await tx.RollbackAsync(cancellationToken);
                    continue;
                }

                await RestoreTaskToPendingForRedispatchAsync(
                    freshAssignedTask,
                    subTaskRepo,
                    dbContext,
                    cancellationToken);

                await dbContext.SaveChangesAsync(cancellationToken);
                await tx.CommitAsync(cancellationToken);
            }
        }

        private static List<DistributableSlot> BuildDistributableSlotsForRobot(Robot robot)
        {
            var slots = new List<DistributableSlot>();
            foreach (var cacheLocation in robot.CacheLocations
                         .OrderBy(c => c.Level)
                         .ThenBy(c => c.Column)
                         .ThenBy(c => c.Row)
                         .ThenBy(c => c.LocationCode))
            {
                if (string.IsNullOrWhiteSpace(cacheLocation.LocationCode))
                {
                    continue;
                }

                if (!string.IsNullOrWhiteSpace(cacheLocation.ContainerId))
                {
                    continue;
                }

                slots.Add(new DistributableSlot(cacheLocation));
            }
            return slots;
        }

        private static bool IsTaskUnstarted(RobotTask task)
        {
            if (task.Status != TaskStatus.Assigned)
            {
                return false;
            }

            if (!task.SubTasks.Any())
            {
                return true;
            }

            return task.SubTasks.All(st =>
                st.ExecutionCount == 0
                && st.Status != TaskStatus.InProgress
                && st.Status != TaskStatus.Completed
                && st.Status != TaskStatus.Failed
                && st.Status != TaskStatus.Cancelled
                && st.Status != TaskStatus.Timeout);
        }

        private string BuildExecutionStartedLatchKey(Guid taskId)
        {
            return $"{_settingsMonitor.CurrentValue.Redis.KeyPrefixes.TaskLeasePrefix}:{TaskExecutionStartedLatchKeySuffix}:{taskId}";
        }

        private async Task<RobotDispatchAnchor> ResolveDispatchAnchorAsync(
            Robot robot,
            Robot liveRobot,
            IReadOnlyCollection<RobotTask> robotActiveTasks,
            IConnectionMultiplexer redis,
            CancellationToken cancellationToken)
        {
            var inProgressTask = robotActiveTasks
                .FirstOrDefault(t => t.SubTasks.Any(st => st.Status == TaskStatus.InProgress));
            var inProgressSubTask = inProgressTask?
                .SubTasks
                .OrderBy(st => st.Sequence)
                .FirstOrDefault(st => st.Status == TaskStatus.InProgress);

            if (inProgressTask != null && inProgressSubTask == null)
            {
                _logger.LogInformation(
                    "[任务调度] 跳过机器人(存在执行中任务但未找到执行中子任务): RobotCode={RobotCode}, TaskCode={TaskCode}",
                    robot.RobotCode,
                    inProgressTask.TaskCode);
                return RobotDispatchAnchor.Deny();
            }

            if (inProgressSubTask != null && inProgressSubTask.EndNode == null)
            {
                _logger.LogInformation(
                    "[任务调度] 跳过机器人(执行中子任务终点缺失): RobotCode={RobotCode}, TaskCode={TaskCode}, SubTaskId={SubTaskId}",
                    robot.RobotCode,
                    inProgressTask?.TaskCode,
                    inProgressSubTask.SubTaskId);
                return RobotDispatchAnchor.Deny();
            }

            if (inProgressTask != null && inProgressSubTask?.EndNode != null)
            {
                var sourcePoint = new DispatchPoint(
                    inProgressSubTask.EndNode.MapId,
                    inProgressSubTask.EndNode.NodeId,
                    inProgressSubTask.EndNode.X,
                    inProgressSubTask.EndNode.Y,
                    null);

                if (robot.ProtocolType == ProtocolType.VDA)
                {
                    var endTheta = await TryGetInProgressSubTaskEndThetaFromVdaPathCacheAsync(
                        redis,
                        robot.RobotId,
                        inProgressTask.TaskId,
                        inProgressSubTask.SubTaskId,
                        cancellationToken);
                    if (!endTheta.HasValue)
                    {
                        _logger.LogInformation(
                            "[任务调度] 跳过机器人(执行中子任务路径缓存终点朝向缺失): RobotCode={RobotCode}, TaskCode={TaskCode}, SubTaskId={SubTaskId}",
                            robot.RobotCode,
                            inProgressTask.TaskCode,
                            inProgressSubTask.SubTaskId);
                        return RobotDispatchAnchor.Deny();
                    }

                    return RobotDispatchAnchor.Allow(sourcePoint with { Theta = endTheta.Value }, useLinearFallbackCost: false);
                }

                return RobotDispatchAnchor.Allow(
                    sourcePoint with { Theta = liveRobot.CurrentTheta ?? robot.CurrentTheta },
                    useLinearFallbackCost: true);
            }

            var mapId = liveRobot.CurrentMapCodeId ?? robot.CurrentMapCodeId;
            var sourceX = liveRobot.CurrentX ?? robot.CurrentX ?? robot.MapNode?.X;
            var sourceY = liveRobot.CurrentY ?? robot.CurrentY ?? robot.MapNode?.Y;
            if (!mapId.HasValue || !sourceX.HasValue || !sourceY.HasValue)
            {
                _logger.LogInformation(
                    "[任务调度] 跳过机器人(缺少起始位姿): RobotCode={RobotCode}",
                    robot.RobotCode);
                return RobotDispatchAnchor.Deny();
            }

            return RobotDispatchAnchor.Allow(new DispatchPoint(
                mapId.Value,
                liveRobot.CurrentNodeId ?? robot.CurrentNodeId,
                sourceX.Value,
                sourceY.Value,
                liveRobot.CurrentTheta ?? robot.CurrentTheta));
        }

        private async Task<double?> TryGetInProgressSubTaskEndThetaFromVdaPathCacheAsync(
            IConnectionMultiplexer redis,
            Guid robotId,
            Guid taskId,
            Guid subTaskId,
            CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            var key = $"{_settingsMonitor.CurrentValue.Redis.KeyPrefixes.VdaPath}:{robotId}:{taskId}:{subTaskId}";
            var cacheData = await redis.GetDatabase().StringGetAsync(key);
            if (!cacheData.HasValue)
            {
                return null;
            }

            VdaSegmentedPathCache? cache;
            try
            {
                cache = System.Text.Json.JsonSerializer.Deserialize<VdaSegmentedPathCache>(cacheData.ToString());
            }
            catch
            {
                return null;
            }

            var lastSegment = cache?.JunctionSegments
                .SelectMany(j => j.ResourceSegments)
                .SelectMany(r => r.Segments)
                .LastOrDefault();
            return lastSegment?.EndTheta;
        }

        private async Task<double> CalculateDispatchCostAsync(
            Robot robot,
            RobotDispatchAnchor anchor,
            RobotTask task,
            IDictionary<Guid, PathGraph?> mapGraphCache,
            IDictionary<PathCostCacheKey, double> pathCostCache,
            CancellationToken cancellationToken)
        {
            var beginNode = task.BeginLocation?.MapNode;
            if (beginNode == null)
            {
                return double.MaxValue;
            }

            var target = new DispatchPoint(
                beginNode.MapId,
                beginNode.NodeId,
                beginNode.X,
                beginNode.Y,
                beginNode.Theta);

            if (anchor.Source.MapId != target.MapId
                || anchor.UseLinearFallbackCost)
            {
                return CalculateEuclideanDistance(anchor.Source, target);
            }

            return await CalculateTravelCostAsync(
                robot,
                anchor.Source,
                target,
                task.Priority,
                mapGraphCache,
                pathCostCache,
                cancellationToken);
        }

        private async Task<bool> TryAssignTaskToSlotAsync(
            RobotDispatchTaskCandidate selected,
            DistributableSlot slot,
            Robot robot,
            Robot liveRobot,
            IRobotTaskRepository taskRepo,
            IRobotSubTaskRepository subTaskRepo,
            ITaskTemplateRepository templateRepo,
            ITaskLeaseService taskLeaseService,
            AppDbContext dbContext,
            CancellationToken cancellationToken)
        {
            ITaskLease? selectedTaskLease = null;
            try
            {
                var selectedTaskLeaseAcquire = await taskLeaseService.TryAcquireAsync(
                    selected.Task.TaskId,
                    robot.RobotId,
                    "dispatch-assign",
                    cancellationToken);
                if (!selectedTaskLeaseAcquire.Success || selectedTaskLeaseAcquire.Lease == null)
                {
                    return false;
                }

                selectedTaskLease = selectedTaskLeaseAcquire.Lease;

                await using var tx = await dbContext.Database.BeginTransactionAsync(cancellationToken);

                var freshTask = await taskRepo.GetByIdWithDetailsAsync(selected.Task.TaskId, cancellationToken);
                if (freshTask == null || freshTask.Status != TaskStatus.Pending)
                {
                    await tx.RollbackAsync(cancellationToken);
                    return false;
                }

                var writeSlot = robot.CacheLocations
                    .FirstOrDefault(c => string.Equals(c.LocationCode, slot.Location.LocationCode, StringComparison.OrdinalIgnoreCase));
                if (writeSlot == null)
                {
                    await tx.RollbackAsync(cancellationToken);
                    return false;
                }

                var template = await GetTemplateForRobotAsync(liveRobot, templateRepo, cancellationToken);
                await AssignTaskToRobotSlotAsync(
                    freshTask,
                    robot,
                    writeSlot,
                    template,
                    subTaskRepo,
                    cancellationToken);

                await taskRepo.SaveChangesAsync(cancellationToken);
                await tx.CommitAsync(cancellationToken);
                return true;
            }
            catch (Exception ex)
            {
                _logger.LogWarning(
                    ex,
                    "[任务调度] 分配失败: TaskCode={TaskCode}, RobotCode={RobotCode}, Slot={SlotCode}",
                    selected.Task.TaskCode,
                    robot.RobotCode,
                    slot.Location.LocationCode);
                return false;
            }
            finally
            {
                if (selectedTaskLease != null)
                {
                    await selectedTaskLease.DisposeAsync();
                }
            }
        }

        private static async Task RestoreTaskToPendingForRedispatchAsync(
            RobotTask task,
            IRobotSubTaskRepository subTaskRepo,
            AppDbContext dbContext,
            CancellationToken cancellationToken)
        {
            var originalRobotId = task.RobotId;
            var originalShelfCode = task.ShelfCode?.Trim();

            task.Status = TaskStatus.Pending;
            task.RobotId = null;
            task.ShelfCode = null;
            task.TaskTemplateId = null;
            task.UpdatedAt = DateTime.Now;

            if (task.SubTasks.Any())
            {
                await subTaskRepo.DeleteRangeAsync(task.SubTasks.ToList(), cancellationToken);
                task.SubTasks.Clear();
            }

            if (originalRobotId.HasValue && !string.IsNullOrWhiteSpace(originalShelfCode))
            {
                var cacheSlot = await dbContext.RobotCacheLocations.FirstOrDefaultAsync(
                    c => c.RobotId == originalRobotId.Value
                         && c.LocationCode == originalShelfCode,
                    cancellationToken);
                if (cacheSlot != null)
                {
                    cacheSlot.ContainerId = null;
                    cacheSlot.UpdatedAt = DateTime.Now;
                }
            }
        }

        private async Task AssignTaskToRobotSlotAsync(
            RobotTask task,
            Robot robot,
            RobotCacheLocation slot,
            TaskTemplate? template,
            IRobotSubTaskRepository subTaskRepo,
            CancellationToken cancellationToken)
        {
            task.RobotId = robot.RobotId;
            task.TaskTemplateId = template?.TemplateId;
            task.ShelfCode = slot.LocationCode;
            task.Status = TaskStatus.Assigned;
            task.UpdatedAt = DateTime.Now;

            slot.ContainerId = task.ContainerID;
            slot.UpdatedAt = DateTime.Now;

            if (template != null && template.TaskSteps.Any())
            {
                await CreateSubTasksFromTemplateAsync(task, robot, template, subTaskRepo, cancellationToken);
            }
        }

        private async Task<(StorageLocationType BeginLocationType, StorageLocationType EndLocationType, List<Robot> CandidateRobots)?> GetStaticDispatchContextAsync(
            RobotTask taskWithDetails,
            IRobotCacheService robotCache,
            IStorageLocationTypeRepository locationTypeRepo,
            IChargingPileRepository chargingPileRepo,
            CancellationToken cancellationToken)
        {
            if (taskWithDetails.BeginLocation?.MapNode == null)
            {
                _logger.LogWarning("[任务调度] 任务 {TaskCode} 无起点库位信息", taskWithDetails.TaskCode);
                return null;
            }

            if (taskWithDetails.EndLocation?.MapNode == null)
            {
                _logger.LogWarning("[任务调度] 任务 {TaskCode} 无终点库位信息", taskWithDetails.TaskCode);
                return null;
            }

            var beginLocationTypeId = taskWithDetails.BeginLocation.MapNode.StorageLocationTypeId;
            var endLocationTypeId = taskWithDetails.EndLocation.MapNode.StorageLocationTypeId;

            if (!beginLocationTypeId.HasValue || !endLocationTypeId.HasValue)
            {
                _logger.LogWarning("[任务调度] 任务 {TaskCode} 库位类型信息不完整", taskWithDetails.TaskCode);
                return null;
            }

            var beginLocationType = await locationTypeRepo.GetByIdAsync(beginLocationTypeId.Value, cancellationToken);
            var endLocationType = await locationTypeRepo.GetByIdAsync(endLocationTypeId.Value, cancellationToken);

            if (beginLocationType == null || endLocationType == null)
            {
                _logger.LogWarning("[任务调度] 任务 {TaskCode} 库位类型不存在", taskWithDetails.TaskCode);
                return null;
            }

            var robotCacheData = await robotCache.GetAllActiveRobotCacheAsync();
            var idleRobots = robotCacheData.Select(r => new Robot
            {
                RobotId = Guid.Parse(r.Basic.RobotId),
                RobotCode = r.Basic.RobotCode,
                RobotName = r.Basic.RobotName,
                RobotVersion = r.Basic.RobotVersion,
                ProtocolName = r.Basic.ProtocolName,
                ProtocolVersion = r.Basic.ProtocolVersion,
                ProtocolType = (ProtocolType)r.Basic.ProtocolType,
                RobotManufacturer = r.Basic.RobotManufacturer,
                RobotSerialNumber = r.Basic.RobotSerialNumber,
                RobotModel = r.Basic.RobotModel,
                RobotType = (RobotType)r.Basic.RobotType,
                IpAddress = r.Basic.IpAddress,
                CoordinateScale = r.Basic.CoordinateScale,
                Active = r.Basic.Active,
                Status = r.Status?.Status ?? RobotStatus.Idle,
                Online = r.Status?.Online ?? OnlineStatus.Offline,
                BatteryLevel = r.Status?.BatteryLevel,
                Driving = r.Status?.Driving ?? false,
                Paused = r.Status?.Paused ?? false,
                Charging = r.Status?.Charging ?? false,
                OperatingMode = r.Status?.OperatingMode ?? OperatingMode.Automatic,
                CurrentMapCodeId = r.Location?.MapId,
                CurrentNodeId = r.Location?.NodeId,
                CurrentX = r.Location?.X,
                CurrentY = r.Location?.Y,
                CurrentTheta = r.Location?.Theta
            }).ToList();

            var activePiles = (await chargingPileRepo.FindAsync(p => p.IsActive, cancellationToken)).ToList();
            idleRobots = ApplyChargingThresholdPolicy(taskWithDetails, idleRobots, activePiles);

            var candidateRobots = idleRobots
                .Where(r => r.CurrentMapCodeId == taskWithDetails.BeginLocation?.MapNode.MapId
                            && r.Online == OnlineStatus.Online
                            && r.Active == true
                            && r.Status != RobotStatus.Error
                            && r.Paused == false
                            && ((r.CurrentNodeId != null && !string.IsNullOrWhiteSpace(r.CurrentNodeId.ToString()) && !r.Driving && r.ProtocolType == ProtocolType.VDA) || r.ProtocolType == ProtocolType.Custom)
                            && r.RobotModel != null
                            && beginLocationType.RobotModels.Contains(r.RobotModel)
                            && endLocationType.RobotModels.Contains(r.RobotModel))
                .ToList();

            return (beginLocationType, endLocationType, candidateRobots);
        }

        /// <summary>
        /// 根据任务起点所在地图和库位类型查找空闲机器人
        /// 筛选起点和终点库位类型都支持的机器人
        /// @author zzy
        /// </summary>
        private async Task<(Robot Robot, RobotCacheLocation CacheLocation)?> FindIdleRobotForTaskAsync(
            RobotTask taskWithDetails,
            IRobotTaskRepository taskRepo,
            IRobotCacheService robotCache,
            IRobotRepository robotRepo,
            IStorageLocationTypeRepository locationTypeRepo,
            IChargingPileRepository chargingPileRepo,
            IDictionary<Guid, DispatchRoundRobotState> dispatchRoundRobotStates,
            CancellationToken cancellationToken)
        {
            var staticDispatchContext = await GetStaticDispatchContextAsync(
                taskWithDetails,
                robotCache,
                locationTypeRepo,
                chargingPileRepo,
                cancellationToken);

            if (!staticDispatchContext.HasValue)
            {
                return null;
            }

            var beginLocationType = staticDispatchContext.Value.BeginLocationType;
            var candidateRobots = staticDispatchContext.Value.CandidateRobots;
            if (!candidateRobots.Any())
            {
                return null;
            }

            var candidateRobotIds = candidateRobots
                .Select(r => r.RobotId)
                .ToHashSet();

            var assignedTasks = (await taskRepo.GetByStatusAsync(TaskStatus.Assigned, cancellationToken))
                .Where(t => t.RobotId.HasValue && candidateRobotIds.Contains(t.RobotId.Value));

            var inProgressTasks = (await taskRepo.GetByStatusAsync(TaskStatus.InProgress, cancellationToken))
                .Where(t => t.RobotId.HasValue && candidateRobotIds.Contains(t.RobotId.Value));

            var activeTaskIds = assignedTasks
                .Concat(inProgressTasks)
                .Select(t => t.TaskId)
                .Distinct()
                .ToList();

            var activeTasksWithDetails = new List<RobotTask>(activeTaskIds.Count);
            foreach (var activeTaskId in activeTaskIds)
            {
                var activeTaskWithDetails = await taskRepo.GetByIdWithDetailsAsync(activeTaskId, cancellationToken);
                if (activeTaskWithDetails?.RobotId.HasValue == true
                    && candidateRobotIds.Contains(activeTaskWithDetails.RobotId.Value))
                {
                    activeTasksWithDetails.Add(activeTaskWithDetails);
                }
            }

            var activeTasksByRobot = activeTasksWithDetails
                .Where(t => t.RobotId.HasValue)
                .GroupBy(t => t.RobotId!.Value)
                .ToDictionary(g => g.Key, g => (IReadOnlyCollection<RobotTask>)g.ToList());

            var reservedCacheLocationCodesByRobot = activeTasksWithDetails
                .Where(t => t.RobotId.HasValue && !string.IsNullOrWhiteSpace(t.ShelfCode))
                .GroupBy(t => t.RobotId!.Value)
                .ToDictionary(
                    g => g.Key,
                    g => g
                        .Select(t => t.ShelfCode!.Trim())
                        .Where(shelfCode => !string.IsNullOrWhiteSpace(shelfCode))
                        .ToHashSet());

            var mixedLineExclusiveCache = new Dictionary<Guid, bool>
            {
                [beginLocationType.TypeId] = beginLocationType.IsMixedLineShelfTaskExclusive
            };

            // 若主任务已指定机器人,根据是否同时指定缓存货架编号走不同分支
            // 1. 仅指定机器人(无ShelfCode):校验机器人可用性,由低到高自动查找空闲货位
            // 2. 同时指定机器人和缓存货架编号:校验对应缓存库位是否为空
            // @author zzy
            if (taskWithDetails.RobotId.HasValue)
            {
                var specifiedRobotId = taskWithDetails.RobotId.Value;
                var specifiedLiveRobot = candidateRobots.FirstOrDefault(r => r.RobotId == specifiedRobotId);
                if (specifiedLiveRobot == null)
                {
                    _logger.LogInformation(
                        "[任务调度] 任务 {TaskCode} 指定机器人 {RobotId} 当前不可调度,跳过本轮",
                        taskWithDetails.TaskCode,
                        specifiedRobotId);
                    return null;
                }

                if (ShouldSkipRobotExcludedByHigherPrioritySoftMixedLineFailure(taskWithDetails, specifiedRobotId, dispatchRoundRobotStates))
                {
                    _logger.LogInformation(
                        "[任务调度] 任务 {TaskCode} 机器人 {RobotCode} 本轮因高优先级任务混行软约束失败已排除,跳过低优先级任务",
                        taskWithDetails.TaskCode,
                        specifiedLiveRobot.RobotCode);
                    return null;
                }

                var specifiedRobotWithCacheLocations = await robotRepo.GetByIdFullDataAsync(specifiedRobotId, cancellationToken);
                if (specifiedRobotWithCacheLocations == null)
                {
                    _logger.LogWarning(
                        "[任务调度] 任务 {TaskCode} 指定机器人 {RobotId} 不存在,跳过本轮",
                        taskWithDetails.TaskCode,
                        specifiedRobotId);
                    return null;
                }

                RobotCacheLocation selectedCacheLocation;

                // 场景2:同时指定了机器人和缓存货架编号,校验对应缓存库位是否为空
                if (!string.IsNullOrWhiteSpace(taskWithDetails.ShelfCode))
                {
                    var specifiedShelfCode = taskWithDetails.ShelfCode.Trim();
                    var specifiedCacheLocation = specifiedRobotWithCacheLocations.CacheLocations
                        .FirstOrDefault(c => c.LocationCode == specifiedShelfCode);
                    if (specifiedCacheLocation == null)
                    {
                        _logger.LogWarning(
                            "[任务调度] 任务 {TaskCode} 指定缓存位 {ShelfCode} 不属于机器人 {RobotCode},跳过本轮",
                            taskWithDetails.TaskCode,
                            specifiedShelfCode,
                            specifiedRobotWithCacheLocations.RobotCode);
                        return null;
                    }

                    if (!string.IsNullOrWhiteSpace(specifiedCacheLocation.ContainerId))
                    {
                        _logger.LogInformation(
                            "[任务调度] 任务 {TaskCode} 指定缓存位 {ShelfCode} 非空,等待释放",
                            taskWithDetails.TaskCode,
                            specifiedShelfCode);
                        return null;
                    }

                    reservedCacheLocationCodesByRobot.TryGetValue(
                        specifiedRobotId,
                        out var specifiedRobotReservedCacheLocationCodes);
                    if (IsCacheLocationReserved(specifiedRobotReservedCacheLocationCodes, specifiedShelfCode))
                    {
                        _logger.LogInformation(
                            "[任务调度] 任务 {TaskCode} 指定缓存位 {ShelfCode} 已存在已分配或执行中的任务,等待释放",
                            taskWithDetails.TaskCode,
                            specifiedShelfCode);
                        return null;
                    }

                    selectedCacheLocation = specifiedCacheLocation;
                }
                else
                {
                    reservedCacheLocationCodesByRobot.TryGetValue(
                        specifiedRobotId,
                        out var autoReservedCacheLocationCodes);

                    // 场景1:仅指定了机器人(无ShelfCode),由低到高自动查找空闲货位
                    var autoAvailableCacheLocation = specifiedRobotWithCacheLocations.CacheLocations
                        .Where(c => string.IsNullOrWhiteSpace(c.ContainerId)
                                    && !IsCacheLocationReserved(autoReservedCacheLocationCodes, c.LocationCode))
                        .OrderBy(c => c.Level)
                        .ThenBy(c => c.Column)
                        .ThenBy(c => c.Row)
                        .ThenBy(c => c.LocationCode)
                        .FirstOrDefault();

                    if (autoAvailableCacheLocation == null)
                    {
                        _logger.LogInformation(
                            "[任务调度] 任务 {TaskCode} 指定机器人 {RobotCode} 无空闲缓存货位,跳过本轮",
                            taskWithDetails.TaskCode,
                            specifiedRobotWithCacheLocations.RobotCode);
                        return null;
                    }

                    selectedCacheLocation = autoAvailableCacheLocation;
                }

                activeTasksByRobot.TryGetValue(specifiedRobotId, out var specifiedRobotActiveTasks);
                var mixedLineAssignmentResult = await CanAssignMixedLineExclusiveTaskAsync(
                        taskWithDetails,
                        beginLocationType,
                        specifiedLiveRobot,
                        specifiedRobotActiveTasks ?? Array.Empty<RobotTask>(),
                        locationTypeRepo,
                        mixedLineExclusiveCache,
                        cancellationToken);
                if (!mixedLineAssignmentResult.CanAssign)
                {
                    if (mixedLineAssignmentResult.IsMixedLineSoftConstraintFailure)
                    {
                        ExcludeRobotForSoftMixedLineFailure(
                            specifiedRobotId,
                            taskWithDetails.Priority,
                            dispatchRoundRobotStates);
                    }

                    return null;
                }

                return (specifiedRobotWithCacheLocations, selectedCacheLocation);
            }

            var dispatchTargetPoint = GetDispatchTargetPoint(taskWithDetails);
            if (dispatchTargetPoint == null)
            {
                _logger.LogWarning("[任务调度] 任务 {TaskCode} 缺少可用于调度评分的目标点信息", taskWithDetails.TaskCode);
                return null;
            }

            var dispatchCandidates = new List<DispatchRobotCandidate>();
            foreach (var liveRobot in candidateRobots)
            {
                if (ShouldSkipRobotExcludedByHigherPrioritySoftMixedLineFailure(taskWithDetails, liveRobot.RobotId, dispatchRoundRobotStates))
                {
                    _logger.LogInformation(
                        "[任务调度] 任务 {TaskCode} 机器人 {RobotCode} 本轮因高优先级任务混行软约束失败已排除,跳过低优先级任务",
                        taskWithDetails.TaskCode,
                        liveRobot.RobotCode);
                    continue;
                }

                var robotWithCacheLocations = await robotRepo.GetByIdFullDataAsync(liveRobot.RobotId, cancellationToken);
                if (robotWithCacheLocations == null)
                {
                    continue;
                }

                reservedCacheLocationCodesByRobot.TryGetValue(
                    liveRobot.RobotId,
                    out var reservedCacheLocationCodes);

                // 多缓存储位场景:按“由低到高、由左到右、由前到后”分配空缓存位
                var availableCacheLocation = robotWithCacheLocations.CacheLocations
                    .Where(c => string.IsNullOrWhiteSpace(c.ContainerId)
                                && !IsCacheLocationReserved(reservedCacheLocationCodes, c.LocationCode))
                    .OrderBy(c => c.Level)
                    .ThenBy(c => c.Column)
                    .ThenBy(c => c.Row)
                    .ThenBy(c => c.LocationCode)
                    .FirstOrDefault();

                if (availableCacheLocation != null)
                {
                    activeTasksByRobot.TryGetValue(liveRobot.RobotId, out var robotActiveTasks);
                    var mixedLineAssignmentResult = await CanAssignMixedLineExclusiveTaskAsync(
                            taskWithDetails,
                            beginLocationType,
                            liveRobot,
                            robotActiveTasks ?? Array.Empty<RobotTask>(),
                            locationTypeRepo,
                            mixedLineExclusiveCache,
                            cancellationToken);
                    if (!mixedLineAssignmentResult.CanAssign)
                    {
                        if (mixedLineAssignmentResult.IsMixedLineSoftConstraintFailure)
                        {
                            ExcludeRobotForSoftMixedLineFailure(
                                liveRobot.RobotId,
                                taskWithDetails.Priority,
                                dispatchRoundRobotStates);
                        }

                        continue;
                    }

                    var currentX = liveRobot.CurrentX ?? robotWithCacheLocations.CurrentX ?? robotWithCacheLocations.MapNode?.X;
                    var currentY = liveRobot.CurrentY ?? robotWithCacheLocations.CurrentY ?? robotWithCacheLocations.MapNode?.Y;

                    dispatchCandidates.Add(new DispatchRobotCandidate(
                        robotWithCacheLocations,
                        availableCacheLocation,
                        currentX,
                        currentY));
                }
            }

            if (!dispatchCandidates.Any())
            {
                return null;
            }

            var mapGraphCache = new Dictionary<Guid, PathGraph?>();
            var scoreCards = new List<DispatchRobotScore>(dispatchCandidates.Count);
            foreach (var candidate in dispatchCandidates)
            {
                activeTasksByRobot.TryGetValue(candidate.Robot.RobotId, out var robotTasks);
                scoreCards.Add(await BuildDispatchScoreAsync(
                    candidate,
                    robotTasks ?? Array.Empty<RobotTask>(),
                    dispatchTargetPoint.Value,
                    taskWithDetails.Priority,
                    mapGraphCache,
                    cancellationToken));
            }

            var selectedScore = SelectBestScore(scoreCards);
            if (selectedScore == null)
            {
                return null;
            }

            _logger.LogInformation(
                "[任务调度] 任务 {TaskCode} 分配评分结果: 机器人={RobotCode}, ETA={EtaDistance:F2}, 增量={DetourDistance:F2}, 负载={LoadDistance:F2}, 任务数={TaskCount}, 综合分={CompositeScore:F4}",
                taskWithDetails.TaskCode,
                selectedScore.Robot.RobotCode,
                selectedScore.EtaDistance,
                selectedScore.DetourDistance,
                selectedScore.LoadDistance,
                selectedScore.ActiveTaskCount,
                selectedScore.CompositeScore);

            return (selectedScore.Robot, selectedScore.CacheLocation);
        }

        /// <summary>
        /// 混行货架任务一致性校验:
        /// 1. 若机器人当前活跃任务中存在 IsMixedLineShelfTaskExclusive=true 的起始库位类型,则机器人被该类型锁定,只能分配同起始类型任务。
        /// 2. 若待分配任务起始库位类型 IsMixedLineShelfTaskExclusive=true,则需保证该机器人活跃任务起始类型全部一致(且无缺失)。
        /// </summary>
        private async Task<MixedLineAssignmentResult> CanAssignMixedLineExclusiveTaskAsync(
            RobotTask dispatchTask,
            StorageLocationType dispatchBeginLocationType,
            Robot candidateRobot,
            IReadOnlyCollection<RobotTask> activeTasks,
            IStorageLocationTypeRepository locationTypeRepo,
            IDictionary<Guid, bool> mixedLineExclusiveCache,
            CancellationToken cancellationToken)
        {
            var activeBeginTypeIds = new HashSet<Guid>();
            var activeExclusiveBeginTypeIds = new HashSet<Guid>();

            foreach (var activeTask in activeTasks)
            {
                var activeBeginTypeId = activeTask.BeginLocation?.MapNode?.StorageLocationTypeId;
                if (!activeBeginTypeId.HasValue)
                {
                    _logger.LogInformation(
                        "[任务调度] 跳过机器人(活跃任务起始类型缺失): TaskCode={TaskCode}, RobotCode={RobotCode}, ActiveTaskId={ActiveTaskId}",
                        dispatchTask.TaskCode,
                        candidateRobot.RobotCode,
                        activeTask.TaskId);
                    return MixedLineAssignmentResult.Deny();
                }

                activeBeginTypeIds.Add(activeBeginTypeId.Value);

                if (!mixedLineExclusiveCache.TryGetValue(activeBeginTypeId.Value, out var isActiveBeginTypeExclusive))
                {
                    var activeBeginType = await locationTypeRepo.GetByIdAsync(activeBeginTypeId.Value, cancellationToken);
                    if (activeBeginType == null)
                    {
                        _logger.LogWarning(
                            "[任务调度] 跳过机器人(活跃任务起始库位类型不存在): TaskCode={TaskCode}, RobotCode={RobotCode}, ActiveTaskId={ActiveTaskId}, ActiveBeginTypeId={ActiveBeginTypeId}",
                            dispatchTask.TaskCode,
                            candidateRobot.RobotCode,
                            activeTask.TaskId,
                            activeBeginTypeId.Value);
                        return MixedLineAssignmentResult.Deny();
                    }

                    isActiveBeginTypeExclusive = activeBeginType.IsMixedLineShelfTaskExclusive;
                    mixedLineExclusiveCache[activeBeginTypeId.Value] = isActiveBeginTypeExclusive;
                }

                if (isActiveBeginTypeExclusive)
                {
                    activeExclusiveBeginTypeIds.Add(activeBeginTypeId.Value);
                }
            }

            // 新增规则:机器人只要存在 Exclusive 活跃任务,即锁定为同起始类型分配
            if (activeExclusiveBeginTypeIds.Count > 0)
            {
                if (activeExclusiveBeginTypeIds.Count > 1)
                {
                    _logger.LogWarning(
                        "[任务调度] 跳过机器人(存在多个 Exclusive 起始类型): TaskCode={TaskCode}, RobotCode={RobotCode}, ExclusiveBeginTypeIds={ExclusiveBeginTypeIds}",
                        dispatchTask.TaskCode,
                        candidateRobot.RobotCode,
                        string.Join(",", activeExclusiveBeginTypeIds));
                    return MixedLineAssignmentResult.Deny();
                }

                var lockedBeginTypeId = activeExclusiveBeginTypeIds.First();
                if (dispatchBeginLocationType.TypeId != lockedBeginTypeId)
                {
                    _logger.LogInformation(
                        "[任务调度] 跳过机器人(被 Exclusive 起始类型锁定): TaskCode={TaskCode}, RobotCode={RobotCode}, DispatchBeginTypeId={DispatchBeginTypeId}, LockedBeginTypeId={LockedBeginTypeId}",
                        dispatchTask.TaskCode,
                        candidateRobot.RobotCode,
                        dispatchBeginLocationType.TypeId,
                        lockedBeginTypeId);
                    return MixedLineAssignmentResult.Deny(
                        lockedBeginTypeId,
                        hasActiveExclusiveLock: true,
                        isMixedLineSoftConstraintFailure: true);
                }

                return MixedLineAssignmentResult.Allow(lockedBeginTypeId, hasActiveExclusiveLock: true);
            }

            // 兼容原有规则:待分配任务为 Exclusive 时,要求活跃任务起始类型全部一致
            if (!dispatchBeginLocationType.IsMixedLineShelfTaskExclusive)
            {
                return MixedLineAssignmentResult.Allow();
            }

            if (activeBeginTypeIds.Count == 0)
            {
                _logger.LogInformation(
                    "[任务调度] 混行专用任务首单放行: TaskCode={TaskCode}, RobotCode={RobotCode}, BeginTypeId={BeginTypeId}",
                    dispatchTask.TaskCode,
                    candidateRobot.RobotCode,
                    dispatchBeginLocationType.TypeId);
                return MixedLineAssignmentResult.Allow();
            }

            if (activeBeginTypeIds.All(id => id == dispatchBeginLocationType.TypeId))
            {
                return MixedLineAssignmentResult.Allow();
            }

            _logger.LogInformation(
                "[任务调度] 混行专用任务跳过机器人(起始类型不一致): TaskCode={TaskCode}, RobotCode={RobotCode}, DispatchBeginTypeId={DispatchBeginTypeId}, ActiveBeginTypeIds={ActiveBeginTypeIds}",
                dispatchTask.TaskCode,
                candidateRobot.RobotCode,
                dispatchBeginLocationType.TypeId,
                string.Join(",", activeBeginTypeIds));
            return MixedLineAssignmentResult.Deny(isMixedLineSoftConstraintFailure: true);
        }

        private static bool ShouldSkipRobotExcludedByHigherPrioritySoftMixedLineFailure(
            RobotTask task,
            Guid robotId,
            IDictionary<Guid, DispatchRoundRobotState> dispatchRoundRobotStates)
        {
            if (!dispatchRoundRobotStates.TryGetValue(robotId, out var robotState)
                || !robotState.SoftMixedLineFailurePriority.HasValue)
            {
                return false;
            }

            return task.Priority < robotState.SoftMixedLineFailurePriority.Value;
        }

        private static bool IsCacheLocationReserved(HashSet<string>? reservedCacheLocationCodes, string? locationCode)
        {
            return reservedCacheLocationCodes != null
                   && !string.IsNullOrWhiteSpace(locationCode)
                   && reservedCacheLocationCodes.Contains(locationCode.Trim());
        }

        /// <summary>
        /// 充电阈值策略:
        /// 1. 非充电中的机器人按绑定关系(机器人ID绑定 / 机器人型号绑定)计算自动充电阈值,电量必须 > 自动充电阈值才可参与任务分配;
        /// 2. 充电中的机器人按绑定关系及当前充电桩恢复阈值计算恢复阈值,电量必须 > 恢复阈值才可参与任务分配,并降为低优先级(排到候选末尾)。
        /// </summary>
        private List<Robot> ApplyChargingThresholdPolicy(
            RobotTask dispatchTask,
            List<Robot> robots,
            IReadOnlyCollection<ChargingPile> activePiles)
        {
            if (robots.Count == 0 || activePiles.Count == 0)
            {
                return robots;
            }

            var autoStartThresholdByRobot = new Dictionary<Guid, decimal>();
            var autoStartThresholdByModel = new Dictionary<string, decimal>(StringComparer.OrdinalIgnoreCase);
            var resumeThresholdByRobot = new Dictionary<Guid, decimal>();
            var resumeThresholdByModel = new Dictionary<string, decimal>(StringComparer.OrdinalIgnoreCase);
            var chargingPileByRobot = new Dictionary<Guid, ChargingPile>();

            foreach (var pile in activePiles)
            {
                if (pile.BoundRobotIds != null)
                {
                    foreach (var boundRobotId in pile.BoundRobotIds)
                    {
                        if (!autoStartThresholdByRobot.TryGetValue(boundRobotId, out var existingAutoStartThreshold)
                            || pile.AutoStartThreshold > existingAutoStartThreshold)
                        {
                            // 同一机器人绑定多个充电桩时,取最高自动充电阈值作为准入门槛
                            autoStartThresholdByRobot[boundRobotId] = pile.AutoStartThreshold;
                        }

                        if (!resumeThresholdByRobot.TryGetValue(boundRobotId, out var existingResumeThreshold)
                            || pile.ResumeThreshold > existingResumeThreshold)
                        {
                            // 同一机器人绑定多个充电桩时,取最高恢复阈值作为准入门槛
                            resumeThresholdByRobot[boundRobotId] = pile.ResumeThreshold;
                        }
                    }
                }

                if (pile.SupportedRobotModels != null)
                {
                    foreach (var supportedModel in pile.SupportedRobotModels)
                    {
                        if (string.IsNullOrWhiteSpace(supportedModel))
                        {
                            continue;
                        }

                        var normalizedModel = supportedModel.Trim();
                        if (!autoStartThresholdByModel.TryGetValue(normalizedModel, out var existingAutoStartThreshold)
                            || pile.AutoStartThreshold > existingAutoStartThreshold)
                        {
                            // 同一型号绑定多个充电桩时,取最高自动充电阈值作为准入门槛
                            autoStartThresholdByModel[normalizedModel] = pile.AutoStartThreshold;
                        }

                        if (!resumeThresholdByModel.TryGetValue(normalizedModel, out var existingResumeThreshold)
                            || pile.ResumeThreshold > existingResumeThreshold)
                        {
                            // 同一型号绑定多个充电桩时,取最高恢复阈值作为准入门槛
                            resumeThresholdByModel[normalizedModel] = pile.ResumeThreshold;
                        }
                    }
                }

                if (pile.CurrentChargingRobotId.HasValue)
                {
                    var chargingRobotId = pile.CurrentChargingRobotId.Value;
                    if (!chargingPileByRobot.TryGetValue(chargingRobotId, out var existingPile)
                        || pile.ResumeThreshold > existingPile.ResumeThreshold)
                    {
                        chargingPileByRobot[chargingRobotId] = pile;
                    }
                }
            }

            var lowPriorityRobotIds = new HashSet<Guid>();
            var availableRobots = new List<Robot>(robots.Count);

            foreach (var robot in robots)
            {
                var batteryLevel = robot.BatteryLevel ?? 0m;
                decimal? requiredThreshold = null;

                if (robot.Charging)
                {
                    var chargingPileCode = string.Empty;
                    if (resumeThresholdByRobot.TryGetValue(robot.RobotId, out var robotBoundThreshold))
                    {
                        requiredThreshold = robotBoundThreshold;
                    }

                    if (!string.IsNullOrWhiteSpace(robot.RobotModel)
                        && resumeThresholdByModel.TryGetValue(robot.RobotModel.Trim(), out var modelBoundThreshold))
                    {
                        requiredThreshold = requiredThreshold.HasValue
                            ? Math.Max(requiredThreshold.Value, modelBoundThreshold)
                            : modelBoundThreshold;
                    }

                    if (chargingPileByRobot.TryGetValue(robot.RobotId, out var chargingPile))
                    {
                        requiredThreshold = requiredThreshold.HasValue
                            ? Math.Max(requiredThreshold.Value, chargingPile.ResumeThreshold)
                            : chargingPile.ResumeThreshold;
                        chargingPileCode = chargingPile.PileCode;
                    }

                    if (requiredThreshold.HasValue && batteryLevel <= requiredThreshold.Value)
                    {
                        _logger.LogInformation(
                            "[任务调度] 跳过机器人(充电中且电量未满足恢复阈值): TaskCode={TaskCode}, RobotCode={RobotCode}, RobotModel={RobotModel}, Battery={BatteryLevel}, RequiredThreshold={RequiredThreshold}, PileCode={PileCode}",
                            dispatchTask.TaskCode,
                            robot.RobotCode,
                            robot.RobotModel,
                            batteryLevel,
                            requiredThreshold.Value,
                            chargingPileCode);
                        continue;
                    }

                    lowPriorityRobotIds.Add(robot.RobotId);
                }
                else
                {
                    if (autoStartThresholdByRobot.TryGetValue(robot.RobotId, out var robotBoundThreshold))
                    {
                        requiredThreshold = robotBoundThreshold;
                    }

                    if (!string.IsNullOrWhiteSpace(robot.RobotModel)
                        && autoStartThresholdByModel.TryGetValue(robot.RobotModel.Trim(), out var modelBoundThreshold))
                    {
                        requiredThreshold = requiredThreshold.HasValue
                            ? Math.Max(requiredThreshold.Value, modelBoundThreshold)
                            : modelBoundThreshold;
                    }

                    if (requiredThreshold.HasValue && batteryLevel <= requiredThreshold.Value)
                    {
                        _logger.LogInformation(
                            "[任务调度] 跳过机器人(非充电中且电量未满足自动充电阈值): TaskCode={TaskCode}, RobotCode={RobotCode}, RobotModel={RobotModel}, Battery={BatteryLevel}, RequiredThreshold={RequiredThreshold}",
                            dispatchTask.TaskCode,
                            robot.RobotCode,
                            robot.RobotModel,
                            batteryLevel,
                            requiredThreshold.Value);
                        continue;
                    }
                }

                availableRobots.Add(robot);
            }

            if (lowPriorityRobotIds.Count == 0)
            {
                return availableRobots;
            }

            var normalPriorityRobots = availableRobots
                .Where(r => !lowPriorityRobotIds.Contains(r.RobotId))
                .ToList();
            var lowPriorityRobots = availableRobots
                .Where(r => lowPriorityRobotIds.Contains(r.RobotId))
                .ToList();
            normalPriorityRobots.AddRange(lowPriorityRobots);

            return normalPriorityRobots;
        }

        private static DispatchPoint? GetDispatchTargetPoint(RobotTask task)
        {
            var nextSubTask = task.GetNextExecutableSubTask();
            var nextTargetNode = nextSubTask?.EndNode ?? task.BeginLocation?.MapNode;
            if (nextTargetNode != null)
            {
                return new DispatchPoint(
                    nextTargetNode.MapId,
                    nextTargetNode.NodeId,
                    nextTargetNode.X,
                    nextTargetNode.Y,
                    nextTargetNode.Theta);
            }

            return null;
        }

        private async Task<DispatchRobotScore> BuildDispatchScoreAsync(
            DispatchRobotCandidate candidate,
            IReadOnlyCollection<RobotTask> activeTasks,
            DispatchPoint dispatchTargetPoint,
            int taskPriority,
            IDictionary<Guid, PathGraph?> mapGraphCache,
            CancellationToken cancellationToken)
        {
            var robotStartPoint = await ResolveRobotStartPointAsync(
                candidate,
                dispatchTargetPoint.MapId,
                mapGraphCache);

            if (!robotStartPoint.HasValue)
            {
                return new DispatchRobotScore(
                    candidate,
                    double.MaxValue,
                    double.MaxValue,
                    double.MaxValue,
                    activeTasks.Count,
                    double.MaxValue);
            }

            var pendingTaskPoints = activeTasks
                .Select(GetDispatchTargetPoint)
                .Where(point => point.HasValue)
                .Select(point => point!.Value)
                .ToList();

            var pathCostCache = new Dictionary<PathCostCacheKey, double>();

            var executionChain = await BuildNearestNeighborChainAsync(
                candidate.Robot,
                robotStartPoint.Value,
                pendingTaskPoints,
                taskPriority,
                mapGraphCache,
                pathCostCache,
                cancellationToken);

            var loadDistance = await CalculatePathDistanceAsync(
                candidate.Robot,
                robotStartPoint.Value,
                executionChain,
                taskPriority,
                mapGraphCache,
                pathCostCache,
                cancellationToken);

            var insertion = await EvaluateBestInsertionAsync(
                candidate.Robot,
                robotStartPoint.Value,
                executionChain,
                dispatchTargetPoint,
                taskPriority,
                mapGraphCache,
                pathCostCache,
                cancellationToken);

            return new DispatchRobotScore(
                candidate,
                insertion.EtaDistance,
                insertion.DetourDistance,
                loadDistance,
                pendingTaskPoints.Count,
                0d);
        }

        private async Task<DispatchInsertionResult> EvaluateBestInsertionAsync(
            Robot robot,
            DispatchPoint start,
            IReadOnlyList<DispatchPoint> chain,
            DispatchPoint target,
            int taskPriority,
            IDictionary<Guid, PathGraph?> mapGraphCache,
            IDictionary<PathCostCacheKey, double> pathCostCache,
            CancellationToken cancellationToken)
        {
            if (chain.Count == 0)
            {
                var directDistance = await CalculateTravelCostAsync(
                    robot,
                    start,
                    target,
                    taskPriority,
                    mapGraphCache,
                    pathCostCache,
                    cancellationToken);
                return new DispatchInsertionResult(directDistance, directDistance);
            }

            var arrivalsAtChainPoint = new double[chain.Count];
            arrivalsAtChainPoint[0] = await CalculateTravelCostAsync(
                robot,
                start,
                chain[0],
                taskPriority,
                mapGraphCache,
                pathCostCache,
                cancellationToken);
            for (int i = 1; i < chain.Count; i++)
            {
                arrivalsAtChainPoint[i] = arrivalsAtChainPoint[i - 1]
                                          + await CalculateTravelCostAsync(
                                              robot,
                                              chain[i - 1],
                                              chain[i],
                                              taskPriority,
                                              mapGraphCache,
                                              pathCostCache,
                                              cancellationToken);
            }

            double bestEta = double.MaxValue;
            double bestDetour = double.MaxValue;

            for (int insertIndex = 0; insertIndex <= chain.Count; insertIndex++)
            {
                var previousPoint = insertIndex == 0 ? start : chain[insertIndex - 1];
                var previousArrival = insertIndex == 0 ? 0d : arrivalsAtChainPoint[insertIndex - 1];
                var prevToTargetCost = await CalculateTravelCostAsync(
                    robot,
                    previousPoint,
                    target,
                    taskPriority,
                    mapGraphCache,
                    pathCostCache,
                    cancellationToken);
                var etaDistance = previousArrival + prevToTargetCost;

                double detourDistance;
                if (insertIndex == chain.Count)
                {
                    detourDistance = prevToTargetCost;
                }
                else
                {
                    var nextPoint = chain[insertIndex];
                    var targetToNextCost = await CalculateTravelCostAsync(
                        robot,
                        target,
                        nextPoint,
                        taskPriority,
                        mapGraphCache,
                        pathCostCache,
                        cancellationToken);
                    var prevToNextCost = await CalculateTravelCostAsync(
                        robot,
                        previousPoint,
                        nextPoint,
                        taskPriority,
                        mapGraphCache,
                        pathCostCache,
                        cancellationToken);
                    detourDistance = prevToTargetCost + targetToNextCost - prevToNextCost;
                }

                if (etaDistance < bestEta || (Math.Abs(etaDistance - bestEta) < 0.0001d && detourDistance < bestDetour))
                {
                    bestEta = etaDistance;
                    bestDetour = detourDistance;
                }
            }

            return new DispatchInsertionResult(bestEta, bestDetour);
        }

        private async Task<List<DispatchPoint>> BuildNearestNeighborChainAsync(
            Robot robot,
            DispatchPoint start,
            IReadOnlyCollection<DispatchPoint> points,
            int taskPriority,
            IDictionary<Guid, PathGraph?> mapGraphCache,
            IDictionary<PathCostCacheKey, double> pathCostCache,
            CancellationToken cancellationToken)
        {
            var remaining = points.ToList();
            var chain = new List<DispatchPoint>(remaining.Count);
            var current = start;

            while (remaining.Count > 0)
            {
                int nearestIndex = 0;
                double nearestDistance = double.MaxValue;

                for (int i = 0; i < remaining.Count; i++)
                {
                    var distance = await CalculateTravelCostAsync(
                        robot,
                        current,
                        remaining[i],
                        taskPriority,
                        mapGraphCache,
                        pathCostCache,
                        cancellationToken);
                    if (distance < nearestDistance)
                    {
                        nearestDistance = distance;
                        nearestIndex = i;
                    }
                }

                current = remaining[nearestIndex];
                chain.Add(current);
                remaining.RemoveAt(nearestIndex);
            }

            return chain;
        }

        private async Task<double> CalculatePathDistanceAsync(
            Robot robot,
            DispatchPoint start,
            IReadOnlyList<DispatchPoint> chain,
            int taskPriority,
            IDictionary<Guid, PathGraph?> mapGraphCache,
            IDictionary<PathCostCacheKey, double> pathCostCache,
            CancellationToken cancellationToken)
        {
            if (chain.Count == 0)
            {
                return 0d;
            }

            var totalDistance = await CalculateTravelCostAsync(
                robot,
                start,
                chain[0],
                taskPriority,
                mapGraphCache,
                pathCostCache,
                cancellationToken);
            for (int i = 1; i < chain.Count; i++)
            {
                totalDistance += await CalculateTravelCostAsync(
                    robot,
                    chain[i - 1],
                    chain[i],
                    taskPriority,
                    mapGraphCache,
                    pathCostCache,
                    cancellationToken);
            }

            return totalDistance;
        }

        private static DispatchRobotScore? SelectBestScore(IReadOnlyCollection<DispatchRobotScore> scoreCards)
        {
            if (!scoreCards.Any())
            {
                return null;
            }

            var bestEta = scoreCards.Min(s => s.EtaDistance);
            var etaPreferred = scoreCards
                .Where(s => s.EtaDistance <= bestEta + EtaPrioritySlackMeters)
                .ToList();

            var etaMin = etaPreferred.Min(s => s.EtaDistance);
            var etaMax = etaPreferred.Max(s => s.EtaDistance);
            var detourMin = etaPreferred.Min(s => s.DetourDistance);
            var detourMax = etaPreferred.Max(s => s.DetourDistance);
            var loadMin = etaPreferred.Min(s => s.LoadDistance);
            var loadMax = etaPreferred.Max(s => s.LoadDistance);
            var taskCountMin = etaPreferred.Min(s => s.ActiveTaskCount);
            var taskCountMax = etaPreferred.Max(s => s.ActiveTaskCount);

            var rescored = etaPreferred
                .Select(s =>
                {
                    var score = EtaWeight * Normalize(s.EtaDistance, etaMin, etaMax)
                                + DetourWeight * Normalize(s.DetourDistance, detourMin, detourMax)
                                + LoadWeight * Normalize(s.LoadDistance, loadMin, loadMax)
                                + TaskCountWeight * Normalize(s.ActiveTaskCount, taskCountMin, taskCountMax);

                    return s with { CompositeScore = score };
                })
                .ToList();

            return rescored
                .OrderBy(s => s.CompositeScore)
                .ThenBy(s => s.EtaDistance)
                .ThenBy(s => s.LoadDistance)
                .ThenBy(s => s.ActiveTaskCount)
                .ThenBy(s => s.Robot.RobotCode)
                .FirstOrDefault();
        }

        private async Task<PathGraph?> GetPathGraphAsync(
            Guid mapId,
            IDictionary<Guid, PathGraph?> mapGraphCache)
        {
            if (mapGraphCache.TryGetValue(mapId, out var cachedGraph))
            {
                return cachedGraph;
            }

            var graph = await _agvPathService.GetOrBuildGraphAsync(mapId);
            mapGraphCache[mapId] = graph;
            return graph;
        }

        private async Task<DispatchPoint?> ResolveRobotStartPointAsync(
            DispatchRobotCandidate candidate,
            Guid mapId,
            IDictionary<Guid, PathGraph?> mapGraphCache)
        {
            var sourceX = candidate.CurrentX ?? candidate.Robot.CurrentX ?? candidate.Robot.MapNode?.X;
            var sourceY = candidate.CurrentY ?? candidate.Robot.CurrentY ?? candidate.Robot.MapNode?.Y;
            var sourceTheta = candidate.Robot.CurrentTheta ?? candidate.Robot.MapNode?.Theta;
            var startNodeId = candidate.Robot.CurrentNodeId;

            PathGraph? graph = null;
            if (startNodeId.HasValue || !sourceX.HasValue || !sourceY.HasValue)
            {
                graph = await GetPathGraphAsync(mapId, mapGraphCache);
            }

            if (startNodeId.HasValue && graph?.Nodes.TryGetValue(startNodeId.Value, out var currentNode) == true)
            {
                sourceX ??= currentNode.X;
                sourceY ??= currentNode.Y;
                sourceTheta ??= currentNode.Theta;
            }

            if (!startNodeId.HasValue && sourceX.HasValue && sourceY.HasValue && graph != null)
            {
                Guid? nearestNodeId = null;
                double? nearestNodeTheta = null;
                var nearestDistanceSquared = double.MaxValue;

                foreach (var node in graph.Nodes.Values)
                {
                    if (!node.Active)
                    {
                        continue;
                    }

                    var dx = sourceX.Value - node.X;
                    var dy = sourceY.Value - node.Y;
                    var distanceSquared = dx * dx + dy * dy;
                    if (distanceSquared < nearestDistanceSquared)
                    {
                        nearestDistanceSquared = distanceSquared;
                        nearestNodeId = node.NodeId;
                        nearestNodeTheta = node.Theta;
                    }
                }

                startNodeId = nearestNodeId;
                sourceTheta ??= nearestNodeTheta;
            }

            if (!sourceX.HasValue || !sourceY.HasValue)
            {
                return null;
            }

            return new DispatchPoint(mapId, startNodeId, sourceX.Value, sourceY.Value, sourceTheta);
        }

        private async Task<double> CalculateTravelCostAsync(
            Robot robot,
            DispatchPoint source,
            DispatchPoint target,
            int taskPriority,
            IDictionary<Guid, PathGraph?> mapGraphCache,
            IDictionary<PathCostCacheKey, double> pathCostCache,
            CancellationToken cancellationToken)
        {
            var fallbackDistance = CalculateEuclideanDistance(source, target);

            if (source.MapId != target.MapId
                || !source.NodeId.HasValue
                || !target.NodeId.HasValue)
            {
                return fallbackDistance;
            }

            var cacheKey = new PathCostCacheKey(
                robot.RobotId,
                source.NodeId.Value,
                target.NodeId.Value,
                RoundForPathCostCache(source.Theta),
                RoundForPathCostCache(target.Theta));
            if (pathCostCache.TryGetValue(cacheKey, out var cachedCost))
            {
                return cachedCost;
            }

            var graph = await GetPathGraphAsync(source.MapId, mapGraphCache);
            if (graph == null
                || !graph.Nodes.ContainsKey(source.NodeId.Value)
                || !graph.Nodes.ContainsKey(target.NodeId.Value))
            {
                pathCostCache[cacheKey] = fallbackDistance;
                return fallbackDistance;
            }

            var request = new PathRequest
            {
                RobotId = robot.RobotId,
                MapId = source.MapId,
                StartNodeId = source.NodeId.Value,
                EndNodeId = target.NodeId.Value,
                CurrentTheta = source.Theta ?? robot.CurrentTheta ?? 0d,
                IsLoaded = false,
                Priority = taskPriority,
                BatteryLevel = robot.BatteryLevel ?? 100,
                MovementType = robot.MovementType,
                ForkRadOffsets = robot.ForkRadOffset,
                RequiredEndRad = target.Theta
            };

            try
            {
                var pathResult = await _agvPathService.CalculatePathAsync(request, cancellationToken);
                if (pathResult.Success
                    && !double.IsNaN(pathResult.TotalCost)
                    && !double.IsInfinity(pathResult.TotalCost))
                {
                    pathCostCache[cacheKey] = pathResult.TotalCost;
                    return pathResult.TotalCost;
                }
            }
            catch (Exception ex)
            {
                _logger.LogDebug(
                    ex,
                    "[任务调度] 路径评分异常,回退直线距离: RobotCode={RobotCode}, StartNodeId={StartNodeId}, EndNodeId={EndNodeId}",
                    robot.RobotCode,
                    source.NodeId,
                    target.NodeId);
            }

            pathCostCache[cacheKey] = fallbackDistance;
            return fallbackDistance;
        }

        /// <summary>
        /// 计算两点直线距离。
        /// </summary>
        private static double CalculateEuclideanDistance(DispatchPoint source, DispatchPoint target)
        {
            var dx = source.X - target.X;
            var dy = source.Y - target.Y;
            return Math.Sqrt(dx * dx + dy * dy);
        }

        private static double RoundForPathCostCache(double? value)
        {
            return value.HasValue ? Math.Round(value.Value, 4) : double.NaN;
        }

        private static double Normalize(double value, double min, double max)
        {
            if (double.IsNaN(value) || value == double.MaxValue)
            {
                return 1d;
            }

            var range = max - min;
            if (Math.Abs(range) < 0.0001d)
            {
                return 0d;
            }

            return (value - min) / range;
        }

        private readonly record struct DispatchPoint(
            Guid MapId,
            Guid? NodeId,
            double X,
            double Y,
            double? Theta);

        private readonly record struct DispatchInsertionResult(double EtaDistance, double DetourDistance);

        private readonly record struct PathCostCacheKey(
            Guid RobotId,
            Guid StartNodeId,
            Guid EndNodeId,
            double StartTheta,
            double EndTheta);

        private readonly record struct PreRecoverTaskSnapshot(
            Guid TaskId,
            string TaskCode,
            Guid? RobotId);

        private sealed record PendingTaskDispatchContext(
            RobotTask Task,
            StorageLocationType BeginLocationType,
            StorageLocationType EndLocationType,
            IReadOnlyCollection<Robot> CandidateRobots,
            HashSet<Guid> CandidateRobotIds);

        private sealed record DistributableSlot(
            RobotCacheLocation Location);

        private sealed record RobotDispatchTaskCandidate(
            RobotTask Task,
            PendingTaskDispatchContext Context,
            double Cost);

        private sealed record RobotDispatchAnchor(
            bool CanDispatch,
            DispatchPoint Source,
            bool UseLinearFallbackCost)
        {
            public static RobotDispatchAnchor Deny()
            {
                return new RobotDispatchAnchor(false, default, false);
            }

            public static RobotDispatchAnchor Allow(DispatchPoint source, bool useLinearFallbackCost = false)
            {
                return new RobotDispatchAnchor(true, source, useLinearFallbackCost);
            }
        }

        private sealed class DispatchRoundRobotState
        {
            public int? SoftMixedLineFailurePriority { get; set; }
        }

        private sealed record MixedLineAssignmentResult(
            bool CanAssign,
            Guid? ActiveExclusiveBeginTypeId,
            bool HasActiveExclusiveLock,
            bool IsMixedLineSoftConstraintFailure)
        {
            public static MixedLineAssignmentResult Allow(
                Guid? activeExclusiveBeginTypeId = null,
                bool hasActiveExclusiveLock = false)
            {
                return new MixedLineAssignmentResult(
                    true,
                    activeExclusiveBeginTypeId,
                    hasActiveExclusiveLock,
                    false);
            }

            public static MixedLineAssignmentResult Deny(
                Guid? activeExclusiveBeginTypeId = null,
                bool hasActiveExclusiveLock = false,
                bool isMixedLineSoftConstraintFailure = false)
            {
                return new MixedLineAssignmentResult(
                    false,
                    activeExclusiveBeginTypeId,
                    hasActiveExclusiveLock,
                    isMixedLineSoftConstraintFailure);
            }
        }

        private sealed record DispatchRobotCandidate(
            Robot Robot,
            RobotCacheLocation CacheLocation,
            double? CurrentX,
            double? CurrentY);

        private sealed record DispatchRobotScore(
            DispatchRobotCandidate Candidate,
            double EtaDistance,
            double DetourDistance,
            double LoadDistance,
            int ActiveTaskCount,
            double CompositeScore)
        {
            public Robot Robot => Candidate.Robot;
            public RobotCacheLocation CacheLocation => Candidate.CacheLocation;
        }

        /// <summary>
        /// 获取机器人对应的任务模板(包含步骤和属性)
        /// 优先获取默认模板,默认模板优先
        /// @author zzy
        /// </summary>
        private async Task<TaskTemplate?> GetTemplateForRobotAsync(
            Robot robot,
            ITaskTemplateRepository templateRepo,
            CancellationToken cancellationToken)
        {
            // 优先获取该机器人类型和制造商的默认模板
            var template = await templateRepo.GetDefaultTemplateAsync(
                robot.RobotType,
                robot.RobotManufacturer,
                cancellationToken: cancellationToken);

            TaskTemplate? resultTemplate = null;
            if (template != null)
            {
                // 获取包含完整详情的模板(步骤、属性、动作)
                resultTemplate = await templateRepo.GetWithFullDetailsAsync(template.TemplateId, cancellationToken);
            }

            if (resultTemplate != null) return resultTemplate;

            // 如果没有默认模板,获取该机器人类型的任意启用模板
            var templates = await templateRepo.GetByRobotTypeAsync(robot.RobotType, cancellationToken);
            var fallbackTemplate = templates.FirstOrDefault(t => t.IsEnabled);

            if (fallbackTemplate != null)
            {
                // 获取包含完整详情的模板(步骤、属性、动作)
                resultTemplate = await templateRepo.GetWithFullDetailsAsync(fallbackTemplate.TemplateId, cancellationToken);
            }

            return resultTemplate;
        }

        /// <summary>
        /// 根据模板中的步骤创建子任务
        /// 以模板中的order排序创建子任务
        /// 除了第一个子任务,后续的子任务的起点都是上一个子任务的终点
        /// 根据step中的Node属性类型(NodeValueType)来确定终点
        /// @author zzy
        /// </summary>
        private async Task CreateSubTasksFromTemplateAsync(
            RobotTask taskWithDetails,
            Robot robot,
            TaskTemplate template,
            IRobotSubTaskRepository subTaskRepo,
            CancellationToken cancellationToken)
        {
            // 按order排序获取模板步骤
            var orderedSteps = template.TaskSteps
                .OrderBy(s => s.Order)
                .ToList();

            if (orderedSteps.Count == 0)
            {
                _logger.LogWarning("[任务调度] 模板 {TemplateCode} 无步骤配置", template.TemplateCode);
                return;
            }

            if (taskWithDetails.BeginLocation?.MapNode == null
                || taskWithDetails.EndLocation?.MapNode == null)
            {
                _logger.LogWarning("[任务调度] 任务 {TaskCode} 缺少起点或终点节点信息", taskWithDetails.TaskCode);
                return;
            }

            Guid beginNodeId = taskWithDetails.BeginLocation.MapNode.NodeId;
            Guid endNodeId = taskWithDetails.EndLocation.MapNode.NodeId;

            // 跟踪上一个子任务的终点:
            // 优先使用机器人当前位置节点,缺失时回退到任务起点,避免可空值取Value导致异常
            Guid previousEndNodeId = robot.CurrentNodeId ?? beginNodeId;
            if (!robot.CurrentNodeId.HasValue)
            {
                _logger.LogWarning(
                    "[任务调度] 任务 {TaskCode} 创建子任务时机器人 {RobotCode} 缺少当前节点,使用任务起点节点 {BeginNodeId} 作为首段起点",
                    taskWithDetails.TaskCode,
                    robot.RobotCode,
                    beginNodeId);
            }
            int sequence = 1;

            foreach (var step in orderedSteps)
            {
                var subTask = new RobotSubTask
                {
                    SubTaskId = Guid.NewGuid(),
                    TaskId = taskWithDetails.TaskId,
                    RobotId = robot.RobotId,
                    Status = TaskStatus.Pending,
                    CreatedAt = DateTime.Now,
                    Sequence = sequence
                };

                // 设置子任务起点:第一个为机器人当前节点,后续为上一个子任务的终点

                subTask.BeginNodeId = previousEndNodeId;
                

                // 根据步骤的Node属性确定终点
                var nodeProperty = step.Properties?.FirstOrDefault(p => p.PropertyType == StepPropertyType.Node);

                subTask.EndNodeId = nodeProperty?.NodeValue.HasValue == true
                    ? nodeProperty.NodeValue.Value switch
                    {
                        NodeValueType.Ts => beginNodeId,  // 任务起点
                        NodeValueType.Te => endNodeId,    // 任务终点
                        NodeValueType.Ws => endNodeId,    // 工位集合 - 暂时使用任务终点,后续可根据具体业务逻辑确定工位节点
                        _ => endNodeId                     // 默认使用任务终点
                    }
                    : endNodeId;  // 没有配置Node属性,默认使用任务终点

                await subTaskRepo.AddAsync(subTask, cancellationToken);

                previousEndNodeId = subTask.EndNodeId;
                sequence++;

                _logger.LogInformation("[任务调度] 创建子任务: 任务={TaskCode}, 子任务ID={SubTaskId}, 顺序={Sequence}, 起点={BeginNode}, 终点={EndNode}",
                    taskWithDetails.TaskCode, subTask.SubTaskId, subTask.Sequence, subTask.BeginNodeId, subTask.EndNodeId);
            }
        }
    }
}