Dashboard.vue 71 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
<script lang="ts" setup>
/**
 * 设备监控界面
 * @author zzy
 * @date 2026-01-05
 */
import { ref, onMounted, onBeforeUnmount, computed, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { useToast } from 'vuestic-ui'
import mapsApi from '../../../services/maps'
import robotTasksApi from '../../../services/robotTasks'
import robotsApi from '../../../services/robots'
import { HHRCSWs, SubscriptionType, type RobotStatus, type StorageArea, type StorageLocation } from '../../../services/HHRCSWs'
import RobotStatusCard from './cards/RobotStatusCard.vue'

const { t } = useI18n()
const { init: notify } = useToast()

/**
 * 检测设备是否为平板
 * @description 通过用户代理字符串检测是否为平板设备(iPad/Android平板等)
 * @author zzy
 * @date 2026-01-31
 */
const isTablet = ref(false)

/**
 * 检测用户代理是否为平板设备
 * @param userAgent 浏览器用户代理字符串
 * @returns 是否为平板设备
 * @author zzy
 */
const detectTablet = (userAgent: string): boolean => {
  const tabletRegex = /(ipad|tablet|(android(?!.*mobile))|(windows(?!.*phone)(.*touch))|kindle|playbook|silk|(puffin(?!.*(IP|AP|WP))))/i
  return tabletRegex.test(userAgent)
}

// 聚焦到指定机器人
const focusOnRobot = (robot: RobotStatus) => {
  if (robot.x == null || robot.y == null) return

  const svg = svgRef.value
  if (!svg) return
  const rect = svg.getBoundingClientRect()
  const width = rect.width
  const height = rect.height
  if (!width || !height) return

  const targetScale = viewport.value.scale // 保持当前缩放不再放大
  const targetX = width / 2 - robot.x * targetScale
  const targetY = height / 2 + robot.y * targetScale

  // 取消之前的动画
  if (animationId) cancelAnimationFrame(animationId)

  // 平滑动画
  const startX = viewport.value.x
  const startY = viewport.value.y
  const startScale = viewport.value.scale
  const duration = 400
  const startTime = performance.now()

  const easeOutCubic = (t: number) => 1 - Math.pow(1 - t, 3)

  const animate = (now: number) => {
    const elapsed = now - startTime
    const progress = Math.min(elapsed / duration, 1)
    const eased = easeOutCubic(progress)

    viewport.value.x = startX + (targetX - startX) * eased
    viewport.value.y = startY + (targetY - startY) * eased
    viewport.value.scale = startScale + (targetScale - startScale) * eased

    if (progress < 1) {
      animationId = requestAnimationFrame(animate)
    } else {
      animationId = null
    }
  }

  animationId = requestAnimationFrame(animate)
}

/**
 * 处理机器人卡片点击
 * @author zzy
 */
const onRobotCardClick = (robot: RobotStatus) => {
  // 如果已经是选中状态,再次点击则聚焦
  if (selectedRobotId.value === robot.robotId) {
    focusOnRobot(robot)
  } else {
    selectedRobotId.value = robot.robotId
    focusOnRobot(robot)
  }
}

/**
 * 检测设备类型并应用相应样式
 * @author zzy
 */
const checkDeviceType = () => {
  const ua = navigator.userAgent
  isTablet.value = detectTablet(ua) || (window.innerWidth >= 600 && window.innerWidth <= 1366 && 'ontouchstart' in window)
  // 如果是平板设备,添加全局样式类
  if (isTablet.value) {
    document.body.classList.add('tablet-mode')
    document.documentElement.classList.add('tablet-mode')
  } else {
    document.body.classList.remove('tablet-mode')
    document.documentElement.classList.remove('tablet-mode')
  }
}

// 地图列表
const mapList = ref<any[]>([])
const selectedMapId = ref<string | null>(null)
const isLoading = ref(false)

// 机器人状态列表
const robotList = ref<RobotStatus[]>([])
let unsubscribeWs: (() => void) | null = null
let unsubscribeLocationWs: (() => void) | null = null

// 当前地图数据
const currentMap = ref({
  id: null as string | null,
  name: '',
  code: '',
  type: 1,
  nodes: [] as any[],
  edges: [] as any[],
  resources: [] as any[]
})

// 画布相关
const NODE_DIAMETER = 256
const NODE_RADIUS = NODE_DIAMETER / 2
const MIN_SCALE = 0.005
const svgRef = ref<HTMLElement | null>(null)
const canvasSize = ref({ width: 0, height: 0 })
const viewport = ref({ x: 0, y: 0, scale: 0.1 })
let resizeObserver: ResizeObserver | null = null
let isPanning = false
let panStart = { x: 0, y: 0 }
let viewportStart = { x: 0, y: 0 }

// 背景图
const bgImageUrl = ref('')
const bgImgSize = ref({ width: 0, height: 0 })
const bgScale = ref(1)
const bgOpacity = ref(0.6)
const bgRotation = ref(0)
const bgOffsetX = ref(0)
const bgOffsetY = ref(0)
const bgWorldWidth = computed(() => Math.max(0, Math.round((bgImgSize.value.width || 0) * (bgScale.value || 0))))
const bgWorldHeight = computed(() => Math.max(0, Math.round((bgImgSize.value.height || 0) * (bgScale.value || 0))))

// 节点、边和资源
const nodes = computed(() => currentMap.value.nodes || [])
const edges = computed(() => currentMap.value.edges || [])
const resources = computed(() => currentMap.value.resources || [])

// 选中的节点(支持多选,最多2个)
const selectedNodeIds = ref<string[]>([])

// 选中的资源区域
const selectedResourceId = ref<string | null>(null)

// 任务起点和终点(显示code,存储id)
const startNodeCode = ref('')
const endNodeCode = ref('')
const startNodeId = ref('')
const endNodeId = ref('')
const endResourceId = ref('')
const endResourceName = ref('')

// 重定位模式状态
const relocateMode = ref(false)
const relocateRobotId = ref<string | null>(null)
const relocateRobotCode = ref<string>('')
const relocatePosition = ref<{ x: number; y: number } | null>(null)
const relocateAngle = ref(0)
const isRelocating = ref(false)

// 画布中选中的机器人
const selectedRobotId = ref<string | null>(null)
const isRobotActionLoading = ref(false)
const isRobotPauseLoading = ref(false)

// 监听选中节点变化,自动填充起点终点
watch(selectedNodeIds, (ids) => {
  
  const node1 = ids.length >= 1 ? nodes.value.find((n: any) => n.id === ids[0]) : null
  const node2 = ids.length >= 2 ? nodes.value.find((n: any) => n.id === ids[1]) : null

  startNodeCode.value = node1?.storageLocations[0]?.locationName || ''
  startNodeId.value = node1?.storageLocations[0]?.locationId || ''
  endNodeCode.value = node2?.storageLocations[0]?.locationName || ''
  endNodeId.value = node2?.storageLocations[0]?.locationId || ''
}, { deep: true })

// 执行任务
const executeTask = async () => {
  if (!startNodeId.value) {
    notify({ message: t('dashboard.taskValidation') || '请选择起点', color: 'warning' })
    return
  }
  // 终点节点和终点区域至少选择一个
  if (!endNodeId.value && !endResourceId.value) {
    notify({ message: t('dashboard.selectEndTarget') || '请选择终点节点或终点区域', color: 'warning' })
    return
  }
  try {
    isLoading.value = true
    const payload: any = {
      beginLocationId: startNodeId.value,
    }
    // 优先使用终点节点,其次使用终点区域
    if (endNodeId.value) {
      payload.endLocationId = endNodeId.value
    } else if (endResourceId.value) {
      payload.endResourceId = endResourceId.value
    }
    const res = await robotTasksApi.createOrUpdate(payload)
    if (res?.success === false || res?.Success === false) {
      notify({ message: res.message || res.Message || t('dashboard.taskFailed'), color: 'danger' })
    } else {
      notify({ message: res?.message || res?.Message || t('dashboard.taskCreated'), color: 'success' })
      startNodeCode.value = ''
      endNodeCode.value = ''
      startNodeId.value = ''
      endNodeId.value = ''
    }
  } catch (err: any) {
    notify({ message: err?.message || t('dashboard.taskFailed'), color: 'danger' })
  } finally {
    isLoading.value = false
  }
}

// 判断节点是否在当前视口可见范围内
const isNodeInViewport = (node: any, width: number, height: number) => {
  const screenX = viewport.value.x + node.x * viewport.value.scale
  const screenY = viewport.value.y - node.y * viewport.value.scale
  const margin = NODE_RADIUS * viewport.value.scale
  return screenX >= -margin && screenX <= width + margin && screenY >= -margin && screenY <= height + margin
}

// 平滑动画到目标视图
let animationId: number | null = null
const animateToShowSelectedNodes = () => {
  if (selectedNodeIds.value.length < 2) return

  // 直接从 SVG 获取尺寸
  const svg = svgRef.value
  if (!svg) return
  const rect = svg.getBoundingClientRect()
  const width = rect.width
  const height = rect.height
  if (!width || !height) return

  const node1 = nodes.value.find((n: any) => n.id === selectedNodeIds.value[0])
  const node2 = nodes.value.find((n: any) => n.id === selectedNodeIds.value[1])
  if (!node1 || !node2) return

  // 如果两个节点都在当前视口内,不进行缩放移动
  if (isNodeInViewport(node1, width, height) && isNodeInViewport(node2, width, height)) return

  // 计算两节点的边界
  const pad = 500
  const xMin = Math.min(node1.x, node2.x) - pad
  const xMax = Math.max(node1.x, node2.x) + pad
  const yMin = Math.min(node1.y, node2.y) - pad
  const yMax = Math.max(node1.y, node2.y) + pad

  // 计算目标缩放和位置
  const worldW = xMax - xMin || 100
  const worldH = yMax - yMin || 100
  const scaleX = width / worldW
  const scaleY = height / worldH
  const targetScale = Math.max(MIN_SCALE, Math.min(scaleX, scaleY) * 0.8)
  const centerX = (xMin + xMax) / 2
  const centerY = (yMin + yMax) / 2
  const targetX = width / 2 - centerX * targetScale
  const targetY = height / 2 + centerY * targetScale

  // 取消之前的动画
  if (animationId) cancelAnimationFrame(animationId)

  // 平滑动画
  const startX = viewport.value.x
  const startY = viewport.value.y
  const startScale = viewport.value.scale
  const duration = 400
  const startTime = performance.now()

  const easeOutCubic = (t: number) => 1 - Math.pow(1 - t, 3)

  const animate = (now: number) => {
    const elapsed = now - startTime
    const progress = Math.min(elapsed / duration, 1)
    const eased = easeOutCubic(progress)

    viewport.value.x = startX + (targetX - startX) * eased
    viewport.value.y = startY + (targetY - startY) * eased
    viewport.value.scale = startScale + (targetScale - startScale) * eased

    if (progress < 1) {
      animationId = requestAnimationFrame(animate)
    } else {
      animationId = null
    }
  }

  animationId = requestAnimationFrame(animate)
}

// 节点点击事件(支持多选,最多2个)
const onNodeClick = (node: any, e: MouseEvent) => {
  e.stopPropagation()
  // 重定位模式下,点击节点只设置重定位位置
  if (relocateMode.value) {
    relocatePosition.value = { x: node.x, y: node.y }
    return
  }
  const idx = selectedNodeIds.value.indexOf(node.id)
  if (idx >= 0) {
    selectedNodeIds.value.splice(idx, 1)
  } else if (selectedNodeIds.value.length < 2) {
    selectedNodeIds.value.push(node.id)
    if (selectedNodeIds.value.length === 2) {
      setTimeout(() => animateToShowSelectedNodes(), 50)
    }
  } else {
    selectedNodeIds.value[1] = node.id
    setTimeout(() => animateToShowSelectedNodes(), 50)
  }
}

// 判断节点是否选中
const isNodeSelected = (id: string) => selectedNodeIds.value.includes(id)

// 选中节点的颜色(起点绿色,终点红色)
const getSelectedNodeColor = (id: string) => {
  const idx = selectedNodeIds.value.indexOf(id)
  return idx === 0 ? '#28a745' : idx === 1 ? '#dc3545' : '#0d6efd'
}

// 指引线路径(起点到终点节点或终点区域)
const guideLine = computed(() => {
  // 必须有起点
  if (selectedNodeIds.value.length < 1) return null
  const node1 = nodes.value.find((n: any) => n.id === selectedNodeIds.value[0])
  if (!node1) return null

  // 优先指向终点节点
  if (selectedNodeIds.value.length >= 2) {
    const node2 = nodes.value.find((n: any) => n.id === selectedNodeIds.value[1])
    if (node2) {
      return { x1: node1.x, y1: -node1.y, x2: node2.x, y2: -node2.y }
    }
  }

  // 其次指向终点区域中心
  if (selectedResourceId.value) {
    const resource = resources.value.find((r: any) => r.id === selectedResourceId.value)
    if (resource) {
      const center = getResourceCenter(resource)
      return { x1: node1.x, y1: -node1.y, x2: center.x, y2: -center.y }
    }
  }

  return null
})

// 世界边界
const worldBounds = computed(() => {
  const ns = nodes.value
  if (!ns.length) return { xMin: -50, xMax: 50, yMin: -50, yMax: 50 }
  let xMin = Infinity, xMax = -Infinity, yMin = Infinity, yMax = -Infinity
  ns.forEach((n: any) => {
    if (n.x < xMin) xMin = n.x
    if (n.x > xMax) xMax = n.x
    if (n.y < yMin) yMin = n.y
    if (n.y > yMax) yMax = n.y
  })
  const pad = 20
  return { xMin: xMin - pad, xMax: xMax + pad, yMin: yMin - pad, yMax: yMax + pad }
})

// 加载地图列表
const loadMapList = async () => {
  try {
    const params = { pageNumber: 1, pageSize: 100, filterModel: JSON.stringify({ active: { filterType: 'text', type: 'equals', filter: 'true' } }) }
    const res = await mapsApi.list(params)
    const data = (res && (res.Data ?? res.data)) || []
    mapList.value = Array.isArray(data) ? data.filter((m: any) => m.active) : []
    // 默认选择第一个地图
    if (mapList.value.length > 0 && !selectedMapId.value) {
      selectedMapId.value = mapList.value[0].mapId
    }
  } catch (err: any) {
    notify({ message: err?.message || t('dashboard.loadMapListFailed'), color: 'danger' })
  }
}

// 加载地图详情
const loadMapData = async (mapId: string) => {
  if (!mapId) return
  isLoading.value = true
  try {
    const res = await mapsApi.getDetails(mapId)
    const data = (res && (res.Data ?? res.data)) || res || {}

    currentMap.value.id = String(data.mapId ?? data.id ?? mapId)
    currentMap.value.name = data.mapName ?? data.name ?? ''
    currentMap.value.code = data.mapCode ?? data.code ?? ''
    currentMap.value.type = data.mapType ?? data.type ?? 1

    // 处理节点
    const nodesData = data.mapNodes ?? data.nodes ?? []
    const nodeIdToCodeMap = new Map()
    currentMap.value.nodes = nodesData.map((node: any) => {
      const nodeId = String(node.nodeId ?? node.id)
      const nodeCode = node.nodeCode ?? node.code ?? node.label ?? `N${nodeId}`
      nodeIdToCodeMap.set(nodeId, nodeCode)
      return {
        id: nodeId,
        x: node.x,
        y: node.y,
        code: nodeCode,
        name: node.nodeName ?? node.name ?? '',
        type: node.type,
        storageLocations: []
      }
    })

    // 处理边
    const edgesData = data.mapEdges ?? data.edges ?? []
    currentMap.value.edges = edgesData.map((edge: any) => {
      const sourceCode = edge.fromNode ? (nodeIdToCodeMap.get(String(edge.fromNode)) ?? edge.sourceCode ?? '') : (edge.sourceCode ?? '')
      const targetCode = edge.toNode ? (nodeIdToCodeMap.get(String(edge.toNode)) ?? edge.targetCode ?? '') : (edge.targetCode ?? '')
      return {
        id: String(edge.edgeId ?? edge.id),
        sourceCode,
        targetCode,
        curve: edge.isCurve ?? edge.curve ?? false,
        radius: edge.radius,
        centerX: edge.centerX,
        centerY: edge.centerY
      }
    })

    // 处理资源
    const resourcesData = data.mapResources ?? data.resources ?? []
    currentMap.value.resources = resourcesData.map((resource: any) => ({
      id: String(resource.resourceId ?? resource.id),
      resourceCode: resource.resourceCode ?? resource.code ?? '',
      resourceName: resource.resourceName ?? resource.name ?? '',
      type: resource.type ?? 1,
      locationCoordinates: resource.locationCoordinates ?? []
    }))

    // 加载背景图(不添加时间戳,利用浏览器缓存)
    try {
      const fileRes = await mapsApi.getMapFile(mapId)
      const fileData = (fileRes && (fileRes.Data ?? fileRes.data)) || null
      if (fileData && fileData.fileUrl) {
        bgOpacity.value = fileData.opacity ?? 1
        bgRotation.value = fileData.rotation ?? 0
        bgOffsetX.value = fileData.offsetX ?? 0
        bgOffsetY.value = fileData.offsetY ?? 0
        const dbScale = fileData.scale ?? 0

        // 先预加载图片,完成后再设置URL,避免重复请求
        const img = new Image()
        img.crossOrigin = 'anonymous'
        img.onload = () => {
          bgImgSize.value = { width: img.naturalWidth, height: img.naturalHeight }
          bgScale.value = dbScale > 0 && dbScale < 1
            ? Math.max(0.01, 800 / img.naturalWidth)
            : (dbScale || Math.max(0.01, 800 / img.naturalWidth))
          bgImageUrl.value = fileData.fileUrl
          setTimeout(() => resetView(), 50)
        }
        img.src = fileData.fileUrl
      } else {
        bgImageUrl.value = ''
        // 无背景图时直接重置视图
        setTimeout(() => resetView(), 100)
      }
    } catch {
      bgImageUrl.value = ''
      setTimeout(() => resetView(), 100)
    }
  } catch (err: any) {
    notify({ message: err?.message || t('dashboard.loadMapDetailFailed'), color: 'danger' })
  } finally {
    isLoading.value = false
  }
}

// 监听地图选择变化
watch(selectedMapId, async (newId) => {
  if (newId) {
    // 清空旧地图的机器人数据和选中状态
    robotList.value = []
    selectedNodeIds.value = []
    loadMapData(newId)
    // 断开旧连接,连接新地图的 WebSocket 并订阅
    await HHRCSWs.disconnect()
    await HHRCSWs.connect(newId)
    await HHRCSWs.subscribe([SubscriptionType.RobotStatus, SubscriptionType.StorageLocations])
  }33
})

// 获取节点坐标
const getNodeByCode = (code: string) => nodes.value.find((n: any) => n.code === code)

// 边路径(中点在2/3处,与MapEditor一致)
const getEdgePath = (edge: any) => {
  const s = getNodeByCode(edge.sourceCode)
  const t = getNodeByCode(edge.targetCode)
  if (!s || !t) return ''
  const dx = t.x - s.x
  const dy = t.y - s.y
  const xm = s.x + (2 / 3) * dx
  const ym = s.y + (2 / 3) * dy
  return `M ${s.x},${-s.y} L ${xm},${-ym} L ${t.x},${-t.y}`
}

// 弧线路径(与MapEditor一致)
const getArcPath = (arc: any) => {
  if (!arc || !arc.radius || arc.centerX == null || arc.centerY == null) return ''

  // 获取起点和终点坐标
  let startX: number, startY: number, endX: number, endY: number
  if (arc.startX != null && arc.startY != null && arc.endX != null && arc.endY != null) {
    startX = arc.startX
    startY = arc.startY
    endX = arc.endX
    endY = arc.endY
  } else {
    const src = getNodeByCode(arc.sourceCode)
    const tgt = getNodeByCode(arc.targetCode)
    if (!src || !tgt) return ''
    startX = src.x
    startY = src.y
    endX = tgt.x
    endY = tgt.y
  }

  const toRad = (deg: number) => deg * (Math.PI / 180)
  const toDeg = (rad: number) => rad * (180 / Math.PI)
  const normDeg = (a: number) => { let x = a % 360; if (x < 0) x += 360; return x }
  const normDelta = (a0: number, a1: number) => {
    const raw = a1 - a0
    let d = ((raw % 360) + 360) % 360
    if (d > 180) d -= 360
    return d
  }

  const startAngle = normDeg(toDeg(Math.atan2(-(startY - arc.centerY), startX - arc.centerX)))
  const endAngle = normDeg(toDeg(Math.atan2(-(endY - arc.centerY), endX - arc.centerX)))
  const delta = normDelta(startAngle, endAngle)
  const sweepFlag = delta > 0 ? 1 : 0
  const midAngle = startAngle + delta * (2 / 3)
  const rx = arc.radius
  const ry = arc.radius

  const x1 = startX
  const y1s = -startY
  const xm = arc.centerX + rx * Math.cos(toRad(midAngle))
  const ym = arc.centerY - ry * Math.sin(toRad(midAngle))
  const xms = xm
  const yms = -ym
  const x2 = endX
  const y2s = -endY
  const largeArcFlag = 0

  return `M ${x1},${y1s} A ${rx},${ry} 0 ${largeArcFlag},${sweepFlag} ${xms},${yms} A ${rx},${ry} 0 ${largeArcFlag},${sweepFlag} ${x2},${y2s}`
}

/**
 * 获取储位整体状态(综合判断所有储位)
 * @param node 节点对象
 * @returns 状态值:0=空闲,1=占用,2=预占用,3=禁用
 * @author zzy
 *
 * 优先级策略:
 * - 如果有任何储位被禁用(3),整体返回禁用(3)
 * - 如果有任何储位被占用(1),整体返回占用(1)
 * - 如果有任何储位被预占用(2),整体返回预占用(2)
 * - 只有全部空闲时,整体返回空闲(0)
 */
const getStorageStatus = (node: any) => {
  // 检查节点是否有储位区域
  if (!node?.storageLocations?.length) return 0

  // 收集所有储位的状态
  const allStatuses: number[] = []

  for (const location of node.storageLocations) {
    const status = location.status ?? 0
    allStatuses.push(status)
  }
  

  // 如果没有任何储位,返回空闲
  if (allStatuses.length === 0) return 0

  // 按优先级判断整体状态
  if (allStatuses.includes(3)) return 3  // 禁用
  if (allStatuses.includes(1)) return 1  // 占用
  if (allStatuses.includes(2)) return 2  // 预占用
  return 0  // 空闲
}

// 节点填充色(与MapEditor一致)
const getNodeFill = (node: any) => {
  if (!node || !node.type) return '#ffffff'
  if (node.type === 1) return '#74c0fc'  // 高速点
  if (node.type === 4) return '#0d47a1'  // 停车位
  return node.type === 2 ? '#ffb020' : '#ffffff'  // 储位
}

// 节点描边色(与MapEditor一致)
const getNodeStroke = (node: any) => {
  if (!node) return '#6c757d'
  if (!node.type) return '#6c757d'
  if (node.type === 3) return '#28a745'  // 充电点
  if (node.type === 2) return '#d9480f'  // 储位
  if (node.type === 4) return '#0d47a1'  // 停车位
  return '#6c757d'
}

// 资源颜色(与MapEditor一致)
const getResourceColor = (type: number, alpha = 1) => {
  const colors: Record<number, string> = {
    1: `rgba(33, 150, 243, ${alpha})`,   // 停靠点 - 蓝色
    2: `rgba(76, 175, 80, ${alpha})`,    // 充电桩 - 绿色
    3: `rgba(156, 39, 176, ${alpha})`,   // 电梯 - 紫色
    4: `rgba(0, 188, 212, ${alpha})`,    // 风淋门 - 青色
    5: `rgba(255, 152, 0, ${alpha})`,    // 传送带 - 橙色
    6: `rgba(121, 85, 72, ${alpha})`,    // 存储区 - 棕色
    7: `rgba(158, 158, 158, ${alpha})`,  // 标记区域 - 灰色
    8: `rgba(96, 125, 139, ${alpha})`    // 其他 - 蓝灰色
  }
  return colors[type] || `rgba(158, 158, 158, ${alpha})`
}

// 资源多边形点
const getResourcePolygonPoints = (resource: any) => {
  if (!resource.locationCoordinates || resource.locationCoordinates.length === 0) return ''
  return resource.locationCoordinates.map((p: any) => `${p.x},${-p.y}`).join(' ')
}

// 资源中心点
const getResourceCenter = (resource: any) => {
  if (!resource.locationCoordinates || resource.locationCoordinates.length === 0) return { x: 0, y: 0 }
  const pts = resource.locationCoordinates
  const sumX = pts.reduce((acc: number, p: any) => acc + p.x, 0)
  const sumY = pts.reduce((acc: number, p: any) => acc + p.y, 0)
  return { x: sumX / pts.length, y: sumY / pts.length }
}

// 资源点击事件
const onResourceClick = (resource: any, e: MouseEvent) => {
  e.stopPropagation()
  // 重定位模式下,点击资源区域只设置重定位位置(使用区域中心点)
  if (relocateMode.value) {
    const center = getResourceCenter(resource)
    relocatePosition.value = { x: center.x, y: center.y }
    return
  }
  // 必须先选择起点节点
  if (selectedNodeIds.value.length < 1) {
    notify({ message: t('dashboard.selectStartFirst') || '请先选择起点节点', color: 'warning' })
    return
  }
  if (selectedResourceId.value === resource.id) {
    selectedResourceId.value = null
    endResourceId.value = ''
    endResourceName.value = ''
  } else {
    selectedResourceId.value = resource.id
    endResourceId.value = resource.id
    endResourceName.value = resource.resourceName || resource.resourceCode
  }
}

// 画布事件
let hasDragged = false
const onCanvasMouseDown = (e: MouseEvent) => {
  isPanning = true
  hasDragged = false
  panStart = { x: e.clientX, y: e.clientY }
  viewportStart = { x: viewport.value.x, y: viewport.value.y }
}

const onCanvasMouseMove = (e: MouseEvent) => {
  if (!isPanning) return
  const dx = e.clientX - panStart.x
  const dy = e.clientY - panStart.y
  if (Math.abs(dx) > 3 || Math.abs(dy) > 3) hasDragged = true
  viewport.value.x = viewportStart.x + dx
  viewport.value.y = viewportStart.y + dy
}

const onCanvasMouseUp = (e: MouseEvent) => {
  if (isPanning && !hasDragged) {
    // 如果在重定位模式下,处理点击选择位置
    if (relocateMode.value) {
      onRelocateCanvasClick(e)
    } else {
      selectedNodeIds.value = []
      selectedResourceId.value = null
    }
  }
  isPanning = false
}

const onCanvasWheel = (e: WheelEvent) => {
  const rect = (e.currentTarget as HTMLElement).getBoundingClientRect()
  const mx = e.clientX - rect.left
  const my = e.clientY - rect.top
  const factor = e.deltaY < 0 ? 1.1 : 0.9
  const newScale = Math.max(MIN_SCALE, viewport.value.scale * factor)
  const wx = (mx - viewport.value.x) / viewport.value.scale
  const wy = (my - viewport.value.y) / viewport.value.scale
  viewport.value.scale = newScale
  viewport.value.x = mx - wx * newScale
  viewport.value.y = my - wy * newScale
}

// 触屏事件
let lastTouchDist = 0
let lastTouchCenter = { x: 0, y: 0 }

const onTouchStart = (e: TouchEvent) => {
  if (e.touches.length === 1) {
    isPanning = true
    hasDragged = false
    panStart = { x: e.touches[0].clientX, y: e.touches[0].clientY }
    viewportStart = { x: viewport.value.x, y: viewport.value.y }
  } else if (e.touches.length === 2) {
    isPanning = false
    const dx = e.touches[1].clientX - e.touches[0].clientX
    const dy = e.touches[1].clientY - e.touches[0].clientY
    lastTouchDist = Math.hypot(dx, dy)
    lastTouchCenter = {
      x: (e.touches[0].clientX + e.touches[1].clientX) / 2,
      y: (e.touches[0].clientY + e.touches[1].clientY) / 2
    }
  }
}

const onTouchMove = (e: TouchEvent) => {
  e.preventDefault()
  if (e.touches.length === 1 && isPanning) {
    const dx = e.touches[0].clientX - panStart.x
    const dy = e.touches[0].clientY - panStart.y
    if (Math.abs(dx) > 3 || Math.abs(dy) > 3) hasDragged = true
    viewport.value.x = viewportStart.x + dx
    viewport.value.y = viewportStart.y + dy
  } else if (e.touches.length === 2) {
    const dx = e.touches[1].clientX - e.touches[0].clientX
    const dy = e.touches[1].clientY - e.touches[0].clientY
    const dist = Math.hypot(dx, dy)
    const center = {
      x: (e.touches[0].clientX + e.touches[1].clientX) / 2,
      y: (e.touches[0].clientY + e.touches[1].clientY) / 2
    }
    if (lastTouchDist > 0) {
      const rect = (e.currentTarget as HTMLElement).getBoundingClientRect()
      const mx = center.x - rect.left
      const my = center.y - rect.top
      const factor = dist / lastTouchDist
      const newScale = Math.max(MIN_SCALE, Math.min(10, viewport.value.scale * factor))
      const wx = (mx - viewport.value.x) / viewport.value.scale
      const wy = (my - viewport.value.y) / viewport.value.scale
      viewport.value.scale = newScale
      viewport.value.x = mx - wx * newScale + (center.x - lastTouchCenter.x)
      viewport.value.y = my - wy * newScale + (center.y - lastTouchCenter.y)
    }
    lastTouchDist = dist
    lastTouchCenter = center
  }
}

const onTouchEnd = (e: TouchEvent) => {
  if (e.touches.length === 0) {
    if (isPanning && !hasDragged) {
      selectedNodeIds.value = []
    }
    isPanning = false
    lastTouchDist = 0
  } else if (e.touches.length === 1) {
    isPanning = true
    hasDragged = true
    panStart = { x: e.touches[0].clientX, y: e.touches[0].clientY }
    viewportStart = { x: viewport.value.x, y: viewport.value.y }
    lastTouchDist = 0
  }
}

const resetView = () => {
  if (!canvasSize.value.width || !canvasSize.value.height) return
  const { xMin, xMax, yMin, yMax } = worldBounds.value
  // 合并节点边界和背景图边界
  const bgXMin = bgOffsetX.value
  const bgXMax = bgOffsetX.value + bgWorldWidth.value
  const bgYMin = bgOffsetY.value
  const bgYMax = bgOffsetY.value + bgWorldHeight.value
  const hasBg = bgImageUrl.value && bgWorldWidth.value > 0
  const finalXMin = hasBg ? Math.min(xMin, bgXMin) : xMin
  const finalXMax = hasBg ? Math.max(xMax, bgXMax) : xMax
  const finalYMin = hasBg ? Math.min(yMin, bgYMin) : yMin
  const finalYMax = hasBg ? Math.max(yMax, bgYMax) : yMax
  const worldW = finalXMax - finalXMin || 100
  const worldH = finalYMax - finalYMin || 100
  const scaleX = canvasSize.value.width / worldW
  const scaleY = canvasSize.value.height / worldH
  const scale = Math.min(scaleX, scaleY) * 0.9
  const centerX = (finalXMin + finalXMax) / 2
  const centerY = (finalYMin + finalYMax) / 2
  viewport.value.scale = Math.max(MIN_SCALE, scale)
  viewport.value.x = canvasSize.value.width / 2 - centerX * viewport.value.scale
  viewport.value.y = canvasSize.value.height / 2 + centerY * viewport.value.scale
}

const zoomIn = () => {
  viewport.value.scale = Math.min(10, viewport.value.scale * 1.2)
}

const zoomOut = () => {
  viewport.value.scale = Math.max(MIN_SCALE, viewport.value.scale / 1.2)
}

/**
 * 进入重定位模式
 * @param robotId 机器人ID
 * @param robotCode 机器人编码
 * @author zzy
 */
const enterRelocateMode = (robotId: string, robotCode: string) => {
  relocateMode.value = true
  relocateRobotId.value = robotId
  relocateRobotCode.value = robotCode
  relocatePosition.value = null
  relocateAngle.value = 0
  notify({ message: t('dashboard.relocate.clickToSelect'), color: 'info' })
}

/**
 * 取消重定位模式
 * @author zzy
 */
const cancelRelocate = () => {
  relocateMode.value = false
  relocateRobotId.value = null
  relocateRobotCode.value = ''
  relocatePosition.value = null
  relocateAngle.value = 0
}

/**
 * 获取选中的机器人对象
 * @author zzy
 */
const selectedRobot = computed(() => {
  if (!selectedRobotId.value) return null
  return robotList.value.find(r => r.robotId === selectedRobotId.value) || null
})

/**
 * 选中机器人面板的样式(跟随机器人位置)
 * @author zzy
 */
const selectedRobotStyle = computed(() => {
  const robot = selectedRobot.value
  if (!robot || robot.x == null || robot.y == null) return {}

  // 计算屏幕坐标:ViewPort + RobotWorldPos * Scale
  // 注意:世界坐标Y轴向上,SVG坐标Y轴向下,所以Y要取反
  const screenX = viewport.value.x + robot.x * viewport.value.scale
  const screenY = viewport.value.y - robot.y * viewport.value.scale

  // 偏移量,避免遮挡机器人
  const offsetX = 50 * viewport.value.scale + 20
  const offsetY = -50 * viewport.value.scale - 20

  return {
    left: `${screenX + offsetX}px`,
    top: `${screenY + offsetY}px`,
    bottom: 'auto',
    right: 'auto',
    transform: 'none' // 确保没有其他transform干扰
  }
})

/**
 * 处理画布中机器人的点击事件
 * @param robot 机器人对象
 * @param e 鼠标事件
 * @author zzy
 */
const onRobotClick = (robot: RobotStatus, e: MouseEvent) => {
  e.stopPropagation()
  // 重定位模式下不处理机器人选中
  if (relocateMode.value) return
  // 切换选中状态
  if (selectedRobotId.value === robot.robotId) {
    selectedRobotId.value = null
  } else {
    selectedRobotId.value = robot.robotId
  }
}

/**
 * 复位选中的机器人(与RobotStatusCard相同功能)
 * @author zzy
 */
const handleSelectedRobotReset = async () => {
  if (isRobotActionLoading.value || !selectedRobot.value) return
  isRobotActionLoading.value = true
  try {
    const res = await robotsApi.reset(selectedRobot.value.robotId)
    if (res?.Success || res?.success) {
      notify({ message: t('dashboard.robotCard.messages.resetSuccess'), color: 'success' })
    } else {
      notify({ message: res?.Message || res?.message || t('dashboard.robotCard.messages.resetFailed'), color: 'danger' })
    }
  } catch (err: any) {
    notify({ message: err?.message || t('dashboard.robotCard.messages.resetFailed'), color: 'danger' })
  } finally {
    isRobotActionLoading.value = false
  }
}

/**
 * 暂停/恢复选中的机器人(与RobotStatusCard相同功能)
 * @author zzy
 */
const handleSelectedRobotPauseToggle = async () => {
  if (isRobotPauseLoading.value || !selectedRobot.value) return
  isRobotPauseLoading.value = true
  const isPaused = selectedRobot.value.paused
  try {
    const action = isPaused ? robotsApi.unpause : robotsApi.pause
    const res = await action(selectedRobot.value.robotId)
    if (res?.Success || res?.success) {
      notify({ message: t('dashboard.robotCard.messages.operationSuccess'), color: 'success' })
    } else {
      notify({ message: res?.Message || res?.message || (isPaused ? t('dashboard.robotCard.messages.resumeFailed') : t('dashboard.robotCard.messages.pauseFailed')), color: 'danger' })
    }
  } catch (err: any) {
    notify({ message: err?.message || (isPaused ? t('dashboard.robotCard.messages.resumeFailed') : t('dashboard.robotCard.messages.pauseFailed')), color: 'danger' })
  } finally {
    isRobotPauseLoading.value = false
  }
}

/**
 * 取消选中机器人的任务(与RobotStatusCard相同功能)
 * @author zzy
 */
const handleSelectedRobotCancelTask = async () => {
  if (isRobotActionLoading.value || !selectedRobot.value) return
  isRobotActionLoading.value = true
  try {
    const res = await robotsApi.cancelTask(selectedRobot.value.robotId)
    if (res?.Success || res?.success) {
      notify({ message: t('dashboard.robotCard.messages.cancelTaskSuccess'), color: 'success' })
    } else {
      notify({ message: res?.Message || res?.message || t('dashboard.robotCard.messages.cancelTaskFailed'), color: 'danger' })
    }
  } catch (err: any) {
    notify({ message: err?.message || t('dashboard.robotCard.messages.cancelTaskFailed'), color: 'danger' })
  } finally {
    isRobotActionLoading.value = false
  }
}

/**
 * 从画布选中机器人进入重定位模式
 * @author zzy
 */
const handleSelectedRobotRelocate = () => {
  if (!selectedRobot.value) return
  const robot = selectedRobot.value
  selectedRobotId.value = null // 清除选中状态
  enterRelocateMode(robot.robotId, robot.robotCode)
}

/**
 * 确认重定位
 * @author zzy
 */
const confirmRelocate = async () => {
  if (!relocateRobotId.value || !relocatePosition.value) return
  
  isRelocating.value = true
  try {
    // 将角度转换为弧度
    const thetaRad = (relocateAngle.value * Math.PI) / 180
    const res = await robotsApi.relocate(
      relocateRobotId.value,
      relocatePosition.value.x,
      relocatePosition.value.y,
      thetaRad
    )
    if (res?.Success || res?.success) {
      notify({ message: t('dashboard.relocate.success'), color: 'success' })
      cancelRelocate()
    } else {
      notify({ message: res?.Message || res?.message || t('dashboard.relocate.failed'), color: 'danger' })
    }
  } catch (err: any) {
    notify({ message: err?.message || t('dashboard.relocate.failed'), color: 'danger' })
  } finally {
    isRelocating.value = false
  }
}

/**
 * 处理重定位模式下的画布点击
 * @param e 鼠标事件
 * @author zzy
 */
const onRelocateCanvasClick = (e: MouseEvent) => {
  if (!relocateMode.value) return
  
  const svg = svgRef.value
  if (!svg) return
  
  const rect = svg.getBoundingClientRect()
  const screenX = e.clientX - rect.left
  const screenY = e.clientY - rect.top
  
  // 将屏幕坐标转换为世界坐标
  const worldX = (screenX - viewport.value.x) / viewport.value.scale
  const worldY = -((screenY - viewport.value.y) / viewport.value.scale)
  
  relocatePosition.value = { x: worldX, y: worldY }
}

/**
 * 角度选择器拖拽状态
 */
let isAngleDragging = false

/**
 * 开始拖拽角度
 * @author zzy
 */
const onAngleDragStart = (e: MouseEvent) => {
  isAngleDragging = true
  updateAngleFromEvent(e)
}

/**
 * 拖拽角度
 * @author zzy
 */
const onAngleDrag = (e: MouseEvent) => {
  if (!isAngleDragging) return
  updateAngleFromEvent(e)
}

/**
 * 结束拖拽角度
 * @author zzy
 */
const onAngleDragEnd = () => {
  isAngleDragging = false
}

/**
 * 从鼠标事件更新角度
 * @author zzy
 */
const updateAngleFromEvent = (e: MouseEvent) => {
  const svg = e.currentTarget as SVGElement
  const rect = svg.getBoundingClientRect()
  const centerX = rect.width / 2
  const centerY = rect.height / 2
  const x = e.clientX - rect.left - centerX
  const y = centerY - (e.clientY - rect.top)
  
  let angle = Math.atan2(y, x) * (180 / Math.PI)
  // 将角度规范化到0-360
  if (angle < 0) angle += 360
  // 四舍五入到最近的5度
  relocateAngle.value = Math.round(angle / 5) * 5 % 360
}

onMounted(async () => {
  // 检测设备类型
  checkDeviceType()
  // 监听窗口大小变化以重新检测设备类型
  window.addEventListener('resize', checkDeviceType)

  await loadMapList()

  // 订阅机器人状态更新
  unsubscribeWs = HHRCSWs.onStatusUpdate((robots) => {
    robotList.value = robots
  })

  /**
   * 订阅库位状态更新
   * @description 通过 WebSocket 接收储位区域数据,并按节点ID更新对应节点的储位列表
   * @author zzy
   */
  unsubscribeLocationWs = HHRCSWs.onLocationUpdate((areas: StorageArea[]) => {
    // 构建节点ID到储位列表的映射表(使用 Map 提升查找性能)
    const storageLocationMap = new Map<string, StorageLocation[]>()

    // 第一遍遍历:收集所有有效的节点-储位映射关系
    for (const area of areas) {
      if (area.nodeId && area.storageLocations?.length >= 0) {
        storageLocationMap.set(area.nodeId, area.storageLocations)
      }
    }

    // 第二遍遍历:更新节点数据(直接修改引用以触发 Vue 响应式更新)
    for (const node of currentMap.value.nodes) {
      const locations = storageLocationMap.get(node.id)
      node.storageLocations = locations ?? []
    }
  })

  // 监听画布大小
  if (svgRef.value) {
    const parent = svgRef.value.parentElement
    if (parent) {
      resizeObserver = new ResizeObserver((entries) => {
        for (const entry of entries) {
          canvasSize.value = { width: entry.contentRect.width, height: entry.contentRect.height }
        }
      })
      resizeObserver.observe(parent)
      canvasSize.value = { width: parent.clientWidth, height: parent.clientHeight }
    }
  }
})

onBeforeUnmount(() => {
  // 移除窗口大小变化监听
  window.removeEventListener('resize', checkDeviceType)
  // 移除平板模式样式类
  document.body.classList.remove('tablet-mode')
  document.documentElement.classList.remove('tablet-mode')

  if (resizeObserver) resizeObserver.disconnect()
  if (unsubscribeWs) unsubscribeWs()
  if (unsubscribeLocationWs) unsubscribeLocationWs()
  HHRCSWs.disconnect()
})
</script>

<template>
  <div class="device-monitor-wrapper" :class="{ 'tablet-fullscreen': isTablet }">
    <!-- 平板模式提示 -->
    <div v-if="isTablet" class="tablet-mode-indicator">
      <VaIcon name="tablet_android" size="small" />
      <span>{{ t('dashboard.tabletMode') || '平板模式' }}</span>
    </div>
    <div class="monitor-main">
      <VaCard class="device-monitor-card">
        <VaCardContent class="device-monitor-content">
        <!-- 顶部工具栏 -->
        <div class="toolbar-container">
          <div class="toolbar-left">
            <VaSelect
              v-model="selectedMapId"
              :options="mapList"
              :placeholder="t('dashboard.selectMap') || '请选择地图'"
              text-by="mapName"
              value-by="mapId"
              class="map-select"
              :loading="isLoading"
            />
            <div class="task-input-group">
              <VaInput
                v-model="startNodeCode"
                :placeholder="t('dashboard.startNode') || '起点'"
                class="node-input"
                readonly
              />
              <span class="arrow-icon">→</span>
              <VaInput
                v-model="endResourceName"
                :placeholder="t('dashboard.endArea') || '终点区域'"
                class="node-input"
                readonly
              />
              <span class="separator">:</span>
              <VaInput
                v-model="endNodeCode"
                :placeholder="t('dashboard.endNode') || '终点节点'"
                class="node-input"
                readonly
              />
              <VaButton
                color="primary"
                @click="executeTask"
                icon="play_arrow"
                round
                :title="t('dashboard.executeTask') || '执行任务'"
                :loading="isLoading"
                class="execute-btn"
              />
            </div>
          </div>
          <div class="toolbar-right">
            <VaButtonGroup class="toolbar-group">
              <VaButton
                color="secondary"
                @click="zoomIn"
                icon="zoom_in"
                size="small"
                :title="t('dashboard.zoomIn')"
              />
              <VaButton
                color="secondary"
                @click="zoomOut"
                icon="zoom_out"
                size="small"
                :title="t('dashboard.zoomOut')"
              />
              <VaButton
                color="secondary"
                @click="resetView"
                icon="history"
                size="small"
                :title="t('dashboard.resetView')"
              />
            </VaButtonGroup>
            <span class="stats-text" v-if="currentMap.id">
              {{ t('dashboard.stats') || '节点' }}: {{ nodes.length }} | {{ t('dashboard.edges') || '边' }}: {{ edges.length }}
            </span>
          </div>
        </div>

        <!-- 地图画布 -->
        <div class="map-canvas-wrapper">
          <div
            v-if="currentMap.id"
            class="topo-canvas"
            :class="{ 'relocate-mode': relocateMode }"
            @mousedown="onCanvasMouseDown"
            @mousemove="onCanvasMouseMove"
            @mouseup="onCanvasMouseUp"
            @mouseleave="onCanvasMouseUp"
            @wheel.prevent="onCanvasWheel"
            @touchstart="onTouchStart"
            @touchmove.prevent="onTouchMove"
            @touchend="onTouchEnd"
          >
            <svg width="100%" height="100%" ref="svgRef">
              <defs>
                <marker id="arrow-black" viewBox="0 0 10 10" refX="10" refY="5" markerUnits="strokeWidth" markerWidth="10" markerHeight="6" orient="auto">
                  <path d="M 0 0 L 10 5 L 0 10 z" fill="#000000" />
                </marker>
                <marker id="arrow-red" viewBox="0 0 10 10" refX="10" refY="5" markerUnits="strokeWidth" markerWidth="10" markerHeight="6" orient="auto">
                  <path d="M 0 0 L 10 5 L 0 10 z" fill="#dc3545" />
                </marker>
                <marker id="arrow-guide" viewBox="0 0 10 10" refX="5" refY="5" markerUnits="strokeWidth" markerWidth="4" markerHeight="4" orient="auto">
                  <path d="M 0 0 L 10 5 L 0 10 z" fill="#ff6b35" />
                </marker>
                <!-- 潜伏车图标 -->
                <symbol id="latent-agv" viewBox="0 0 50 40">
                  <linearGradient id="agvGreen1" x1="0%" y1="0%" x2="100%" y2="0%">
                    <stop offset="0%" stop-color="#90EE90" stop-opacity="0.6"/>
                    <stop offset="100%" stop-color="#90EE90" stop-opacity="0.15"/>
                  </linearGradient>
                  <rect x="5" y="5" width="35" height="30" rx="5" fill="#aa2116"/>
                  <rect x="10" y="10" width="25" height="20" rx="3" fill="#1a1a1a"/>
                  <polygon points="40,12 40,28 48,32 48,8" fill="url(#agvGreen1)"/>
                </symbol>
                <!-- 叉车图标 -->
                <symbol id="forklift-agv" viewBox="-8 0 65 40">
                  <linearGradient id="agvGreen2" x1="0%" y1="0%" x2="100%" y2="0%">
                    <stop offset="0%" stop-color="#90EE90" stop-opacity="0.6"/>
                    <stop offset="100%" stop-color="#90EE90" stop-opacity="0.15"/>
                  </linearGradient>
                  <rect x="-6" y="11" width="35" height="6" rx="3" fill="#1a1a1a"/>
                  <rect x="-6" y="23" width="35" height="6" rx="3" fill="#1a1a1a"/>
                  <ellipse cx="0" cy="14" rx="4" ry="2" fill="#555"/>
                  <ellipse cx="0" cy="26" rx="4" ry="2" fill="#555"/>
                  <rect x="24" y="8" width="16" height="24" rx="4" fill="#aa2116"/>
                  <polygon points="40,12 40,28 50,32 50,8" fill="url(#agvGreen2)"/>
                </symbol>
              </defs>

              <g :transform="`translate(${viewport.x}, ${viewport.y}) scale(${viewport.scale})`">
                <!-- 背景图 -->
                <g v-if="bgImageUrl">
                  <g :transform="`translate(${bgWorldWidth / 2 + bgOffsetX}, ${-bgWorldHeight / 2 - bgOffsetY}) rotate(${bgRotation}) translate(${-bgWorldWidth / 2}, ${bgWorldHeight / 2})`">
                    <image
                      :href="bgImageUrl"
                      :x="0"
                      :y="-bgWorldHeight"
                      :width="bgWorldWidth"
                      :height="bgWorldHeight"
                      :opacity="bgOpacity"
                      preserveAspectRatio="none"
                      crossorigin="anonymous"
                    />
                  </g>
                </g>

                <!-- 网格(简化:只显示坐标轴) -->
                <g class="grid">
                  <line :x1="0" :y1="-worldBounds.yMin" :x2="0" :y2="-worldBounds.yMax" stroke="#adb5bd" :stroke-width="0.2 / viewport.scale" />
                  <line :x1="worldBounds.xMin" y1="0" :x2="worldBounds.xMax" y2="0" stroke="#adb5bd" :stroke-width="0.2 / viewport.scale" />
                </g>

                <!-- 资源区域 -->
                <g class="resources">
                  <g v-for="resource in resources" :key="resource.id">
                    <polygon
                      :points="getResourcePolygonPoints(resource)"
                      :fill="selectedResourceId === resource.id ? 'rgba(13, 110, 253, 0.4)' : getResourceColor(resource.type, 0.3)"
                      :stroke="selectedResourceId === resource.id ? '#0d6efd' : getResourceColor(resource.type, 1)"
                      :stroke-width="(selectedResourceId === resource.id ? 2 : 1) / viewport.scale"
                      :stroke-dasharray="selectedResourceId === resource.id ? 'none' : `${0.5 / viewport.scale} ${0.25 / viewport.scale}`"
                      @mousedown.stop
                      @click.stop="onResourceClick(resource, $event)"
                      style="cursor: pointer"
                    />
                    <text
                      v-if="resource.locationCoordinates && resource.locationCoordinates.length > 0"
                      :x="getResourceCenter(resource).x"
                      :y="-Math.max(...resource.locationCoordinates.map((p: any) => p.y)) - 10 / viewport.scale"
                      :font-size="15 / viewport.scale"
                      fill="#333"
                      text-anchor="middle"
                      dominant-baseline="auto"
                    >{{ resource.resourceName || resource.resourceCode }}</text>
                  </g>
                </g>

                <!-- 边 -->
                <g class="edges">
                  <g v-for="edge in edges.filter((e: any) => !e.curve)" :key="edge.id">
                    <path
                      :d="getEdgePath(edge)"
                      fill="none"
                      :stroke="'#000000'"
                      stroke-width="6"
                      :marker-mid="'url(#arrow-black)'"
                    />
                  </g>
                </g>

                <!-- 弧线 -->
                <g class="arcs">
                  <g v-for="arc in edges.filter((e: any) => e.curve)" :key="arc.id">
                    <path
                      :d="getArcPath(arc)"
                      fill="none"
                      :stroke="'#000000'"
                      stroke-width="6"
                      :marker-mid="'url(#arrow-black)'"
                    />
                  </g>
                </g>

                <!-- 机器人路径线条(橙色) -->
                <g class="robot-paths">
                  <g v-for="robot in robotList" :key="'path-' + robot.robotId">
                    <!-- 重定位模式下隐藏正在重定位的机器人路径 -->
                    <polyline
                      v-if="robot.path && robot.path.length > 1 && !(relocateMode && robot.robotId === relocateRobotId)"
                      :points="robot.path.map((p: number[]) => `${p[0]},${-p[1]}`).join(' ')"
                      fill="none"
                      stroke="#fdb933"
                      stroke-width="160"
                      stroke-linecap="round"
                      stroke-linejoin="round"
                    />
                  </g>
                </g>

                <!-- 节点 -->
                <g class="nodes">
                  <g v-for="node in nodes" :key="node.id" :transform="`translate(${node.x}, ${-node.y})`"
                     @mousedown.stop @click="onNodeClick(node, $event)" style="cursor: pointer">
                    <!-- 储位类型:1000x1000橙黄色方框 -->
                    <g v-if="node.type === 2">
                      <rect x="-500" y="-500" width="1000" height="1000" rx="50" ry="50"
                            :fill="isNodeSelected(node.id) ? '#7bbfea' : '#fcf16e'"
                            :stroke="isNodeSelected(node.id) ? getSelectedNodeColor(node.id) : '#fdb933'"
                            stroke-width="50" />
                      <!-- 库位状态图标:禁用=红叉,占用=绿色托盘,预占用=灰色托盘 -->
                      <g v-if="getStorageStatus(node) === 3" transform="translate(-450,-450)">
                        <line x1="100" y1="100" x2="800" y2="800" stroke="#dc3545" stroke-width="100" stroke-linecap="round"/>
                        <line x1="800" y1="100" x2="100" y2="800" stroke="#dc3545" stroke-width="100" stroke-linecap="round"/>
                      </g>
                      <g v-else-if="getStorageStatus(node) === 1 || getStorageStatus(node) === 2" transform="translate(-450,-450)">
                        <!-- 托盘俯视图:三横三纵木板结构 900x900 -->
                        <rect x="0" y="0" width="900" height="900" rx="30" :fill="getStorageStatus(node) === 1 ? '#8B4513' : '#9e9e9e'" opacity="0.3"/>
                        <!-- 横向木板 -->
                        <rect x="30" y="50" width="840" height="80" rx="10" :fill="getStorageStatus(node) === 1 ? '#A0522D' : '#757575'"/>
                        <rect x="30" y="410" width="840" height="80" rx="10" :fill="getStorageStatus(node) === 1 ? '#A0522D' : '#757575'"/>
                        <rect x="30" y="770" width="840" height="80" rx="10" :fill="getStorageStatus(node) === 1 ? '#A0522D' : '#757575'"/>
                        <!-- 纵向木板 -->
                        <rect x="50" y="30" width="80" height="840" rx="10" :fill="getStorageStatus(node) === 1 ? '#CD853F' : '#888'"/>
                        <rect x="410" y="30" width="80" height="840" rx="10" :fill="getStorageStatus(node) === 1 ? '#CD853F' : '#888'"/>
                        <rect x="770" y="30" width="80" height="840" rx="10" :fill="getStorageStatus(node) === 1 ? '#CD853F' : '#888'"/>
                      </g>
                      <text v-else x="0" y="0" text-anchor="middle" dominant-baseline="central" font-size="200"
                            :fill="isNodeSelected(node.id) ? getSelectedNodeColor(node.id) : '#d68910'">
                        {{ node.name || node.code }}
                      </text>
                    </g>
                    <!-- 非储位类型:圆形 -->
                    <g v-else>
                      <circle :r="NODE_RADIUS"
                              :fill="isNodeSelected(node.id) ? getSelectedNodeColor(node.id) : getNodeFill(node)"
                              :stroke="isNodeSelected(node.id) ? getSelectedNodeColor(node.id) : getNodeStroke(node)"
                              :stroke-width="isNodeSelected(node.id) ? 6 : 2" />
                      <text v-if="!isNodeSelected(node.id) && node.type === 3" x="0" y="0" text-anchor="middle" dominant-baseline="central" :font-size="NODE_RADIUS * 1.4" fill="#28a745">⚡</text>
                      <text v-if="!isNodeSelected(node.id) && node.type === 4" x="0" y="0" text-anchor="middle" dominant-baseline="central" :font-size="NODE_RADIUS * 1.4" fill="#ffffff">P</text>
                    </g>
                  </g>
                </g>

                <!-- 机器人图标 -->
                <g class="robots">
                  <template v-for="robot in robotList" :key="'robot-' + robot.robotId">
                    <!-- 重定位模式下隐藏正在重定位的机器人 -->
                    <g v-if="robot.x != null && robot.y != null && !(relocateMode && robot.robotId === relocateRobotId)"
                       :transform="`translate(${robot.x}, ${-robot.y!}) rotate(${-(robot.theta ?? 0)})`"
                       @mousedown.stop
                       @click="onRobotClick(robot, $event)"
                       style="cursor: pointer">
                      <!-- 选中高亮圆环 -->
                      <g v-if="selectedRobotId === robot.robotId" :transform="`rotate(${robot.theta ?? 0})`">
                        <circle r="1200" fill="var(--va-primary)" fill-opacity="0.15" stroke="var(--va-primary)" stroke-width="60" stroke-dasharray="150 75" />
                      </g>
                      <use v-if="robot.robotType === 2" href="#forklift-agv" x="-341" y="-853" width="2773" height="1707" />
                      <use v-else href="#latent-agv" x="-1067" y="-853" width="2133" height="1707" />
                      <text x="0" y="1067" text-anchor="middle" font-size="400" fill="#333">{{ robot.robotCode }}</text>
                    </g>
                  </template>
                </g>

                <!-- 重定位标记 -->
                <g v-if="relocateMode && relocatePosition" class="relocate-marker">
                  <g :transform="`translate(${relocatePosition.x}, ${-relocatePosition.y})`">
                    <!-- 定位圆环 -->
                    <circle r="400" fill="rgba(33, 150, 243, 0.2)" stroke="#2196f3" stroke-width="40" stroke-dasharray="80 40" />
                    <circle r="200" fill="rgba(33, 150, 243, 0.4)" stroke="#2196f3" stroke-width="20" />
                    <circle r="50" fill="#2196f3" />
                    <!-- 方向箭头 -->
                    <g :transform="`rotate(${-relocateAngle})`">
                      <line x1="0" y1="0" x2="600" y2="0" stroke="#f44336" stroke-width="40" stroke-linecap="round" />
                      <polygon points="600,-80 750,0 600,80" fill="#f44336" />
                    </g>
                    <!-- 坐标文字 -->
                    <text x="0" y="-500" text-anchor="middle" font-size="200" fill="#333" font-weight="bold">
                      {{ relocateRobotCode }}
                    </text>
                  </g>
                </g>

                <!-- 指引线(选中两个节点时显示) -->
                <g v-if="guideLine" class="guide-line">
                  <line
                    :x1="guideLine.x1"
                    :y1="guideLine.y1"
                    :x2="guideLine.x2"
                    :y2="guideLine.y2"
                    stroke="#ff6b35"
                    :stroke-width="4 / viewport.scale"
                    stroke-dasharray="20 10"
                    stroke-linecap="round"
                    marker-end="url(#arrow-guide)"
                  />
                </g>
              </g>
            </svg>
          </div>

          <!-- 未选择地图提示 -->
          <div v-else class="empty-state">
            <VaIcon name="map" size="64px" color="secondary" />
            <p>{{ t('dashboard.selectMapHint') || '请从上方下拉框选择要监控的地图' }}</p>
          </div>

          <!-- 重定位控制面板 -->
          <div v-if="relocateMode" class="relocate-panel">
            <div class="relocate-panel-header">
              <VaIcon name="gps_fixed" color="primary" />
              <span>{{ t('dashboard.relocate.title') }} - {{ relocateRobotCode }}</span>
            </div>
            
            <div class="relocate-panel-body">
              <!-- 位置信息 -->
              <div class="relocate-info">
                <div class="info-row">
                  <span class="info-label">X:</span>
                  <span class="info-value">{{ relocatePosition ? relocatePosition.x.toFixed(0) : '-' }}</span>
                </div>
                <div class="info-row">
                  <span class="info-label">Y:</span>
                  <span class="info-value">{{ relocatePosition ? relocatePosition.y.toFixed(0) : '-' }}</span>
                </div>
              </div>

              <!-- 角度选择器 -->
              <div class="angle-selector-wrapper">
                <div class="angle-label">{{ t('dashboard.relocate.direction') }}</div>
                <div class="angle-disk-container">
                  <svg viewBox="0 0 120 120" class="angle-disk">
                    <!-- 外圈 -->
                    <circle cx="60" cy="60" r="50" fill="none" stroke="#e0e0e0" stroke-width="2"/>
                    <!-- 刻度 -->
                    <g v-for="i in 8" :key="i">
                      <line
                        :x1="60 + 42 * Math.cos((i - 1) * 45 * Math.PI / 180)"
                        :y1="60 - 42 * Math.sin((i - 1) * 45 * Math.PI / 180)"
                        :x2="60 + 50 * Math.cos((i - 1) * 45 * Math.PI / 180)"
                        :y2="60 - 50 * Math.sin((i - 1) * 45 * Math.PI / 180)"
                        stroke="#999"
                        stroke-width="2"
                      />
                    </g>
                    <!-- 方向指针 -->
                    <g :transform="`rotate(${-relocateAngle}, 60, 60)`">
                      <line x1="60" y1="60" x2="100" y2="60" stroke="#f44336" stroke-width="3" stroke-linecap="round"/>
                      <polygon points="100,55 110,60 100,65" fill="#f44336" />
                    </g>
                    <!-- 中心点 -->
                    <circle cx="60" cy="60" r="6" fill="#2196f3"/>
                    <!-- 可点击区域 -->
                    <circle 
                      cx="60" cy="60" r="50" 
                      fill="transparent" 
                      class="angle-click-area"
                      @mousedown="onAngleDragStart"
                      @mousemove="onAngleDrag"
                      @mouseup="onAngleDragEnd"
                      @mouseleave="onAngleDragEnd"
                    />
                    <!-- 角度标签 -->
                    <text x="60" y="12" text-anchor="middle" font-size="9" fill="#666">90°</text>
                    <text x="108" y="63" text-anchor="middle" font-size="9" fill="#666">0°</text>
                    <text x="60" y="115" text-anchor="middle" font-size="9" fill="#666">-90°</text>
                    <text x="12" y="63" text-anchor="middle" font-size="9" fill="#666">180°</text>
                  </svg>
                </div>
                <div class="angle-value">{{ relocateAngle }}°</div>
                <!-- 快捷角度按钮 -->
                <div class="angle-shortcuts">
                  <VaButton v-for="angle in [0, 90, 180, 270]" :key="angle" size="small" preset="secondary" @click="relocateAngle = angle">
                    {{ angle }}°
                  </VaButton>
                </div>
              </div>
            </div>

            <div class="relocate-panel-footer">
              <VaButton color="secondary" @click="cancelRelocate">
                {{ t('common.cancel') }}
              </VaButton>
              <VaButton 
                color="primary" 
                :disabled="!relocatePosition"
                :loading="isRelocating"
                @click="confirmRelocate"
              >
                {{ t('dashboard.relocate.confirm') }}
              </VaButton>
            </div>
          </div>

          <!-- 选中机器人操作面板 -->
          <div v-if="selectedRobot && !relocateMode" class="selected-robot-panel" :style="selectedRobotStyle">
            <div class="selected-robot-header">
              <VaIcon name="smart_toy" color="white" />
              <span>{{ selectedRobot.robotName }}-{{ selectedRobot.robotCode }}</span>
              <VaButton 
                preset="plain" 
                color="white" 
                size="small"
                @click="selectedRobotId = null"
                class="close-btn"
            >
                <VaIcon name="close" size="small" />
              </VaButton>
            </div>
            <div class="selected-robot-actions">
              <VaButton 
                size="small" 
                preset="secondary"
                color="primary" 
                :loading="isRobotActionLoading" 
                :disabled="selectedRobot.online !== 1"
                @click="handleSelectedRobotReset" 
                :title="t('dashboard.robotCard.actions.reset')"
                class="action-btn"
              >
                <VaIcon name="restart_alt" size="small" class="mr-1" />
                {{ t('dashboard.robotCard.actions.reset') }}
              </VaButton>
              <VaButton 
                size="small" 
                preset="secondary"
                color="primary"
                :loading="isRobotPauseLoading" 
                :disabled="selectedRobot.online !== 1"
                @click="handleSelectedRobotPauseToggle" 
                :title="selectedRobot.paused ? t('dashboard.robotCard.actions.resume') : t('dashboard.robotCard.actions.pause')"
                class="action-btn"
              >
                <VaIcon :name="selectedRobot.paused ? 'play_arrow' : 'pause'" size="small" class="mr-1" />
                {{ selectedRobot.paused ? t('dashboard.robotCard.actions.resume') : t('dashboard.robotCard.actions.pause') }}
              </VaButton>
              <VaButton 
                size="small" 
                preset="secondary"
                color="primary"
                :loading="isRobotActionLoading" 
                :disabled="selectedRobot.online !== 1"
                @click="handleSelectedRobotCancelTask" 
                :title="t('dashboard.robotCard.actions.cancelTask')"
                class="action-btn"
              >
                <VaIcon name="cancel" size="small" class="mr-1" />
                {{ t('dashboard.robotCard.actions.cancelTask') }}
              </VaButton>
              <VaButton 
                size="small" 
                preset="secondary"
                color="primary"
                :disabled="selectedRobot.online !== 1"
                @click="handleSelectedRobotRelocate" 
                :title="t('dashboard.robotCard.actions.relocate')"
                class="action-btn"
              >
                <VaIcon name="gps_fixed" size="small" class="mr-1" />
                {{ t('dashboard.robotCard.actions.relocate') }}
              </VaButton>
            </div>
          </div>
        </div>
      </VaCardContent>
    </VaCard>
    </div>

    <!-- 右侧机器人状态面板 -->
    <div class="robot-panel">
      <VaCard class="robot-panel-card">
        <VaCardTitle class="robot-panel-title">
          <VaIcon name="smart_toy" size="small" />
          <span>{{ t('dashboard.robotStatus') }}</span>
          <VaBadge :text="String(robotList.length)" color="primary" />
        </VaCardTitle>
        <VaCardContent class="robot-panel-content">
          <div v-if="robotList.length === 0" class="no-robots">
            <VaIcon name="info" color="secondary" />
            <span>{{ t('dashboard.noRobotData') }}</span>
          </div>
          <div v-else class="robot-list">
            <RobotStatusCard 
              v-for="robot in robotList" 
              :key="robot.robotId" 
              :robot="robot" 
              :is-selected="selectedRobotId === robot.robotId"
              @relocate="enterRelocateMode"
              @click="onRobotCardClick"
            />
          </div>
        </VaCardContent>
      </VaCard>
    </div>
  </div>
</template>

<style scoped>
.device-monitor-wrapper {
  height: calc(100vh - 80px);
  padding: 0;
  display: flex;
  gap: 12px;
}

/* 平板设备全屏模式 - 隐藏顶部、底部和左侧菜单栏 */
.device-monitor-wrapper.tablet-fullscreen {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  height: 100vh;
  width: 100vw;
  z-index: 9999;
  background: var(--va-background-primary);
}

/* 平板模式下显示右侧设备列表卡片 */
.device-monitor-wrapper.tablet-fullscreen {
  display: flex;
  flex-direction: row;
  gap: 8px;
  padding: 8px;
}

.device-monitor-wrapper.tablet-fullscreen .robot-panel {
  width: 200px;
  display: block;
  flex-shrink: 0;
}

/* 平板模式下主内容区域自适应 */
.device-monitor-wrapper.tablet-fullscreen .monitor-main {
  flex: 1;
  min-width: 0;
  height: 100%;
}

.device-monitor-wrapper.tablet-fullscreen .device-monitor-card {
  border-radius: 8px;
  height: 100%;
}

.device-monitor-wrapper.tablet-fullscreen .robot-panel-card {
  border-radius: 8px;
}

.device-monitor-wrapper.tablet-fullscreen .device-monitor-content {
  padding: 8px;
}

/* 平板模式下调整工具栏大小 */
.device-monitor-wrapper.tablet-fullscreen .toolbar-container {
  padding: 4px 0;
  margin-bottom: 8px;
}

.device-monitor-wrapper.tablet-fullscreen .map-select {
  min-width: 150px;
}

.device-monitor-wrapper.tablet-fullscreen .node-input {
  width: 100px;
}

.device-monitor-wrapper.tablet-fullscreen .task-input-group {
  gap: 4px;
}

.device-monitor-wrapper.tablet-fullscreen .execute-btn {
  width: 36px;
  height: 36px;
  font-size: 18px;
}

/* 平板模式下的地图画布 */
.device-monitor-wrapper.tablet-fullscreen .map-canvas-wrapper {
  border-radius: 4px;
}

/* 平板模式指示器 */
.tablet-mode-indicator {
  position: fixed;
  bottom: 8px;
  left: 8px;
  z-index: 10000;
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 6px 12px;
  background: rgba(33, 150, 243, 0.9);
  color: white;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  pointer-events: none;
}

.monitor-main {
  flex: 1;
  min-width: 0;
}

.device-monitor-card {
  height: 100%;
}

.device-monitor-content {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 12px;
}

/* 右侧机器人面板 */
.robot-panel {
  width: 240px;
  flex-shrink: 0;
}

.robot-panel-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.robot-panel-title {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px;
  border-bottom: 1px solid var(--va-background-border);
  font-size: 14px;
  font-weight: 600;
}

.robot-panel-content {
  flex: 1;
  overflow-y: auto;
  padding: 8px !important;
}

.no-robots {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  gap: 8px;
  color: var(--va-text-secondary);
  font-size: 13px;
}

.robot-list {
  display: flex;
  flex-direction: column;
}

.toolbar-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid var(--va-background-border);
  margin-bottom: 12px;
}

