MapEditor.vue 139 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886
<template>
  <div class="map-editor-wrapper">
    <VaCard class="map-editor-card">
      <VaCardContent class="map-editor-content">
        <!-- 左侧配置面板 20% -->
        <div class="config-panel-wrapper">
          <div class="config-panel-inner">
            <!-- 顶部按钮组 -->
            <div class="panel-actions-top">
              <VaButton @click="saveMap" :disabled="isSaving" color="primary" size="small">{{ t('maps.editor.buttons.save') }}</VaButton>
              <VaButton @click="goBack" color="secondary" size="small">{{ t('maps.editor.buttons.back') }}</VaButton>
            </div>
            
            <h6 class="panel-title">{{ t('maps.editor.titles.elementConfig') }}</h6>
            
            <!-- 节点配置 -->
            <div v-if="selectedSingleNode" class="config-form">
              <VaInput :label="t('maps.editor.labels.code')" :model-value="selectedSingleNode.code" disabled readonly class="mb-3" />
              
              <VaSelect 
                :label="t('maps.editor.labels.type')" 
                v-model="selectedSingleNode.type" 
                :options="nodeTypeOptions"
                text-by="text"
                value-by="value"
                @update:model-value="syncToCurrentMap"
                class="mb-3"
              />
              
              <VaInput 
                :label="t('maps.editor.labels.coordinateX')" 
                v-model.number="selectedSingleNode.x" 
                type="number"
                @change="syncToCurrentMap"
                class="mb-3"
              />
              
              <VaInput 
                :label="t('maps.editor.labels.coordinateY')" 
                v-model.number="selectedSingleNode.y" 
                type="number"
                @change="syncToCurrentMap"
                class="mb-3"
              />
              
              <VaSelect 
                :label="t('maps.editor.labels.orientation')" 
                v-model.number="selectedSingleNode.orientation" 
                :options="orientationOptions"
                text-by="text"
                value-by="value"
                @update:model-value="syncToCurrentMap"
                class="mb-3"
              />
              
              <VaCheckbox 
                v-model="selectedSingleNode.allowRotate" 
                :label="t('maps.editor.labels.allowRotate')"
                @update:model-value="syncToCurrentMap"
                class="mb-2"
              />
              
              <VaCheckbox 
                v-model="selectedSingleNode.allowReverseEntry" 
                :label="t('maps.editor.labels.allowReverseEntry')"
                @update:model-value="syncToCurrentMap"
                class="mb-3"
              />
              
              <VaInput 
                :label="t('maps.editor.labels.maxCoordinateOffset')" 
                v-model.number="selectedSingleNode.maxCoordinateOffset" 
                type="number"
                :step="0.01"
                @change="syncToCurrentMap"
                class="mb-3"
              />
              
              <VaInput 
                :label="t('maps.editor.labels.maxAngleDeviation')" 
                v-model.number="selectedSingleNode.maxAngleDeviation" 
                type="number"
                :step="0.1"
                @change="syncToCurrentMap"
                class="mb-3"
              />
              
              <VaInput 
                :label="t('maps.editor.labels.maxSpeed')" 
                v-model.number="selectedSingleNode.maxSpeed" 
                type="number"
                :step="0.1"
                @change="syncToCurrentMap"
                class="mb-3"
              />
            </div>

            <!-- 连线配置 -->
            <div v-else-if="selectedSingleEdge" class="config-form">
              <VaInput :label="t('maps.editor.labels.code')" :model-value="selectedSingleEdge.code" disabled readonly class="mb-3" />
              
              <VaInput :label="t('maps.editor.labels.startNodeCode')" :model-value="selectedSingleEdge.sourceCode" disabled readonly class="mb-3" />
              
              <VaInput :label="t('maps.editor.labels.endNodeCode')" :model-value="selectedSingleEdge.targetCode" disabled readonly class="mb-3" />
              
              <VaCheckbox 
                v-model="selectedSingleEdge.isReverse" 
                :label="t('maps.editor.labels.isReverse')"
                @update:model-value="syncToCurrentMap"
                class="mb-2"
              />
              
              <VaCheckbox 
                :model-value="!!selectedSingleEdge.isArc" 
                :label="t('maps.editor.labels.isArc')"
                disabled
                class="mb-2"
              />
              
              <VaInput 
                :label="t('maps.editor.labels.centerX')" 
                :model-value="typeof selectedSingleEdge.centerX === 'number' ? selectedSingleEdge.centerX.toFixed(3) : ''" 
                disabled 
                readonly
                class="mb-3"
              />
              
              <VaInput 
                :label="t('maps.editor.labels.centerY')" 
                :model-value="typeof selectedSingleEdge.centerY === 'number' ? selectedSingleEdge.centerY.toFixed(3) : ''" 
                disabled 
                readonly
              />
            </div>

            <!-- 弧线配置 -->
            <div v-else-if="selectedSingleArc" class="config-form">
              <VaInput :label="t('maps.editor.labels.code')" :model-value="selectedSingleArc.code" disabled readonly class="mb-3" />
              
              <VaInput :label="t('maps.editor.labels.startNodeCode')" :model-value="getArcStartNodeId(selectedSingleArc)" disabled readonly class="mb-3" />
              
              <VaInput :label="t('maps.editor.labels.endNodeCode')" :model-value="getArcEndNodeId(selectedSingleArc)" disabled readonly class="mb-3" />
              
              <VaCheckbox 
                v-model="selectedSingleArc.isReverse" 
                :label="t('maps.editor.labels.isReverse')"
                @update:model-value="syncToCurrentMap"
                class="mb-2"
              />
              
              <VaCheckbox 
                :model-value="true" 
                :label="t('maps.editor.labels.isArc')"
                disabled
                class="mb-2"
              />
              
              <VaInput 
                :label="t('maps.editor.labels.centerX')" 
                :model-value="typeof selectedSingleArc.centerX === 'number' ? selectedSingleArc.centerX.toFixed(3) : ''" 
                disabled 
                readonly
                class="mb-3"
              />
              
              <VaInput 
                :label="t('maps.editor.labels.centerY')" 
                :model-value="typeof selectedSingleArc.centerY === 'number' ? selectedSingleArc.centerY.toFixed(3) : ''" 
                disabled 
                readonly
              />
            </div>

            <!-- 未选中提示 -->
            <div v-else class="text-secondary">{{ t('maps.editor.messages.selectNodeOrEdge') }}</div>
          </div>
        </div>

        <!-- 右侧地图预览 80% -->
        <div class="preview-panel-wrapper">
          <div class="map-preview">
            <!-- 工具栏 -->
            <div class="toolbar-container">
              <VaButtonGroup v-if="currentMap.type === 1"  class="toolbar-group">
                <VaButton 
                  :color="mode === 'select' ? 'primary' : 'secondary'"
                  @click="setMode('select')"
                  icon="touch_app"
                  size="small"
                  :title="t('maps.editor.buttons.select')"
                />
                <VaButton 
                  :color="mode === 'pan' ? 'primary' : 'secondary'"
                  @click="setMode('pan')"
                  icon="pan_tool"
                  size="small"
                  :title="t('maps.editor.buttons.pan')"
                />
                <VaButton 
                  :color="mode === 'addNode' ? 'primary' : 'secondary'"
                  @click="setMode('addNode')"
                  icon="add_circle"
                  size="small"
                  :title="t('maps.editor.buttons.addNode')"
                />
                <VaButton 
                  :color="mode === 'connect' ? 'primary' : 'secondary'"
                  @click="setMode('connect')"
                  icon="link"
                  size="small"
                  :title="t('maps.editor.buttons.connect')"
                />
                <VaButton 
                  :color="mode === 'arc' ? 'primary' : 'secondary'"
                  @click="setMode('arc')"
                  icon="architecture"
                  size="small"
                  :title="t('maps.editor.buttons.arc')"
                />
                <VaButton 
                  color="secondary"
                  @click="openBatchArcPanel"
                  :disabled="selectedStraightEdgeCount < 2"
                  icon="compass_calibration"
                  size="small"
                  :title="t('maps.editor.buttons.batchArc')"
                />
                <VaButton 
                  color="secondary"
                  @click="generateFourVariantsForSelectedEdges"
                  :disabled="(selectedEdgeId == null && selectedEdgeIds.size === 0) && (selectedArcId == null && selectedArcIds.size === 0)"
                  icon="shuffle"
                  size="small"
                  :title="t('maps.editor.buttons.fourWayEdge')"
                />
                <VaButton 
                  color="secondary"
                  @click="generateEdgesForSelectedNodesX"
                  :disabled="!(selectedNodeIds.size >= 2)"
                  icon="swap_horiz"
                  size="small"
                  :title="t('maps.editor.buttons.xDirectionEdge')"
                />
                <VaButton 
                  color="secondary"
                  @click="generateEdgesForSelectedNodesY"
                  :disabled="!(selectedNodeIds.size >= 2)"
                  icon="swap_vert"
                  size="small"
                  :title="t('maps.editor.buttons.yDirectionEdge')"
                />
                <VaButton 
                  color="secondary"
                  @click="openBatchEditPanel"
                  :disabled="selectedNodeIds.size < 2"
                  icon="edit"
                  size="small"
                  :title="t('maps.editor.buttons.batchEdit')"
                />
                <VaButton 
                  color="secondary"
                  @click="openCopyPanel"
                  :disabled="(selectedNodeIds.size === 0 && selectedNodeId == null)"
                  icon="content_copy"
                  size="small"
                  :title="t('maps.editor.buttons.copy')"
                />
                <VaButton 
                  color="secondary"
                  @click="openMovePanel"
                  :disabled="(selectedNodeIds.size === 0 && selectedNodeId == null)"
                  icon="open_with"
                  size="small"
                  :title="t('maps.editor.buttons.move')"
                />
              </VaButtonGroup>

              <VaButtonGroup  class="toolbar-group">
                <VaButton 
                  color="secondary"
                  @click="() => bgFileInputRef && bgFileInputRef.click()"
                  icon="add_photo_alternate"
                  size="small"
                  :title="t('maps.editor.buttons.importBgImage')"
                />
                <VaButton 
                  color="secondary"
                  @click="openBgSettingsModal"
                  icon="settings"
                  size="small"
                  :title="t('maps.editor.buttons.bgSettings')"
                />
                <VaButton 
                  color="secondary"
                  @click="clearBgImage"
                  :disabled="!bgImageUrl"
                  icon="delete"
                  size="small"
                  :title="t('maps.editor.buttons.clearBgImage')"
                />
                <input ref="bgFileInputRef" type="file" accept="image/*,.pgm" @change="onBgFileChange" style="display:none" />
              </VaButtonGroup>

              <VaButtonGroup class="toolbar-group">
                <VaButton 
                  color="secondary"
                  @click="undo"
                  :disabled="!canUndo"
                  icon="undo"
                  size="small"
                  :title="t('maps.editor.buttons.undo')"
                />
                <VaButton 
                  color="secondary"
                  @click="zoomIn"
                  icon="zoom_in"
                  size="small"
                  :title="t('maps.editor.buttons.zoomIn')"
                />
                <VaButton 
                  color="secondary"
                  @click="zoomOut"
                  icon="zoom_out"
                  size="small"
                  :title="t('maps.editor.buttons.zoomOut')"
                />
                <VaButton 
                  color="secondary"
                  @click="resetView"
                  icon="history"
                  size="small"
                  :title="t('maps.editor.buttons.resetView')"
                />
              </VaButtonGroup>

              <div class="stats-text">{{ t('maps.editor.stats.statsFormat', { nodes: nodes.length, edges: edges.length }) }}</div>
            </div>

                <div :class="['topo-canvas', canvasCursorClass, 'flex-grow-1']"
                     @mousedown="onCanvasMouseDown"
                     @mousemove="onCanvasMouseMove"
                     @mouseup="onCanvasMouseUp"
                     @mouseleave="onCanvasMouseUp"
                     @wheel.prevent="onCanvasWheel">
                  <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-blue" 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="#0d6efd" />
                      </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-orange" 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="#f59f00" />
                      </marker>
                    </defs>
                    

                    <!-- World space content (Cartesian: X right, Y up) -->
                    <g :transform="`translate(${viewport.x}, ${viewport.y}) scale(${viewport.scale})`">
                      <!-- background image (world space) -->
                      <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>
                      <!-- grid -->
                      <g class="grid">
                        <g>
                          <line v-for="gx in gridXLines" :key="`gx-${gx.x}`"
                                :x1="gx.x" :y1="-worldBounds.yMin" :x2="gx.x" :y2="-worldBounds.yMax"
                                :stroke="gx.major ? '#e9ecef' : '#f1f3f5'" :stroke-width="(gx.major ? 0.1 : 0.05) / viewport.scale" />
                        </g>
                        <g>
                          <line v-for="gy in gridYLines" :key="`gy-${gy.y}`"
                                :x1="worldBounds.xMin" :y1="-gy.y" :x2="worldBounds.xMax" :y2="-gy.y"
                                :stroke="gy.major ? '#e9ecef' : '#f1f3f5'" :stroke-width="(gy.major ? 0.1 : 0.05) / viewport.scale" />
                        </g>
                        <!-- axes -->
                        <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>
                      <!-- edges -->
                      <g class="edges">
                        <g v-for="edge in edges.filter(e => !e.curve)" :key="edge.id">
                          <path
                            :d="getEdgePath(edge)"
                            fill="none"
                            :stroke="getEdgeStroke(edge)"
                            :stroke-width="(mode === 'arc' && arcMode.step === 1 && (arcMode.firstEdgeId === edge.id || arcHoverEdgeId === edge.id)) ? 8 : (isEdgeSelected(edge.id) ? 8 : 6)"
                            :stroke-dasharray="(mode === 'arc' && arcMode.step === 1 && (arcMode.firstEdgeId === edge.id || arcHoverEdgeId === edge.id)) ? '8 6' : null"
                            :marker-mid="getEdgeMarker(edge)"
                          />
                          <path
                            :d="getEdgePath(edge)"
                            fill="none"
                            stroke="transparent"
                            :stroke-width="16"
                            pointer-events="stroke"
                            @click.stop="onEdgeClick(edge, $event)"
                          />
                        </g>
                      </g>
                      <!-- arcs -->
                      <g class="arcs">
                        <g v-for="arc in edges.filter(e => e.curve)" :key="arc.id">
                          <path
                            :d="getArcPath(arc)"
                            fill="none"
                            :stroke="getArcStroke(arc)"
                            :stroke-width="isArcSelected(arc.id) ? 8 : 6"
                            :marker-mid="getArcMarker(arc)"
                          />
                          <!-- clickable overlay to improve hit area -->
                          <path
                            :d="getArcPath(arc)"
                            fill="none"
                            stroke="transparent"
                            :stroke-width="16"
                            pointer-events="stroke"
                            @click.stop="onArcClick($event)"
                          />
                        </g>
                      </g>
                      <!-- nodes -->
                      <g class="nodes">
                        <g v-for="node in nodes" :key="node.id"
                           class="node"
                           :transform="`translate(${node.x}, ${-node.y})`"
                           @mousedown.stop="onNodeMouseDown($event, node)"
                           @click.stop="onNodeClick($event, node)">
                          <!-- 储位类型:1000x1000橙黄色方框 -->
                          <g v-if="node.type === 2" pointer-events="none">
                            <rect
                              x="-500" y="-500"
                              width="1000" height="1000"
                              rx="50" ry="50"
                              :fill="isNodeSelected(node.id) ? '#7bbfea' : '#fcf16e'"
                              :stroke="isNodeSelected(node.id) ? '#0d6efd' : '#fdb933'"
                              stroke-width="50"
                              pointer-events="auto"
                            />
                            <!-- 库位状态图标:禁用=红叉,占用=绿色托盘,预占用=灰色托盘 -->
                            <text v-if="getStorageStatus(node) === 3"
                                  x="0" y="0"
                                  text-anchor="middle"
                                  dominant-baseline="central"
                                  font-size="600"
                                  fill="#dc3545"
                                  pointer-events="none">✕</text>
                            <text v-else-if="getStorageStatus(node) === 1"
                                  x="0" y="0"
                                  text-anchor="middle"
                                  dominant-baseline="central"
                                  font-size="500"
                                  fill="#28a745"
                                  pointer-events="none">▣</text>
                            <text v-else-if="getStorageStatus(node) === 2"
                                  x="0" y="0"
                                  text-anchor="middle"
                                  dominant-baseline="central"
                                  font-size="500"
                                  fill="#6c757d"
                                  pointer-events="none">▣</text>
                            <text v-else
                              x="0" y="0"
                              text-anchor="middle"
                              alignment-baseline="central"
                              dominant-baseline="central"
                              font-size="200"
                              :fill="isNodeSelected(node.id) ? '#0d6efd' : '#d68910'"
                              pointer-events="none">{{ node.name || node.code }}</text>
                          </g>
                          <!-- 非储位类型:圆形 -->
                          <circle v-else :r="NODE_RADIUS"
                                  :fill="isNodeSelected(node.id) ? '#0d6efd' : getNodeFill(node)"
                                  :stroke="isNodeSelected(node.id) ? '#0d6efd' : getNodeStroke(node)"
                                  :stroke-width="getNodeStrokeWidth(node)" />
                          <text v-if="!isNodeSelected(node.id) && node.type === 3"
                                x="0" y="0"
                                text-anchor="middle"
                                alignment-baseline="central"
                                dominant-baseline="central"
                                :font-size="NODE_RADIUS * 1.4"
                                fill="#28a745"
                                pointer-events="none">⚡</text>
                          <text v-if="!isNodeSelected(node.id) && node.type === 4"
                                x="0" y="0"
                                text-anchor="middle"
                                alignment-baseline="central"
                                dominant-baseline="central"
                                :font-size="NODE_RADIUS * 1.4"
                                fill="#ffffff"
                                pointer-events="none">P</text>
                          <text v-if="!isNodeSelected(node.id) && node.type === 1"
                                x="0" y="0"
                                text-anchor="middle"
                                alignment-baseline="central"
                                dominant-baseline="central"
                                :font-size="NODE_RADIUS * 1.2"
                                fill="#ff6b6b"
                                pointer-events="none"></text>
                        </g>
                      </g>
                  <!-- snap guides -->
                  <g v-if="snapGuideX != null || snapGuideY != null" class="snap-guides">
                    <line v-if="snapGuideX != null"
                          :x1="snapGuideX"
                          :y1="-worldBounds.yMin"
                          :x2="snapGuideX"
                          :y2="-worldBounds.yMax"
                          class="snap-guide-line" />
                    <line v-if="snapGuideY != null"
                          :x1="worldBounds.xMin"
                          :y1="-snapGuideY"
                          :x2="worldBounds.xMax"
                          :y2="-snapGuideY"
                          class="snap-guide-line" />
                  </g>
                    </g>
                    <!-- marquee selection (screen space) -->
                    <!-- Rulers (screen space, rendered on top) -->
                    <g class="ruler-top" style="pointer-events: none;">
                      <rect x="0" y="0" :width="canvasSize.width" height="16" fill="#f8f9fa" />
                      <g>
                        <g v-for="t in topRulerTicks" :key="`rtx-${t.x}`">
                          <line :x1="t.x" y1="0" :x2="t.x" :y2="t.major ? 12 : 8" stroke="#adb5bd" stroke-width="1" />
                          <text v-if="t.major" :x="t.x + 2" y="14" font-size="10" fill="#868e96">{{ t.label }}</text>
                        </g>
                      </g>
                    </g>
                    <g class="ruler-left" style="pointer-events: none;">
                      <rect x="0" y="0" width="32" :height="canvasSize.height" fill="#f8f9fa" />
                      <g>
                        <g v-for="t in leftRulerTicks" :key="`rty-${t.y}`">
                          <line x1="0" :y1="t.y" :x2="t.major ? 20 : 12" :y2="t.y" stroke="#adb5bd" stroke-width="1" />
                          <text v-if="t.major" x="22" :y="t.y - 2" font-size="10" fill="#868e96">{{ t.label }}</text>
                        </g>
                      </g>
                    </g>
                    
                    
                    <g v-if="isMarqueeSelecting">
                      <rect :x="marqueeRect.x"
                            :y="marqueeRect.y"
                            :width="marqueeRect.width"
                            :height="marqueeRect.height"
                            class="marquee-rect" />
                    </g>
                  </svg>
                  <!-- 鼠标提示:选择第一条边(屏幕坐标系) -->
                  <div
                    v-if="mode === 'arc' && arcMode.step === 0"
                    class="mouse-hint"
                    :style="{ left: mousePos.x + 12 + 'px', top: mousePos.y + 12 + 'px' }"
                  >
                    {{ t('maps.editor.messages.selectFirstEdge') }}
                  </div>
                  <div
                    v-if="pickCycleInfo && pickCycleInfo.visible"
                    class="mouse-hint"
                    :style="{ left: mousePos.x + 12 + 'px', top: mousePos.y + 12 + 'px' }"
                  >
                    {{ t('maps.editor.messages.candidate') }} {{ pickCycleInfo.index + 1 }}/{{ pickCycleInfo.total }}
                  </div>
              <!-- 圆弧半径面板 -->
              <VaCard v-if="showArcRadiusPanel" class="floating-panel floating-panel-enhanced" @mousedown.stop @click.stop>
                <VaCardTitle class="panel-title-enhanced">
                  <VaIcon name="architecture" class="panel-icon" />
                  {{ t('maps.editor.titles.setArcRadius') }}
                </VaCardTitle>
                <VaCardContent class="panel-content-enhanced">
                  <VaChip color="info" size="small" class="mb-3">
                    {{ t('maps.editor.messages.maxRadius', { radius: arcMaxRadius.toFixed(3) }) }}
                  </VaChip>
                  <VaInput 
                    v-model.number="arcRadiusInput" 
                    :label="t('maps.editor.labels.arcRadius')"
                    type="number"
                    :min="0.0001"
                    :step="0.001"
                    class="mb-4"
                  >
                    <template #prepend>
                      <VaIcon name="straighten" size="small" />
                    </template>
                  </VaInput>
                  <div class="d-flex justify-content-end gap-2">
                    <VaButton @click="cancelArcRadiusPanel" preset="secondary" size="small" icon="close">{{ t('maps.editor.buttons.cancel') }}</VaButton>
                    <VaButton @click="confirmArcRadius" size="small" icon="check">{{ t('maps.editor.buttons.confirm') }}</VaButton>
                  </div>
                </VaCardContent>
              </VaCard>

              <!-- 批量圆弧面板 -->
              <VaCard v-if="batchArcPanelVisible" class="floating-panel floating-panel-enhanced" @mousedown.stop @click.stop>
                <VaCardTitle class="panel-title-enhanced">
                  <VaIcon name="compass_calibration" class="panel-icon" />
                  {{ t('maps.editor.titles.batchGenerateArc') }}
                </VaCardTitle>
                <VaCardContent class="panel-content-enhanced">
                  <VaChip color="success" size="small" class="mb-3">
                    <VaIcon name="done_all" size="small" />
                    {{ t('maps.editor.messages.selectedLines', { count: selectedStraightEdgeCount }) }}
                  </VaChip>
                  <VaInput 
                    v-model.number="batchArcRadiusInput" 
                    :label="t('maps.editor.labels.arcRadius')"
                    type="number"
                    :min="0.0001"
                    :step="0.001"
                    class="mb-4"
                  >
                    <template #prepend>
                      <VaIcon name="straighten" size="small" />
                    </template>
                  </VaInput>
                  <div class="d-flex justify-content-end gap-2">
                    <VaButton @click="cancelBatchArcPanel" preset="secondary" size="small" icon="close">{{ t('maps.editor.buttons.cancel') }}</VaButton>
                    <VaButton @click="confirmBatchArcRadius" size="small" icon="auto_awesome">{{ t('maps.editor.buttons.generate') }}</VaButton>
                  </div>
                </VaCardContent>
              </VaCard>

              <!-- 批量编辑面板 -->
              <VaCard v-if="batchEditPanelVisible" class="floating-panel floating-panel-enhanced" @mousedown.stop @click.stop>
                <VaCardTitle class="panel-title-enhanced">
                  <VaIcon name="edit" class="panel-icon" />
                  {{ t('maps.editor.titles.batchEditNodes') }}
                </VaCardTitle>
                <VaCardContent class="panel-content-enhanced">
                  <VaChip color="primary" size="small" class="mb-3">
                    <VaIcon name="check_circle" size="small" />
                    {{ t('maps.editor.messages.selectedNodes', { count: selectedNodeIds.size }) }}
                  </VaChip>
                  <VaSelect 
                    v-model="batchNodeTypeChoice" 
                    :label="t('maps.editor.labels.nodeType')"
                    :options="batchNodeTypeOptions"
                    text-by="text"
                    value-by="value"
                    class="mb-3"
                  >
                    <template #prepend>
                      <VaIcon name="category" size="small" />
                    </template>
                  </VaSelect>
                  <VaSelect 
                    v-model="batchNodeOrientationChoice" 
                    :label="t('maps.editor.labels.nodeOrientation')"
                    :options="batchNodeOrientationOptions"
                    text-by="text"
                    value-by="value"
                    class="mb-3"
                  >
                    <template #prepend>
                      <VaIcon name="explore" size="small" />
                    </template>
                  </VaSelect>
                  <VaSelect 
                    v-model="batchNodeAllowRotateChoice" 
                    :label="t('maps.editor.labels.allowRotateLabel')"
                    :options="batchRotateOptions"
                    text-by="text"
                    value-by="value"
                    class="mb-3"
                  >
                    <template #prepend>
                      <VaIcon name="360" size="small" />
                    </template>
                  </VaSelect>
                  <VaSelect 
                    v-model="batchNodeAllowReverseEntryChoice" 
                    :label="t('maps.editor.labels.reverseEntryLabel')"
                    :options="batchBooleanOptions"
                    text-by="text"
                    value-by="value"
                    class="mb-4"
                  >
                    <template #prepend>
                      <VaIcon name="u_turn_left" size="small" />
                    </template>
                  </VaSelect>
                  <div class="d-flex justify-content-end gap-2">
                    <VaButton @click="cancelBatchEditPanel" preset="secondary" size="small" icon="close">{{ t('maps.editor.buttons.cancel') }}</VaButton>
                    <VaButton @click="confirmBatchEdit" size="small" icon="check">{{ t('maps.editor.buttons.apply') }}</VaButton>
                  </div>
                </VaCardContent>
              </VaCard>

              <!-- 复制面板 -->
              <VaCard v-if="copyPanelVisible" class="floating-panel floating-panel-enhanced" @mousedown.stop @click.stop>
                <VaCardTitle class="panel-title-enhanced">
                  <VaIcon name="content_copy" class="panel-icon" />
                  {{ t('maps.editor.titles.copyAndMove') }}
                </VaCardTitle>
                <VaCardContent class="panel-content-enhanced">
                  <VaChip color="warning" size="small" class="mb-3">
                    <VaIcon name="check_circle" size="small" />
                    {{ t('maps.editor.messages.selectedNodes', { count: selectedNodeIds.size }) }}
                  </VaChip>
                  <VaInput 
                    v-model.number="copyOffsetX" 
                    :label="t('maps.editor.labels.xOffset')"
                    type="number"
                    :step="1"
                    class="mb-3"
                  >
                    <template #prepend>
                      <VaIcon name="swap_horiz" size="small" />
                    </template>
                  </VaInput>
                  <VaInput 
                    v-model.number="copyOffsetY" 
                    :label="t('maps.editor.labels.yOffset')"
                    type="number"
                    :step="1"
                    class="mb-4"
                  >
                    <template #prepend>
                      <VaIcon name="swap_vert" size="small" />
                    </template>
                  </VaInput>
                  <div class="d-flex justify-content-end gap-2">
                    <VaButton @click="cancelCopyPanel" preset="secondary" size="small" icon="close">{{ t('maps.editor.buttons.cancel') }}</VaButton>
                    <VaButton 
                      @click="confirmCopy" 
                      size="small"
                      icon="content_copy"
                      :disabled="(Number(copyOffsetX) || 0) === 0 && (Number(copyOffsetY) || 0) === 0"
                    >
                      {{ t('maps.editor.buttons.copy') }}
                    </VaButton>
                  </div>
                </VaCardContent>
              </VaCard>

              <!-- 平移面板 -->
              <VaCard v-if="movePanelVisible" class="floating-panel floating-panel-enhanced" @mousedown.stop @click.stop>
                <VaCardTitle class="panel-title-enhanced">
                  <VaIcon name="open_with" class="panel-icon" />
                  {{ t('maps.editor.titles.moveSelectedElements') }}
                </VaCardTitle>
                <VaCardContent class="panel-content-enhanced">
                  <VaChip color="primary" size="small" class="mb-3">
                    <VaIcon name="check_circle" size="small" />
                    {{ t('maps.editor.messages.selectedNodes', { count: selectedNodeIds.size }) }}
                  </VaChip>
                  <VaInput 
                    v-model.number="moveOffsetX" 
                    :label="t('maps.editor.labels.xOffset')"
                    type="number"
                    :step="1"
                    class="mb-3"
                  >
                    <template #prepend>
                      <VaIcon name="swap_horiz" size="small" />
                    </template>
                  </VaInput>
                  <VaInput 
                    v-model.number="moveOffsetY" 
                    :label="t('maps.editor.labels.yOffset')"
                    type="number"
                    :step="1"
                    class="mb-4"
                  >
                    <template #prepend>
                      <VaIcon name="swap_vert" size="small" />
                    </template>
                  </VaInput>
                  <div class="d-flex justify-content-end gap-2">
                    <VaButton @click="cancelMovePanel" preset="secondary" size="small" icon="close">{{ t('maps.editor.buttons.cancel') }}</VaButton>
                    <VaButton 
                      @click="confirmMove" 
                      size="small"
                      icon="open_with"
                      :disabled="(Number(moveOffsetX) || 0) === 0 && (Number(moveOffsetY) || 0) === 0"
                    >
                      {{ t('maps.editor.buttons.move') }}
                    </VaButton>
                  </div>
                </VaCardContent>
              </VaCard>
            </div>
          </div>
        </div>
      </VaCardContent>
    </VaCard>

    <!-- 背景图设置弹窗 -->
    <VaModal
      v-model="bgSettingsModalVisible"
      :title="t('maps.editor.titles.bgSettings')"
      size="small"
      :close-button="true"
      :ok-text="t('maps.editor.buttons.confirm')"
      :cancel-text="t('maps.editor.buttons.cancel')"
      @ok="saveBgSettings"
    >
      <div class="bg-settings-content">
        <VaInput
          v-model.number="bgScale"
          :label="t('maps.editor.labels.scale')"
          type="number"
          :min="0.01"
          :step="0.1"
          class="mb-3"
        />
        <VaInput
          v-model.number="bgOpacity"
          :label="t('maps.editor.labels.opacity')"
          type="number"
          :min="0"
          :max="1"
          :step="0.05"
          class="mb-3"
        />
        <VaInput
          v-model.number="bgRotation"
          :label="t('maps.editor.labels.rotation')"
          type="number"
          :min="-180"
          :max="180"
          :step="1"
          class="mb-3"
        />
        <VaInput
          v-model.number="bgOffsetX"
          :label="t('maps.editor.labels.offsetX')"
          type="number"
          :step="0.01"
          class="mb-3"
        />
        <VaInput
          v-model.number="bgOffsetY"
          :label="t('maps.editor.labels.offsetY')"
          type="number"
          :step="0.01"
          class="mb-3"
        />
        <div class="text-secondary small mb-3">
          {{ t('maps.editor.messages.rotationHint') }}
        </div>
      </div>
    </VaModal>

    <!-- 确认返回弹窗 -->
    <VaModal
      v-model="confirmBackModalVisible"
      :title="t('maps.editor.titles.confirmBack')"
      size="small"
      :close-button="true"
      :ok-text="t('maps.editor.buttons.confirm')"
      :cancel-text="t('maps.editor.buttons.cancel')"
      @ok="confirmBack"
    >
      <div class="text-secondary mb-3">
        {{ t('maps.editor.messages.unsavedChanges') }}
      </div>
    </VaModal>

    <!-- 保存中加载弹窗 -->
    <VaModal
      v-model="isSaving"
      :title="t('maps.editor.titles.saving')"
      size="small"
      :close-button="false"
      :hide-default-actions="true"
      no-outside-dismiss
    >
      <div class="loading-content">
        <VaProgressCircle indeterminate />
        <div class="loading-text">{{ t('maps.editor.messages.savingData') }}</div>
      </div>
    </VaModal>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed, watch, getCurrentInstance, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import mapsApi from '../../services/maps'
