SmartLight.vue 86.9 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
<template>
  <div class="smart-light-page">
    <!-- 第一行:状态Tab + 搜索 -->
    <div class="top-toolbar">
      <div class="status-tabs">
        <div 
          v-for="tab in statusTabs" 
          :key="tab.key"
          :class="['status-tab', { active: currentStatus === tab.key }]"
          @click="currentStatus = tab.key"
        >
          {{ tab.label }}
        </div>
      </div>
    </div>

    <!-- 筛选栏(仅实时状态显示) -->
    <div v-if="currentStatus === 'realtime'" class="filter-bar">
      <el-input
        v-model="searchKeyword"
        placeholder="输入设备名称搜索"
        clearable
        size="default"
        style="width: 220px; margin-right: 16px;"
        @keyup.enter="doSearch"
        @clear="doSearch"
      />
      <div class="filter-tags">
        <span :class="['tag-item', 'black', { active: !lampStateFilter }]" @click="filterByLampState('')"><i></i>全部{{ totalCounts.all }}台</span>
        <span :class="['tag-item', 'red', { active: lampStateFilter === '1' }]" @click="filterByLampState('1')"><i></i>红:{{ totalCounts.red }}台</span>
        <span :class="['tag-item', 'yellow', { active: lampStateFilter === '2' }]" @click="filterByLampState('2')"><i></i>黄:{{ totalCounts.yellow }}台</span>
        <span :class="['tag-item', 'green', { active: lampStateFilter === '3' }]" @click="filterByLampState('3')"><i></i>绿:{{ totalCounts.green }}台</span>
        <span :class="['tag-item', 'blue', { active: lampStateFilter === '4' }]" @click="filterByLampState('4')"><i></i>蓝:{{ totalCounts.blue }}台</span>
        <span :class="['tag-item', 'gray', { active: lampStateFilter === '0' }]" @click="filterByLampState('0')"><i></i>灭灯:{{ totalCounts.gray }}台</span>
      </div>
    </div>

    <!-- ========== 实时状态:设备卡片 ========== -->
    <div v-if="currentStatus === 'realtime'" class="tab-content">
      <!-- 设备卡片网格 -->
    <div class="device-grid" :class="{ 'grid-full': totalDevices > PAGE_SIZE || (pagedDevices.length >= PAGE_SIZE && totalDevices > PAGE_SIZE), 'grid-normal': pagedDevices.length <= 6 }">
      <div v-for="device in pagedDevices" :key="device.id" :class="['device-card', device.status]">
        <!-- 标题栏 -->
        <div class="card-header">
          <span class="device-name">{{ device.name }}</span>
        </div>
        
        <!-- 内容区:左侧状态灯 + 右侧信息 -->
        <div class="card-body">
          <div class="status-bar">
            <div :class="['bar-block', 'block-red', { active: device.status === 'red' }]"></div>
            <div :class="['bar-block', 'block-yellow', { active: device.status === 'yellow' }]"></div>
            <div :class="['bar-block', 'block-green', { active: device.status === 'green' }]"></div>
            <div :class="['bar-block', 'block-blue', { active: device.status === 'blue' }]"></div>
          </div>
          
          <div class="card-content">
            <div class="info-row">稼动率: <span class="value-highlight">{{ device.utilization }}%</span></div>
            <div class="info-row">{{ getLampLabel(device.status) }}: <span>{{ device.status === 'gray' ? '0分' : device.lightTime }}</span></div>
            
            <div class="digital-display">
              <span v-for="(digit, idx) in device.displayValue" :key="idx" class="digit">{{ digit }}</span>
            </div>
          </div>
        </div>

        <!-- 底部按钮 -->
        <div class="card-footer">
          <button class="action-btn" @click="openDetail('oee', device)">
            <el-icon><DataLine /></el-icon>OEE时序
          </button>
          <button class="action-btn" @click="openDetail('utilization', device)">
            <el-icon><Warning /></el-icon>稼动率
          </button>
          <button v-if="false" class="action-btn" @click="openDetail('setting', device)">
            <el-icon><Setting /></el-icon>设置
          </button>
          <button v-if="false" class="action-btn" @click="openDetail('count', device)">
            <el-icon><Document /></el-icon>计数明细
          </button>
        </div>
      </div>
    </div>

    <!-- 分页 -->
    <div v-if="totalDevices > 0" class="pagination-wrapper">
      <!-- 分页控件 -->
      <div class="pagination-controls">
        <!-- 每页条数选择 -->
        <select class="page-size-select" :value="PAGE_SIZE">
          <option value="12">12 条/页</option>
        </select>

        <!-- 导航按钮组 -->
        <button class="page-btn" :disabled="currentPage === 1" @click="currentPage = 1">«</button>
        <button class="page-btn" :disabled="currentPage === 1" @click="currentPage--"><</button>
        <template v-for="(p, i) in visiblePages" :key="i">
          <button v-if="typeof p === 'number'" :class="['page-btn', { active: currentPage === p }]" @click="currentPage = p">{{ p }}</button>
          <span v-else class="page-dots">{{ p }}</span>
        </template>
        <button class="page-btn" :disabled="currentPage === totalPages" @click="currentPage++">></button>
        <button class="page-btn" :disabled="currentPage === totalPages" @click="currentPage = totalPages">»</button>
      </div>
    </div>
    </div><!-- /tab-content realtime -->

    <!-- ========== 时序状态:时间轴甘特图 ========== -->
    <div v-else-if="currentStatus === 'timeseries'" class="tab-content timeseries-view">
      <div class="ts-toolbar">
        <span class="ts-label">查询方式:</span>
        <el-radio-group v-model="tsQueryMode" size="small">
          <el-radio-button value="day">日查询</el-radio-button>
        </el-radio-group>
        <el-date-picker
          v-model="tsDate"
          type="date"
          size="small"
          placeholder="选择日期"
          value-format="YYYY-MM-DD"
          :disabled-date="disabledDate"
          style="width: 160px; margin-left: 8px;"
        />
        <el-button type="primary" size="small" :loading="tsLoading" @click="fetchTimeSeriesData">查询</el-button>
      </div>

      <!-- Canvas 甘特图区域 -->
      <div class="ts-table-wrap" ref="ganttContainerRef" @wheel.prevent="onGanttWheel" @mousemove="onGanttMouseMove" @mouseleave="onGanttMouseLeave">
        <canvas ref="ganttCanvasRef" class="gantt-canvas"></canvas>
        <!-- Hover Tooltip -->
        <div v-if="ganttHoveredSeg" class="gantt-tooltip" :style="{ left: ganttTooltipPos.x + 'px', top: ganttTooltipPos.y + 'px' }">
          <div class="gtt-row"><span class="gtt-dot" :style="{ background: getLampColor(ganttHoveredSeg.lampState) }"></span>{{ getLampLabelName(ganttHoveredSeg.lampState) }}: {{ formatDuration(ganttHoveredSeg.duration) }}</div>
          <div class="gtt-sub">{{ formatTimeRange(ganttHoveredSeg.startTime, ganttHoveredSeg.endTime) }}</div>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <span>共 {{ tsTotal }} 条</span>
        <div class="pagination-controls" style="margin-left: auto;">
          <button class="page-btn" :disabled="tsPageNo === 1" @click="tsPageNo = 1; fetchTimeSeriesData()">«</button>
          <button class="page-btn" :disabled="tsPageNo === 1" @click="tsPageNo--; fetchTimeSeriesData()">&lt;</button>
          <template v-for="(p, i) in tsVisiblePages" :key="i">
            <button v-if="typeof p === 'number'" :class="['page-btn', { active: tsPageNo === p }]" @click="tsPageNo = p; fetchTimeSeriesData()">{{ p }}</button>
            <span v-else class="page-dots">{{ p }}</span>
          </template>
          <button class="page-btn" :disabled="tsPageNo >= tsTotalPages" @click="tsPageNo++; fetchTimeSeriesData()">&gt;</button>
          <button class="page-btn" :disabled="tsPageNo >= tsTotalPages" @click="tsPageNo = tsTotalPages; fetchTimeSeriesData()">»</button>
        </div>
      </div>
    </div>

    <!-- ========== 稼动率:多图表视图(Canvas) ========== -->
    <div v-else-if="currentStatus === 'utilization'" class="tab-content util-view" style="position:relative;">
      <div class="util-toolbar">
        <span class="util-label">查询方式:</span>
        <el-radio-group v-model="utilQueryMode" size="small">
          <el-radio-button value="day">日查询</el-radio-button>
          <el-radio-button value="week">周查询</el-radio-button>
          <el-radio-button value="month">月查询</el-radio-button>
        </el-radio-group>
        <el-date-picker
          v-if="utilQueryMode === 'day'"
          v-model="utilDate"
          type="date"
          placeholder="选择日期"
          size="small"
          value-format="YYYY-MM-DD"
          style="width:160px;margin-left:8px;"
        />
        <el-date-picker
          v-else-if="utilQueryMode === 'week'"
          v-model="utilWeekDate"
          type="date"
          :format="utilWeekDisplayFormat"
          placeholder="选择周"
          size="small"
          value-format="YYYY-MM-DD"
          :disabled-date="disableNonMonday"
          style="width:160px;margin-left:8px;"
        />
        <el-date-picker
          v-else-if="utilQueryMode === 'month'"
          v-model="utilMonthDate"
          type="month"
          placeholder="选择月份"
          size="small"
          value-format="YYYY-MM"
          style="width:140px;margin-left:8px;"
        />
        <el-button type="primary" size="small" :loading="utilLoading" @click="fetchUtilData">查询</el-button>
      </div>

      <!-- 上排:3个饼图 + 异常机台排名 -->
      <div class="util-top-charts">
        <!-- 总时长 饼图 -->
        <div class="pie-card">
          <div class="pie-title">总时长:</div>
          <canvas ref="utilPieTotalRef" class="util-canvas-pie"
                  @mousemove="onUtilPieMove('total', $event)" @mouseleave="onUtilPieLeave('total')"></canvas>
          <div v-if="utilLoading" class="util-loading-overlay"><div class="util-spinner"></div></div>
          <div class="pie-legend util-total-leg">
            <template v-for="(seg,i) in utilTotalSegments" :key="i">
              <span class="leg-item">
                <i class="dot" :style="{background: seg.color }"></i>{{ seg.label }}<br/>
              </span>
            </template>
          </div>
        </div>
        <!-- 稼动率 饼图 -->
        <div class="pie-card">
          <div class="pie-title">稼动率:</div>
          <canvas ref="utilPieRateRef" class="util-canvas-pie"
                  @mousemove="onUtilPieMove('rate', $event)" @mouseleave="onUtilPieLeave('rate')"></canvas>
          <div v-if="utilLoading" class="util-loading-overlay"><div class="util-spinner"></div></div>
          <div class="pie-legend center-leg">
            <span class="leg-item"><i class="dot g"></i>绿灯</span>
            <span class="leg-item"><i class="dot y"></i>黄灯</span>
            <span class="leg-item"><i class="dot r"></i>红灯</span>
          </div>
        </div>
        <!-- 当前机台运行状态 饼图 -->
        <div class="pie-card">
          <div class="pie-title">当前机台运行状态:</div>
          <canvas ref="utilPieStatusRef" class="util-canvas-pie"
                  @mousemove="onUtilPieMove('status', $event)" @mouseleave="onUtilPieLeave('status')"></canvas>
          <div v-if="utilLoading" class="util-loading-overlay"><div class="util-spinner"></div></div>
          <div class="pie-legend center-leg">
            <span class="leg-item"><i class="dot g"></i>绿灯</span>
            <span class="leg-item"><i class="dot y"></i>黄灯</span>
            <span class="leg-item"><i class="dot r"></i>红灯</span>
            <span class="leg-item"><i class="dot gy"></i>灭灯</span>
          </div>
        </div>
        <!-- 异常机台排名 水平柱状图 -->
        <div class="bar-card">
          <div class="pie-title">异常机台排名:</div>
          <canvas ref="utilAbnormalRef" class="util-canvas-abnormal"
                  @mousemove="onUtilAbnormalMove" @mouseleave="onUtilAbnormalLeave"></canvas>
          <div v-if="utilLoading" class="util-loading-overlay"><div class="util-spinner"></div></div>
          <div class="abn-legend"><i class="dot y"></i>黄灯 &nbsp; <i class="dot r"></i>红灯</div>
        </div>
      </div>

      <!-- 饼图统一Tooltip -->
      <div v-if="utilPieTip.show" class="util-tooltip" :style="{ left: utilPieTip.x+'px', top: utilPieTip.y+'px' }">
        <div class="utip-title">{{ utilPieTip.title }}</div>
        <template v-for="(line,i) in utilPieTip.lines" :key="i">
          <div class="utip-line"><i :style="{background: line.color }"></i>{{ line.label }} {{ line.value }}</div>
        </template>
      </div>

      <!-- 异常机台Tooltip -->
      <div v-if="utilAbnTip.show" class="util-tooltip utip-wide" :style="{ left: utilAbnTip.x+'px', top: utilAbnTip.y+'px' }">
        <div class="utip-title">{{ utilAbnTip.name }}</div>
        <div class="utip-line"><i class="dot y"></i>黄灯 {{ utilAbnTip.yellowDur }}({{ utilAbnTip.yellowPct }})</div>
        <div class="utip-line"><i class="dot r"></i>红灯 {{ utilAbnTip.redDur }}({{ utilAbnTip.redPct }})</div>
      </div>

      <!-- 下排堆叠柱状图 -->
      <div class="util-bottom-chart">
        <div class="stack-bar-toolbar">
          <span>排序:</span>
          <el-radio-group v-model="sortMode" size="small" @change="drawUtilStackBar">
            <el-radio-button value="duration">绿灯时长</el-radio-button>
            <el-radio-button value="rate">稼动率</el-radio-button>
          </el-radio-group>
        </div>
        <div class="stack-bar-legend">
          <span class="leg-item"><i class="dot g"></i>绿灯</span>
          <span class="leg-item"><i class="dot y"></i>黄灯</span>
          <span class="leg-item"><i class="dot r"></i>红灯</span>
          <span class="leg-item"><i class="dot gy"></i>灭灯</span>
        </div>
        <div class="stack-bar-canvas-wrap" style="position:relative;">
          <canvas ref="utilStackRef" class="util-stack-canvas"
                  @mousemove="onUtilStackMove" @mouseleave="onUtilStackLeave"></canvas>
          <div v-if="utilLoading" class="util-loading-overlay"><div class="util-spinner"></div></div>
        </div>
      </div>

      <!-- 堆叠柱状图Tooltip -->
      <div v-if="utilStackTip.show" class="util-tooltip utip-wide" :style="{ left: utilStackTip.x+'px', top: utilStackTip.y+'px' }">
        <div class="utip-title">{{ utilStackTip.name }}</div>
        <div class="utip-line" v-for="(l,i) in utilStackTip.lines" :key="i"><i :style="{background:l.color}"></i>{{ l.label }} {{ l.dur }}({{ l.pct }})</div>
      </div>
    </div>

    <!-- ========== 开机率:柱状图 ========== -->
    <div v-else-if="currentStatus === 'startup'" class="tab-content startup-view">
      <div class="startup-toolbar">
        <span class="startup-label">查询方式:</span>
        <el-radio-group v-model="startupQueryMode" size="small">
          <el-radio-button value="day">日查询</el-radio-button>
          <el-radio-button value="week">周查询</el-radio-button>
          <el-radio-button value="month">月查询</el-radio-button>
        </el-radio-group>
        <el-date-picker
          v-if="startupQueryMode === 'day'"
          v-model="startupDate"
          type="date"
          placeholder="选择日期"
          size="small"
          value-format="YYYY-MM-DD"
          style="width:160px;margin-left:8px;"
        />
        <el-date-picker
          v-else-if="startupQueryMode === 'week'"
          v-model="startupWeekDate"
          type="date"
          :format="startupWeekDisplayFormat"
          placeholder="选择周"
          size="small"
          value-format="YYYY-MM-DD"
          :disabled-date="disableNonMonday"
          style="width:160px;margin-left:8px;"
        />
        <el-date-picker
          v-else-if="startupQueryMode === 'month'"
          v-model="startupMonthDate"
          type="month"
          placeholder="选择月份"
          size="small"
          value-format="YYYY-MM"
          style="width:140px;margin-left:8px;"
        />
        <el-button type="primary" size="small" :loading="startupLoading" @click="fetchStartupData">查询</el-button>
      </div>

      <div class="startup-legend">
        <i class="dot g" style="display:inline-block;width:14px;height:14px;border-radius:3px;background:#67c23a;"></i>
        开机率
      </div>
      <div class="startup-chart" style="position:relative;">
        <canvas ref="startupCanvasRef" class="startup-canvas"
                @mousemove="onStartupMove" @mouseleave="onStartupLeave"></canvas>
        <div v-if="startupLoading" class="util-loading-overlay"><div class="util-spinner"></div></div>
      </div>

      <!-- Tooltip -->
      <div v-if="startupTip.show" class="util-tooltip utip-wide" :style="{ left: startupTip.x+'px', top: startupTip.y+'px' }">
        <div class="utip-title">{{ startupTip.name }}</div>
        <div class="utip-line"><i style="background:#67c23a"></i>开机率 {{ startupTip.bootRate }}</div>
        <div class="utip-line"><i style="background:#91cc75"></i>开机时长 {{ startupTip.onDuration }}</div>
        <div class="utip-line"><i style="background:#909399"></i>关机时长 {{ startupTip.offDuration }}</div>
        <div class="utip-line">总时长 {{ startupTip.totalDuration }}</div>
      </div>
    </div>

    <!-- OEE时序弹窗 -->
    <OeeDialog 
      v-model:visible="dialogVisible.oee" 
      :device="currentDevice"
    />

    <!-- 设置弹窗 -->
    <SettingDialog 
      v-model:visible="dialogVisible.setting" 
      :device="currentDevice"
    />

    <!-- 稼动率弹窗 -->
    <UtilizationDialog 
      v-model:visible="dialogVisible.utilization" 
      :device="currentDevice"
    />

    <!-- 计数明细弹窗 -->
    <CountDialog 
      v-model:visible="dialogVisible.count" 
      :device="currentDevice"
    />
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch, nextTick, inject } from 'vue'
import { Search, Menu, DataLine, Setting, Document, Warning } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import OeeDialog from '../components/OeeDialog.vue'
import SettingDialog from '../components/SettingDialog.vue'
import UtilizationDialog from '../components/UtilizationDialog.vue'
import CountDialog from '../components/CountDialog.vue'