.toolbar-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.toolbar-right {
  display: flex;
  align-items: center;
  gap: 16px;
}

.map-select {
  min-width: 250px;
}

.task-input-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.node-input {
  width: 150px;
}

.execute-btn {
  width: 48px;
  height: 48px;
  font-size: 24px;
}

.arrow-icon {
  font-size: 16px;
  color: var(--va-text-secondary);
}

.separator {
  font-size: 16px;
  color: var(--va-text-secondary);
  font-weight: bold;
}

.toolbar-group {
  display: flex;
}

.stats-text {
  font-size: 13px;
  color: var(--va-text-secondary);
}

.map-canvas-wrapper {
  flex: 1;
  position: relative;
  overflow: hidden;
  border-radius: 8px;
  background: #fafafa;
}

.topo-canvas {
  width: 100%;
  height: 100%;
  cursor: grab;
}

.topo-canvas:active {
  cursor: grabbing;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: var(--va-text-secondary);
  gap: 16px;
}

.empty-state p {
  font-size: 16px;
}

/* 重定位面板样式 */
.relocate-panel {
  position: absolute;
  bottom: 16px;
  left: 16px;
  background: var(--va-background-primary);
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  width: 240px;
  z-index: 100;
  overflow: hidden;
}

.relocate-panel-header {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 16px;
  background: linear-gradient(135deg, #2196f3, #1976d2);
  color: white;
  font-weight: 600;
  font-size: 14px;
}

.relocate-panel-body {
  padding: 16px;
}

.relocate-info {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
  padding: 12px;
  background: var(--va-background-secondary);
  border-radius: 8px;
}

.info-row {
  display: flex;
  align-items: center;
  gap: 4px;
}

.info-label {
  font-weight: 600;
  color: var(--va-text-secondary);
  font-size: 12px;
}

.info-value {
  font-family: 'Consolas', monospace;
  font-size: 14px;
  font-weight: 600;
  color: var(--va-primary);
}

.angle-selector-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.angle-label {
  font-size: 12px;
  color: var(--va-text-secondary);
  margin-bottom: 8px;
}

.angle-disk-container {
  width: 120px;
  height: 120px;
}

.angle-disk {
  width: 100%;
  height: 100%;
  cursor: crosshair;
}

.angle-click-area {
  cursor: crosshair;
}

.angle-click-area:hover {
  fill: rgba(33, 150, 243, 0.1);
}

.angle-value {
  font-size: 18px;
  font-weight: 700;
  color: #f44336;
  margin: 8px 0;
}

.angle-shortcuts {
  display: flex;
  gap: 4px;
  flex-wrap: wrap;
  justify-content: center;
}

.relocate-panel-footer {
  display: flex;
  gap: 8px;
  padding: 12px 16px;
  border-top: 1px solid var(--va-background-border);
  justify-content: flex-end;
}

/* 重定位模式下的画布样式 */
.topo-canvas.relocate-mode {
  cursor: crosshair !important;
}

/* 选中机器人操作面板样式 */
.selected-robot-panel {
  position: absolute;
  bottom: 16px;
  right: 16px;
  background: rgba(255, 255, 255, 0.75);
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  min-width: 160px;
  z-index: 100;
  overflow: hidden;
  border: 1px solid rgba(255, 255, 255, 0.3);
}

.selected-robot-header {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 16px;
  background: var(--va-primary);
  color: white;
  font-weight: 600;
  font-size: 14px;
}

.selected-robot-header span {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.selected-robot-header .close-btn {
  min-width: 24px !important;
  width: 24px !important;
  height: 24px !important;
  padding: 0 !important;
}

.selected-robot-actions {
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding: 12px;
}

.selected-robot-actions .action-btn {
  width: 100%;
}
</style>

<!-- 平板模式全局样式 - 非 scoped -->
<style>
/* 平板模式下隐藏左侧菜单栏 */
.tablet-mode .app-layout__sidebar,
.tablet-mode .sidebar,
.tablet-mode aside[class*="sidebar"],
.tablet-mode .va-sidebar {
  display: none !important;
}

/* 平板模式下隐藏顶部导航栏 */
.tablet-mode .app-layout__navbar,
.tablet-mode .navbar,
.tablet-mode header[class*="navbar"],
.tablet-mode nav[class*="navbar"],
.tablet-mode .va-navbar {
  display: none !important;
}

/* 平板模式下隐藏底部区域 */
.tablet-mode .app-layout__footer,
.tablet-mode footer,
.tablet-mode .footer {
  display: none !important;
}

/* 平板模式下调整主内容区域 */
.tablet-mode .app-layout__main,
.tablet-mode main,
.tablet-mode .main-content,
.tablet-mode .app-layout {
  margin-left: 0 !important;
  padding: 0 !important;
  width: 100vw !important;
  height: 100vh !important;
}

/* 隐藏面包屑导航 */
.tablet-mode .va-breadcrumbs,
.tablet-mode .breadcrumbs,
.tablet-mode nav[class*="breadcrumbs"] {
  display: none !important;
}
</style>