import { useToast } from 'vuestic-ui'
import { useOptions } from '../../composables/useOptions'

const route = useRoute()
const router = useRouter()
const { t } = useI18n()
const { loadOptions, getMapNodeTypeOptions } = useOptions()

const nodeTypeOptions = computed(() => getMapNodeTypeOptions())

const orientationOptions = computed(() => [
  { text: t('maps.editor.orientations.none'), value: null },
  { text: t('maps.editor.orientations.deg0'), value: 0 },
  { text: t('maps.editor.orientations.deg90'), value: 90 },
  { text: t('maps.editor.orientations.deg180'), value: 180 },
  { text: t('maps.editor.orientations.deg270'), value: 270 },
])

const batchNodeTypeOptions = computed(() => [
  { text: t('maps.editor.booleanOptions.noChange') + t('maps.editor.labels.type'), value: 'NO_CHANGE' },
  ...nodeTypeOptions.value
])

const batchNodeOrientationOptions = computed(() => [
  { text: t('maps.editor.booleanOptions.noChange') + t('maps.editor.labels.orientation'), value: 'NO_CHANGE' },
  { text: t('maps.editor.orientations.none'), value: 'NULL' },
  { text: t('maps.editor.orientations.deg0'), value: '0' },
  { text: t('maps.editor.orientations.deg90'), value: '90' },
  { text: t('maps.editor.orientations.deg180'), value: '180' },
  { text: t('maps.editor.orientations.deg270'), value: '270' },
])

const batchBooleanOptions = computed(() => [
  { text: t('maps.editor.booleanOptions.noChange'), value: 'NO_CHANGE' },
  { text: t('maps.editor.booleanOptions.yes'), value: 'TRUE' },
  { text: t('maps.editor.booleanOptions.no'), value: 'FALSE' },
])

const batchRotateOptions = computed(() => [
  { text: t('maps.editor.booleanOptions.noChange'), value: 'NO_CHANGE' },
  { text: t('maps.editor.booleanOptions.allow'), value: 'TRUE' },
  { text: t('maps.editor.booleanOptions.notAllow'), value: 'FALSE' },
])

// 响应式数据
const isEditMode = ref(false)
const currentMap = ref({
  id: null,
  name: '',
  code: '',
  type: 1,
  description: '',
  // 拓扑数据
  nodes: [],
  edges: []
})

// ======== 表单验证(名称/编码/类型) ========
const editorErrors = ref({ name: '', code: '', type: '' })
const editorTouched = ref({ name: false, code: false, type: false })
const NAME_MAX = 50
const CODE_PATTERN = /^[A-Z]{2}$/

const validateEditorField = (field) => {
  const v = currentMap.value
  switch (field) {
    case 'name':
      editorErrors.value.name = !v.name
        ? t('maps.editor.validation.nameRequired')
        : v.name.length > NAME_MAX
        ? t('maps.editor.validation.nameTooLong', { max: NAME_MAX })
        : ''
      break
    case 'code':
      editorErrors.value.code = !v.code
        ? t('maps.editor.validation.codeRequired')
        : !CODE_PATTERN.test(v.code)
        ? t('maps.editor.validation.codeInvalid')
        : ''
      break
    case 'type':
      editorErrors.value.type = !v.type ? t('maps.editor.validation.typeRequired') : ''
      break
    default:
      break
  }
}
const { proxy } = getCurrentInstance()
const validateEditorAll = () => {
  ;['name', 'code', 'type'].forEach(validateEditorField)
  return Object.values(editorErrors.value).every(x => !x)
}

const isEditorFormValid = computed(() => {
  const v = currentMap.value
  return !!(v.name && v.code && v.type && Object.values(editorErrors.value).every(x => !x))
})

const markTouchedEditor = (field) => {
  if (field in editorTouched.value) editorTouched.value[field] = true
}

const onEditorInput = (field) => {
  if (editorTouched.value[field]) validateEditorField(field)
}