const selectedFactory = ref('金马')
const searchKeyword = ref('')
const currentStatus = ref('realtime')
const lampStateFilter = ref('') // 灯状态筛选: ''=全部, '1'=绿, '2'=红, '3'=黄, '0'=灭灯

// 从全局获取corpCode
const corpCode = inject('corpCode')
import { getApiUrl } from '../config/api.js'

function withCorpCode(url) {
  const fullUrl = getApiUrl(url)
  if (!corpCode.value) return fullUrl
  const sep = fullUrl.includes('?') ? '&' : '?'
  return `${fullUrl}${sep}corpCode=${encodeURIComponent(corpCode.value)}`
}

// 各颜色数量(接口返回后更新,初始默认值)
const totalCounts = reactive({ all: 0, red: 0, yellow: 0, green: 0, blue: 0, gray: 0 })

// 点击筛选标签
function filterByLampState(lampState) {
  if (lampStateFilter.value === lampState) return
  lampStateFilter.value = lampState
  currentPage.value = 1
  fetchDeviceList()
}

// 搜索
function doSearch() {
  currentPage.value = 1
  fetchDeviceList()
}

const statusTabs = [
  { key: 'realtime', label: '实时状态' },
  { key: 'timeseries', label: '时序状态' },
  { key: 'utilization', label: '稼动率' },
  { key: 'startup', label: '开机率' }
]

// lampState → 卡片状态映射: 0=灭灯, 1=红, 2=黄, 3=绿, 4=蓝
function mapLampStatus(lampState) {
  if (lampState === '3') return 'green'
  if (lampState === '1') return 'red'
  if (lampState === '2') return 'yellow'
  if (lampState === '4') return 'blue'
  return 'gray' // 0 或其他 → 灭灯/灰灯
}

// 状态 → 灯色名称
const LAMP_LABEL_MAP = { green: '绿灯', yellow: '黄灯', red: '红灯', gray: '灭灯' }
function getLampLabel(status) {
  return LAMP_LABEL_MAP[status] || '灭灯'
}

const PAGE_SIZE = 12
const currentPage = ref(1)
const deviceList = ref([])
const totalDevices = ref(0)
const totalPages = computed(() => Math.ceil(totalDevices.value / PAGE_SIZE) || 1)

// 分页数据直接来自接口返回的list(服务端分页)
const pagedDevices = computed(() => deviceList.value)

// 页码显示逻辑
const visiblePages = computed(() => {
  const pages = []
  const maxVisible = 5
  const cp = currentPage.value
  const tp = totalPages.value
  let start = Math.max(1, cp - Math.floor(maxVisible / 2))
  let end = Math.min(tp, start + maxVisible - 1)
  if (end - start + 1 < maxVisible) start = Math.max(1, end - maxVisible + 1)
  if (start > 1) { pages.push(1); if (start > 2) pages.push('...') }
  for (let i = start; i <= end; i++) pages.push(i)
  if (end < tp) { if (end < tp - 1) pages.push('...'); pages.push(tp) }
  return pages
})

// 获取设备列表
async function fetchDeviceList() {
  try {
    const params = new URLSearchParams({
      pageNo: currentPage.value,
      pageSize: PAGE_SIZE,
    })
    if (searchKeyword.value) params.append('deviceName', searchKeyword.value)
    if (lampStateFilter.value) params.append('lampState', lampStateFilter.value)

    const res = await fetch(withCorpCode(`/api/device/list?${params}`))
    const data = await res.json()
    deviceList.value = (data.list || []).map(item => ({
      id: item.id,
      name: item.deviceName || item.dtuSn,
      status: mapLampStatus(item.lampState),
      utilization: parseFloat(item.utilizationRate) || 0,
      lightTime: item.duration || '0分',
      displayValue: '000000',
      _raw: item,
    }))
    totalDevices.value = data.total || 0

    // 刷新统计数据
    await fetchStats()
  } catch (err) {
    console.error('获取设备列表失败:', err)
  }
}

// 获取灯状态统计
async function fetchStats() {
  try {
    const res = await fetch(withCorpCode('/api/device/stats'))
    const data = await res.json()
    totalCounts.all = data.all || 0
    totalCounts.red = data.red || 0
    totalCounts.yellow = data.yellow || 0
    totalCounts.green = data.green || 0
    totalCounts.blue = data.blue || 0
    totalCounts.gray = data.off || 0 // 接口off → 灭灯/灰灯
  } catch (err) {
    console.error('获取统计失败:', err)
  }
}

// 切页时重新请求
watch(currentPage, () => {
  fetchDeviceList()
})

// 初始加载
onMounted(() => {
  fetchDeviceList()
})

const dialogVisible = reactive({
  oee: false,
  setting: false,
  count: false,
  utilization: false
})
const currentDevice = ref(null)

function openDetail(type, device) {
  currentDevice.value = device
  dialogVisible[type] = true
}

// ========== 时序状态数据 ==========
const tsQueryMode = ref('day')
const tsDate = ref(null)
const tsLoading = ref(false)
const tsPageNo = ref(1)
const tsPageSize = 20
const tsTotal = ref(0)
const timeSeriesData = ref([])

// 最大页码限制
const TS_MAX_PAGES = 20
const tsTotalPages = computed(() => Math.min(Math.ceil(tsTotal.value / tsPageSize) || 1, TS_MAX_PAGES))

// 可见页码
const tsVisiblePages = computed(() => {
  const pages = []
  const maxVisible = 5
  const cp = tsPageNo.value
  const tp = tsTotalPages.value
  let start = Math.max(1, cp - Math.floor(maxVisible / 2))
  let end = Math.min(tp, start + maxVisible - 1)
  if (end - start + 1 < maxVisible) start = Math.max(1, end - maxVisible + 1)
  if (start > 1) { pages.push(1); if (start > 2) pages.push('...') }
  for (let i = start; i <= end; i++) pages.push(i)
  if (end < tp) { if (end < tp - 1) pages.push('...'); pages.push(tp) }
  return pages
})

// 日期禁用:超过今天不可选
function disabledDate(time) {
  return time.getTime() > Date.now()
}

// Canvas refs & 缩放参数(参考 OeeDialog)
const ganttCanvasRef = ref(null)
const ganttContainerRef = ref(null)
const ganttZoomLevel = ref(1)
const ganttViewOffsetX = ref(0)
const GANTT_MIN_ZOOM = 0.02       // 最小 zoom(最大放大)
const GANTT_MAX_ZOOM = 1          // 最大 zoom(最小放大,即原始大小)

// Hover 状态
const ganttHoveredSeg = ref(null)
const ganttTooltipPos = ref({ x: 0, y: 0 })