const onCodeInputEditor = (e) => {
  const raw = (e?.target?.value ?? '').toString().toUpperCase().replace(/[^A-Z]/g, '')
  currentMap.value.code = raw.slice(0, 2)
  validateEditorField('code')
}

// 统一生成边的业务编码:倒车则追加 "-P"
const formatEdgeCode = (sourceCode, targetCode, isReverse) => {
  if (!sourceCode || !targetCode) return ''
  return `${sourceCode}-${targetCode}${isReverse ? '-P' : ''}`
}

// 方法
const onMapTypeChange = () => {}
const { init: notify } = useToast()
const isSaving = ref(false)
const saveMap = async () => {
  if (isSaving.value) return
  try {
    isSaving.value = true
    // 确保拓扑数据已同步,并转换为保存格式
    const nodesToSave = nodes.value.map(node => ({
      nodeId: String(node.id),
      nodeCode: node.code,
      nodeName: node.name || '',
      x: node.x,
      y: node.y,
      theta: node.orientation,
      allowRotate: node.allowRotate || false,
      type: node.type,
      isReverseParking: node.allowReverseEntry || false,
      maxCoordinateOffset: node.maxCoordinateOffset,
      maxAngleDeviation: node.maxAngleDeviation,
      maxSpeed: node.maxSpeed,
      active: true
    }))
    
    const edgesToSave = edges.value.map(edge => ({
      edgeId: String(edge.id),
      fromNode: edge.sourceCode,
      toNode: edge.targetCode,
      edgeCode: formatEdgeCode(edge.sourceCode, edge.targetCode, !!edge.isReverse),
      edgeName: edge.name || '',
      regress: edge.isReverse || false,
      isCurve: edge.curve || false,
      radius: edge.radius,
      centerX: edge.centerX,
      centerY: edge.centerY,
      active: true
    }))

    const payload = {
      mapId: currentMap.value.id ? String(currentMap.value.id) : undefined,
      mapCode: currentMap.value.code,
      mapName: currentMap.value.name,
      mapType: currentMap.value.type,
      version: '1.0.0',
      description: currentMap.value.description,
      active: true,
      mapNodes: nodesToSave,
      mapEdges: edgesToSave
    }
    
    console.log(payload)
    const res = await mapsApi.Canvas(payload)
    if(res.success) {
      notify({ message: t('maps.editor.messages.saveSuccess'), color: 'success' })
    }
    else{
      notify({ message: (t('maps.editor.messages.saveFailed') + ': ' + res.message), color: 'failed' })
    }
  } catch (error) {
    notify({ message: t('maps.editor.messages.saveFailed', { error: error?.message || '' }), color: 'danger' })
  } finally {
    isSaving.value = false
  }
}

const previewMap = () => {
  var jsonStr = JSON.stringify(currentMap.value);
  console.log(jsonStr);
  // 打开预览窗口或模态框
  notify({ message: t('maps.editor.messages.previewDeveloping'), color: 'info' })
}

const confirmBackModalVisible = ref(false)

const goBack = () => {
  confirmBackModalVisible.value = true
}

const confirmBack = () => {
  confirmBackModalVisible.value = false
  router.push({ name: 'maps' })
}

const loadMapData = async (mapId) => {
  try {
    const res = await mapsApi.getDetails(String(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;
    currentMap.value.description = data.description ?? '';
    
    // 处理节点数据:转换后端字段到前端字段
    const nodes = data.mapNodes ?? data.nodes ?? []
    console.log('[loadMapData] 原始节点数据:', nodes)
    const nodeIdToCodeMap = new Map()
    currentMap.value.nodes = nodes.map(node => {
      const nodeId = String(node.nodeId ?? node.id)
      const nodeCode = node.nodeCode ?? node.code ?? node.label ?? `N${node.nodeId ?? node.id}`
      nodeIdToCodeMap.set(nodeId, nodeCode)
      return {
        id: nodeId,
        x: node.x,
        y: node.y,
        code: nodeCode,
        name: node.nodeName ?? node.name ?? '',
        orientation: node.theta ?? node.orientation,
        allowRotate: node.allowRotate ?? false,
        type: node.type,
        allowReverseEntry: node.isReverseParking ?? node.allowReverseEntry ?? false,
        maxCoordinateOffset: node.maxCoordinateOffset ?? 0.5,
        maxAngleDeviation: node.maxAngleDeviation ?? 15,
        maxSpeed: node.maxSpeed ?? 1.2,
        storageLocations: node.storageLocations ?? []
      }
    })
    console.log(12313)
    // 打印储位节点的库位数据
    const storeNodes = currentMap.value.nodes.filter(n => n.type === 2)
    console.log('[loadMapData] 储位节点数量:', storeNodes.length)
    storeNodes.forEach(n => console.log('[loadMapData] 储位节点:', n.code, 'storageLocations:', n.storageLocations))
    console.log('[loadMapData] 转换后节点数据:', currentMap.value.nodes)

    // 处理边数据:转换后端字段到前端字段
    const edges = data.mapEdges ?? data.edges ?? []
    currentMap.value.edges = edges.map(edge => {
      // fromNode/toNode 是 nodeId(UUID),需要通过映射转换为 nodeCode
      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 ?? '')
      const isCurve = edge.isCurve ?? edge.curve ?? false
      const base = {
        id: String(edge.edgeId ?? edge.id),
        sourceCode,
        targetCode,
        code: edge.edgeCode ?? edge.code ?? formatEdgeCode(sourceCode, targetCode, !!edge.regress),
        name: edge.edgeName ?? edge.name ?? '',
        isReverse: edge.regress ?? edge.isReverse ?? false,
        curve: isCurve,
        radius: edge.radius,
        centerX: edge.centerX,
        centerY: edge.centerY
      }
      if (isCurve && edge.controlPoints && edge.controlPoints.length >= 2) {
        base.startX = edge.controlPoints[0].x
        base.startY = edge.controlPoints[0].y
        base.endX = edge.controlPoints[1].x
        base.endY = edge.controlPoints[1].y
      }
      return base
    })
    
    // 初始化 ID 计数器,确保新生成的 ID 不会与现有数据冲突
    if (currentMap.value.nodes && currentMap.value.nodes.length > 0) {
      const maxNodeId = Math.max(...currentMap.value.nodes.map(n => {
        const id = typeof n.id === 'string' ? parseInt(n.id, 10) : n.id
        return isNaN(id) ? 0 : id
      }))
      if (maxNodeId >= nextNodeIdCounter) {
        nextNodeIdCounter = maxNodeId + 1
      }
    }
    if (currentMap.value.edges && currentMap.value.edges.length > 0) {
      const maxEdgeId = Math.max(...currentMap.value.edges.map(e => {
        const id = typeof e.id === 'string' ? parseInt(e.id, 10) : e.id
        return isNaN(id) ? 0 : id
      }))
      if (maxEdgeId >= nextEdgeIdCounter) {
        nextEdgeIdCounter = maxEdgeId + 1
      }
    }

    // 加载背景图文件信息
    try {
      const fileRes = await mapsApi.getMapFile(String(mapId))
      const fileData = (fileRes && (fileRes.Data ?? fileRes.data)) || null
      
      if (fileData && fileData.fileUrl) {
        // 使用后端返回的完整URL,添加时间戳防止缓存
        const timestamp = new Date().getTime()
        const imageUrl = `${fileData.fileUrl}?t=${timestamp}`
        
        console.log('加载背景图:', imageUrl)
        
        // 加载图片
        const img = new Image()
        img.onload = () => {
          bgImgSize.value = { width: img.naturalWidth || img.width || 0, height: img.naturalHeight || img.height || 0 }
          bgImageUrl.value = imageUrl
          bgOpacity.value = fileData.opacity ?? 1
          bgRotation.value = fileData.rotation ?? 0
          bgOffsetX.value = fileData.offsetX ?? 0
          bgOffsetY.value = fileData.offsetY ?? 0

          // 如果数据库中的 scale 值太小(小于1),说明是旧的计算方式,使用默认计算
          const dbScale = fileData.scale ?? 0
          if (dbScale > 0 && dbScale < 1) {
            // 旧的 scale 值,重新计算合理的默认值
            bgScale.value = bgImgSize.value.width ? Math.max(0.01, 800 / bgImgSize.value.width) : 1
          } else {
            // 使用数据库中的值或默认值
            bgScale.value = dbScale || (bgImgSize.value.width ? Math.max(0.01, 800 / bgImgSize.value.width) : 1)
          }

          console.log('背景图加载成功:', {
            width: bgImgSize.value.width,
            height: bgImgSize.value.height,
            opacity: bgOpacity.value,
            scale: bgScale.value,
            dbScale: fileData.scale,
            bgWorldWidth: bgWorldWidth.value,
            bgWorldHeight: bgWorldHeight.value,
            url: bgImageUrl.value
          })

          // 如果没有节点数据,重置视图以显示背景图
          if (!nodes.value || nodes.value.length === 0) {
            setTimeout(() => {
              setFirstQuadrantView()
            }, 100)
          }
        }
        img.onerror = (err) => {
          console.error('加载背景图失败:', imageUrl, err)
        }
        img.src = imageUrl
      }
    } catch (error) {
      console.error('加载背景图信息失败:', error)
    }
  } catch (error) {
    console.error('加载地图详情失败:', error)
  }
}

// ======== 拓扑编辑逻辑 ========
const mode = ref('select') // select | addNode | connect | arc | pan
// 默认节点可视直径(屏幕像素)
const NODE_DIAMETER = 256
const NODE_RADIUS = NODE_DIAMETER / 2
const NODE_STROKE_WIDTH = 2
// 最小缩放(范围扩大1倍)
const MIN_SCALE = 0.005
const nodes = ref(currentMap.value.nodes)
const edges = ref(currentMap.value.edges)
const snapGuideX = ref(null)
const snapGuideY = ref(null)

// 当外部载入数据后,同步到本地编辑状态
watch(() => currentMap.value.nodes, (val) => {
  console.log('[watch nodes] 触发更新, 节点数量:', val?.length)
  nodes.value = val || []
}, { immediate: true })
watch(() => currentMap.value.edges, (val) => { edges.value = val || [] }, { immediate: true })

const viewport = ref({ x: 0, y: 0, scale: 0.1 })
let isPanning = false
let panStart = { x: 0, y: 0 }
let viewportStart = { x: 0, y: 0 }
const svgRef = ref(null)
const canvasSize = ref({ width: 0, height: 0 })
let resizeObserver = null

const selectedNodeId = ref(null) // legacy single-select (kept for compatibility)
const selectedEdgeId = ref(null) // legacy single-select (kept for compatibility)
const selectedNodeIds = ref(new Set())
const selectedEdgeIds = ref(new Set())
const selectedArcId = ref(null)
const selectedArcIds = ref(new Set())
const arcMode = ref({ step: 0, firstEdgeId: null, secondEdgeId: null })
const arcHoverEdgeId = ref(null)
const showArcRadiusPanel = ref(false)
const arcRadiusInput = ref(1)
const arcMaxRadius = ref(0)

// ======== 批量切线圆弧(UI 状态) ========
const batchArcPanelVisible = ref(false)
const batchArcRadiusInput = ref(1)

// ======== 批量编辑节点(UI 状态) ========
const batchEditPanelVisible = ref(false)
const batchNodeTypeChoice = ref('NO_CHANGE') // 'NO_CHANGE' | 1 | 2 | 3 | 4
const batchNodeOrientationChoice = ref('NO_CHANGE') // 'NO_CHANGE' | 'NULL' | '0' | '90' | '180' | '270'
const batchNodeAllowRotateChoice = ref('NO_CHANGE') // 'NO_CHANGE' | 'TRUE' | 'FALSE'
const batchNodeAllowReverseEntryChoice = ref('NO_CHANGE') // 'NO_CHANGE' | 'TRUE' | 'FALSE'

// ======== 复制并平移(UI 状态) ========
const copyPanelVisible = ref(false)
const copyOffsetX = ref(0)
const copyOffsetY = ref(0)

// ======== 平移(UI 状态) ========
const movePanelVisible = ref(false)
const moveOffsetX = ref(0)
const moveOffsetY = ref(0)

// ======== 背景图(导入与比例) ========
const bgFileInputRef = ref(null)
const bgImageUrl = ref('')
const bgImgSize = ref({ width: 0, height: 0 }) // 像素尺寸
const bgScale = ref(1) // 比例:每像素对应的世界单位
const bgOpacity = ref(0.6) // 透明度 0~1
const bgRotation = ref(0) // 旋转角度(度)
const bgOffsetX = ref(0) // 地图左下角偏移量X
const bgOffsetY = ref(0) // 地图左下角偏移量Y
const bgSettingsModalVisible = ref(false) // 背景图设置弹窗
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 revokeBgUrl = () => {
  try {
    if (bgImageUrl.value && bgImageUrl.value.startsWith('blob:')) URL.revokeObjectURL(bgImageUrl.value)
  } catch {}
}

const onBgFileChange = async (evt) => {
  const input = evt?.target
  const file = input && input.files && input.files[0]
  if (!file) return
  
  const lowerName = (file.name || '').toLowerCase()
  const isPgm = lowerName.endsWith('.pgm')

  if (isPgm) {
    revokeBgUrl()
    handlePgmFile(file)
      .catch(() => {})
      .finally(() => { try { if (input) input.value = '' } catch {} })
    return
  }

  revokeBgUrl()
  const objectUrl = URL.createObjectURL(file)
  const img = new Image()
  img.onload = async () => {
    bgImgSize.value = { width: img.naturalWidth || img.width || 0, height: img.naturalHeight || img.height || 0 }
    bgImageUrl.value = objectUrl
    if (!bgScale.value || bgScale.value <= 0) {
      bgScale.value = bgImgSize.value.width ? Math.max(0.01, 800 / bgImgSize.value.width) : 1
    }

    // 上传文件到服务器
    if (currentMap.value.id) {
      try {
        const formData = new FormData()
        formData.append('file', file)
        formData.append('opacity', String(bgOpacity.value))
        formData.append('scale', String(bgScale.value))
        formData.append('rotation', String(bgRotation.value || 0))
        
        const response = await mapsApi.uploadFile(currentMap.value.id, formData)
        
        if (response.success) {
          notify({ message: t('maps.editor.messages.uploadSuccess') || '背景图片上传成功', color: 'success' })
        } else {
          notify({ message: t('maps.editor.messages.uploadFailed') || '背景图片上传失败: ' + (response.message || ''), color: 'danger' })
        }
      } catch (error) {
        console.error('上传背景图片失败:', error)
        notify({ message: t('maps.editor.messages.uploadFailed') || '背景图片上传失败', color: 'danger' })
      }
    }
  }
  img.onerror = () => {
    URL.revokeObjectURL(objectUrl)
  }
  img.src = objectUrl
  try { if (input) input.value = '' } catch {}
}

const clearBgImage = async () => {
  if (!currentMap.value.id) {
    revokeBgUrl()
    bgImageUrl.value = ''
    bgImgSize.value = { width: 0, height: 0 }
    bgRotation.value = 0
    return
  }

  try {
    const response = await mapsApi.deleteMapFile(currentMap.value.id)
    
    if (response.success) {
      revokeBgUrl()
      bgImageUrl.value = ''
      bgImgSize.value = { width: 0, height: 0 }
      bgRotation.value = 0
      notify({ message: t('maps.editor.messages.bgImageDeleted') || '背景图已删除', color: 'success' })
    } else {
      notify({ message: t('maps.editor.messages.bgImageDeleteFailed') || '删除背景图失败', color: 'danger' })
    }
  } catch (error) {
    console.error('删除背景图失败:', error)
    notify({ message: t('maps.editor.messages.bgImageDeleteFailed') || '删除背景图失败', color: 'danger' })
  }
}

const openBgSettingsModal = () => {
  bgSettingsModalVisible.value = true
}

const closeBgSettingsModal = () => {
  bgSettingsModalVisible.value = false
}

const saveBgSettings = async () => {
  if (!currentMap.value.id) return

  // 如果没有背景图,只保存本地参数,不调用后端
  if (!bgImageUrl.value) {
    notify({ message: t('maps.editor.messages.noImageToSave') || '请先上传背景图片', color: 'warning' })
    return
  }

  try {
    const formData = new FormData()
    formData.append('opacity', String(bgOpacity.value))
    formData.append('scale', String(bgScale.value))
    formData.append('rotation', String(bgRotation.value))
    formData.append('offsetX', String(bgOffsetX.value))
    formData.append('offsetY', String(bgOffsetY.value))

    const response = await mapsApi.updateFileSettings(currentMap.value.id, formData)

    if (response.success) {
      notify({ message: t('maps.editor.messages.settingsSaved') || '设置已保存', color: 'success' })
    } else {
      notify({ message: t('maps.editor.messages.settingsSaveFailed') || '设置保存失败', color: 'danger' })
    }
  } catch (error) {
    console.error('保存背景图设置失败:', error)
    notify({ message: t('maps.editor.messages.settingsSaveFailed') || '设置保存失败', color: 'danger' })
  }
}

// ======== 撤销历史 ========
const historyStack = ref([])
const isRestoringHistory = ref(false)
const MAX_HISTORY = 200

const canUndo = computed(() => historyStack.value.length > 0)

const pushHistorySnapshot = () => {
  if (isRestoringHistory.value) return
  try {
    const snapshot = {
      nodes: JSON.parse(JSON.stringify(nodes.value || [])),
      edges: JSON.parse(JSON.stringify(edges.value || [])),
      selectedNodeIds: Array.from(selectedNodeIds.value || []),
      selectedEdgeIds: Array.from(selectedEdgeIds.value || []),
      selectedArcIds: Array.from(selectedArcIds.value || []),
      selectedNodeId: selectedNodeId.value ?? null,
      selectedEdgeId: selectedEdgeId.value ?? null,
      selectedArcId: selectedArcId.value ?? null,
      pendingConnectSourceId: pendingConnectSourceId.value ?? null,
      viewport: { ...(viewport.value || { x: 0, y: 0, scale: 1 }) }
    }
    historyStack.value.push(snapshot)
    if (historyStack.value.length > MAX_HISTORY) historyStack.value.shift()
  } catch {}
}

const undo = () => {
  if (historyStack.value.length === 0) return
  const snap = historyStack.value.pop()
  if (!snap) return
  isRestoringHistory.value = true
  try {
    nodes.value = Array.isArray(snap.nodes) ? snap.nodes : []
    edges.value = Array.isArray(snap.edges) ? snap.edges : []
    selectedNodeIds.value = new Set(snap.selectedNodeIds || [])
    selectedEdgeIds.value = new Set(snap.selectedEdgeIds || [])
    selectedArcIds.value = new Set(snap.selectedArcIds || [])
    selectedNodeId.value = snap.selectedNodeId ?? null
    selectedEdgeId.value = snap.selectedEdgeId ?? null
    selectedArcId.value = snap.selectedArcId ?? null
    pendingConnectSourceId.value = snap.pendingConnectSourceId ?? null
    if (snap.viewport) viewport.value = { ...snap.viewport }
    syncToCurrentMap()
  } finally {
    isRestoringHistory.value = false
  }
}

// 解析并渲染 PGM(P2/P5)为 PNG DataURL,然后设置为背景
const handlePgmFile = async (file) => {
  const buffer = await file.arrayBuffer()
  const parsed = parsePGM(buffer)
  if (!parsed) return
  const { width, height, pixels } = parsed
  const canvas = document.createElement('canvas')
  canvas.width = width
  canvas.height = height
  const ctx = canvas.getContext('2d', { willReadFrequently: true })
  const imageData = ctx.createImageData(width, height)
  const data = imageData.data
  for (let i = 0; i < width * height; i++) {
    const v = pixels[i]
    const j = i * 4
    data[j] = v
    data[j + 1] = v
    data[j + 2] = v
    data[j + 3] = 255
  }
  ctx.putImageData(imageData, 0, 0)
  const dataUrl = canvas.toDataURL('image/png')
  bgImgSize.value = { width, height }
  bgImageUrl.value = dataUrl
  if (!bgScale.value || bgScale.value <= 0) {
    bgScale.value = width ? Math.max(0.01, 800 / width) : 1
  }

  // 上传 PGM 转换后的 PNG 到服务器
  if (currentMap.value.id) {
    try {
      // 将 canvas 转换为 Blob
      const blob = await new Promise(resolve => canvas.toBlob(resolve, 'image/png'))
      if (!blob) return
      
      // 创建 File 对象
      const pngFile = new File([blob], file.name.replace(/\.pgm$/i, '.png'), { type: 'image/png' })
      
      const formData = new FormData()
      formData.append('file', pngFile)
      formData.append('opacity', String(bgOpacity.value))
      formData.append('scale', String(bgScale.value))
      formData.append('rotation', String(bgRotation.value || 0))
      
      const response = await mapsApi.uploadFile(currentMap.value.id, formData)
      
      if (response.success) {
        notify({ message: t('maps.editor.messages.uploadSuccess') || '背景图片上传成功', color: 'success' })
      } else {
        notify({ message: t('maps.editor.messages.uploadFailed') || '背景图片上传失败: ' + (response.message || ''), color: 'danger' })
      }
    } catch (error) {
      console.error('上传 PGM 背景图片失败:', error)
      notify({ message: t('maps.editor.messages.uploadFailed') || '背景图片上传失败', color: 'danger' })
    }
  }
}

// 基础 PGM 解析,支持 P2(ASCII) 与 P5(Binary, 1 或 2 字节灰度)
const parsePGM = (arrayBuffer) => {
  const bytes = new Uint8Array(arrayBuffer)
  let i = 0

  const isWs = (c) => c === 9 || c === 10 || c === 13 || c === 32
  const skipWsAndComments = (idx) => {
    let p = idx
    while (p < bytes.length) {
      if (bytes[p] === 35) { // '#'
        while (p < bytes.length && bytes[p] !== 10 && bytes[p] !== 13) p++
      } else if (isWs(bytes[p])) {
        p++
      } else {
        break
      }
    }
    return p
  }

  const readInt = () => {
    i = skipWsAndComments(i)
    if (i >= bytes.length) return null
    let sign = 1
    if (bytes[i] === 43 || bytes[i] === 45) { // '+' or '-'
      if (bytes[i] === 45) sign = -1
      i++
    }
    let val = 0
    let found = false
    while (i < bytes.length) {
      const c = bytes[i]
      if (c >= 48 && c <= 57) { // '0'-'9'
        val = val * 10 + (c - 48)
        found = true
        i++
      } else {
        break
      }
    }
    return found ? sign * val : null
  }

  i = skipWsAndComments(i)
  if (i + 1 >= bytes.length) return null
  if (bytes[i] !== 80) return null // 'P'
  i++
  const magic = bytes[i++]
  if (magic !== 50 && magic !== 53) return null // '2' or '5'

  const width = readInt()
  const height = readInt()
  const maxVal = readInt()
  if (!(width > 0 && height > 0 && maxVal > 0)) return null

  const total = width * height
  const pixels = new Uint8Array(total)

  if (magic === 50) {
    // P2 ASCII
    for (let k = 0; k < total; k++) {
      const v = readInt()
      if (v == null) return null
      let vv = Math.max(0, Math.min(maxVal, v))
      if (maxVal !== 255) vv = Math.round(vv * 255 / maxVal)
      pixels[k] = vv
    }
    return { width, height, maxVal, pixels }
  }

  // P5 Binary
  i = skipWsAndComments(i)
  if (maxVal < 256) {
    if (i + total > bytes.length) return null
    for (let k = 0; k < total; k++) {
      let v = bytes[i + k]
      if (maxVal !== 255) v = Math.round(v * 255 / maxVal)
      pixels[k] = v
    }
  } else {
    if (i + total * 2 > bytes.length) return null
    for (let k = 0; k < total; k++) {
      const hi = bytes[i + 2 * k]
      const lo = bytes[i + 2 * k + 1]
      let v = (hi << 8) | lo
      v = Math.round(v * 255 / maxVal)
      pixels[k] = v
    }
  }
  return { width, height, maxVal, pixels }
}

const isNodeSelected = (id) => selectedNodeIds.value.has(id) || selectedNodeId.value === id
const isEdgeSelected = (id) => selectedEdgeIds.value.has(id) || selectedEdgeId.value === id
const isArcSelected = (id) => selectedArcIds.value.has(id) || selectedArcId.value === id
let dragNodeState = { isDragging: false, nodeId: null, offsetX: 0, offsetY: 0 }
const pendingConnectSourceId = ref(null)
let nextNodeIdCounter = 1000
let nextEdgeIdCounter = 1000
const getNextNodeId = () => String(++nextNodeIdCounter)
const getNextEdgeId = () => String(++nextEdgeIdCounter)

// marquee selection (screen space)
const isMarqueeSelecting = ref(false)
const marqueeStart = ref({ x: 0, y: 0 })
const marqueeEnd = ref({ x: 0, y: 0 })
const mousePos = ref({ x: 0, y: 0 }) // 屏幕坐标(相对SVG容器)
// 叠在线段精准选取(连点轮换)
const pickCycleInfo = ref({ visible: false, index: 0, total: 0, candidatesKey: '', pos: { x: 0, y: 0 }, lastClickTs: 0 })
let pickCycleHideTimer = null
const marqueeRect = computed(() => {
  const x1 = Math.min(marqueeStart.value.x, marqueeEnd.value.x)
  const y1 = Math.min(marqueeStart.value.y, marqueeEnd.value.y)
  const x2 = Math.max(marqueeStart.value.x, marqueeEnd.value.x)
  const y2 = Math.max(marqueeStart.value.y, marqueeEnd.value.y)
  return { x: x1, y: y1, width: x2 - x1, height: y2 - y1 }
})

const setMode = (m) => {
  mode.value = m
  pendingConnectSourceId.value = null
  // 切换模式时清空辅助线
  snapGuideX.value = null
  snapGuideY.value = null
  arcHoverEdgeId.value = null
  if (mode.value !== 'arc') arcMode.value = { step: 0, firstEdgeId: null, secondEdgeId: null }
  showArcRadiusPanel.value = false
}

const getNodeById = (id) => nodes.value.find(n => n.id === id)
// 使用 Map 做 code -> node 的快速索引,避免渲染期 O(N·E) 线性查找
const codeToNodeMap = computed(() => {
  const m = new Map()
  for (const n of (nodes.value || [])) {
    if (n && typeof n.code === 'string') m.set(n.code, n)
  }
  return m
})
const getNodeByCode = (code) => codeToNodeMap.value.get(code) || null
const getNodeCodeById = (id) => {
  const node = getNodeById(id)
  return node ? node.code : null
}
const getNodeIdByCode = (code) => {
  const node = getNodeByCode(code)
  return node ? node.id : null
}

// 生成唯一的节点业务编码,避免与现有节点重复
const getAllNodeCodesSet = () => {
  const set = new Set()
  for (const n of (nodes.value || [])) {
    if (n && typeof n.code === 'string' && n.code) set.add(n.code)
  }
  return set
}

const generateUniqueNodeCode = (prefix = 'N') => {
  const used = getAllNodeCodesSet()
  const regex = new RegExp(`^${prefix}(\\d+)$`)
  let maxNum = 0
  for (const c of used) {
    const m = c.match(regex)
    if (m) {
      const num = parseInt(m[1], 10)
      if (!Number.isNaN(num) && num > maxNum) maxNum = num
    }
  }
  let candidateNum = maxNum + 1
  let candidate = `${prefix}${candidateNum}`
  while (used.has(candidate)) {
    candidateNum += 1
    candidate = `${prefix}${candidateNum}`
  }
  return candidate
}

// 为节点与边补充默认属性
const ensureNodeDefaults = (node) => {
  if (node == null) return
  if (node.name === undefined) node.name = node.code ?? ''
  if (node.type === undefined) node.type = 1
  if (node.orientation === undefined) node.orientation = null
  if (node.allowRotate === undefined) node.allowRotate = false
  if (node.allowReverseEntry === undefined) node.allowReverseEntry = false
  if (node.maxCoordinateOffset === undefined) node.maxCoordinateOffset = 0.5
  if (node.maxAngleDeviation === undefined) node.maxAngleDeviation = 15
  if (node.maxSpeed === undefined) node.maxSpeed = 1.2
}

const ensureEdgeDefaults = (edge) => {
  if (edge == null) return
  if (edge.name === undefined) edge.name = ''
  if (edge.isReverse === undefined) edge.isReverse = false
  if (edge.isArc === undefined) edge.isArc = false
  if (edge.centerX === undefined) edge.centerX = null
  if (edge.centerY === undefined) edge.centerY = null
  // 确保sourceCode和targetCode字段存在
  if (edge.sourceCode === undefined && edge.sourceId !== undefined) {
    edge.sourceCode = getNodeCodeById(edge.sourceId)
  }
  if (edge.targetCode === undefined && edge.targetId !== undefined) {
    edge.targetCode = getNodeCodeById(edge.targetId)
  }
  // 确保code字段存在
  if (edge.code === undefined && edge.sourceCode && edge.targetCode) {
    edge.code = formatEdgeCode(edge.sourceCode, edge.targetCode, !!edge.isReverse)
  }
}

const ensureArcDefaults = (arc) => {
  if (arc == null) return
  if (arc.name === undefined) arc.name = ''
  if (arc.isReverse === undefined) arc.isReverse = false
}

/**
 * 获取储位状态
 * @param node 节点对象
 * @returns 状态值:0=空闲,1=占用,2=预占用,3=禁用
 * @author zzy
 */
const getStorageStatus = (node) => {
  if (!node?.storageLocations?.length) {
    console.log('[getStorageStatus] 节点无库位数据:', node?.code, node?.storageLocations)
    return 0
  }
  const status = node.storageLocations[0].status ?? 0
  console.log('[getStorageStatus] 节点库位状态:', node.code, status)
  return status
}

// 节点填充颜色:储位为橙黄色,其它为白色(未选中时)
const getNodeFill = (node) => {
  if (!node || !node.type) return '#ffffff'
  if (node.type === 1) return '#74c0fc'  // speediness
  if (node.type === 4) return '#0d47a1'  // parking
  return node.type === 2 ? '#ffb020' : '#ffffff'  // store
}

// 节点描边颜色:跟随类型
const getNodeStroke = (node) => {
  if (!node) return '#6c757d'
  // 当允许旋转时,外圆线显示为蓝色
  if (node.allowRotate) return '#0d6efd'
  if (!node.type) return '#6c757d'
  if (node.type === 3) return '#28a745'  // charger
  if (node.type === 2) return '#d9480f'  // store
  if (node.type === 4) return '#0d47a1'  // parking
  return '#6c757d'
}

// 节点描边粗细与监控界面一致:选中为 6,未选中为 2
const getNodeStrokeWidth = (node) => {
  if (!node) return 2
  return isNodeSelected(node.id) ? 6 : 2
}

// 选中单个元素(优先支持多选集合中单个的情况)
const selectedSingleNode = computed(() => {
  if (selectedNodeIds.value && selectedNodeIds.value.size === 1) {
    const id = Array.from(selectedNodeIds.value)[0]
    const n = getNodeById(id)
    ensureNodeDefaults(n)
    return n || null
  }
  if (selectedNodeId.value != null) {
    const n = getNodeById(selectedNodeId.value)
    ensureNodeDefaults(n)
    return n || null
  }
  return null
})

const selectedSingleEdge = computed(() => {
  if (selectedEdgeIds.value && selectedEdgeIds.value.size === 1) {
    const id = Array.from(selectedEdgeIds.value)[0]
    const e = edges.value.find(x => x.id === id)
    ensureEdgeDefaults(e)
    return e || null
  }
  if (selectedEdgeId.value != null) {
    const e = edges.value.find(x => x.id === selectedEdgeId.value)
    ensureEdgeDefaults(e)
    return e || null
  }
  return null
})

const selectedSingleArc = computed(() => {
  if (selectedArcIds.value && selectedArcIds.value.size === 1) {
    const id = Array.from(selectedArcIds.value)[0]
    const a = (edges.value || []).find(x => x.id === id && x.curve)
    ensureArcDefaults(a)
    return a || null
  }
  if (selectedArcId.value != null) {
    const a = (edges.value || []).find(x => x.id === selectedArcId.value && x.curve)
    ensureArcDefaults(a)
    return a || null
  }
  return null
})

// 已选直线数量(不包含弧线)
const selectedStraightEdgeCount = computed(() => {
  const ids = new Set(selectedEdgeIds.value)
  if (selectedEdgeId.value != null) ids.add(selectedEdgeId.value)
  let count = 0
  for (const id of ids) {
    const e = edges.value.find(x => x.id === id)
    if (e && !e.curve) count += 1
  }
  return count
})

const getArcStartNodeId = (arc) => {
  if (!arc) return ''
  if (arc.sourceCode != null) return arc.sourceCode
  const n = findExistingNodeAt(arc.startX, arc.startY, 1e-4)
  return n ? n.code : ''
}

const getArcEndNodeId = (arc) => {
  if (!arc) return ''
  if (arc.targetCode != null) return arc.targetCode
  const n = findExistingNodeAt(arc.endX, arc.endY, 1e-4)
  return n ? n.code : ''
}

const toWorldPoint = (clientX, clientY) => {
  const svg = document.querySelector('.topo-canvas svg')
  const rect = svg?.getBoundingClientRect()
  if (!rect) return { x: 0, y: 0 }
  const scaleEff = viewport.value.scale || 1
  const x = (clientX - rect.left - viewport.value.x) / scaleEff
  const yScreen = (clientY - rect.top - viewport.value.y) / scaleEff
  // Cartesian Y up: invert screen y
  const y = -yScreen
  return { x, y }
}

// ======== 对齐吸附(同 X/Y 轴) ========
const SNAP_THRESHOLD_PX = 8

const getSvgRect = () => {
  const el = svgRef.value
  return el ? el.getBoundingClientRect() : null
}

const getMouseScreenPoint = (e) => {
  const rect = getSvgRect()
  if (!rect) return { x: 0, y: 0 }
  return { x: e.clientX - rect.left, y: e.clientY - rect.top }
}

const worldToScreenX = (worldX) => {
  const scaleEff = viewport.value.scale || 1
  return worldX * scaleEff + (viewport.value.x || 0)
}
const worldToScreenY = (worldY) => {
  const scaleEff = viewport.value.scale || 1
  return (-worldY) * scaleEff + (viewport.value.y || 0)
}

const findNearestSnapX = (screenX, excludeNodeId = null) => {
  let best = { dx: Number.POSITIVE_INFINITY, worldX: null }
  for (const n of nodes.value) {
    if (excludeNodeId != null && n.id === excludeNodeId) continue
    const nx = worldToScreenX(n.x)
    const dx = Math.abs(screenX - nx)
    if (dx < best.dx) best = { dx, worldX: n.x }
  }
  return best.dx <= SNAP_THRESHOLD_PX ? best.worldX : null
}

const findNearestSnapY = (screenY, excludeNodeId = null) => {
  let best = { dy: Number.POSITIVE_INFINITY, worldY: null }
  for (const n of nodes.value) {
    if (excludeNodeId != null && n.id === excludeNodeId) continue
    const ny = worldToScreenY(n.y)
    const dy = Math.abs(screenY - ny)
    if (dy < best.dy) best = { dy, worldY: n.y }
  }
  return best.dy <= SNAP_THRESHOLD_PX ? best.worldY : null
}

const getSnappedWorldFromEvent = (e, baseOffsetX = 0, baseOffsetY = 0, excludeNodeId = null) => {
  // 先算出基于鼠标与偏移的候选世界坐标
  const p = toWorldPoint(e.clientX, e.clientY)
  let candidateX = Math.round(p.x + baseOffsetX)
  let candidateY = Math.round(p.y + baseOffsetY)

  // 将候选世界坐标换算到屏幕坐标,用于阈值判断
  const screenX = worldToScreenX(candidateX)
  const screenY = worldToScreenY(candidateY)

  // 查找最近的同 X/Y 轴对齐目标
  const snappedX = findNearestSnapX(screenX, excludeNodeId)
  const snappedY = findNearestSnapY(screenY, excludeNodeId)

  if (snappedX != null) candidateX = snappedX
  if (snappedY != null) candidateY = snappedY

  // 更新辅助线显示
  snapGuideX.value = snappedX != null ? snappedX : null
  snapGuideY.value = snappedY != null ? snappedY : null

  return { x: candidateX, y: candidateY }
}

const onCanvasMouseDown = (e) => {
  // Middle mouse button pans regardless of mode
  if (e && e.button === 1) {
    isPanning = true
    panStart = { x: e.clientX, y: e.clientY }
    viewportStart = { x: viewport.value.x, y: viewport.value.y }
    try { e.preventDefault && e.preventDefault() } catch {}
    return
  }

  if (mode.value === 'pan') {
    isPanning = true
    panStart = { x: e.clientX, y: e.clientY }
    viewportStart = { x: viewport.value.x, y: viewport.value.y }
    return
  }

  if (mode.value === 'addNode') {
    const p = getSnappedWorldFromEvent(e)
    pushHistorySnapshot()
    const newNode = { id: getNextNodeId(), x: Math.round(p.x), y: Math.round(p.y), code: generateUniqueNodeCode('N'), orientation: null, allowRotate: false, maxCoordinateOffset: 0.5, maxAngleDeviation: 15, maxSpeed: 1.2 }
    nodes.value.push(newNode)
    selectedNodeId.value = newNode.id
    syncToCurrentMap()
    return
  }

  if (mode.value === 'select') {
    // start marquee selection
    const p = getMouseScreenPoint(e)
    marqueeStart.value = p
    marqueeEnd.value = p
    isMarqueeSelecting.value = true
    selectedNodeId.value = null
    selectedEdgeId.value = null
    selectedArcId.value = null
    if (!e.shiftKey) {
      selectedNodeIds.value = new Set()
      selectedEdgeIds.value = new Set()
      selectedArcIds.value = new Set()
    }
  }
}

const onCanvasMouseMove = (e) => {
  // 更新鼠标屏幕位置(用于提示)
  const rect = getSvgRect()
  if (rect) {
    mousePos.value = { x: e.clientX - rect.left, y: e.clientY - rect.top }
  }

  if (isPanning) {
    const dx = e.clientX - panStart.x
    const dy = e.clientY - panStart.y
    viewport.value.x = viewportStart.x + dx
    viewport.value.y = viewportStart.y + dy
    // 平移时不显示吸附辅助线
    snapGuideX.value = null
    snapGuideY.value = null
  }

  if (dragNodeState.isDragging && dragNodeState.nodeId != null) {
    const node = getNodeById(dragNodeState.nodeId)
    if (node) {
      const p = getSnappedWorldFromEvent(
        e,
        dragNodeState.offsetX,
        dragNodeState.offsetY,
        dragNodeState.nodeId
      )
      node.x = Math.round(p.x)
      node.y = Math.round(p.y)
      // 拖拽过程中不进行全量同步,结束时统一同步以降低重渲染
    }
    return
  }

  // addNode 模式下,移动时给出吸附预览
  if (mode.value === 'addNode') {
    getSnappedWorldFromEvent(e)
    return
  }

  // marquee selection live update
  if (mode.value === 'select' && isMarqueeSelecting.value) {
    marqueeEnd.value = getMouseScreenPoint(e)
    scheduleMarqueeSelectionUpdate(!!e.shiftKey)
    return
  }

  // arc 模式第二条边选择时的悬停高亮
  if (mode.value === 'arc' && arcMode.value.step === 1) {
    const p = getMouseScreenPoint(e)
    const ids = getEdgeCandidatesAtPoint(p.x, p.y)
    // 过滤掉第一条已选中的边
    const hoverId = ids.find(id => id !== arcMode.value.firstEdgeId) ?? null
    arcHoverEdgeId.value = hoverId || null
  }

  // 其他情况隐藏辅助线
  if (mode.value !== 'addNode') {
    snapGuideX.value = null
    snapGuideY.value = null
  }
}

const onCanvasMouseUp = () => {
  const wasDragging = !!dragNodeState.isDragging
  isPanning = false
  dragNodeState = { isDragging: false, nodeId: null, offsetX: 0, offsetY: 0 }
  // 结束交互时清空辅助线(addNode 悬停除外,由 move 决定)
  if (mode.value !== 'addNode') {
    snapGuideX.value = null
    snapGuideY.value = null
  }
  if (mode.value !== 'arc') {
    arcHoverEdgeId.value = null
  }
  // end marquee
  if (isMarqueeSelecting.value) {
    isMarqueeSelecting.value = false
  }
  if (wasDragging) syncToCurrentMap()
}

const onCanvasWheel = (e) => {
  const factor = e.deltaY > 0 ? 0.9 : 1.1
  const newScale = Math.min(3, Math.max(MIN_SCALE, viewport.value.scale * factor))

  // 缩放中心围绕鼠标位置
  const svg = document.querySelector('.topo-canvas svg')
  const rect = svg?.getBoundingClientRect()
  if (rect) {
    const cx = e.clientX - rect.left
    const cy = e.clientY - rect.top
    const scaleFactor = newScale / viewport.value.scale
    viewport.value.x = cx - scaleFactor * (cx - viewport.value.x)
    viewport.value.y = cy - scaleFactor * (cy - viewport.value.y)
  }

  viewport.value.scale = newScale
}

const onNodeMouseDown = (e, node) => {
  // Middle mouse button pans even when down on a node
  if (e && e.button === 1) {
    isPanning = true
    panStart = { x: e.clientX, y: e.clientY }
    viewportStart = { x: viewport.value.x, y: viewport.value.y }
    try { e.preventDefault && e.preventDefault() } catch {}
    return
  }

  if (mode.value === 'select') {
    pushHistorySnapshot()
    selectedNodeId.value = node.id
    const p = toWorldPoint(e.clientX, e.clientY)
    dragNodeState = { isDragging: true, nodeId: node.id, offsetX: node.x - p.x, offsetY: node.y - p.y }
  } else if (mode.value === 'pan') {
    onCanvasMouseDown(e)
  }
}

const onNodeClick = (evt, node) => {
  if (mode.value === 'connect') {
    if (!pendingConnectSourceId.value) {
      // 第一次点击:设置起点
      pendingConnectSourceId.value = node.id
      selectedNodeId.value = node.id
    } else if (pendingConnectSourceId.value === node.id) {
      // 点击同一节点:取消连线链
      pendingConnectSourceId.value = null
      selectedNodeId.value = node.id
    } else {
      // 创建从上一个节点到当前节点的边(非连续连线:创建后清空起点)
      const sourceCode = getNodeCodeById(pendingConnectSourceId.value)
      const targetCode = getNodeCodeById(node.id)
      const edgeCode = formatEdgeCode(sourceCode, targetCode, false)
      // 若已存在相同三元组或重复编码,则不再新增
      const dupTriple = edgeExists(sourceCode, targetCode, false)
      const dupCode = codeExists(edgeCode)
      if (dupTriple || dupCode) {
        const exist = edges.value.find(e => !e.curve && e.sourceCode === sourceCode && e.targetCode === targetCode && !!e.isReverse === false)
        if (exist) {
          selectedEdgeId.value = exist.id
          selectedEdgeIds.value = new Set([exist.id])
        }
        // 非连续:检测到重复后也结束一次连线操作
        pendingConnectSourceId.value = null
        selectedNodeId.value = node.id
        return
      }
      pushHistorySnapshot()
      const newEdge = { id: getNextEdgeId(), sourceCode, targetCode, code: edgeCode, isReverse: false, curve: false, isArc: false }
      edges.value.push(newEdge)
      // 非连续:成功创建后清空起点
      pendingConnectSourceId.value = null
      selectedNodeId.value = node.id
      syncToCurrentMap()
    }
  } else if (mode.value === 'select') {
    // 点击节点时选中节点并清空边的选择
    if (!evt || !evt.shiftKey) {
      selectedNodeIds.value = new Set([node.id])
    } else {
      const set = new Set(selectedNodeIds.value)
      if (set.has(node.id)) set.delete(node.id); else set.add(node.id)
      selectedNodeIds.value = set
    }
    selectedNodeId.value = node.id
    selectedEdgeId.value = null
    selectedEdgeIds.value = new Set()
  }
}

const onEdgeClick = (edge, evt) => {
  const e = evt || window.event
  const p = getMouseScreenPoint(e)
  const candidateIds = getEdgeCandidatesAtPoint(p.x, p.y)
  const pickedId = pickEdgeFromCandidates(candidateIds, p.x, p.y)
  if (pickedId == null) return

  if (mode.value === 'select') {
    if (!e || !e.shiftKey) {
      selectedEdgeIds.value = new Set([pickedId])
    } else {
      const set = new Set(selectedEdgeIds.value)
      if (set.has(pickedId)) set.delete(pickedId); else set.add(pickedId)
      selectedEdgeIds.value = set
    }
    selectedEdgeId.value = pickedId
    selectedNodeId.value = null
    selectedNodeIds.value = new Set()
    selectedArcId.value = null
    selectedArcIds.value = new Set()
  } else if (mode.value === 'arc') {
    if (arcMode.value.step === 0) {
      arcMode.value.firstEdgeId = pickedId
      arcMode.value.step = 1
    } else if (arcMode.value.step === 1) {
      if (pickedId === arcMode.value.firstEdgeId) {
        arcMode.value = { step: 0, firstEdgeId: null, secondEdgeId: null }
        return
      }
      arcMode.value.secondEdgeId = pickedId
      arcHoverEdgeId.value = null
      prepareArcRadiusPanel()
    }
  }
}

const PICK_RADIUS_PX = 36

const getEdgeCandidatesAtPoint = (sx, sy) => {
  const arr = []
  for (const ed of edges.value) {
    const s = getNodeByCode(ed.sourceCode)
    const t = getNodeByCode(ed.targetCode)
    if (!s || !t) continue
    const x1 = worldToScreenX(s.x)
    const y1 = worldToScreenY(s.y)
    const x2 = worldToScreenX(t.x)
    const y2 = worldToScreenY(t.y)
    const d = pointToSegmentDistancePx(sx, sy, x1, y1, x2, y2)
    if (d <= PICK_RADIUS_PX) arr.push({ id: ed.id, d })
  }
  arr.sort((a, b) => (a.d - b.d) || (a.id - b.id))
  return arr.map(x => x.id)
}

const pointToSegmentDistancePx = (px, py, x1, y1, x2, y2) => {
  const vx = x2 - x1
  const vy = y2 - y1
  const wx = px - x1
  const wy = py - y1
  const c1 = vx * wx + vy * wy
  if (c1 <= 0) return Math.hypot(px - x1, py - y1)
  const c2 = vx * vx + vy * vy
  if (c2 <= c1) return Math.hypot(px - x2, py - y2)
  const t = c1 / c2
  const projx = x1 + t * vx
  const projy = y1 + t * vy
  return Math.hypot(px - projx, py - projy)
}

const pickEdgeFromCandidates = (ids, sx, sy) => {
  if (!ids || ids.length === 0) {
    pickCycleInfo.value.visible = false
    return null
  }
  const key = ids.join(',')
  const now = Date.now()
  const last = pickCycleInfo.value
  const near = Math.hypot((sx - last.pos.x), (sy - last.pos.y)) <= 4
  const sameSet = last.candidatesKey === key
  const within = now - (last.lastClickTs || 0) <= 1000
  let index = 0
  if (sameSet && near && within) {
    index = (last.index + 1) % ids.length
  }
  pickCycleInfo.value = { visible: true, index, total: ids.length, candidatesKey: key, pos: { x: sx, y: sy }, lastClickTs: now }
  if (pickCycleHideTimer) clearTimeout(pickCycleHideTimer)
  pickCycleHideTimer = setTimeout(() => { pickCycleInfo.value.visible = false }, 900)
  return ids[index]
}

const onArcClick = (evt) => {
  if (mode.value !== 'select') return
  const e = evt || window.event
  const p = getMouseScreenPoint(e)
  const candidateIds = getArcCandidatesAtPoint(p.x, p.y)
  const pickedId = pickArcFromCandidates(candidateIds, p.x, p.y)
  if (pickedId == null) return
  if (!e || !e.shiftKey) {
    selectedArcIds.value = new Set([pickedId])
  } else {
    const set = new Set(selectedArcIds.value)
    if (set.has(pickedId)) set.delete(pickedId); else set.add(pickedId)
    selectedArcIds.value = set
  }
  selectedArcId.value = pickedId
  // clear others when selecting arcs (single source of truth like nodes/edges)
  selectedNodeId.value = null
  selectedEdgeId.value = null
  selectedNodeIds.value = new Set()
  selectedEdgeIds.value = new Set()
}

const getArcCandidatesAtPoint = (sx, sy) => {
  const arr = []
  for (const a of (edges.value || []).filter(e => e.curve)) {
    const d = pointToArcDistancePx(a, sx, sy)
    if (d <= PICK_RADIUS_PX) arr.push({ id: a.id, d })
  }
  arr.sort((a, b) => (a.d - b.d) || (a.id > b.id ? 1 : -1))
  return arr.map(x => x.id)
}

const pointToArcDistancePx = (arc, px, py) => {
  // sample the polyline along the arc path and compute min distance in screen space
  const toRad = (deg) => deg * (Math.PI / 180)
  const toDeg = (rad) => rad * (180 / Math.PI)
  const normDeg = (a) => { let x = a % 360; if (x < 0) x += 360; return x }
  const normDelta = (a0, a1) => {
    const raw = a1 - a0
    let d = ((raw % 360) + 360) % 360
    if (d > 180) d -= 360
    return d
  }
  // compute angles from geometry instead of chargerd fields
  const startAngle = normDeg(toDeg(Math.atan2(-(arc.startY - arc.centerY), arc.startX - arc.centerX)))
  const endAngle = normDeg(toDeg(Math.atan2(-(arc.endY - arc.centerY), arc.endX - arc.centerX)))
  const delta = normDelta(startAngle, endAngle)
  const steps = Math.max(8, Math.min(64, Math.ceil(Math.abs(delta) / 6)))
  let minD = Number.POSITIVE_INFINITY
  let prev = null
  for (let i = 0; i <= steps; i++) {
    const t = i / steps
    const ang = startAngle + delta * t
    const x = arc.centerX + arc.radius * Math.cos(toRad(ang))
    const y = arc.centerY - arc.radius * Math.sin(toRad(ang))
    const sxp = worldToScreenX(x)
    const syp = worldToScreenY(y)
    if (prev) {
      const d = pointToSegmentDistancePx(px, py, prev.x, prev.y, sxp, syp)
      if (d < minD) minD = d
    }
    prev = { x: sxp, y: syp }
  }
  return minD
}

const pickArcFromCandidates = (ids, sx, sy) => {
  if (!ids || ids.length === 0) {
    pickCycleInfo.value.visible = false
    return null
  }
  const key = `arc:` + ids.join(',')
  const now = Date.now()
  const last = pickCycleInfo.value
  const near = Math.hypot((sx - last.pos.x), (sy - last.pos.y)) <= 4
  const sameSet = last.candidatesKey === key
  const within = now - (last.lastClickTs || 0) <= 1000
  let index = 0
  if (sameSet && near && within) {
    index = (last.index + 1) % ids.length
  }
  pickCycleInfo.value = { visible: true, index, total: ids.length, candidatesKey: key, pos: { x: sx, y: sy }, lastClickTs: now }
  if (pickCycleHideTimer) clearTimeout(pickCycleHideTimer)
  pickCycleHideTimer = setTimeout(() => { pickCycleInfo.value.visible = false }, 900)
  return ids[index]
}

const zoomIn = () => { viewport.value.scale = Math.min(3, viewport.value.scale + 0.1) }
const zoomOut = () => { viewport.value.scale = Math.max(MIN_SCALE, viewport.value.scale - 0.1) }
const setFirstQuadrantView = () => {
  const height = canvasSize.value.height || 0
  viewport.value = { x: 0, y: height, scale: 0.1 }
}
const resetView = () => { setFirstQuadrantView() }

const syncToCurrentMap = () => {
  // 规范化边的业务编码(倒车后缀 -P)
  const normalizedEdges = (edges.value || []).map(e => ({
    ...e,
    code: formatEdgeCode(e.sourceCode, e.targetCode, !!e.isReverse)
  }))
  edges.value = normalizedEdges
  currentMap.value.nodes = [...nodes.value]
  currentMap.value.edges = normalizedEdges
}

const canvasCursorClass = computed(() => {
  switch (mode.value) {
    case 'addNode': return 'cursor-crosshair'
    case 'pan': return 'cursor-grab'
    case 'connect': return 'cursor-alias'
    case 'arc': return 'cursor-alias'
    default: return 'cursor-default'
  }
})

  // Node inner scale to keep visual size constant regardless of viewport zoom
  const nodeScreenScale = computed(() => {
    const s = viewport.value.scale || 1
    return s > 0 ? (1 / s) : 1
  })

// ======== 网格与刻度 ========
const worldBounds = computed(() => {
  const w = canvasSize.value.width || 0
  const h = canvasSize.value.height || 0
  const scaleEff = viewport.value.scale || 1
  const xMin = (-viewport.value.x) / scaleEff
  // For Cartesian Y up, map screen to world: worldY = -(screenY - viewport.y)/scaleEff
  const yMax = (viewport.value.y) / scaleEff
  const yMin = -((h - viewport.value.y) / scaleEff)
  const xMax = (w - viewport.value.x) / scaleEff
  return { xMin, xMax, yMin, yMax }
})

const gridStep = computed(() => {
  // 动态选择合适的网格间距(世界单位)
  // 目标:每格在屏幕上约 targetPx 像素;使用 1/2/5 系列(...0.1,0.2,0.5,1,2,5,10...)
  const targetPx = 20 // 约 40px 一个格
  const scaleEff = (viewport.value.scale || 1)
  const raw = targetPx / scaleEff
  if (!(raw > 0)) return 1
  const exp = Math.floor(Math.log10(raw))
  const mag = Math.pow(10, exp)
  const norm = raw / mag
  let mult = 1
  if (norm < 1.5) mult = 1
  else if (norm < 3) mult = 2
  else if (norm < 7) mult = 5
  else mult = 10
  return mag * mult
})

const gridXLines = computed(() => {
  const { xMin, xMax } = worldBounds.value
  const step = gridStep.value
  const start = Math.floor(xMin / step) * step
  const end = Math.ceil(xMax / step) * step
  const lines = []
  for (let x = start; x <= end; x += step) {
    lines.push({ x, major: (x % (step * 5) === 0) })
  }
  return lines
})

const gridYLines = computed(() => {
  const { yMin, yMax } = worldBounds.value
  const step = gridStep.value
  const start = Math.floor(yMin / step) * step
  const end = Math.ceil(yMax / step) * step
  const lines = []
  for (let y = start; y <= end; y += step) {
    lines.push({ y, major: (y % (step * 5) === 0) })
  }
  return lines
})

const topRulerTicks = computed(() => {
  const step = gridStep.value
  const ticks = []
  for (const gx of gridXLines.value) {
    const scaleEff = viewport.value.scale || 1
    const screenX = gx.x * scaleEff + viewport.value.x
    if (screenX >= 32 && screenX <= (canvasSize.value.width || 0)) {
      ticks.push({ x: screenX, major: gx.major, label: gx.major ? gx.x : '' })
    }
  }
  return ticks
})

const leftRulerTicks = computed(() => {
  const ticks = []
  for (const gy of gridYLines.value) {
    // Cartesian Y up: world y -> screen y = -y
    const scaleEff = viewport.value.scale || 1
    const screenY = (-gy.y) * scaleEff + viewport.value.y
    if (screenY >= 16 && screenY <= (canvasSize.value.height || 0)) {
      ticks.push({ y: screenY, major: gy.major, label: gy.major ? gy.y : '' })
    }
  }
  return ticks
})

const updateCanvasSize = () => {
  const el = svgRef.value
  if (!el) return
  const rect = el.getBoundingClientRect()
  canvasSize.value = { width: Math.round(rect.width), height: Math.round(rect.height) }
}

onMounted(() => {
  nextTick(() => {
    const initCanvas = () => {
      updateCanvasSize()
      // 确保尺寸有效后再设置视图
      if (canvasSize.value.width > 0 && canvasSize.value.height > 0) {
        setFirstQuadrantView()
      } else {
        // 尺寸无效时延迟重试
        requestAnimationFrame(initCanvas)
        return
      }
      window.addEventListener('resize', updateCanvasSize)
      window.addEventListener('keydown', onKeyDown)
      if (window.ResizeObserver) {
        resizeObserver = new ResizeObserver(() => {
          updateCanvasSize()
          // 首次获取有效尺寸时重新设置视图
          if (canvasSize.value.height > 0 && viewport.value.y === 0) {
            setFirstQuadrantView()
          }
        })
        if (svgRef.value) resizeObserver.observe(svgRef.value)
      }
      try { document.body && document.body.classList && document.body.classList.add('no-scroll') } catch {}
    }
    requestAnimationFrame(initCanvas)
  })
  // 加载下拉选项数据
  loadOptions()
  //检查是否为编辑模式
  const mapId = route.params.id || route.query.id
  if (mapId) {
    isEditMode.value = true
    loadMapData(String(mapId))
  }
})

onUnmounted(() => {
  window.removeEventListener('resize', updateCanvasSize)
  window.removeEventListener('keydown', onKeyDown)
  if (resizeObserver) try { resizeObserver.disconnect() } catch {}
  resizeObserver = null
  // 恢复页面滚动
  try { document.body && document.body.classList && document.body.classList.remove('no-scroll') } catch {}
})

const deleteSelectedEdge = () => {
  if (selectedEdgeIds.value.size === 0 && selectedEdgeId.value == null) return
  pushHistorySnapshot()
  const ids = new Set(selectedEdgeIds.value)
  if (selectedEdgeId.value != null) ids.add(selectedEdgeId.value)
  edges.value = edges.value.filter(e => !ids.has(e.id))
  selectedEdgeId.value = null
  selectedEdgeIds.value = new Set()
  // prune arcs whose edges were removed
  pruneInvalidArcs()
  syncToCurrentMap()
}

// ===== 为框选节点:按X方向最近点生成一条直线(去重) =====
const generateEdgesForSelectedNodesX = () => {
  const nodeIds = Array.from(new Set(selectedNodeIds.value))
  if (nodeIds.length < 2) return
  pushHistorySnapshot()
  const selected = nodeIds.map(id => getNodeById(id)).filter(Boolean)
  if (selected.length < 2) return

  const EPS = 1e-6
  const floatsEq = (a, b) => Math.abs(a - b) <= EPS

  const addEdgeOneWay = (from, to) => {
    if (!from || !to || from.id === to.id) return
    let source = from
    let target = to
    if (from.x > to.x || (floatsEq(from.x, to.x) && from.y > to.y)) {
      source = to
      target = from
    }
    const edgeCode = formatEdgeCode(source.code, target.code, false)
    const dupTriple = edgeExists(source.code, target.code, false)
    const dupCode = codeExists(edgeCode)
    if (dupTriple || dupCode) return
    const name = `${source?.code ?? source.id}-${target?.code ?? target.id}`
    edges.value.push({ id: getNextEdgeId(), sourceCode: source.code, targetCode: target.code, code: edgeCode, isReverse: false, curve: false, isArc: false, name })
  }

  // For each node: find nearest aligned on X (same Y) within selection
  for (const n of selected) {
    let left = null, right = null
    for (const m of selected) {
      if (!m || m.id === n.id) continue
      if (floatsEq(m.y, n.y)) {
        if (m.x < n.x) { if (!left || m.x > left.x) left = m }
        if (m.x > n.x) { if (!right || m.x < right.x) right = m }
      }
    }
    if (left) addEdgeOneWay(n, left)
    if (right) addEdgeOneWay(n, right)
  }

  syncToCurrentMap()
}

// ===== 为框选节点:按Y方向最近点生成一条直线(去重) =====
const generateEdgesForSelectedNodesY = () => {
  const nodeIds = Array.from(new Set(selectedNodeIds.value))
  if (nodeIds.length < 2) return
  pushHistorySnapshot()
  const selected = nodeIds.map(id => getNodeById(id)).filter(Boolean)
  if (selected.length < 2) return

  const EPS = 1e-6
  const floatsEq = (a, b) => Math.abs(a - b) <= EPS

  const addEdgeOneWay = (from, to) => {
    if (!from || !to || from.id === to.id) return
    let source = from
    let target = to
    if (from.x > to.x || (floatsEq(from.x, to.x) && from.y > to.y)) {
      source = to
      target = from
    }
    const edgeCode = formatEdgeCode(source.code, target.code, false)
    const dupTriple = edgeExists(source.code, target.code, false)
    const dupCode = codeExists(edgeCode)
    if (dupTriple || dupCode) return
    const name = `${source?.code ?? source.id}-${target?.code ?? target.id}`
    edges.value.push({ id: getNextEdgeId(), sourceCode: source.code, targetCode: target.code, code: edgeCode, isReverse: false, curve: false, isArc: false, name })
  }

  // For each node: find nearest aligned on Y (same X) within selection
  for (const n of selected) {
    let up = null, down = null
    for (const m of selected) {
      if (!m || m.id === n.id) continue
      if (floatsEq(m.x, n.x)) {
        if (m.y < n.y) { if (!down || m.y > down.y) down = m }
        if (m.y > n.y) { if (!up || m.y < up.y) up = m }
      }
    }
    if (up) addEdgeOneWay(n, up)
    if (down) addEdgeOneWay(n, down)
  }

  syncToCurrentMap()
}

const deleteSelectedNode = () => {
  if (selectedNodeIds.value.size === 0 && selectedNodeId.value == null) return
  pushHistorySnapshot()
  const nodeIds = new Set(selectedNodeIds.value)
  if (selectedNodeId.value != null) nodeIds.add(selectedNodeId.value)
  
  // 获取要删除的节点的code集合
  const nodeCodesToDelete = new Set()
  for (const nodeId of nodeIds) {
    const node = getNodeById(nodeId)
    if (node && node.code) {
      nodeCodesToDelete.add(node.code)
    }
  }
  
  nodes.value = nodes.value.filter(n => !nodeIds.has(n.id))
  
  // 删除关联的边(基于sourceCode和targetCode)
  edges.value = edges.value.filter(e => {
    return !nodeCodesToDelete.has(e.sourceCode) && !nodeCodesToDelete.has(e.targetCode)
  })
  
  selectedNodeId.value = null
  selectedEdgeId.value = null
  selectedNodeIds.value = new Set()
  selectedEdgeIds.value = new Set()
  // prune arcs whose edges were removed by node deletion
  pruneInvalidArcs()
  syncToCurrentMap()
}

const deleteSelectedArc = () => {
  if (selectedArcIds.value.size === 0 && selectedArcId.value == null) return
  pushHistorySnapshot()
  const ids = new Set(selectedArcIds.value)
  if (selectedArcId.value != null) ids.add(selectedArcId.value)
  edges.value = edges.value.filter(a => !(a.curve && ids.has(a.id)))
  selectedArcId.value = null
  selectedArcIds.value = new Set()
  syncToCurrentMap()
}

const pruneInvalidArcs = () => {
  // No edge id linkage maintained after removing edge1Id/edge2Id
  const arcIdSet = new Set(edges.value.filter(e => e.curve).map(x => x.id))
  if (selectedArcId.value != null && !arcIdSet.has(selectedArcId.value)) selectedArcId.value = null
  const newSel = new Set()
  for (const id of selectedArcIds.value) { if (arcIdSet.has(id)) newSel.add(id) }
  selectedArcIds.value = newSel
}

const onKeyDown = (e) => {
  // Ignore global delete/backspace when typing in inputs/textareas/selects or contenteditable
  const target = e.target
  const tag = target && target.tagName ? String(target.tagName).toLowerCase() : ''
  const isEditable = !!(target && (target.isContentEditable || tag === 'input' || tag === 'textarea' || tag === 'select'))
  if (isEditable) return

  if (e.key === 'Delete' || e.key === 'Backspace') {
    const hasNodeSel = selectedNodeId.value != null || selectedNodeIds.value.size > 0
    const hasEdgeSel = selectedEdgeId.value != null || selectedEdgeIds.value.size > 0
    const hasArcSel = selectedArcId.value != null || selectedArcIds.value.size > 0
    if (hasNodeSel || hasEdgeSel || hasArcSel) {
      e.preventDefault()
      // delete all selected types in one go
      if (hasNodeSel) deleteSelectedNode()
      if (hasEdgeSel) deleteSelectedEdge()
      if (hasArcSel) deleteSelectedArc()
    }
  }
}

const updateMarqueeSelection = (isAdditive) => {
  const rect = marqueeRect.value
  const isNodeInside = (n) => {
    const sx = worldToScreenX(n.x)
    const sy = worldToScreenY(n.y)
    return sx >= rect.x && sx <= rect.x + rect.width && sy >= rect.y && sy <= rect.y + rect.height
  }

  const newSelectedNodes = new Set(isAdditive ? selectedNodeIds.value : [])
  for (const n of nodes.value) {
    if (isNodeInside(n)) newSelectedNodes.add(n.id)
  }
  selectedNodeIds.value = newSelectedNodes

  // auto-select edges whose both endpoints are selected
  const selectedNodeSet = selectedNodeIds.value
  const newSelectedEdges = new Set(isAdditive ? selectedEdgeIds.value : [])
  for (const e of edges.value) {
    const sourceNode = getNodeByCode(e.sourceCode)
    const targetNode = getNodeByCode(e.targetCode)
    if (sourceNode && targetNode && selectedNodeSet.has(sourceNode.id) && selectedNodeSet.has(targetNode.id)) {
      newSelectedEdges.add(e.id)
    }
  }
  selectedEdgeIds.value = newSelectedEdges

  // arcs selection by marquee: if both arc endpoints are inside, select it
  const newSelectedArcs = new Set(isAdditive ? selectedArcIds.value : [])
  for (const a of (edges.value || []).filter(e => e.curve)) {
    const sx1 = worldToScreenX(a.startX)
    const sy1 = worldToScreenY(a.startY)
    const sx2 = worldToScreenX(a.endX)
    const sy2 = worldToScreenY(a.endY)
    const inside1 = sx1 >= rect.x && sx1 <= rect.x + rect.width && sy1 >= rect.y && sy1 <= rect.y + rect.height
    const inside2 = sx2 >= rect.x && sx2 <= rect.x + rect.width && sy2 >= rect.y && sy2 <= rect.y + rect.height
    if (inside1 && inside2) newSelectedArcs.add(a.id)
  }
  selectedArcIds.value = newSelectedArcs
}

// 使用 rAF 节流框选集合更新,降低大数据量下的每帧计算
let marqueeUpdateScheduled = false
let marqueeIsAdditivePending = false
const scheduleMarqueeSelectionUpdate = (isAdditive) => {
  marqueeIsAdditivePending = !!isAdditive
  if (marqueeUpdateScheduled) return
  marqueeUpdateScheduled = true
  requestAnimationFrame(() => {
    marqueeUpdateScheduled = false
    updateMarqueeSelection(marqueeIsAdditivePending)
  })
}

// ======== 圆弧计算(参考 edubeam arcUtils) ========
const calculateArcBetweenEdges = (edge1, edge2, radius, arcId) => {
  const n11 = getNodeByCode(edge1.sourceCode)
  const n12 = getNodeByCode(edge1.targetCode)
  const n21 = getNodeByCode(edge2.sourceCode)
  const n22 = getNodeByCode(edge2.targetCode)
  if (!n11 || !n12 || !n21 || !n22) return null

  const p1a = { x: n11.x, y: n11.y }
  const p1b = { x: n12.x, y: n12.y }
  const p2a = { x: n21.x, y: n21.y }
  const p2b = { x: n22.x, y: n22.y }

  const intersection = findLineIntersectionInfinite(p1a, p1b, p2a, p2b)
  if (!intersection) return null

  const len1 = Math.hypot(p1b.x - p1a.x, p1b.y - p1a.y)
  const len2 = Math.hypot(p2b.x - p2a.x, p2b.y - p2a.y)
  if (len1 < 1e-12 || len2 < 1e-12) return null

  const u1Line = { x: (p1b.x - p1a.x) / len1, y: (p1b.y - p1a.y) / len1 }
  const u2Line = { x: (p2b.x - p2a.x) / len2, y: (p2b.y - p2a.y) / len2 }

  const selectDirection = (pa, pb, uLine, ip) => {
    const sA = (pa.x - ip.x) * uLine.x + (pa.y - ip.y) * uLine.y
    const sB = (pb.x - ip.x) * uLine.x + (pb.y - ip.y) * uLine.y
    const pos1 = Math.max(0, Math.max(sA, sB))
    const sA2 = -sA
    const sB2 = -sB
    const pos2 = Math.max(0, Math.max(sA2, sB2))
    if (pos2 > pos1 + 1e-12) return { u: { x: -uLine.x, y: -uLine.y }, sPosMax: pos2 }
    return { u: uLine, sPosMax: pos1 }
  }

  const dirSel1 = selectDirection(p1a, p1b, u1Line, intersection)
  const dirSel2 = selectDirection(p2a, p2b, u2Line, intersection)
  const u1 = dirSel1.u
  const u2 = dirSel2.u

  const dot = Math.max(-1, Math.min(1, u1.x * u2.x + u1.y * u2.y))
  const theta = Math.acos(dot)
  if (!(theta > 1e-6 && theta < Math.PI - 1e-6)) return null

  const sinHalf = Math.sin(theta / 2)
  const cosHalf = Math.cos(theta / 2)
  if (Math.abs(sinHalf) < 1e-12) return null

  let radiusUsed = radius
  let d = radiusUsed * (cosHalf / sinHalf)

  const s1PosMax = dirSel1.sPosMax
  const s2PosMax = dirSel2.sPosMax
  const dMax = Math.min(s1PosMax, s2PosMax)
  if (dMax <= 1e-12) return null
  const rMax = dMax * Math.tan(theta / 2)
  if (rMax <= 1e-12) return null
  if (radiusUsed > rMax + 1e-8) radiusUsed = rMax
  d = radiusUsed * (cosHalf / sinHalf)
  if (d > dMax + 1e-8) return null

  const bisectorVec = { x: u1.x + u2.x, y: u1.y + u2.y }
  const bisLen = Math.hypot(bisectorVec.x, bisectorVec.y)
  if (bisLen < 1e-12) return null
  const bisUnit = { x: bisectorVec.x / bisLen, y: bisectorVec.y / bisLen }
  const h = radiusUsed / sinHalf
  const centerX = intersection.x + bisUnit.x * h
  const centerY = intersection.y + bisUnit.y * h

  const startPoint = { x: intersection.x + u1.x * d, y: intersection.y + u1.y * d }
  const endPoint = { x: intersection.x + u2.x * d, y: intersection.y + u2.y * d }

  if (!isPointOnLineSegment(p1a, p1b, startPoint, 1e-6)) return null
  if (!isPointOnLineSegment(p2a, p2b, endPoint, 1e-6)) return null

  const toDeg = (rad) => rad * (180 / Math.PI)
  const normDeg = (a) => { let x = a % 360; if (x < 0) x += 360; return x }
  const shortestDelta = (a0, a1) => { let dlt = (a1 - a0) % 360; if (dlt <= -180) dlt += 360; if (dlt > 180) dlt -= 360; return dlt }

  // start/end angles are derivable when rendering; do not persist them on edges

  return {
    id: arcId,
    radius: radiusUsed,
    centerX,
    centerY,
    startX: startPoint.x,
    startY: startPoint.y,
    endX: endPoint.x,
    endY: endPoint.y
  }
}

const findLineIntersectionInfinite = (p1, p2, p3, p4) => {
  const x1 = p1.x, y1 = p1.y
  const x2 = p2.x, y2 = p2.y
  const x3 = p3.x, y3 = p3.y
  const x4 = p4.x, y4 = p4.y
  const denom = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4)
  if (Math.abs(denom) < 1e-10) return null
  const t = ((x1 - x3) * (y3 - y4) - (y1 - y3) * (x3 - x4)) / denom
  return { x: x1 + t * (x2 - x1), y: y1 + t * (y2 - y1) }
}