// 鼠标滚轮缩放(以鼠标位置为中心点)— 与 OeeDialog 一致的简洁坐标系统
function onGanttWheel(e) {
  const container = ganttContainerRef.value
  if (!container) return
  const rect = container.getBoundingClientRect()
  const PAD = 6
  const LF = 230  // leftFixedWidth (nameCol 160 + rateCol 70)
  const mx = e.clientX - rect.left - PAD
  if (mx < LF || mx < 0) return

  const z = ganttZoomLevel.value
  const vo = ganttViewOffsetX.value

  // 坐标系(与 drawGanttChart 完全一致):
  //   数据空间 dataX → 屏幕 screenX = LF + (dataX - vo) / z
  //   反推(屏幕→数据):dataX = vo + (screenX - LF) * z
  const mouseDataX = vo + (mx - LF) * z

  // 向上滚动(deltaY < 0)放大(zoom 变小),向下(deltaY > 0)缩小(zoom 变大)
  // 与 OeeDialog 一致:deltaY<0 → delta=0.8, deltaY>0 → delta=1.25
  const delta = e.deltaY < 0 ? 0.8 : 1.25
  const nextZ = Math.max(GANTT_MIN_ZOOM, Math.min(GANTT_MAX_ZOOM, z * delta))

  // 保持鼠标下数据点不变:LF + (mouseDataX - vo_new)/nextZ = mx
  // 解得:vo_new = mouseDataX - (mx - LF) * nextZ
  ganttViewOffsetX.value = mouseDataX - (mx - LF) * nextZ
  ganttZoomLevel.value = nextZ
  drawGanttChart()
}

// 鼠标移动检测 hover 条形 — 与 OeeDialog 一致的坐标系统
function onGanttMouseMove(e) {
  const container = ganttContainerRef.value
  if (!container) return
  const rect = container.getBoundingClientRect()
  const PAD = 6
  const LF = 230  // leftFixedWidth (nameCol 160 + rateCol 70)
  const mx = e.clientX - rect.left - PAD
  const my = e.clientY - rect.top - PAD

  if (mx < LF || mx < 0) {
    if (ganttHoveredSeg.value) { ganttHoveredSeg.value = null; drawGanttChart() }
    return
  }

  const z = ganttZoomLevel.value
  const vo = ganttViewOffsetX.value
  const rowHeight = 36
  const headerHeight = 40

  // 屏幕X → 数据空间X(与 drawGanttChart 完全一致的公式:dataX = vo + (screenX - LF)*z)
  const mouseDataX = vo + (mx - LF) * z

  // 检测哪一行(Y轴不受缩放影响)
  const rowIdx = Math.floor((my - headerHeight) / rowHeight)
  if (rowIdx < 0 || rowIdx >= timeSeriesData.value.length) {
    if (ganttHoveredSeg.value) { ganttHoveredSeg.value = null; drawGanttChart() }
    return
  }

  const dev = timeSeriesData.value[rowIdx]
  if (!dev.segments || dev.segments.length === 0) {
    if (ganttHoveredSeg.value) { ganttHoveredSeg.value = null; drawGanttChart() }
    return
  }

  // 计算参数(与 drawGanttChart 完全一致)
  const { startTime: tStart, endTime: tEnd } = getTimeBounds()
  const totalMs = tEnd - tStart || (48 * 60 * 60 * 1000)
  const containerW = container.clientWidth - 12
  const plotW = containerW - LF
  const barPad = 4
  const innerPlotW = plotW - barPad * 2

  // Y 轴条形范围检查(与 drawGanttChart 中的 barY/barH 一致)
  const rowY = headerHeight + rowIdx * rowHeight
  const barY = rowY + (rowHeight - 18) / 2   // = rowY + 9
  const barH = 18
  if (my < barY || my > barY + barH) {
    if (ganttHoveredSeg.value) { ganttHoveredSeg.value = null; drawGanttChart() }
    return
  }

  // 全部在数据空间比较(与 drawGanttChart 绘制条形时使用同一坐标系)
  let hitSeg = null
  for (let i = dev.segments.length - 1; i >= 0; i--) {
    const seg = dev.segments[i]
    const segStartMs = parseStartTime(seg.startTime)
    // duration 单位是秒 → 毫秒(与 OeeDialog 一致:durSec * 1000)
    const durMs = (seg.duration || 0) * 1000
    const pct = Math.max(0, (segStartMs - tStart) / totalMs)
    const wPct = durMs / totalMs
    // 数据空间中的条形位置和宽度(与 drawGanttChart 一致)
    const dataSx = barPad + pct * innerPlotW
    const dataSw = Math.max(wPct * innerPlotW, 1)

    if (mouseDataX >= dataSx && mouseDataX <= dataSx + dataSw) {
      hitSeg = seg; break
    }
  }

  if (hitSeg !== ganttHoveredSeg.value) {
    ganttHoveredSeg.value = hitSeg
    if (hitSeg) {
      ganttTooltipPos.value = { x: e.clientX - rect.left + 12, y: e.clientY - rect.top + 12 }
    }
    drawGanttChart()
  } else if (hitSeg) {
    ganttTooltipPos.value = { x: e.clientX - rect.left + 12, y: e.clientY - rect.top + 12 }
  }
}

function onGanttMouseLeave() {
  if (ganttHoveredSeg.value) { ganttHoveredSeg.value = null; drawGanttChart() }
}

// Hover tooltip 格式化函数
function getLampLabelName(lampState) {
  if (lampState === 3) return '绿灯'
  if (lampState === 2) return '黄灯'
  if (lampState === 1) return '红灯'
  return '灭灯'
}
function formatDuration(dur) {
  if (!dur && dur !== 0) return ''
  if (dur > 3600) {
    const h = Math.floor(dur / 3600), m = Math.floor((dur % 3600) / 60)
    return `${h}时${m}分`
  }
  if (dur > 60) { const m = Math.floor(dur / 60), s = Math.floor(dur % 60); return `${m}分${s}秒` }
  return `${Math.floor(dur)}秒`
}
function formatTimeRange(start, end) {
  const fmt = (ts) => {
    const d = ts ? new Date(ts.replace(/-/g, '/')) : new Date()
    return `${d.getFullYear()}/${String(d.getMonth()+1).padStart(2,'0')}/${String(d.getDate()).padStart(2,'0')} ${String(d.getHours()).padStart(2,'0')}:${String(d.getMinutes()).padStart(2,'0')}:${String(d.getSeconds()).padStart(2,'0')}`
  }
  return `${fmt(start)} ~ ${fmt(end || start)}`
}

// 灯状态颜色映射: lampState → 颜色
function getLampColor(lampState) {
  if (lampState === 3) return '#67c23a'   // 绿
  if (lampState === 2) return '#e6a23c'   // 黄
  if (lampState === 1) return '#f56c6c'   // 红
  return '#909399'                         // 灭灯/灰
}

// 获取时间轴起止时间(基于当天00:00到次日00:00)
function getTimeBounds() {
  const dateStr = tsDate.value || ''
  if (!dateStr) {
    const today = new Date()
    today.setHours(0, 0, 0, 0)
    const tomorrow = new Date(today)
    tomorrow.setDate(tomorrow.getDate() + 1)
    return { startTime: today.getTime(), endTime: tomorrow.getTime() }
  }
  const startDate = new Date(dateStr)
  startDate.setHours(0, 0, 0, 0)
  const endDate = new Date(dateStr)
  endDate.setHours(23, 59, 59, 999)
  return { startTime: startDate.getTime(), endTime: endDate.getTime() + 1 }
}

// 解析startTime字符串为时间戳
function parseStartTime(timeStr) {
  // 格式如 "2026-05-13 23:59:11" 或 "2026-05-13T..."
  const d = new Date(timeStr.replace(/-/g, '/'))
  return d.getTime()
}

// 绘制Canvas甘特图(支持缩放/平移)- 固定列与时间轴区域隔离
function drawGanttChart() {
  const canvas = ganttCanvasRef.value
  const container = ganttContainerRef.value
  if (!canvas || !container) return

  const containerW = container.clientWidth - 12
  const containerH = container.clientHeight - 12
  const rowHeight = 36
  const headerHeight = 40
  const nameColWidth = 160
  const rateColWidth = 70
  const leftFixedWidth = nameColWidth + rateColWidth
  const plotW = containerW - leftFixedWidth   // 时间轴区域宽度(数据空间)
  const totalHeight = Math.max(headerHeight + timeSeriesData.value.length * rowHeight, containerH)

  // 不使用 DPR 缩放(避免模糊),直接用 CSS 像素尺寸
  canvas.width = containerW
  canvas.height = totalHeight
  canvas.style.width = containerW + 'px'
  canvas.style.height = totalHeight + 'px'

  const ctx = canvas.getContext('2d')
  const W = containerW
  const H = Math.max(totalHeight, 200)

  // 清空背景
  ctx.fillStyle = '#fff'
  ctx.fillRect(0, 0, W, H)

  const { startTime: tStart, endTime: tEnd } = getTimeBounds()
  const totalMs = tEnd - tStart || (48 * 60 * 60 * 1000)
  const totalSec = totalMs / 1000

  // 缩放参数
  const z = ganttZoomLevel.value
  const vo = ganttViewOffsetX.value

  // ========== 坐标系定义(OeeDialog 同款简洁方式)==========
  // 数据空间 dataX → 屏幕像素 screenX = leftFixedWidth + (dataX - vo) / z
  // 反推:数据空间 dataX = vo + (screenX - leftFixedWidth) * z
  // 所有绘制都用手动坐标转换,不用 ctx.translate/scale 链

  // ========== 第一部分:固定列区域(不受缩放影响) ==========
  ctx.fillStyle = '#fafafa'
  ctx.fillRect(0, 0, leftFixedWidth, headerHeight)
  ctx.strokeStyle = '#e0e0e0'; ctx.lineWidth = 2
  ctx.beginPath(); ctx.moveTo(0, headerHeight); ctx.lineTo(leftFixedWidth, headerHeight); ctx.stroke()
  ctx.fillStyle = '#333'; ctx.font = 'bold 13px sans-serif'
  ctx.textAlign = 'center'; ctx.textBaseline = 'middle'
  ctx.fillText('设备名称', nameColWidth / 2, headerHeight / 2)
  ctx.fillText('稼动率', nameColWidth + rateColWidth / 2, headerHeight / 2)
  ctx.strokeStyle = '#ebeef5'; ctx.lineWidth = 1
  ctx.beginPath(); ctx.moveTo(nameColWidth, 0); ctx.lineTo(nameColWidth, headerHeight); ctx.stroke()
  ctx.beginPath(); ctx.moveTo(leftFixedWidth, 0); ctx.lineTo(leftFixedWidth, H); ctx.stroke()

  timeSeriesData.value.forEach((dev, idx) => {
    const y = headerHeight + idx * rowHeight
    ctx.fillStyle = idx % 2 === 0 ? '#fff' : '#fafbfc'
    ctx.fillRect(0, y, leftFixedWidth, rowHeight)
    ctx.strokeStyle = '#ebeef5'; ctx.lineWidth = 1
    ctx.beginPath(); ctx.moveTo(0, y); ctx.lineTo(leftFixedWidth, y); ctx.stroke()
    ctx.beginPath(); ctx.moveTo(nameColWidth, y); ctx.lineTo(nameColWidth, y + rowHeight); ctx.stroke()
    ctx.fillStyle = '#409eff'; ctx.font = '12px sans-serif'
    ctx.textAlign = 'left'; ctx.textBaseline = 'middle'
    const dn = dev.name.length > 14 ? dev.name.slice(0, 14) + '..' : dev.name
    ctx.fillText(dn, 12, y + rowHeight / 2)
    ctx.fillStyle = '#333'; ctx.font = 'bold 12px sans-serif'
    ctx.textAlign = 'center'
    ctx.fillText(dev.rate + '%', nameColWidth + rateColWidth / 2, y + rowHeight / 2)
  })

  // ========== 第二部分:时间轴区域(手动坐标映射) ==========
  // 时间轴表头背景
  ctx.fillStyle = '#fafafa'
  ctx.fillRect(leftFixedWidth, 0, plotW, headerHeight)
  ctx.strokeStyle = '#e0e0e0'; ctx.lineWidth = 2
  ctx.beginPath(); ctx.moveTo(leftFixedWidth, headerHeight); ctx.lineTo(W, headerHeight); ctx.stroke()

  // ----- 时间刻度 -----
  // 可见时间范围:z 越小(放大越多)→ 可见范围越小 → 刻度越精细
  const visMs = Math.max(1000, totalMs * z)
  let stepMs = 2 * 3600 * 1000       // 默认2小时
  if (visMs <= 2000)          stepMs = 1000            // ≤2s   → 每秒
  else if (visMs <= 6000)     stepMs = 2000            // ≤6s   → 每2秒
  else if (visMs <= 15000)    stepMs = 5000            // ≤15s  → 每5秒
  else if (visMs <= 30000)    stepMs = 10000           // ≤30s  → 每10秒
  else if (visMs <= 60000)    stepMs = 15000           // ≤1min → 每15秒
  else if (visMs <= 120000)   stepMs = 30000           // ≤2min → 每30秒
  else if (visMs <= 300000)   stepMs = 60 * 1000       // ≤5min → 每分钟
  else if (visMs <= 600000)   stepMs = 2 * 60 * 1000   // ≤10min→ 每2分钟
  else if (visMs <= 1800000)  stepMs = 5 * 60 * 1000   // ≤30min→ 每5分钟
  else if (visMs <= 3600000)  stepMs = 10 * 60 * 1000  // ≤1h   → 每10分钟
  else if (visMs <= 7200000)  stepMs = 15 * 60 * 1000  // ≤2h   → 每15分钟
  else if (visMs <= 14400000) stepMs = 30 * 60 * 1000  // ≤4h   → 每30分钟
  else if (visMs <= 28800000) stepMs = 3600 * 1000      // ≤8h   → 每小时
  else                       stepMs = 2 * 3600 * 1000   // >8h   → 每2小时

  // 视口左边界对应的时间偏移 → 对齐到 stepMs 边界
  const leftMs = (vo / plotW) * totalMs
  let firstMs = Math.floor(leftMs / stepMs) * stepMs
  if (firstMs < 0) firstMs = 0

  ctx.font = '11px sans-serif'; ctx.fillStyle = '#666'

  for (let ms = firstMs; ms <= totalMs + stepMs * 2; ms += stepMs) {
    // 数据空间的 x 坐标
    const dataX = (ms / totalMs) * plotW
    // 手动转换到屏幕坐标:screenX = LF + (dataX - vo) / z
    const screenX = leftFixedWidth + (dataX - vo) / z
    if (screenX < leftFixedWidth - 80 || screenX > W + 80) continue

    // 时间文字
    ctx.save()
    ctx.textAlign = 'center'; ctx.textBaseline = 'middle'
    const dt = new Date(tStart + ms)
    if (stepMs < 60000) {
      ctx.fillText(`${String(dt.getHours()).padStart(2,'0')}:${String(dt.getMinutes()).padStart(2,'0')}:${String(dt.getSeconds()).padStart(2,'0')}`, screenX, headerHeight / 2)
    } else {
      ctx.fillText(`${String(dt.getHours()).padStart(2,'0')}:${String(dt.getMinutes()).padStart(2,'0')}`, screenX, headerHeight / 2)
    }
    ctx.restore()

    // 垂直刻度线(屏幕坐标)
    ctx.strokeStyle = '#f0f0f0'; ctx.lineWidth = 0.5
    ctx.beginPath(); ctx.moveTo(screenX, headerHeight); ctx.lineTo(screenX, H); ctx.stroke()
  }

  // ----- 设备行背景 + 条形 -----
  timeSeriesData.value.forEach((dev, idx) => {
    const y = headerHeight + idx * rowHeight
    // 行背景(屏幕坐标,覆盖时间轴区域)
    ctx.fillStyle = idx % 2 === 0 ? '#fff' : '#fafbfc'
    ctx.fillRect(leftFixedWidth, y, W - leftFixedWidth, rowHeight)
    // 行顶分割线
    ctx.strokeStyle = '#ebeef5'; ctx.lineWidth = 1
    ctx.beginPath(); ctx.moveTo(leftFixedWidth, y); ctx.lineTo(W, y); ctx.stroke()

    // 甘特图条形
    if (dev.segments && dev.segments.length > 0) {
      const barY = y + (rowHeight - 18) / 2
      const barH = 18
      let barY_hover = barY
      let barH_hover = barH
      const pad = 4
      const innerPlotW = plotW - pad * 2

      // 裁剪区域:条形不能溢出到左侧固定列
      ctx.save()
      ctx.beginPath()
      ctx.rect(leftFixedWidth, headerHeight, W - leftFixedWidth, H - headerHeight)
      ctx.clip()

      dev.segments.forEach(seg => {
        const segStartMs = parseStartTime(seg.startTime)
        // duration 单位是秒 → 毫秒(与 OeeDialog 一致)
        const durMs = (seg.duration || 0) * 1000
        const pct = Math.max(0, (segStartMs - tStart) / totalMs)
        const wPct = durMs / totalMs
        // 数据空间坐标
        const dataSx = pad + pct * innerPlotW
        const dataSw = Math.max(wPct * innerPlotW, 1)
        // 转换为屏幕坐标
        const sx = leftFixedWidth + (dataSx - vo) / z
        const sw = dataSw / z

        // 可见性裁剪(屏幕坐标)
        if (sx + sw < leftFixedWidth - 20 || sx > W + 20) return

        const isHovered = ganttHoveredSeg.value === seg

        ctx.fillStyle = getLampColor(seg.lampState)
        if (isHovered) {
          ctx.globalAlpha = 0.7
          barH_hover = barH + 4; barY_hover = barY - 2
          ctx.fillRect(sx, barY_hover, sw, barH_hover)
          ctx.globalAlpha = 1
        } else {
          ctx.fillRect(sx, barY, sw, barH)
        }
        // 边框
        ctx.strokeStyle = isHovered ? 'rgba(0,0,0,0.5)' : 'rgba(255,255,255,0.35)'
        ctx.lineWidth = isHovered ? 1.5 : 0.5
        ctx.strokeRect(sx, isHovered ? barY_hover : barY, sw, isHovered ? barH_hover : barH)
      })

      // 恢复裁剪区域,不影响后续行的绘制
      ctx.restore()
    }
  })
}