const isPointOnLineSegment = (p1, p2, point, tolerance = 1e-6) => {
  const dx = p2.x - p1.x
  const dy = p2.y - p1.y
  const length = Math.sqrt(dx * dx + dy * dy)
  if (length === 0) return false
  const t = ((point.x - p1.x) * dx + (point.y - p1.y) * dy) / (length * length)
  if (t < 0 || t > 1) return false
  const closestX = p1.x + t * dx
  const closestY = p1.y + t * dy
  const distance = Math.sqrt((point.x - closestX) ** 2 + (point.y - closestY) ** 2)
  return distance <= tolerance
}

const getArcPath = (arc) => {
  if (!arc) return ''
  const toRad = (deg) => deg * (Math.PI / 180)
  const toDeg = (rad) => rad * (180 / Math.PI)
  const normDeg = (a) => { let x = a % 360; if (x < 0) x += 360; return x }
  const normDelta = (a0, a1) => {
    const raw = a1 - a0
    let d = ((raw % 360) + 360) % 360
    if (d > 180) d -= 360
    return d
  }
  const startAngle = normDeg(toDeg(Math.atan2(-(arc.startY - arc.centerY), arc.startX - arc.centerX)))
  const endAngle = normDeg(toDeg(Math.atan2(-(arc.endY - arc.centerY), arc.endX - arc.centerX)))
  const delta = normDelta(startAngle, endAngle)
  const sweepFlag = delta > 0 ? 1 : 0
  // mid at 2/3 of angular delta
  const midAngle = startAngle + delta * (2 / 3)
  const rx = arc.radius
  const ry = arc.radius
  // world coords (y up), convert to screen by negating y in path
  const x1 = arc.startX
  const y1s = -arc.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 = arc.endX
  const y2s = -arc.endY
  // Both segments are <= 180 degrees, safe to use largeArcFlag=0
  const largeArcFlag = 0
  return `M ${x1},${y1s} A ${rx},${ry} 0 ${largeArcFlag},${sweepFlag} ${xms},${yms} A ${rx},${ry} 0 ${largeArcFlag},${sweepFlag} ${x2},${y2s}`
}

const getEdgePath = (edge) => {
  if (!edge) return ''
  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
  const x1 = s.x
  const y1s = -s.y
  const xms = xm
  const yms = -ym
  const x2 = t.x
  const y2s = -t.y
  return `M ${x1},${y1s} L ${xms},${yms} L ${x2},${y2s}`
}

// 线段颜色和箭头颜色保持一致
const getEdgeStroke = (edge) => {
  if (mode.value === 'arc' && arcMode.value.step === 1 && arcMode.value.firstEdgeId === edge.id) return '#f59f00'
  if (mode.value === 'arc' && arcMode.value.step === 1 && arcHoverEdgeId.value === edge.id) return '#0d6efd'
  // 非选中时黑色线;选中时根据倒车与否变化
  if (!isEdgeSelected(edge.id)) return '#000000'
  if (edge.isReverse) return '#dc3545'
  return '#0d6efd'
}

const getEdgeMarker = (edge) => {
  if (mode.value === 'arc' && arcMode.value.step === 1 && arcMode.value.firstEdgeId === edge.id) return 'url(#arrow-orange)'
  if (mode.value === 'arc' && arcMode.value.step === 1 && arcHoverEdgeId.value === edge.id) return 'url(#arrow-blue)'
  // 非选中时统一黑色箭头;选中时根据倒车与否变化
  if (!isEdgeSelected(edge.id)) return 'url(#arrow-black)'
  if (edge.isReverse) return 'url(#arrow-red)'
  return 'url(#arrow-blue)'
}