// 获取时序数据
async function fetchTimeSeriesData() {
  if (!tsDate.value) {
    ElMessage.warning('请选择查询日期')
    return
  }

  tsLoading.value = true
  try {
    const params = new URLSearchParams({
      startDate: tsDate.value,
      endDate: tsDate.value,
      pageNo: tsPageNo.value,
      pageSize: tsPageSize,
    })
    const res = await fetch(withCorpCode(`/api/device/oeeTimeline?${params}`))
    const data = await res.json()

    if (data.data && data.data.records) {
      const records = data.data.records || []
      tsTotal.value = data.data.total || records.length * tsPageSize
      timeSeriesData.value = records.map(record => ({
        name: record.deviceName || record.dtuSn || '',
        rate: parseFloat(record.availabilityRatio || 0).toFixed(1),
        greenDuration: record.greenDuration || '',
        segments: (record.lampData || []).map(item => ({
          duration: item.duration,
          lampState: item.lampState,
          startTime: item.startTime,
          endTime: item.endTime || '',
        })),
      }))
    }

    // 数据加载后绘制Canvas
    await nextTick()
    drawGanttChart()
  } catch (err) {
    console.error('获取时序数据失败:', err)
    ElMessage.error('获取时序数据失败')
  } finally {
    tsLoading.value = false
  }
}