// 弧线颜色与箭头
const getArcStroke = (arc) => {
  // 非选中时黑色线;选中时根据倒车与否变化
  if (!isArcSelected(arc.id)) return '#000000'
  if (arc.isReverse) return '#dc3545'
  return '#0d6efd'
}

const getArcMarker = (arc) => {
  // 非选中时黑色箭头;选中时根据倒车与否变化
  if (!isArcSelected(arc.id)) return 'url(#arrow-black)'
  if (arc.isReverse) return 'url(#arrow-red)'
  return 'url(#arrow-blue)'
}

const createArcBetweenSelectedEdges = () => {
  const e1 = edges.value.find(e => e.id === arcMode.value.firstEdgeId)
  const e2 = edges.value.find(e => e.id === arcMode.value.secondEdgeId)
  if (!e1 || !e2) return
  const arcId = getNextEdgeId()
  const radius = Math.min(Math.max(0.0001, arcRadiusInput.value || 0.0001), arcMaxRadius.value || 1e9)
  const arc = calculateArcBetweenEdges(e1, e2, radius, arcId)
  if (!arc) return
  pushHistorySnapshot()
  // 在两条选中边的切点处创建/复用节点,并对边进行分割
  const startNodeCode = ensureNodeAtPointAndSplitEdge(e1, arc.startX, arc.startY)
  const endNodeCode = ensureNodeAtPointAndSplitEdge(e2, arc.endX, arc.endY)
  // 绑定圆弧端点节点编号
  arc.sourceCode = startNodeCode
  arc.targetCode = endNodeCode
  arc.code = formatEdgeCode(startNodeCode, endNodeCode, false)
  // 记录圆弧(融合到 edges 列表),避免重复编码
  if (!codeExists(arc.code)) {
    edges.value.push({ ...arc, curve: true, isReverse: false, name: arc.name ?? '' })
  }
  // 清空边选择,避免引用已被分割的旧边
  selectedEdgeId.value = null
  selectedEdgeIds.value = new Set()
  syncToCurrentMap()
}

const prepareArcRadiusPanel = () => {
  // 计算最大半径(通过二分搜索)
  const e1 = edges.value.find(e => e.id === arcMode.value.firstEdgeId)
  const e2 = edges.value.find(e => e.id === arcMode.value.secondEdgeId)
  if (!e1 || !e2) return
  const arcId = `probe_${Date.now()}`
  let lo = 0.0001, hi = 100000, best = 0
  for (let i = 0; i < 40; i++) {
    const mid = (lo + hi) / 2
    const res = calculateArcBetweenEdges(e1, e2, mid, arcId)
    if (res) { best = mid; lo = mid } else { hi = mid }
  }
  arcMaxRadius.value = best
  arcRadiusInput.value = Math.max(0.0001, Number(best.toFixed(3)))
  showArcRadiusPanel.value = true
}

const cancelArcRadiusPanel = () => {
  showArcRadiusPanel.value = false
  arcMode.value = { step: 0, firstEdgeId: null, secondEdgeId: null }
  arcHoverEdgeId.value = null
}

const confirmArcRadius = () => {
  createArcBetweenSelectedEdges()
  showArcRadiusPanel.value = false
  arcMode.value = { step: 0, firstEdgeId: null, secondEdgeId: null }
  mode.value = 'select'
  arcHoverEdgeId.value = null
}

// ======== 批量切线圆弧 ========
const openBatchArcPanel = () => {
  if (selectedStraightEdgeCount.value < 2) return
  batchArcRadiusInput.value = Math.max(0.0001, Number((batchArcRadiusInput.value || 1).toFixed(3)))
  batchArcPanelVisible.value = true
}

const cancelBatchArcPanel = () => {
  batchArcPanelVisible.value = false
}

const confirmBatchArcRadius = () => {
  const r = Math.max(0.0001, batchArcRadiusInput.value || 0.0001)
  generateBatchTangentialArcs(r)
  batchArcPanelVisible.value = false
}

// ======== 批量编辑节点 ========
const openBatchEditPanel = () => {
  if (selectedNodeIds.value.size < 2) return
  batchNodeTypeChoice.value = 'NO_CHANGE'
  batchNodeOrientationChoice.value = 'NO_CHANGE'
  batchNodeAllowRotateChoice.value = 'NO_CHANGE'
  batchNodeAllowReverseEntryChoice.value = 'NO_CHANGE'
  batchEditPanelVisible.value = true
}

const cancelBatchEditPanel = () => {
  batchEditPanelVisible.value = false
}

const confirmBatchEdit = () => {
  const applyType = batchNodeTypeChoice.value !== 'NO_CHANGE'
  const applyOri = batchNodeOrientationChoice.value !== 'NO_CHANGE'
  const applyRotate = batchNodeAllowRotateChoice.value !== 'NO_CHANGE'
  const applyReverse = batchNodeAllowReverseEntryChoice.value !== 'NO_CHANGE'
  if (!applyType && !applyOri && !applyRotate && !applyReverse) {
    batchEditPanelVisible.value = false
    return
  }
  pushHistorySnapshot()
  const ids = Array.from(selectedNodeIds.value || [])
  for (const id of ids) {
    const n = getNodeById(id)
    if (!n) continue
    ensureNodeDefaults(n)
    if (applyType) {
      n.type = batchNodeTypeChoice.value
    }
    if (applyOri) {
      if (batchNodeOrientationChoice.value === 'NULL') {
        n.orientation = null
      } else {
        const num = Number(batchNodeOrientationChoice.value)
        if (!Number.isNaN(num)) n.orientation = num
      }
    }
    if (applyRotate) {
      n.allowRotate = (batchNodeAllowRotateChoice.value === 'TRUE')
    }
    if (applyReverse) {
      n.allowReverseEntry = (batchNodeAllowReverseEntryChoice.value === 'TRUE')
    }
  }
  syncToCurrentMap()
  batchEditPanelVisible.value = false
}

// ======== 复制并平移 ========
const openCopyPanel = () => {
  const hasNodeSel = (selectedNodeIds.value && selectedNodeIds.value.size > 0) || (selectedNodeId.value != null)
  if (!hasNodeSel) return
  copyOffsetX.value = 0
  copyOffsetY.value = 0
  copyPanelVisible.value = true
}

const cancelCopyPanel = () => {
  copyPanelVisible.value = false
}

const confirmCopy = () => {
  const dx = Number(copyOffsetX.value) || 0
  const dy = Number(copyOffsetY.value) || 0
  // 禁止在 (0,0) 偏移时复制
  if (dx === 0 && dy === 0) {
    try { proxy?.$swal?.fire(t('maps.editor.messages.offsetCannotBeZero'), '', 'warning') } catch {}
    return
  }
  // 收集选中节点(包含单选)
  const nodeIdSet = new Set(selectedNodeIds.value || [])
  if (selectedNodeId.value != null) nodeIdSet.add(selectedNodeId.value)
  if (nodeIdSet.size === 0) { copyPanelVisible.value = false; return }

  // 构建选中节点、以及旧code集合
  const selectedNodes = Array.from(nodeIdSet).map(id => getNodeById(id)).filter(Boolean)
  const selectedNodeCodeSet = new Set(selectedNodes.map(n => n.code).filter(Boolean))

  // 维护一个局部已用code集合,避免新节点编码冲突
  const usedCodes = getAllNodeCodesSet()
  const generateUniqueNodeCodeLocal = (prefix = 'N') => {
    const regex = new RegExp(`^${prefix}(\\d+)$`)
    let maxNum = 0
    for (const c of usedCodes) {
      const m = c.match(regex)
      if (m) {
        const num = parseInt(m[1], 10)
        if (!Number.isNaN(num) && num > maxNum) maxNum = num
      }
    }
    let candidateNum = maxNum + 1
    let candidate = `${prefix}${candidateNum}`
    while (usedCodes.has(candidate)) {
      candidateNum += 1
      candidate = `${prefix}${candidateNum}`
    }
    usedCodes.add(candidate)
    return candidate
  }

  pushHistorySnapshot()

  // 1) 复制节点(ID新、编码新、坐标偏移,属性保持)
  const oldCodeToNewCode = new Map()
  const newNodeIds = []
  for (const src of selectedNodes) {
    const newId = getNextNodeId()
    const newCode = generateUniqueNodeCodeLocal('N')
    const dst = {
      id: newId,
      x: Math.round((src.x || 0) + dx),
      y: Math.round((src.y || 0) + dy),
      code: newCode,
      name: src.name ?? '',
      type: src.type ?? 1,
      orientation: src.orientation ?? null,
      allowRotate: !!src.allowRotate,
      allowReverseEntry: !!src.allowReverseEntry,
      maxCoordinateOffset: src.maxCoordinateOffset ?? 0.5,
      maxAngleDeviation: src.maxAngleDeviation ?? 15,
      maxSpeed: src.maxSpeed ?? 1.2,
    }
    ensureNodeDefaults(dst)
    nodes.value.push(dst)
    oldCodeToNewCode.set(src.code, newCode)
    newNodeIds.push(newId)
  }

  // 2) 复制直线边:仅当两端节点均在选中节点集合内
  const edgeIdSet = new Set(selectedEdgeIds.value || [])
  if (selectedEdgeId.value != null) edgeIdSet.add(selectedEdgeId.value)
  const newEdgeIds = []
  for (const eid of edgeIdSet) {
    const e = (edges.value || []).find(x => x.id === eid && !x.curve)
    if (!e) continue
    const a = e.sourceCode
    const b = e.targetCode
    if (!selectedNodeCodeSet.has(a) || !selectedNodeCodeSet.has(b)) continue
    const na = oldCodeToNewCode.get(a)
    const nb = oldCodeToNewCode.get(b)
    if (!na || !nb) continue
    const attrs = { name: e.name ?? '', isReverse: !!e.isReverse }
    const newCode = formatEdgeCode(na, nb, !!attrs.isReverse)
    if (edgeExists(na, nb, !!attrs.isReverse) || codeExists(newCode)) continue
    const ne = { id: getNextEdgeId(), sourceCode: na, targetCode: nb, code: newCode, isReverse: !!attrs.isReverse, curve: false, isArc: false, name: attrs.name }
    edges.value.push(ne)
    newEdgeIds.push(ne.id)
  }

  // 3) 复制弧线:仅当两端节点均在选中节点集合内;几何整体平移
  const arcIdSet = new Set(selectedArcIds.value || [])
  if (selectedArcId.value != null) arcIdSet.add(selectedArcId.value)
  for (const aid of arcIdSet) {
    const a = (edges.value || []).find(x => x.id === aid && x.curve)
    if (!a) continue
    const s = a.sourceCode
    const t = a.targetCode
    if (!selectedNodeCodeSet.has(s) || !selectedNodeCodeSet.has(t)) continue
    const ns = oldCodeToNewCode.get(s)
    const nt = oldCodeToNewCode.get(t)
    if (!ns || !nt) continue
    const newCode = formatEdgeCode(ns, nt, !!a.isReverse)
    if (codeExists(newCode)) continue
    const ar = {
      id: getNextEdgeId(),
      curve: true,
      isReverse: !!a.isReverse,
      radius: a.radius,
      centerX: (a.centerX ?? 0) + dx,
      centerY: (a.centerY ?? 0) + dy,
      startX: (a.startX ?? 0) + dx,
      startY: (a.startY ?? 0) + dy,
      endX: (a.endX ?? 0) + dx,
      endY: (a.endY ?? 0) + dy,
      sourceCode: ns,
      targetCode: nt,
      code: newCode,
      name: a.name ?? ''
    }
    edges.value.push(ar)
    newEdgeIds.push(ar.id)
  }

  // 4) 更新选择为新复制的内容
  selectedNodeIds.value = new Set(newNodeIds)
  selectedEdgeIds.value = new Set(newEdgeIds)
  selectedArcIds.value = new Set(newEdgeIds.filter(id => {
    const ed = edges.value.find(e => e.id === id)
    return !!(ed && ed.curve)
  }))
  selectedNodeId.value = null
  selectedEdgeId.value = null
  selectedArcId.value = null

  syncToCurrentMap()
  copyPanelVisible.value = false
}

// ======== 平移 ========
const openMovePanel = () => {
  const hasNodeSel = (selectedNodeIds.value && selectedNodeIds.value.size > 0) || (selectedNodeId.value != null)
  if (!hasNodeSel) return
  moveOffsetX.value = 0
  moveOffsetY.value = 0
  movePanelVisible.value = true
}

const cancelMovePanel = () => {
  movePanelVisible.value = false
}

const confirmMove = () => {
  const dx = Number(moveOffsetX.value) || 0
  const dy = Number(moveOffsetY.value) || 0
  // 禁止在 (0,0) 偏移时平移
  if (dx === 0 && dy === 0) {
    return
  }
  // 收集选中节点(包含单选)
  const nodeIdSet = new Set(selectedNodeIds.value || [])
  if (selectedNodeId.value != null) nodeIdSet.add(selectedNodeId.value)
  if (nodeIdSet.size === 0) { movePanelVisible.value = false; return }

  pushHistorySnapshot()

  // 1) 平移选中的节点
  const selectedNodes = Array.from(nodeIdSet).map(id => getNodeById(id)).filter(Boolean)
  const selectedNodeCodeSet = new Set(selectedNodes.map(n => n.code).filter(Boolean))
  
  for (const node of selectedNodes) {
    node.x = Math.round((node.x || 0) + dx)
    node.y = Math.round((node.y || 0) + dy)
  }

  // 2) 平移弧线:仅当两端节点均在选中节点集合内时才平移几何坐标
  const arcIdSet = new Set(selectedArcIds.value || [])
  if (selectedArcId.value != null) arcIdSet.add(selectedArcId.value)
  for (const aid of arcIdSet) {
    const a = (edges.value || []).find(x => x.id === aid && x.curve)
    if (!a) continue
    const s = a.sourceCode
    const t = a.targetCode
    // 只有当弧线的两端节点都被选中时,才平移弧线的几何坐标
    if (selectedNodeCodeSet.has(s) && selectedNodeCodeSet.has(t)) {
      a.centerX = (a.centerX ?? 0) + dx
      a.centerY = (a.centerY ?? 0) + dy
      a.startX = (a.startX ?? 0) + dx
      a.startY = (a.startY ?? 0) + dy
      a.endX = (a.endX ?? 0) + dx
      a.endY = (a.endY ?? 0) + dy
    }
  }

  syncToCurrentMap()
  movePanelVisible.value = false
}

// ======== 节点创建与边分割 ========
const EPS_PT = 1e-6

const findExistingNodeAt = (x, y, eps = EPS_PT) => {
  for (const n of nodes.value) {
    if (Math.hypot(n.x - x, n.y - y) <= eps) return n
  }
  return null
}

const createNodeAt = (x, y, namePrefix = 'N') => {
  const newId = getNextNodeId()
  const newNode = { id: newId, x, y, code: generateUniqueNodeCode(namePrefix), orientation: null, allowRotate: false, maxCoordinateOffset: 0.5, maxAngleDeviation: 15, maxSpeed: 1.2 }
  ensureNodeDefaults(newNode)
  nodes.value.push(newNode)
  return newNode
}

const ensureNodeAtPointAndSplitEdge = (edge, x, y) => {
  // 若切点接近端点,直接复用端点
  const src = getNodeByCode(edge.sourceCode)
  const tgt = getNodeByCode(edge.targetCode)
  if (!src || !tgt) return null
  if (Math.hypot(src.x - x, src.y - y) <= EPS_PT) return src.code
  if (Math.hypot(tgt.x - x, tgt.y - y) <= EPS_PT) return tgt.code

  // 若已存在同位置节点,复用之;否则创建
  const existing = findExistingNodeAt(x, y)
  const node = existing ?? createNodeAt(x, y)

  // 分割该边(若点在线段上且不在端点)
  if (isPointOnLineSegment({ x: src.x, y: src.y }, { x: tgt.x, y: tgt.y }, { x, y }, 1e-4)) {
    splitEdgeAtInternalPoint(edge, node.code)
  }
  return node.code
}

const cloneEdgeAttrs = (edge) => {
  const out = {}
  if ('name' in edge) out.name = edge.name
  if ('isReverse' in edge) out.isReverse = edge.isReverse
  return out
}

const splitEdgeAtInternalPoint = (edge, newNodeCode) => {
  // 防御:确认newNode落在该边内部(非端点)
  if (newNodeCode === edge.sourceCode || newNodeCode === edge.targetCode) return
  const src = getNodeByCode(edge.sourceCode)
  const tgt = getNodeByCode(edge.targetCode)
  const mid = getNodeByCode(newNodeCode)
  if (!src || !tgt || !mid) return
  // 再次确认在线段上
  if (!isPointOnLineSegment({ x: src.x, y: src.y }, { x: tgt.x, y: tgt.y }, { x: mid.x, y: mid.y }, 1e-4)) return

  // 移除原边,添加两条新边
  const idx = edges.value.findIndex(e => e.id === edge.id)
  if (idx === -1) return
  const attrs = cloneEdgeAttrs(edge)
  const newEdge1 = { 
    id: getNextEdgeId(), 
    sourceCode: edge.sourceCode, 
    targetCode: newNodeCode, 
    code: formatEdgeCode(edge.sourceCode, newNodeCode, !!attrs.isReverse),
    ...attrs 
  }
  const newEdge2 = { 
    id: getNextEdgeId(), 
    sourceCode: newNodeCode, 
    targetCode: edge.targetCode, 
    code: formatEdgeCode(newNodeCode, edge.targetCode, !!attrs.isReverse),
    ...attrs 
  }
  // 替换
  edges.value.splice(idx, 1)
  if (!edgeExists(newEdge1.sourceCode, newEdge1.targetCode, !!newEdge1.isReverse) && !codeExists(newEdge1.code)) {
    edges.value.push(newEdge1)
  }
  if (!edgeExists(newEdge2.sourceCode, newEdge2.targetCode, !!newEdge2.isReverse) && !codeExists(newEdge2.code)) {
    edges.value.push(newEdge2)
  }
}

// 在当前边集合中查找包含点(x,y)的直线边
const findStraightEdgeContainingPoint = (x, y, eps = 1e-4) => {
  for (const e of (edges.value || [])) {
    if (e.curve) continue
    const s = getNodeByCode(e.sourceCode)
    const t = getNodeByCode(e.targetCode)
    if (!s || !t) continue
    if (isPointOnLineSegment({ x: s.x, y: s.y }, { x: t.x, y: t.y }, { x, y }, eps)) {
      // 排除端点
      if (Math.hypot(s.x - x, s.y - y) <= eps) continue
      if (Math.hypot(t.x - x, t.y - y) <= eps) continue
      return e
    }
  }
  return null
}

// 在任意包含该点的直线边处确保节点存在,并进行分割,返回节点code
const ensureNodeAtPointAndSplitAnyEdge = (x, y) => {
  const existing = findExistingNodeAt(x, y)
  if (existing) return existing.code
  const node = createNodeAt(x, y)
  const host = findStraightEdgeContainingPoint(x, y)
  if (host) splitEdgeAtInternalPoint(host, node.code)
  return node.code
}

// 近似判断是否已存在相同几何弧(起止点+方向)
const arcGeometryExists = (sx, sy, ex, ey, isRev, eps = 1e-6) => {
  for (const a of (edges.value || []).filter(e => e.curve)) {
    const ok = Math.abs(a.startX - sx) <= eps && Math.abs(a.startY - sy) <= eps &&
               Math.abs(a.endX - ex) <= eps && Math.abs(a.endY - ey) <= eps &&
               (!!a.isReverse === !!isRev)
    if (ok) return true
  }
  return false
}

// 计算两条边在四个象限(方向组合)下、指定半径的所有可行切线圆弧
const calculateArcsAllQuadrantsBetweenEdges = (edge1, edge2, radius, idStart) => {
  const n11 = getNodeByCode(edge1.sourceCode)
  const n12 = getNodeByCode(edge1.targetCode)
  const n21 = getNodeByCode(edge2.sourceCode)
  const n22 = getNodeByCode(edge2.targetCode)
  if (!n11 || !n12 || !n21 || !n22) return []

  const p1a = { x: n11.x, y: n11.y }
  const p1b = { x: n12.x, y: n12.y }
  const p2a = { x: n21.x, y: n21.y }
  const p2b = { x: n22.x, y: n22.y }

  const ip = findLineIntersectionInfinite(p1a, p1b, p2a, p2b)
  if (!ip) return []

  const len1 = Math.hypot(p1b.x - p1a.x, p1b.y - p1a.y)
  const len2 = Math.hypot(p2b.x - p2a.x, p2b.y - p2a.y)
  if (len1 < 1e-12 || len2 < 1e-12) return []

  const u1Base = { x: (p1b.x - p1a.x) / len1, y: (p1b.y - p1a.y) / len1 }
  const u2Base = { x: (p2b.x - p2a.x) / len2, y: (p2b.y - p2a.y) / len2 }

  const variants = []
  const flips = [1, -1]
  for (const f1 of flips) {
    for (const f2 of flips) {
      const u1 = { x: u1Base.x * f1, y: u1Base.y * f1 }
      const u2 = { x: u2Base.x * f2, y: u2Base.y * f2 }
      const dotRaw = u1.x * u2.x + u1.y * u2.y
      const dot = Math.max(-1, Math.min(1, dotRaw))
      const theta = Math.acos(dot)
      if (!(theta > 1e-6 && theta < Math.PI - 1e-6)) continue
      const sinHalf = Math.sin(theta / 2)
      const cosHalf = Math.cos(theta / 2)
      if (Math.abs(sinHalf) < 1e-12) continue
      const d = radius * (cosHalf / sinHalf)
      // 最大可行d(基于各段在该方向上的可用正向长度)
      const proj = (p, u) => (p.x - ip.x) * u.x + (p.y - ip.y) * u.y
      const sPosMax1 = Math.max(0, Math.max(proj(p1a, u1), proj(p1b, u1)))
      const sPosMax2 = Math.max(0, Math.max(proj(p2a, u2), proj(p2b, u2)))
      if (!(d > 0 && d <= sPosMax1 + 1e-8 && d <= sPosMax2 + 1e-8)) continue
      // 角平分线方向
      const bis = { x: u1.x + u2.x, y: u1.y + u2.y }
      const bisLen = Math.hypot(bis.x, bis.y)
      if (bisLen < 1e-12) continue
      const bisUnit = { x: bis.x / bisLen, y: bis.y / bisLen }
      const h = radius / sinHalf
      const centerX = ip.x + bisUnit.x * h
      const centerY = ip.y + bisUnit.y * h
      const startPoint = { x: ip.x + u1.x * d, y: ip.y + u1.y * d }
      const endPoint = { x: ip.x + u2.x * d, y: ip.y + u2.y * d }
      if (!isPointOnLineSegment(p1a, p1b, startPoint, 1e-6)) continue
      if (!isPointOnLineSegment(p2a, p2b, endPoint, 1e-6)) continue
      variants.push({
        id: idStart,
        radius,
        centerX,
        centerY,
        startX: startPoint.x,
        startY: startPoint.y,
        endX: endPoint.x,
        endY: endPoint.y
      })
    }
  }
  return variants
}

const generateBatchTangentialArcs = (radius) => {
  pushHistorySnapshot()
  const ids = new Set(selectedEdgeIds.value)
  if (selectedEdgeId.value != null) ids.add(selectedEdgeId.value)
  const list = Array.from(ids)
    .map(id => edges.value.find(e => e.id === id))
    .filter(e => e && !e.curve)
  if (list.length < 2) return

  // 逐对尝试四象限圆弧
  for (let i = 0; i < list.length; i++) {
    for (let j = i + 1; j < list.length; j++) {
      const e1 = list[i]
      const e2 = list[j]
      const arcs = calculateArcsAllQuadrantsBetweenEdges(e1, e2, radius, getNextEdgeId())
      for (const a of arcs) {
        // 去重(几何级)
        if (arcGeometryExists(a.startX, a.startY, a.endX, a.endY, false)) continue
        // 在切点创建/复用节点,并分割承载的直线边
        const startCode = ensureNodeAtPointAndSplitAnyEdge(a.startX, a.startY)
        const endCode = ensureNodeAtPointAndSplitAnyEdge(a.endX, a.endY)
        // 生成业务编码并落库
        const code = formatEdgeCode(startCode, endCode, false)
        if (codeExists(code)) continue
        edges.value.push({
          id: getNextEdgeId(),
          curve: true,
          isReverse: false,
          radius: a.radius,
          centerX: a.centerX,
          centerY: a.centerY,
          startX: a.startX,
          startY: a.startY,
          endX: a.endX,
          endY: a.endY,
          sourceCode: startCode,
          targetCode: endCode,
          code,
          name: ''
        })
      }
    }
  }
  syncToCurrentMap()
}

// ======== 选中边批量生成四向连线(去重) ========
const ensureEdgeDefaultsForGen = (edge) => {
  if (edge == null) return
  if (edge.isReverse === undefined) edge.isReverse = false
  if (edge.isArc === undefined) edge.isArc = false
}

const edgeExists = (sourceCode, targetCode, isReverse) => {
  return edges.value.some(e => e.sourceCode === sourceCode && e.targetCode === targetCode && !!e.isReverse === !!isReverse && !e.curve)
}

const codeExists = (code) => {
  if (!code) return false
  return (edges.value || []).some(e => e.code === code)
}

const generateFourVariantsForSelectedEdges = () => {
  pushHistorySnapshot()
  const ids = new Set(selectedEdgeIds.value)
  if (selectedEdgeId.value != null) ids.add(selectedEdgeId.value)
  const arcIds = new Set(selectedArcIds.value)
  if (selectedArcId.value != null) arcIds.add(selectedArcId.value)
  if (ids.size === 0 && arcIds.size === 0) return
  for (const id of ids) {
    const base = edges.value.find(e => e.id === id)
    if (!base) continue
    // 若是弧线,跳过直线四向生成
    if (base.curve) continue
    ensureEdgeDefaultsForGen(base)
    const a = base.sourceCode
    const b = base.targetCode
    const nodeA = getNodeByCode(a)
    const nodeB = getNodeByCode(b)
    const nameAB = `${nodeA?.code ?? a}-${nodeB?.code ?? b}`
    const nameBA = `${nodeB?.code ?? b}-${nodeA?.code ?? a}`
    const variants = [
      { s: a, t: b, r: true,  name: `${nameAB} 倒车` },
      { s: a, t: b, r: false, name: `${nameAB} 非倒车` },
      { s: b, t: a, r: true,  name: `${nameBA} 倒车` },
      { s: b, t: a, r: false, name: `${nameBA} 非倒车` },
    ]
    for (const v of variants) {
      const edgeCode = formatEdgeCode(v.s, v.t, v.r)
      if (edgeExists(v.s, v.t, v.r) || codeExists(edgeCode)) continue
      const e = { id: getNextEdgeId(), sourceCode: v.s, targetCode: v.t, code: edgeCode, isReverse: v.r, curve: false, isArc: false, name: v.name }
      edges.value.push(e)
    }
  }
  // 扩展:对选中的弧线,生成四向圆弧(避免重复)
  const eps = 1e-6
  const floatsEq = (a, b) => Math.abs(a - b) <= eps
  const arcExists = (sx, sy, ex, ey, isRev) => {
    return (edges.value || []).some(ar => ar.curve &&
      floatsEq(ar.startX, sx) && floatsEq(ar.startY, sy) &&
      floatsEq(ar.endX, ex) && floatsEq(ar.endY, ey) &&
      (!!ar.isReverse === !!isRev)
    )
  }
  const reverseArcGeom = (a) => ({
    radius: a.radius,
    centerX: a.centerX,
    centerY: a.centerY,
    startX: a.endX,
    startY: a.endY,
    endX: a.startX,
    endY: a.startY,
  })
  for (const aid of arcIds) {
    const a = (edges.value || []).find(x => x.id === aid && x.curve)
    if (!a) continue
    // 命名:尽量用端点节点标签
    const sNode = findExistingNodeAt(a.startX, a.startY, 1e-4)
    const eNode = findExistingNodeAt(a.endX, a.endY, 1e-4)
    const sName = sNode?.code ?? 'S'
    const eName = eNode?.code ?? 'E'
    const nameAB = `${sName}-${eName}`
    const nameBA = `${eName}-${sName}`
    // AB: 倒车/非倒车
    const abFwd = { radius: a.radius, centerX: a.centerX, centerY: a.centerY, startX: a.startX, startY: a.startY, endX: a.endX, endY: a.endY, sourceCode: sNode?.code ?? null, targetCode: eNode?.code ?? null, code: formatEdgeCode(sName, eName, false), isReverse: false, name: `${nameAB} 非倒车` }
    const abRev = { ...abFwd, isReverse: true, code: formatEdgeCode(sName, eName, true), name: `${nameAB} 倒车` }
    // BA: 通过几何反向得到
    const revGeom = reverseArcGeom(a)
    const baFwd = { ...revGeom, sourceCode: eNode?.code ?? null, targetCode: sNode?.code ?? null, code: formatEdgeCode(eName, sName, false), isReverse: false, name: `${nameBA} 非倒车` }
    const baRev = { ...revGeom, sourceCode: eNode?.code ?? null, targetCode: sNode?.code ?? null, code: formatEdgeCode(eName, sName, true), isReverse: true, name: `${nameBA} 倒车` }
    const list = [abRev, abFwd, baRev, baFwd]
    for (const ar of list) {
      if (codeExists(ar.code)) continue
      if (!arcExists(ar.startX, ar.startY, ar.endX, ar.endY, ar.isReverse)) {
        edges.value.push({ ...ar, id: getNextEdgeId(), curve: true })
      }
    }
  }
  syncToCurrentMap()
}
</script>

<style scoped>
.map-editor-wrapper {
  height: calc(100vh - 135px);
  width: 100%;
  overflow: hidden;
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.map-editor-card {
  height: 100%;
  display: flex;
  flex-direction: column;
  margin: 0;
  padding: 0;
}

.map-editor-card :deep(.va-card__content) {
  padding: 0px 20px 20px 20px;
  height: 100%;
}

.map-editor-content {
  display: flex;
  height: 100%;
  gap: 0;
  padding: 0;
  overflow: hidden;
}

.config-panel-wrapper {
  width: 15%;
  height: 100%;
  border-right: 1px solid var(--va-background-border);
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.config-panel-inner {
  padding: 1rem;
  overflow-y: auto;
  height: 100%;
}

.panel-title {
  color: var(--va-primary);
  margin-bottom: 1rem;
  font-weight: 600;
}

.panel-actions-top {
  display: flex;
  gap: 0.5rem;
  margin-bottom: 1rem;
  padding-bottom: 1rem;
  border-bottom: 1px solid var(--va-background-border);
}

.config-form {
  display: flex;
  flex-direction: column;
}

.preview-panel-wrapper {
  width: 85%;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.map-preview {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 1rem;
  gap: 1rem;
}

.toolbar-container {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
  align-items: center;
}

.toolbar-group {
  flex-shrink: 0;
}

.toolbar-input {
  display: inline-flex;
}

.toolbar-input-inline {
  display: inline-flex;
}

.toolbar-group.d-flex {
  gap: 0.5rem;
}

.align-items-center {
  align-items: center;
}

.stats-text {
  color: var(--va-text-secondary);
  font-size: 0.875rem;
  margin-left: auto;
}

.topo-canvas {
  flex: 1;
  display: flex;
  min-height: 0;
  background: #ffffff;
  border: 1px solid var(--va-background-border);
  border-radius: 4px;
  position: relative;
  user-select: none;
}

.topo-canvas svg {
  display: block;
  width: 100%;
  height: 100%;
}

.cursor-default { cursor: default; }
.cursor-crosshair { cursor: crosshair; }
.cursor-grab { cursor: grab; }
.cursor-alias { cursor: alias; }

.snap-guide-line {
  stroke: var(--va-primary);
  stroke-width: 20;
  stroke-dasharray: 20 15;
  pointer-events: none;
}

.marquee-rect {
  fill: transparent;
  stroke: var(--va-primary);
  stroke-width: 1;
  shape-rendering: crispEdges;
}

.mouse-hint {
  position: absolute;
  background: rgba(33, 37, 41, 0.9);
  color: #fff;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  pointer-events: none;
  z-index: 10;
  white-space: nowrap;
}

.floating-panel {
  position: absolute;
  right: 16px;
  top: 16px;
  width: 280px;
  z-index: 20;
  box-shadow: 0 2px 8px rgba(0,0,0,0.15);
}

.floating-panel-enhanced {
  width: 320px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15), 0 2px 8px rgba(0, 0, 0, 0.1);
  border-radius: 12px;
  overflow: hidden;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.panel-title-enhanced {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 16px 20px;
  background: linear-gradient(135deg, var(--va-primary) 0%, var(--va-primary-dark) 100%);
  color: white;
  font-weight: 600;
  font-size: 16px;
  margin: 0;
}

.panel-icon {
  color: white;
  opacity: 0.9;
}

.panel-content-enhanced {
  padding: 50px 50px;
}

.panel-content-enhanced .va-chip {
  display: inline-flex;
}

.text-secondary {
  color: var(--va-text-secondary);
  font-size: 0.875rem;
}

.d-flex {
  display: flex;
}

.justify-content-end {
  justify-content: flex-end;
}

.gap-2 {
  gap: 0.5rem;
}

.mb-2 {
  margin-bottom: 0.5rem;
}

.mb-3 {
  margin-bottom: 1rem;
}

.bg-settings-content {
  padding: 0.5rem 0;
}

.small {
  font-size: 0.875rem;
}

.loading-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 1rem;
  padding: 1rem 0;
}

.loading-text {
  color: var(--va-text-primary);
  font-size: 0.875rem;
  text-align: center;
}
</style>

<style>
html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}
.no-scroll {
  overflow: hidden !important;
}
</style>