// 监听tab切换到时序状态时触发查询
watch(currentStatus, (newVal) => {
  if (newVal === 'timeseries') {
    if (!tsDate.value) {
      // 默认选今天
      const today = new Date()
      tsDate.value = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`
    }
    fetchTimeSeriesData()
  }
})

// ========== 稼动率数据(Canvas绘制) ==========
const utilQueryMode = ref('day')
const utilDate = ref('')
const utilWeekDate = ref('')
const utilMonthDate = ref('')
const utilLoading = ref(false)
const sortMode = ref('rate')

// 周查询显示格式:2026-第20周
const utilWeekDisplayFormat = computed(() => {
  if (!utilWeekDate.value) return ''
  const d = new Date(utilWeekDate.value)
  return `${d.getFullYear()}-${String(getWeekNumber(d)).padStart(2, '0')}周`
})

// 获取日期所在年的第几周(ISO标准:周一为每周起始)
function getWeekNumber(date) {
  const d = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()))
  const dayNum = d.getUTCDay() || 7
  d.setUTCDate(d.getUTCDate() + 4 - dayNum)
  const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1))
  return Math.ceil(((d - yearStart) / 86400000 + 1) / 7)
}

// 获取某日所在自然周的周一和周日 { start: YYYY-MM-DD, end: YYYY-MM-DD }
function getWeekRange(dateStr) {
  if (!dateStr) return { start: '', end: '' }
  const d = new Date(dateStr)
  // 调整到本周一
  const day = d.getDay() || 7
  const diff = d.getDate() - day + 1
  const monday = new Date(d.setDate(diff))
  const sunday = new Date(monday)
  sunday.setDate(monday.getDate() + 6)
  return {
    start: formatYMD(monday),
    end: formatYMD(sunday),
  }
}

// 获取某月的1号和最后一天
function getMonthRange(ymStr) {
  if (!ymStr) return { start: '', end: '' }
  const [y, m] = ymStr.split('-').map(Number)
  const lastDay = new Date(y, m, 0).getDate()
  return { start: `${ymStr}-01`, end: `${ymStr}-${String(lastDay).padStart(2,'0')}` }
}

// 格式化为 YYYY-MM-DD
function formatYMD(d) {
  return `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`
}

// 获取当前自然周的周一日期字符串
function getCurrentMonday() {
  const today = new Date()
  const day = today.getDay() || 7
  today.setDate(today.getDate() - day + 1)
  return formatYMD(today)
}

// 周选择器只允许选周一
function disableNonMonday(date) {
  return date.getDay() !== 1
}

// 获取当前年月字符串
function getCurrentYM() {
  const now = new Date()
  return `${now.getFullYear()}-${String(now.getMonth()+1).padStart(2,'0')}`
}

// Canvas refs
const utilPieTotalRef = ref(null)
const utilPieRateRef = ref(null)
const utilPieStatusRef = ref(null)
const utilAbnormalRef = ref(null)
const utilStackRef = ref(null)

// API 数据
const utilData = reactive({
  totalDuration: { green: {}, yellow: {}, red: {}, off: {}, blue: {} },
  availabilityRate: '0%',
  currentStatus: { green: 0, red: 0, off: 0, blue: 0, yellow: 0 },
  abnormalRanking: [],
  deviceList: [],
})

// 饼图总时长分段(用于图例)
const utilTotalSegments = computed(() => {
  const td = utilData.totalDuration
  const totalSec = (td.green?.seconds||0)+(td.yellow?.seconds||0)+(td.red?.seconds||0)+(td.off?.seconds||0)
  if (!totalSec) return []
  return [
    { label: '绿灯', color: '#67c23a', duration: td.green?.duration||'', pct: ((td.green.seconds||0)/totalSec*100).toFixed(2)+'%' },
    { label: '黄灯', color: '#e6a23c', duration: td.yellow?.duration||'', pct: ((td.yellow.seconds||0)/totalSec*100).toFixed(2)+'%' },
    { label: '红灯', color: '#f56c6c', duration: td.red?.duration||'', pct: ((td.red.seconds||0)/totalSec*100).toFixed(2)+'%' },
    { label: '灭灯', color: '#909399', duration: td.off?.duration||'', pct: ((td.off.seconds||0)/totalSec*100).toFixed(2)+'%' },
  ]
})

// 异常排名底部文字
const utilAbnormalFooterText = computed(() => {
  const list = utilData.abnormalRanking || []
  if (list.length === 0) return ''
  // 取前5个的rygTotalDuration
  return list.slice(0,5).map((item,i) =>
    `${item.deviceName||item.dtuSn} ${item.availabilityRatio}`
  ).join(' | ')
})

// 饼图 hover 状态(canvas级别,按key+segIdx跟踪)
const utilHoveredPieKey = ref('')
const utilHoveredPieSegIdx = ref(-1)
const utilPieTip = reactive({ show: false, x: 0, y: 0, title: '', lines: [] })

// 饼图通用 mousemove 处理(DPR模式下用逻辑坐标)
function onUtilPieMove(pieKey, e) {
  const canvasMap = { total: utilPieTotalRef, rate: utilPieRateRef, status: utilPieStatusRef }
  const anglesMap = { total: utilTotalAngles, rate: utilRateAngles, status: utilStatusAngles }
  const canvas = canvasMap[pieKey]?.value
  if (!canvas) return

  const rect = canvas.getBoundingClientRect()
  // setupPieCanvas 已将 ctx.scale(dpr,dpr),所以直接用 CSS 像素坐标即可(逻辑坐标)
  const mx = e.clientX - rect.left
  const my = e.clientY - rect.top

  const W = 320, H = 280   // 与 setupPieCanvas 一致
  const cx = W / 2, cy = H / 2, r = 100
  const angles = anglesMap[pieKey]
  if (!angles || angles.length === 0) return

  const hitIdx = hitTestPie(mx, my, cx, cy, r, angles)

  if (hitIdx !== utilHoveredPieSegIdx.value || utilHoveredPieKey.value !== pieKey) {
    utilHoveredPieKey.value = pieKey
    utilHoveredPieSegIdx.value = hitIdx

    if (hitIdx >= 0 && pieKey !== 'status') {
      const seg = angles[hitIdx]
      const total = angles.reduce((s, a) => s + a.value, 0)
      // 根据不同饼图设置标题和内容
      const titles = { total: '总时长', rate: '稼动率', status: '当前机台运行状态' }
      utilPieTip.title = titles[pieKey] || seg.label || ''
      utilPieTip.lines = [
        { color: seg.color, label: `${seg.label} ${seg.rawDur || ''}`, value: '' },
        { color: seg.color, label: '时长占比', value: ((seg.value / total) * 100).toFixed(2) + '%' },
      ]
      utilPieTip.x = e.clientX + 12
      utilPieTip.y = e.clientY + 12
      utilPieTip.show = true
    } else {
      utilPieTip.show = false
    }
    drawAllUtilCharts()
  } else if (hitIdx >= 0) {
    utilPieTip.x = e.clientX + 12
    utilPieTip.y = e.clientY + 12
  }
}

// 饼图 mouseleave
function onUtilPieLeave(pieKey) {
  if (utilHoveredPieKey.value === pieKey) {
    utilHoveredPieKey.value = ''
    utilHoveredPieSegIdx.value = -1
    utilPieTip.show = false
    drawAllUtilCharts()
  }
}

// 异常机台 hover 状态
const utilAbnTip = reactive({ show: false, x: 0, y: 0, name: '', yellowDur: '', yellowPct: '', redDur: '', redPct: '' })
let utilAbnHitIdx = -1

// 堆叠柱状图 hover 状态
const utilStackTip = reactive({ show: false, x: 0, y: 0, name: '', lines: [] })
let utilStackHitIdx = -1

// ---------- 绘制工具函数 ----------
// 绘制实心饼图(filled pie) - 返回扇区角度数组用于 hit-test
function drawPie(ctx, cx, cy, r, segments, options = {}) {
  const { activeIdx = -1 } = options
  const total = segments.reduce((s, seg) => s + seg.value, 0)
  if (total <= 0) return []
  let angle = -Math.PI / 2
  const angles = []

  segments.forEach((seg, i) => {
    const sweep = (seg.value / total) * Math.PI * 2
    const isActive = i === activeIdx

    ctx.beginPath()
    ctx.moveTo(cx, cy)
    ctx.arc(cx, cy, r, angle, angle + sweep)
    ctx.closePath()
    ctx.fillStyle = seg.color
    ctx.fill()

    if (isActive) {
      ctx.save()
      ctx.shadowColor = 'rgba(0,0,0,0.35)'
      ctx.shadowBlur = 12
      ctx.strokeStyle = '#fff'
      ctx.lineWidth = 2
      ctx.stroke()
      ctx.restore()
    } else {
      ctx.strokeStyle = 'rgba(255,255,255,0.5)'
      ctx.lineWidth = 0.8
      ctx.stroke()
    }

    // 在扇区中心位置绘制白色文字标签(字体缩小2号)
    if (seg.value > 0) {
      const midAngle = angle + sweep / 2
      const labelR = r * 0.6
      const lx = cx + Math.cos(midAngle) * labelR
      const ly = cy + Math.sin(midAngle) * labelR

      ctx.save()
      ctx.fillStyle = '#fff'
      ctx.textAlign = 'center'
      ctx.textBaseline = 'middle'

      const pct = ((seg.value / total) * 100).toFixed(2) + '%'
      ctx.font = isActive ? 'bold 13px sans-serif' : '12px sans-serif'
      ctx.fillText(pct, lx, ly - 6)

      ctx.font = isActive ? 'bold 11px sans-serif' : '10px sans-serif'
      ctx.fillText(seg.textLabel || '', lx, ly + 7)
      ctx.restore()
    }

    angles.push({ startAngle: angle, endAngle: angle + sweep, ...seg })
    angle += sweep
  })
  return angles
}

// 饼图 DPR 缩放辅助:设置 canvas 物理尺寸并返回缩放后的 context
function setupPieCanvas(canvas) {
  const dpr = window.devicePixelRatio || 1
  const w = 320, h = 280
  canvas.style.width = w + 'px'
  canvas.style.height = h + 'px'
  canvas.width = Math.round(w * dpr)
  canvas.height = Math.round(h * dpr)
  const ctx = canvas.getContext('2d')
  ctx.scale(dpr, dpr)
  return { ctx, W: w, H: h }
}

// 饼图 hit-test: 判断鼠标是否在某个扇区(实心饼图)
function hitTestPie(mx, my, cx, cy, r, angles) {
  const dx = mx - cx, dy = my - cy
  const dist = Math.sqrt(dx * dx + dy * dy)
  if (dist > r) return -1
  let ang = Math.atan2(dy, dx)
  if (ang < -Math.PI / 2) ang += Math.PI * 2
  for (let i = 0; i < angles.length; i++) {
    let sa = angles[i].startAngle, ea = angles[i].endAngle
    if (sa < -Math.PI / 2) sa += Math.PI * 2
    if (ea < -Math.PI / 2) ea += Math.PI * 2
    if (ang >= sa && ang < ea) return i
  }
  return -1
}

// 格式化秒数为 "xxx.xx时"
function fmtSecHour(sec) {
  sec = Math.max(0, sec || 0)
  return (sec / 3600).toFixed(2) + '时'
}

// 格式化秒数为可读时长
function fmtSec(sec) {
  sec = Math.max(0, sec | 0)
  const h = Math.floor(sec / 3600), m = Math.floor((sec % 3600) / 60), s = sec % 60
  if (h > 0) return `${h}时${m}分${s}秒`
  if (m > 0) return `${m}分${s}秒`
  return `${s}秒`
}

// ---------- 绘制总时长饼图 ----------
let utilTotalAngles = []
function drawUtilPieTotal() {
  const canvas = utilPieTotalRef.value
  if (!canvas) return
  const { ctx, W, H } = setupPieCanvas(canvas)
  const cx = W / 2, cy = H / 2, r = 100

  const td = utilData.totalDuration
  const gSec = td.green?.seconds || 0, ySec = td.yellow?.seconds || 0
  const rSec = td.red?.seconds || 0, oSec = td.off?.seconds || 0
  const totalSec = gSec + ySec + rSec + oSec

  if (totalSec <= 0) {
    ctx.fillStyle = '#999'; ctx.font = '13px sans-serif'; ctx.textAlign = 'center'
    ctx.fillText('暂无数据', cx, cy); return
  }

  const segments = [
    { label:'绿灯', value:gSec, color:'#67c23a', textLabel: `绿灯`, rawDur: fmtSec(gSec) },
    { label:'黄灯', value:ySec, color:'#e6a23c', textLabel: `黄灯:${fmtSecHour(ySec)}`, rawDur: fmtSec(ySec) },
    { label:'红灯', value:rSec, color:'#f56c6c', textLabel: `红灯:${fmtSecHour(rSec)}`, rawDur: fmtSec(rSec) },
    { label:'灭灯', value:oSec, color:'#909399', textLabel: `灭灯:${fmtSecHour(oSec)}`, rawDur: fmtSec(oSec) },
  ]
  utilTotalAngles = drawPie(ctx, cx, cy, r, segments, {
    activeIdx: utilHoveredPieKey.value === 'total' ? utilHoveredPieSegIdx.value : -1
  })
}

// ---------- 绘制稼动率饼图 ----------
let utilRateAngles = []
function drawUtilPieRate() {
  const canvas = utilPieRateRef.value
  if (!canvas) return
  const { ctx, W, H } = setupPieCanvas(canvas)
  const cx = W / 2, cy = H / 2, r = 100

  const td = utilData.totalDuration
  const gSec = td.green?.seconds || 0, ySec = td.yellow?.seconds || 0
  const rSec = td.red?.seconds || 0
  const rygTotal = gSec + ySec + rSec
  if (rygTotal <= 0) { ctx.fillStyle='#999';ctx.font='13px sans-serif';ctx.textAlign='center';ctx.fillText('暂无数据',cx,cy); return }

  const segments = [
    { label:'绿灯', value:gSec, color:'#67c23a', textLabel: `绿灯:${fmtSecHour(gSec)}`, rawDur: fmtSec(gSec) },
    { label:'黄灯', value:ySec, color:'#e6a23c', textLabel: `黄灯:${fmtSecHour(ySec)}`, rawDur: fmtSec(ySec) },
    { label:'红灯', value:rSec, color:'#f56c6c', textLabel: `红灯:${fmtSecHour(rSec)}`, rawDur: fmtSec(rSec) },
  ]
  utilRateAngles = drawPie(ctx, cx, cy, r, segments, {
    activeIdx: utilHoveredPieKey.value === 'rate' ? utilHoveredPieSegIdx.value : -1
  })
}

// ---------- 绘制当前机台运行状态饼图 ----------
let utilStatusAngles = []
function drawUtilPieStatus() {
  const canvas = utilPieStatusRef.value
  if (!canvas) return
  const { ctx, W, H } = setupPieCanvas(canvas)
  const cx = W / 2, cy = H / 2, r = 100

  const cs = utilData.currentStatus
  const gN = cs.green||0, yN = cs.yellow||0, rN = cs.red||0, oN = cs.off||0
  const total = gN + yN + rN + oN
  if (total <= 0) { ctx.fillStyle='#999';ctx.font='13px sans-serif';ctx.textAlign='center';ctx.fillText('暂无数据',cx,cy); return }

  const segments = [
    { label:`绿灯`, value:gN, color:'#67c23a', textLabel: `绿灯${gN}台`, rawDur: `${gN}台` },
    { label:`黄灯`, value:yN, color:'#e6a23c', textLabel: `黄灯${yN}台`, rawDur: `${yN}台` },
    { label:`红灯`, value:rN, color:'#f56c6c', textLabel: `红灯${rN}台`, rawDur: `${rN}台` },
    { label:`灭灯`, value:oN, color:'#909399', textLabel: `灭灯${oN}台`, rawDur: `${oN}台` },
  ]
  utilStatusAngles = drawPie(ctx, cx, cy, r, segments, {
    activeIdx: utilHoveredPieKey.value === 'status' ? utilHoveredPieSegIdx.value : -1
  })
}

// ---------- 绘制异常机台排名水平柱状图 ----------
function drawUtilAbnormal() {
  const canvas = utilAbnormalRef.value
  if (!canvas) return
  const container = canvas.parentElement
  if (!container) return
  const cw = container.clientWidth, ch = 320
  canvas.width = cw; canvas.height = ch
  const ctx = canvas.getContext('2d')
  ctx.clearRect(0, 0, cw, ch)

  let list = (utilData.abnormalRanking || []).filter(item => {
    const yS = item.yellowSeconds || 0, rS = item.redSeconds || 0
    return (yS + rS) > 0
  })
  if (list.length === 0) {
    ctx.fillStyle='#999'; ctx.font='13px sans-serif'; ctx.textAlign='center'
    ctx.fillText('暂无异常数据', cw/2, ch/2); return
  }

  const PAD_L = 60, PAD_R = 20, PAD_T = 28, PAD_B = 8
  const plotW = cw - PAD_L - PAD_R, plotH = ch - PAD_T - PAD_B
  const rowH = Math.min(22, plotH / list.length)
  const barH = rowH - 4

  // 找最大值(黄+红总秒数)
  let maxVal = 1
  list.forEach(item => { maxVal = Math.max(maxVal, (item.yellowSeconds||0)+(item.redSeconds||0)) })

  // X轴时间刻度(放在顶部)
  const tickCount = 5
  ctx.strokeStyle = '#ddd'; ctx.lineWidth = 1; ctx.fillStyle = '#666'; ctx.font = '11px sans-serif'; ctx.textAlign = 'center'
  for (let i = 0; i <= tickCount; i++) {
    const val = maxVal * i / tickCount
    const x = PAD_L + (plotW * i / tickCount)
    ctx.fillText(fmtSec(Math.round(val)), x, 16)
    if (i > 0) {
      ctx.beginPath(); ctx.moveTo(x, PAD_T); ctx.lineTo(x, ch - PAD_B); ctx.stroke()
    }
  }
  // 基线加粗(顶部基线)
  ctx.strokeStyle = '#bbb'; ctx.lineWidth = 1.5
  ctx.beginPath(); ctx.moveTo(PAD_L, PAD_T); ctx.lineTo(cw - PAD_R, PAD_T); ctx.stroke()

  // 每行
  list.forEach((item, idx) => {
    const y = PAD_T + idx * rowH
    // 设备名
    ctx.fillStyle = '#333'
    ctx.font = '12px sans-serif'
    ctx.textAlign = 'right'; ctx.textBaseline = 'middle'
    const dn = (item.deviceName || item.dtuSn || '')
    ctx.fillText(dn.length > 7 ? dn.slice(0,7) + '..' : dn, PAD_L - 6, y + rowH / 2)

    const yS = item.yellowSeconds || 0, rS = item.redSeconds || 0

    const yW = (yS / maxVal) * plotW
    const rW = (rS / maxVal) * plotW

    // 黄色段
    ctx.fillStyle = '#e6a23c'
    ctx.fillRect(PAD_L, y + 2, yW, barH)
    // 红色段
    ctx.fillStyle = '#f56c6c'
    ctx.fillRect(PAD_L + yW, y + 2, rW, barH)
  })
}

// 异常机台 mousemove
function onUtilAbnormalMove(e) {
  const canvas = utilAbnormalRef.value
  if (!canvas) return
  const rect = canvas.getBoundingClientRect()
  const mx = e.clientX - rect.left, my = e.clientY - rect.top
  const rawList = utilData.abnormalRanking || []
  // 与 drawUtilAbnormal 保持一致:过滤掉数据为0的项
  let list = rawList.filter(item => {
    const yS = item.yellowSeconds || 0, rS = item.redSeconds || 0
    return (yS + rS) > 0
  })

  const PAD_L = 60, PAD_T = 28, PAD_B = 8
  const rowH = Math.min(22, (canvas.clientHeight - PAD_T - PAD_B) / Math.max(list.length, 1))
  const rowIdx = Math.floor((my - PAD_T) / rowH)

  if (rowIdx < 0 || rowIdx >= list.length) {
    if (utilAbnTip.show) { utilAbnTip.show = false; drawUtilAbnormal() }
    return
  }

  if (rowIdx !== utilAbnHitIdx) {
    utilAbnHitIdx = rowIdx
    const item = list[rowIdx]
    const yS = item.yellowSeconds || 0, rS = item.redSeconds || 0, totalS = yS + rS
    utilAbnTip.name = item.deviceName || item.dtuSn || ''
    utilAbnTip.yellowDur = fmtSec(yS)
    utilAbnTip.yellowPct = totalS > 0 ? ((yS/totalS)*100).toFixed(2)+'%' : '0%'
    utilAbnTip.redDur = fmtSec(rS)
    utilAbnTip.redPct = totalS > 0 ? ((rS/totalS)*100).toFixed(2)+'%' : '0%'
    utilAbnTip.x = e.clientX + 12
    utilAbnTip.y = e.clientY + 12
    utilAbnTip.show = true
  } else {
    utilAbnTip.x = e.clientX + 12
    utilAbnTip.y = e.clientY + 12
  }
}
function onUtilAbnormalLeave() {
  utilAbnTip.show = false; utilAbnHitIdx = -1
}

// ---------- 绘制堆叠柱状图 ----------
let utilStackBars = []  // 存储每根柱子的位置信息用于hit-test
function drawUtilStackBar() {
  const canvas = utilStackRef.value
  if (!canvas) return
  const wrap = canvas.parentElement
  if (!wrap) return
  const cw = wrap.clientWidth, ch = 300
  canvas.width = cw; canvas.height = ch
  const ctx = canvas.getContext('2d')
  ctx.clearRect(0, 0, cw, ch)

  const list = utilData.deviceList || []
  if (list.length === 0) {
    ctx.fillStyle='#999'; ctx.font='13px sans-serif'; ctx.textAlign='center'
    ctx.fillText('暂无数据', cw/2, ch/2); return
  }

  // 排序
  const sorted = sortMode.value === 'rate'
    ? [...list].sort((a,b) => parseFloat(b.availabilityRatio||0) - parseFloat(a.availabilityRatio||0))
    : [...list].sort((a,b) => (b.greenSeconds||0) - (a.greenSeconds||0))

  const PAD_L = 36, PAD_R = 20, PAD_T = 24, PAD_B = 42
  const plotW = cw - PAD_L - PAD_R, plotH = ch - PAD_T - PAD_B
  const colW = Math.min(32, Math.floor(plotW / Math.max(sorted.length, 1) * 0.85))
  const gap = Math.max(2, (plotW - colW * sorted.length) / (sorted.length + 1))

  // 找最大值
  let maxVal = 1
  sorted.forEach(item => {
    const t = (item.greenSeconds||0)+(item.yellowSeconds||0)+(item.redSeconds||0)+(item.offSeconds||0)
    maxVal = Math.max(maxVal, t)
  })

  // Y轴刻度(小时)
  const maxHours = maxVal / 3600
  const yTicks = [Math.ceil(maxHours), Math.ceil(maxHours*0.75), Math.ceil(maxHours*0.5), Math.ceil(maxHours*0.25), 0]
  ctx.strokeStyle = '#eee'; ctx.lineWidth = 1; ctx.fillStyle = '#999'; ctx.font = '10px sans-serif'; ctx.textAlign = 'end'

  yTicks.forEach(val => {
    if (val <= maxHours) {
      const py = PAD_T + plotH * (1 - val / maxHours)
      ctx.fillText(val + '时', PAD_L - 4, py + 3)
      ctx.beginPath(); ctx.moveTo(PAD_L, py); ctx.lineTo(cw - PAD_R, py); ctx.stroke()
    }
  })

  // 基线
  ctx.strokeStyle = '#ddd'; ctx.lineWidth = 1
  ctx.beginPath(); ctx.moveTo(PAD_L, PAD_T + plotH); ctx.lineTo(cw - PAD_R, PAD_T + plotH); ctx.stroke()

  // 绘制每根柱子
  utilStackBars = []
  sorted.forEach((item, idx) => {
    const px = PAD_L + gap + idx * (colW + gap)
    const gS = item.greenSeconds||0, yS = item.yellowSeconds||0, rS = item.redSeconds||0, oS = item.offSeconds||0
    const total = gS+yS+rS+oS
    if (total <= 0) return

    const scale = plotH / maxVal
    let curY = PAD_T + plotH  // 从底部往上堆叠

    // 绿灯(底部)
    const gH = gS * scale
    curY -= gH; ctx.fillStyle='#67c23a'; ctx.fillRect(px, curY, colW, gH)
    // 黄灯
    const yH = yS * scale
    curY -= yH; ctx.fillStyle='#e6a23c'; ctx.fillRect(px, curY, colW, yH)
    // 红灯
    const rH = rS * scale
    curY -= rH; ctx.fillStyle='#f56c6c'; ctx.fillRect(px, curY, colW, rH)
    // 灭灯(顶部)
    const oH = oS * scale
    curY -= oH; ctx.fillStyle='#909399'; ctx.fillRect(px, curY, colW, oH)

    // 设备名标签
    ctx.fillStyle = '#666'; ctx.font = '9px sans-serif'; ctx.textAlign = 'center'
    ctx.save()
    ctx.translate(px + colW / 2, PAD_T + plotH + 10)
    ctx.rotate(-Math.PI / 6)
    const dn = (item.deviceName || item.dtuSn || '').replace(/中速|高速|号机/g,'').slice(0,6)
    ctx.fillText(dn, 0, 0)
    ctx.restore()

    // 存储hit区域
    utilStackBars.push({
      x: px, y: curY, w: colW, h: gH+yH+rH+oH,
      data: item,
      name: item.deviceName || item.dtuSn,
      gSec: gS, ySec: yS, rSec: rS, oSec: oS,
    })

    // hover 高亮
    if (idx === utilStackHitIdx) {
      ctx.strokeStyle='#333'; ctx.lineWidth=1.5
      ctx.strokeRect(px, curY, colW, gH+yH+rH+oH)
      ctx.fillStyle='rgba(64,158,255,0.08)'
      ctx.fillRect(px-2, curY-2, colW+4, gH+yH+rH+oH+4)
    }
  })
}

// 堆叠柱状图 mousemove
function onUtilStackMove(e) {
  const canvas = utilStackRef.value
  if (!canvas) return
  const rect = canvas.getBoundingClientRect()
  const mx = e.clientX - rect.left, my = e.clientY - rect.top

  let hitIdx = -1
  for (let i = 0; i < utilStackBars.length; i++) {
    const b = utilStackBars[i]
    if (mx >= b.x && mx <= b.x + b.w && my >= b.y && my <= b.y + b.h) {
      hitIdx = i; break
    }
  }

  if (hitIdx === -1 && my > 200) {
    // 也检查标签区域
    for (let i = 0; i < utilStackBars.length; i++) {
      const b = utilStackBars[i]
      if (mx >= b.x && mx <= b.x + b.w) { hitIdx = i; break }
    }
  }

  if (hitIdx !== utilStackHitIdx) {
    utilStackHitIdx = hitIdx
    if (hitIdx >= 0) {
      const b = utilStackBars[hitIdx]
      const total = b.gSec+b.ySec+b.rSec+b.oSec
      utilStackTip.name = b.name
      utilStackTip.lines = []
      if (b.gSec>0) utilStackTip.lines.push({label:'绿灯',color:'#67c23a',dur:fmtSec(b.gSec),pct:(b.gSec/total*100).toFixed(2)+'%'})
      if (b.ySec>0) utilStackTip.lines.push({label:'黄灯',color:'#e6a23c',dur:fmtSec(b.ySec),pct:(b.ySec/total*100).toFixed(2)+'%'})
      if (b.rSec>0) utilStackTip.lines.push({label:'红灯',color:'#f56c6c',dur:fmtSec(b.rSec),pct:(b.rSec/total*100).toFixed(2)+'%'})
      if (b.oSec>0) utilStackTip.lines.push({label:'灭灯',color:'#909399',dur:fmtSec(b.oSec),pct:(b.oSec/total*100).toFixed(2)+'%'})
      utilStackTip.x = e.clientX + 12
      utilStackTip.y = e.clientY - 10
      utilStackTip.show = true
    } else {
      utilStackTip.show = false
    }
    drawUtilStackBar()
  } else if (hitIdx >= 0) {
    utilStackTip.x = e.clientX + 12
    utilStackTip.y = e.clientY - 10
  }
}
function onUtilStackLeave() { utilStackTip.show = false; utilStackHitIdx = -1; drawUtilStackBar() }

// ---------- 绘制所有图表 ----------
function drawAllUtilCharts() {
  drawUtilPieTotal()
  drawUtilPieRate()
  drawUtilPieStatus()
  drawUtilAbnormal()
  drawUtilStackBar()
}

// ---------- 获取稼动率数据 ----------
async function fetchUtilData() {
  let startDate = '', endDate = ''

  if (utilQueryMode.value === 'day') {
    const dateStr = utilDate.value
    if (!dateStr) { ElMessage.warning('请选择查询日期'); return }
    startDate = endDate = dateStr
  } else if (utilQueryMode.value === 'week') {
    if (!utilWeekDate.value) { ElMessage.warning('请选择查询周'); return }
    const range = getWeekRange(utilWeekDate.value)
    startDate = range.start
    endDate = range.end
  } else if (utilQueryMode.value === 'month') {
    if (!utilMonthDate.value) { ElMessage.warning('请选择查询月份'); return }
    const range = getMonthRange(utilMonthDate.value)
    startDate = range.start
    endDate = range.end
  }

  utilLoading.value = true
  try {
    const res = await fetch(withCorpCode(`/api/device/lampStatistics?startDate=${startDate}&endDate=${endDate}`))
    const data = await res.json()

    if (data.totalDuration) Object.assign(utilData.totalDuration, data.totalDuration)
    if (data.availabilityRate) utilData.availabilityRate = data.availabilityRate
    if (data.currentStatus) Object.assign(utilData.currentStatus, data.currentStatus)
    if (data.abnormalRanking) utilData.abnormalRanking = data.abnormalRanking
    if (data.deviceList) utilData.deviceList = data.deviceList

    await nextTick()
    drawAllUtilCharts()
  } catch (err) {
    console.error('获取稼动率数据失败:', err)
    ElMessage.error('获取数据失败')
  } finally {
    utilLoading.value = false
  }
}

// 监听tab切换
watch(currentStatus, async (newVal) => {
  if (newVal === 'utilization') {
    setUtilDefaultDate()
    fetchUtilData()
  }
})

// 监听查询方式切换,自动设置默认日期并触发查询
watch(utilQueryMode, () => {
  setUtilDefaultDate()
  fetchUtilData()
})

// 根据当前查询模式设置默认日期
function setUtilDefaultDate() {
  if (utilQueryMode.value === 'day') {
    if (!utilDate.value) {
      const today = new Date()
      utilDate.value = formatYMD(today)
    }
  } else if (utilQueryMode.value === 'week') {
    if (!utilWeekDate.value) {
      utilWeekDate.value = getCurrentMonday()
    }
  } else if (utilQueryMode.value === 'month') {
    if (!utilMonthDate.value) {
      utilMonthDate.value = getCurrentYM()
    }
  }
}

// ========== 开机率数据 ==========
const startupQueryMode = ref('day')
const startupDate = ref('')
const startupWeekDate = ref('')
const startupMonthDate = ref('')
const startupLoading = ref(false)
const startupCanvasRef = ref(null)

// 周查询显示格式
const startupWeekDisplayFormat = computed(() => {
  if (!startupWeekDate.value) return ''
  const d = new Date(startupWeekDate.value)
  return `${d.getFullYear()}-${String(getWeekNumber(d)).padStart(2, '0')}周`
})

// API 数据
const startupList = ref([])
const startupSummary = reactive({
  totalDevices: 0,
  overallBootRate: '0%',
  totalDuration: '',
  onDuration: '',
  offDuration: '',
  dataDays: 0,
})

// Tooltip
const startupTip = reactive({ show: false, x: 0, y: 0, name: '', bootRate: '', onDuration: '', offDuration: '', totalDuration: '' })
let startupHitIdx = -1

// 获取开机率日期范围
function getStartupDateRange() {
  let startDate = '', endDate = ''
  if (startupQueryMode.value === 'day') {
    const dateStr = startupDate.value
    if (!dateStr) return { startDate: '', endDate: '' }
    startDate = endDate = dateStr
  } else if (startupQueryMode.value === 'week') {
    if (!startupWeekDate.value) return { startDate: '', endDate: '' }
    const range = getWeekRange(startupWeekDate.value)
    startDate = range.start
    endDate = range.end
  } else if (startupQueryMode.value === 'month') {
    if (!startupMonthDate.value) return { startDate: '', endDate: '' }
    const range = getMonthRange(startupMonthDate.value)
    startDate = range.start
    endDate = range.end
  }
  return { startDate, endDate }
}

// 获取开机率数据
async function fetchStartupData() {
  const { startDate, endDate } = getStartupDateRange()
  if (!startDate || !endDate) {
    ElMessage.warning('请选择查询时间'); return
  }

  startupLoading.value = true
  try {
    const res = await fetch(withCorpCode(`/api/device/bootRate?startDate=${startDate}&endDate=${endDate}`))
    const data = await res.json()

    startupList.value = data.list || []
    if (data.summary) Object.assign(startupSummary, data.summary)

    await nextTick()
    drawStartupChart()
  } catch (err) {
    console.error('获取开机率数据失败:', err)
    ElMessage.error('获取数据失败')
  } finally {
    startupLoading.value = false
  }
}

// 设置开机率默认日期
function setStartupDefaultDate() {
  if (startupQueryMode.value === 'day') {
    if (!startupDate.value) {
      startupDate.value = formatYMD(new Date())
    }
  } else if (startupQueryMode.value === 'week') {
    if (!startupWeekDate.value) {
      startupWeekDate.value = getCurrentMonday()
    }
  } else if (startupQueryMode.value === 'month') {
    if (!startupMonthDate.value) {
      startupMonthDate.value = getCurrentYM()
    }
  }
}

// 监听tab切换
watch(currentStatus, async (newVal) => {
  if (newVal === 'startup') {
    setStartupDefaultDate()
    fetchStartupData()
  }
})

// 监听查询方式切换
watch(startupQueryMode, () => {
  setStartupDefaultDate()
  fetchStartupData()
})

// ---------- 绘制开机率柱状图 ----------
let startupBars = []
function drawStartupChart() {
  const canvas = startupCanvasRef.value
  if (!canvas) return
  const container = canvas.parentElement
  if (!container) return
  const cw = container.clientWidth
  const ch = Math.min(400, Math.max(320, startupList.value.length * 28 + 80))

  // DPR 缩放提升清晰度
  const dpr = window.devicePixelRatio || 1
  canvas.style.width = cw + 'px'
  canvas.style.height = ch + 'px'
  canvas.width = Math.round(cw * dpr)
  canvas.height = Math.round(ch * dpr)
  const ctx = canvas.getContext('2d')
  ctx.scale(dpr, dpr)
  ctx.clearRect(0, 0, cw, ch)

  const list = startupList.value
  if (list.length === 0) {
    ctx.fillStyle = '#999'
    ctx.font = '13px sans-serif'
    ctx.textAlign = 'center'
    ctx.fillText('暂无数据', cw / 2, ch / 2)
    return
  }

  const PAD_L = 50, PAD_R = 20, PAD_T = 24, PAD_B = 50
  const plotW = cw - PAD_L - PAD_R, plotH = ch - PAD_T - PAD_B
  const colW = Math.min(32, Math.floor(plotW / Math.max(list.length, 1) * 0.85))
  const gap = Math.max(3, (plotW - colW * list.length) / (list.length + 1))

  // Y轴刻度
  ctx.strokeStyle = '#eee'
  ctx.lineWidth = 1
  ctx.fillStyle = '#999'
  ctx.font = '10px sans-serif'
  ctx.textAlign = 'end'

  for (let i = 0; i <= 5; i++) {
    const val = i * 20
    const py = PAD_T + plotH * (1 - val / 100)
    ctx.fillText(val + '%', PAD_L - 5, py + 3)
    if (i > 0) {
      ctx.beginPath()
      ctx.moveTo(PAD_L, py)
      ctx.lineTo(cw - PAD_R, py)
      ctx.stroke()
    }
  }

  // 基线
  ctx.strokeStyle = '#ddd'
  ctx.lineWidth = 1.5
  ctx.beginPath()
  ctx.moveTo(PAD_L, PAD_T + plotH)
  ctx.lineTo(cw - PAD_R, PAD_T + plotH)
  ctx.stroke()

  // 绘制柱子背景(统一样式)
  list.forEach((item, idx) => {
    const px = PAD_L + gap + idx * (colW + gap)
    ctx.fillStyle = '#f2f3f5'
    roundRect(ctx, px, PAD_T, colW, plotH, 3)
    ctx.fill()
  })

  // 绘制柱子
  startupBars = []
  list.forEach((item, idx) => {
    const px = PAD_L + gap + idx * (colW + gap)
    const rate = item.bootRateValue || 0
    const barH = rate / 100 * plotH
    const barY = PAD_T + plotH - barH

    let color = '#67c23a'
    if (rate >= 95) color = '#4caf50'
    else if (rate < 50) color = '#91cc75'

    const isHovered = idx === startupHitIdx

    if (isHovered) {
      // hover效果:阴影+放大+提亮+边框
      ctx.save()
      ctx.shadowColor = 'rgba(103,194,58,0.5)'
      ctx.shadowBlur = 16
      ctx.shadowOffsetY = 3
      ctx.fillStyle = lightenColor(color, 30)
      const hoverPad = 2
      roundRect(ctx, px - hoverPad, barY - hoverPad, colW + hoverPad * 2, barH + hoverPad * 2, 4)
      ctx.fill()
      ctx.restore()
      // 边框
      ctx.strokeStyle = '#3d8b3d'
      ctx.lineWidth = 1.5
      roundRect(ctx, px - hoverPad, barY - hoverPad, colW + hoverPad * 2, barH + hoverPad * 2, 4)
      ctx.stroke()
    } else {
      roundRect(ctx, px, barY, colW, barH, 3)
      ctx.fillStyle = color
      ctx.fill()
    }

    ctx.fillStyle = '#666'
    ctx.font = '9px sans-serif'
    ctx.textAlign = 'center'
    ctx.save()
    ctx.translate(px + colW / 2, PAD_T + plotH + 12)
    ctx.rotate(-Math.PI / 6)
    const dn = (item.deviceName || item.dtuSn || '').slice(0, 8)
    ctx.fillText(dn, 0, 0)
    ctx.restore()

    // 始终用基础坐标存储hit区域,扩大到整列方便hover
    startupBars.push({
      x: px - 2, y: PAD_T, w: colW + 4, h: plotH,
      name: item.deviceName || item.dtuSn,
      bootRate: item.bootRate,
      onDuration: item.onDuration,
      offDuration: item.offDuration,
      totalDuration: item.totalDuration,
    })
  })
}

// 圆角矩形辅助函数
function roundRect(ctx, x, y, w, h, r) {
  r = Math.min(r, w / 2, h / 2)
  ctx.beginPath()
  ctx.moveTo(x + r, y)
  ctx.lineTo(x + w - r, y)
  ctx.arcTo(x + w, y, x + w, y + r, r)
  ctx.lineTo(x + w, y + h - r)
  ctx.arcTo(x + w, y + h, x + w - r, y + h, r)
  ctx.lineTo(x + r, y + h)
  ctx.arcTo(x, y + h, x, y + h - r, r)
  ctx.lineTo(x, y + r)
  ctx.arcTo(x, y, x + r, y, r)
  ctx.closePath()
}

// 颜色提亮工具函数
function lightenColor(hex, amount) {
  let r = parseInt(hex.slice(1, 3), 16)
  let g = parseInt(hex.slice(3, 5), 16)
  let b = parseInt(hex.slice(5, 7), 16)
  r = Math.min(255, r + amount)
  g = Math.min(255, g + amount)
  b = Math.min(255, b + amount)
  return `rgb(${r},${g},${b})`
}

function onStartupMove(e) {
  const canvas = startupCanvasRef.value
  if (!canvas) return
  const rect = canvas.getBoundingClientRect()
  const mx = e.clientX - rect.left
  const my = e.clientY - rect.top

  let hitIdx = -1
  for (let i = 0; i < startupBars.length; i++) {
    const b = startupBars[i]
    if (mx >= b.x && mx <= b.x + b.w && my >= b.y && my <= b.y + b.h) {
      hitIdx = i; break
    }
  }

  if (hitIdx !== startupHitIdx) {
    startupHitIdx = hitIdx
    if (hitIdx >= 0) {
      const b = startupBars[hitIdx]
      startupTip.name = b.name
      startupTip.bootRate = b.bootRate
      startupTip.onDuration = b.onDuration
      startupTip.offDuration = b.offDuration
      startupTip.totalDuration = b.totalDuration
      startupTip.x = e.clientX + 12
      startupTip.y = e.clientY - 10
      startupTip.show = true
    } else {
      startupTip.show = false
    }
    drawStartupChart()
  } else if (hitIdx >= 0) {
    startupTip.x = e.clientX + 12
    startupTip.y = e.clientY - 10
  }
}
function onStartupLeave() { startupTip.show = false; startupHitIdx = -1; drawStartupChart() }
</script>

<style scoped>
.smart-light-page {
  min-height: 100%;
  height: calc(100vh - 0px);
  display: flex;
  flex-direction: column;
  background-color: #f0f2f5;
}
.device-grid {
  flex: 1;
  padding: 16px 20px;
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  gap: 16px;
  align-content: start;
}
.device-grid.grid-full {
  align-content: stretch;
}
.device-grid.grid-normal {
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
}
.top-toolbar {
  background: #fff;
  padding: 0 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid #e8e8e8;
}
.status-tabs {
  display: flex;
  gap: 4px;
}
.status-tab {
  padding: 14px 18px;
  cursor: pointer;
  font-size: 13px;
  color: #666;
  position: relative;
  transition: all 0.2s;
}
.status-tab:hover {
  color: #409eff;
}
.status-tab.active {
  color: #409eff;
  font-weight: bold;
}
.status-tab.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 60%;
  height: 2px;
  background: #409eff;
}
.toolbar-right {
  display: flex;
  align-items: center;
  gap: 8px;
}
.filter-bar {
  background: #fff;
  padding: 10px 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid #e8e8e8;
}
.filter-label {
  font-size: 13px;
  color: #999;
}
.filter-tags {
  display: flex;
  gap: 16px;
}
.tag-item {
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 4px;
  cursor: pointer;
  padding: 2px 6px;
  border-radius: 4px;
  transition: background 0.2s;
}
.tag-item:hover {
  background: rgba(0,0,0,0.05);
}
.tag-item.active {
  font-weight: bold;
  background: rgba(64,158,255,0.08);
}
.tag-item i {
  width: 10px;
  height: 10px;
  display: inline-block;
  border-radius: 2px;
}
.tag-item.black i { background: #333; }
.tag-item.red i { background: #f56c6c; }
.tag-item.yellow i { background: #e6a23c; }
.tag-item.green i { background: #67c23a; }
.tag-item.blue i { background: #409eff; }
.tag-item.gray i { background: #909399; }

.device-card {
  height: 340px;
  border-radius: 12px;
  overflow: hidden;
  transition: transform 0.2s;
  display: flex;
  flex-direction: column;
}
.device-card.green {
  background: linear-gradient(160deg, #5cb85c 0%, #449d44 50%, #3d8b3d 100%);
  box-shadow: 0 4px 16px rgba(92,184,92,0.35);
}
.device-card.yellow {
  background: linear-gradient(160deg, #f5a623 0%, #e69811 50%, #cc8409 100%);
  box-shadow: 0 4px 16px rgba(245,166,35,0.35);
}
.device-card.red {
  background: linear-gradient(160deg, #e74c3c 0%, #c0392b 50%, #a93226 100%);
  box-shadow: 0 4px 16px rgba(231,76,60,0.35);
}
.device-card.gray {
  background: linear-gradient(160deg, #8a9a9a 0%, #6b7b7b 50%, #5a6a6a 100%);
  box-shadow: 0 4px 16px rgba(100,110,110,0.25);
}
.device-card:hover {
  transform: translateY(-3px);
}
.device-card.green:hover {
  box-shadow: 0 6px 24px rgba(92,184,92,0.45);
}
.device-card.yellow:hover {
  box-shadow: 0 6px 24px rgba(245,166,35,0.5);
}
.device-card.red:hover {
  box-shadow: 0 6px 24px rgba(231,76,60,0.5);
}
.device-card.gray:hover {
  box-shadow: 0 6px 24px rgba(100,110,110,0.35);
}

/* 标题栏 */
.card-header {
  padding: 12px 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
  font-weight: bold;
  color: #fff;
  flex-shrink: 0;
}
.menu-icon {
  cursor: pointer;
  color: rgba(255,255,255,0.85);
  font-size: 18px;
}

/* 内容区 */
.card-body {
  padding: 16px 14px 12px;
  display: flex;
  gap: 12px;
  align-items: stretch;
  flex: 1;
}

/* 左侧状态条 - 四块色块 */
.status-bar {
  width: 28px;
  border-radius: 14px;
  flex-shrink: 0;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  gap: 3px;
  padding: 3px 0;
}
.bar-block {
  flex: 1;
  border-radius: 6px;
  transition: opacity 0.2s, filter 0.2s;
}
/* 默认暗态(未激活)- 全部灰色 */
.block-red { background: rgba(120, 130, 140, 0.35); }
.block-yellow { background: rgba(120, 130, 140, 0.35); }
.block-green { background: rgba(120, 130, 140, 0.35); }
.block-blue { background: rgba(120, 130, 140, 0.35); }
/* 激活亮态 - 纯色实心与背景区分 */
.block-red.active { background: #c0392b; }
.block-yellow.active { background: #e67e22; }
.block-green.active { background: #1a7a37; }
.block-blue.active { background: #2463aa; }

/* 右侧内容 */
.card-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 10px;
  justify-content: center;
}

.info-row {
  font-size: 14px;
  color: rgba(255,255,255,0.95);
  line-height: 1.8;
}
.value-highlight {
  color: #fff;
  font-weight: bold;
  font-size: 15px;
}

/* 数字显示屏 */
.digital-display {
  background: #1a1a2e;
  padding: 10px 14px;
  border-radius: 8px;
  display: flex;
  justify-content: center;
  gap: 3px;
  margin-top: 30px;
}
.digit {
  color: #00ff88;
  font-family: 'Courier New', monospace;
  font-size: 24px;
  font-weight: bold;
  text-shadow: 0 0 10px rgba(0,255,136,0.5);
  min-width: 16px;
  text-align: center;
}

/* 底部按钮 */
.card-footer {
  padding: 10px 14px 12px;
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 8px;
  flex-shrink: 0;
}
.action-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
  padding: 7px 8px;
  border-radius: 5px;
  font-size: 13px;
  cursor: pointer;
  transition: all 0.2s;
  background: rgba(255,255,255,0.18);
  border: 1.5px solid rgba(255,255,255,0.4);
  color: #fff;
  backdrop-filter: blur(4px);
}
.action-btn:hover {
  background: rgba(255,255,255,0.3);
  border-color: rgba(255,255,255,0.65);
}

/* ========== 自定义分页 ========== */
.pagination-wrapper {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  padding: 14px 20px;
  border-top: 1px solid #e8e8e8;
}
.pagination-info { font-size: 13px; color: #666; }
.pagination-info strong { color: #333; }

.pagination-controls {
  display: flex;
  align-items: center;
  gap: 4px;
}
.page-size-select {
  height: 30px;
  padding: 2px 8px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background: #fff;
  font-size: 13px;
  color: #606266;
  outline: none;
  cursor: pointer;
}
.page-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background: #fff;
  color: #606266;
  font-size: 13px;
  cursor: pointer;
  transition: all 0.15s;
}
.page-btn:hover:not(:disabled) {
  color: #409eff;
  border-color: #409eff;
}
.page-btn.active {
  background-color: #409eff;
  border-color: #409eff;
  color: #fff;
}
.page-btn:disabled {
  opacity: 0.45;
  cursor: not-allowed;
}
.page-dots {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  color: #999;
  font-size: 13px;
}

/* ========== Tab内容区通用 ========== */
.tab-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

/* ========== 时序状态 ========== */
.timeseries-view {
  background: #f0f2f5;
}
.ts-toolbar {
  background: #fff;
  padding: 12px 16px;
  display: flex;
  align-items: center;
  gap: 8px;
  border-bottom: 1px solid #ebeef5;
}
.ts-label {
  font-size: 13px; color: #666; white-space: nowrap;
}
.ts-table-wrap {
  flex: 1;
  overflow: hidden;
  margin: 12px 20px;
  /* 与 OeeDialog timeline-chart 风格一致 */
  background: #fff;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  padding: 6px;
}
.ts-header-row {
  display: flex;
  align-items: flex-end;
  position: sticky;
  top: 0;
  background: #fafafa;
  border-bottom: 2px solid #e0e0e0;
  z-index: 2;
}
.ts-col-name {
  width: 160px;
  padding: 8px 12px;
  font-size: 13px;
  font-weight: bold;
  color: #333;
  flex-shrink: 0;
  text-align: center;
}
.ts-sub-col { width: 70px; }
.ts-timeline-area {
  flex: 1;
  min-width: 800px;
}
.ts-row {
  display: flex;
  align-items: center;
  border-bottom: 1px solid #f0f0f0;
  min-height: 36px;
}
.ts-row.row-gray .ts-cell-name { background: #f5f5f5; }
.ts-cell-name {
  width: 160px;
  padding: 6px 12px;
  flex-shrink: 0;
  font-size: 12px;
}
.ts-link { color: #409eff; cursor: pointer; }
.ts-link:hover { text-decoration: underline; }
.ts-cell-rate {
  width: 70px;
  padding: 6px 4px;
  text-align: center;
  font-size: 12px;
  font-weight: bold;
  color: #333;
  flex-shrink: 0;
}
.ts-row.row-gray .ts-cell-rate { background: #f0f0f0; }
.ts-cell-bars {
  flex: 1;
  min-width: 800px;
  padding: 4px 8px;
}
.bar-track {
  height: 22px;
  background: #f5f5f5;
  border-radius: 3px;
  position: relative;
  overflow: hidden;
}
.bar-seg {
  position: absolute;
  top: 0;
  height: 100%;
  border-radius: 0 2px 2px 0;
}
.seg-g { background: #67c23a; }
.seg-y { background: #e6a23c; }
.seg-r { background: #f56c6c; }
.seg-gy { background: #909399; }

/* Canvas甘特图 */
.gantt-canvas {
  width: 100%;
  display: block;
}

/* Hover Tooltip */
.gantt-tooltip {
  position: absolute;
  z-index: 10;
  background: rgba(32, 40, 51, 0.92);
  color: #fff;
  padding: 8px 12px;
  border-radius: 4px;
  font-size: 12px;
  line-height: 1.6;
  pointer-events: none;
  white-space: nowrap;
  box-shadow: 0 2px 12px rgba(0,0,0,0.2);
}
.gtt-row {
  display: flex;
  align-items: center;
  gap: 5px;
}
.gtt-dot {
  display: inline-block;
  width: 9px;
  height: 9px;
  border-radius: 2px;
  flex-shrink: 0;
}
.gtt-sub {
  font-size: 11px;
  color: #bbb;
}

/* ========== 稼动率 (Canvas) ========== */
.util-view {
  background: #f5f7fa;
  overflow-y: auto;
}
.util-toolbar {
  background: #fff;
  padding: 10px 20px;
  display: flex;
  align-items: center;
  gap: 10px;
  border-bottom: 1px solid #e8e8e8;
}
.util-label {
  font-size: 13px; color: #666; font-weight: bold;
}
.util-top-charts {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 14px;
  padding: 14px 20px;
}
.pie-card, .bar-card {
  background: #fff;
  border-radius: 6px;
  box-shadow: 0 1px 4px rgba(0,0,0,0.06);
  padding: 12px 14px;
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
}
.pie-title {
  font-size: 13px;
  font-weight: bold;
  color: #333;
  margin-bottom: 6px;
  flex-shrink: 0;
  align-self: flex-start;
  width: 100%;
}
/* Canvas 饼图 */
.util-canvas-pie {
  width: 320px;
  height: 280px;
  display: block;
}

/* 饼图加载转圈 */
.util-loading-overlay {
  position: absolute;
  top: 0; left: 0; right: 0; bottom: 0;
  background: rgba(255,255,255,0.85);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 5;
  border-radius: 6px;
}
.util-spinner {
  width: 32px; height: 32px;
  border: 3px solid #e0e0e0;
  border-top-color: #409eff;
  border-radius: 50%;
  animation: utilSpin 0.8s linear infinite;
}
@keyframes utilSpin {
  to { transform: rotate(360deg); }
}
.util-total-leg {
  margin-top: 4px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  font-size: 11px;
  color: #666;
  line-height: 1.5;
}
.util-total-leg .leg-sub { color: #999; font-size: 10px; }
.pie-legend {
  margin-top: 6px;
  display: flex;
  gap: 8px;
  font-size: 16px;
  color: #666;
  line-height: 1.5;
  flex-wrap: wrap;
}
.center-leg { justify-content: center; }
.leg-item {
  display: inline-flex;
  align-items: center;
  gap: 3px;
  cursor: pointer;
  transition: background 0.15s;
  border-radius: 3px;
  padding: 1px 4px;
}
.leg-item:hover { background: rgba(64,158,255,0.06); }
.dot { display: inline-block; width: 9px; height: 9px; border-radius: 2px; flex-shrink: 0; }
.dot.g { background: #67c23a; }
.dot.y { background: #e6a23c; }
.dot.r { background: #f56c6c; }
.dot.gy { background: #909399; }

/* 异常机台排名 Canvas */
.util-canvas-abnormal {
  flex: 1;
  min-height: 280px;
  width: 100%;
  display: block;
}
.abn-footer {
  margin-top: 6px;
  font-size: 10px;
  color: #bbb;
  text-align: right;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.abn-legend {
  margin-top: 8px;
  font-size: 15px;
  color: #555;
  display: flex;
  gap: 16px;
  justify-content: center;
  padding: 6px 0;
}
.abn-legend .dot { width: 14px; height: 14px; border-radius: 3px; }

/* 堆叠柱状图 Canvas */
.util-bottom-chart {
  margin: 0 20px 14px;
  background: #fff;
  border-radius: 6px;
  box-shadow: 0 1px 4px rgba(0,0,0,0.06);
  padding: 14px;
}
.stack-bar-toolbar {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
  font-size: 13px;
  color: #666;
}
.stack-bar-legend {
  display: flex;
  gap: 18px;
  margin-bottom: 8px;
  font-size: 12px;
  color: #666;
}
.stack-bar-canvas-wrap {
  overflow-x: auto;
}
.util-stack-canvas {
  width: 100%;
  height: auto;
  display: block;
}

/* 统一 Tooltip 样式 - 使用 fixed 定位,坐标基于页面 */
.util-tooltip {
  position: fixed;
  z-index: 1000;
  background: rgba(32,40,51,0.92);
  color: #fff;
  padding: 8px 12px;
  border-radius: 4px;
  font-size: 12px;
  line-height: 1.7;
  pointer-events: none;
  box-shadow: 0 2px 12px rgba(0,0,0,0.2);
  max-width: 260px;
}
.utip-wide { max-width: 300px; }
.utip-title {
  font-weight: bold;
  font-size: 13px;
  margin-bottom: 4px;
  border-bottom: 1px solid rgba(255,255,255,0.2);
  padding-bottom: 4px;
}
.utip-line {
  display: flex;
  align-items: center;
  gap: 5px;
}
.utip-line i {
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 2px;
  flex-shrink: 0;
}

/* ========== 开机率 ========== */
.startup-view {
  background: #f5f7fa;
  overflow-y: auto;
}
.startup-toolbar {
  background: #fff;
  padding: 10px 20px;
  display: flex;
  align-items: center;
  gap: 10px;
  border-bottom: 1px solid #e8e8e8;
}
.startup-label {
  font-size: 13px; color: #666; font-weight: bold;
}
.startup-summary {
  background: #fff;
  margin: 12px 20px 0;
  padding: 10px 16px;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.05);
  display: flex;
  gap: 24px;
  font-size: 12px;
  color: #666;
  flex-wrap: wrap;
}
.startup-summary b { color: #333; }
.startup-legend {
  padding: 10px 24px 0;
  font-size: 13px;
  color: #666;
  display: flex;
  align-items: center;
  gap: 6px;
}
.startup-chart {
  margin: 0 20px 20px;
  background: #fff;
  border-radius: 6px;
  box-shadow: 0 1px 4px rgba(0,0,0,0.06);
  padding: 14px;
  min-height: 340px;
}
.startup-canvas {
  width: 100%;
  height: auto;
  display: block;
}
</style>