Energy.vue 82.8 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
<template>
  <div class="energy-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: !runStatusFilter }]" @click="filterByRunStatus('')"><i></i>全部{{ totalCounts.all }}台</span>
        <span :class="['tag-item', 'red', { active: runStatusFilter === '1' }]" @click="filterByRunStatus('1')"><i></i>停机:{{ totalCounts.stop }}台</span>
        <span :class="['tag-item', 'green', { active: runStatusFilter === '2' }]" @click="filterByRunStatus('2')"><i></i>待机:{{ totalCounts.standby }}台</span>
        <span :class="['tag-item', 'blue', { active: runStatusFilter === '3' }]" @click="filterByRunStatus('3')"><i></i>运行:{{ totalCounts.run }}台</span>
        <span :class="['tag-item', 'gray', { active: runStatusFilter === '0' }]" @click="filterByRunStatus('0')"><i></i>离线:{{ totalCounts.offline }}台</span>
      </div>
    </div>

    <!-- ========== 实时状态:设备卡片 ========== -->
    <div v-if="currentStatus === 'realtime'" class="tab-content">
    <!-- 设备卡片网格 -->
    <div class="device-grid">
      <div class="grid-inner">
      <div v-for="device in pagedDevices" :key="device.id" :class="['energy-card', 'status-' + device.runStatus]">
        <div class="card-header">
          <span class="device-name">{{ device.name }}</span>
        </div>
        
        <div class="card-body">
          <div class="energy-icon lightning-icon">
            <svg viewBox="0 0 64 64" xmlns="http://www.w3.org/2003/2000/svg">
              <path d="M35.5 4 L17 36 h14 l-6 24 22 -32 H33 l8 -24 Z"
                    fill="#f5a623" stroke="#d48806" stroke-width="1.5" stroke-linejoin="round"/>
            </svg>
          </div>
          
          <div class="info-list">
            <div class="info-item">用电量:<span>{{ device.evalue }} kw·h</span></div>
            <div class="info-item">{{ getRunStatusLabel(device.runStatus) }}:<span>{{ device.duration }}</span></div>
          </div>
        </div>

        <div class="card-footer">
          <button class="action-btn primary" @click="openDetail('report', device)">
            <el-icon><Document /></el-icon>运行状态
          </button>
          <button class="action-btn danger" @click="openDetail('safety', device)">
            <el-icon><Lock /></el-icon>用时用电
          </button>
        </div>
      </div>
      </div><!-- /grid-inner -->
    </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; fetchDeviceList()">«</button>
        <button class="page-btn" :disabled="currentPage === 1" @click="currentPage--; fetchDeviceList()"><</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; fetchDeviceList()">{{ p }}</button>
          <span v-else class="page-dots">{{ p }}</span>
        </template>
        <button class="page-btn" :disabled="currentPage === totalPages" @click="currentPage++; fetchDeviceList()">></button>
        <button class="page-btn" :disabled="currentPage === totalPages" @click="currentPage = totalPages; fetchDeviceList()">»</button>
      </div>
    </div>
    </div><!-- /tab-content realtime -->

    <!-- ========== 时序状态:Canvas甘特图 ========== -->
    <div v-else-if="currentStatus === 'timeseries'" class="tab-content timeseries-view" ref="tsWrapRef">
      <div class="ts-toolbar">
        <span class="ts-label">查询方式:</span>
        <el-radio-group v-model="tsQueryMode" size="small" @change="onTsModeChange">
          <el-radio-button value="day">日查询</el-radio-button>
        </el-radio-group>
        <el-date-picker v-model="tsSelectedDate" type="date" placeholder="" size="small"
          style="width:160px;margin-left:8px;" value-format="YYYY-MM-DD"
          :disabled-date="disabledDateFuture" @change="fetchTimelineData" />
        <el-button type="primary" size="small" style="margin-left:8px;" @click="fetchTimelineData">查询</el-button>
      </div>

      <div class="ts-gantt-wrap" v-loading="tsLoading">
        <div class="ts-fixed-col"><canvas ref="tsFixedCanvasRef"></canvas></div>
        <div class="ts-scroll-area" ref="tsScrollAreaRef" @scroll="onTsScroll">
          <canvas ref="tsGanttCanvasRef" @mousemove="onTsGanttMouseMove" @mouseleave="onTsGanttMouseLeave" @wheel.prevent.stop="onTsGanttWheel"></canvas>
          <div v-if="tsHover.show" class="gantt-tooltip" :style="{ left: tsHover.x + 'px', top: tsHover.y + 'px' }">
            <div class="gtt-title">{{ tsHover.deviceName }}</div>
            <div class="gtt-row"><span class="gtt-label">状态</span><span class="gtt-val" :style="{ color: TS_STATUS_COLORS[tsHover.status] }">{{ tsStatusLabel(tsHover.status) }}</span></div>
            <div class="gtt-row"><span class="gtt-label">开始</span><span class="gtt-val">{{ tsHover.startTime }}</span></div>
            <div class="gtt-row"><span class="gtt-label">结束</span><span class="gtt-val">{{ tsHover.endTime || '-' }}</span></div>
            <div class="gtt-row"><span class="gtt-label">时长</span><span class="gtt-val gtt-highlight">{{ tsFormatDuration(tsHover.duration) }}</span></div>
          </div>
        </div>
      </div>

      <div class="pagination-wrapper">
        <span>共 {{ tsTotal }} 条</span>
        <el-pagination small layout="sizes, prev, pager, next, jumper"
          v-model:current-page="tsPageNo" v-model:page-size="tsPageSize"
          :total="tsTotal" :page-sizes="[12, 24, 48]" @size-change="fetchTimelineData" @current-change="fetchTimelineData" />
      </div>
    </div>

    <!-- ========== 稼动率:Canvas多图表视图 ========== -->
    <div v-else-if="currentStatus === 'utilization'" class="tab-content util-view" ref="utilWrapRef">
      <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="month">月查询</el-radio-button>
        </el-radio-group>
        <el-date-picker v-if="utilQueryMode === 'day'" v-model="utilDayDate" type="date"
          placeholder="" size="small" style="width:160px;margin-left:8px;"
          value-format="YYYY-MM-DD" :disabled-date="disabledDateFuture" @change="fetchUtilData" />
        <el-date-picker v-if="utilQueryMode === 'week'" v-model="utilWeekDate" type="date"
          placeholder="" size="small" style="width:160px;margin-left:8px;"
          value-format="YYYY-MM-DD" :disabled-date="disabledDateFuture" @change="fetchUtilData" />
        <el-date-picker v-if="utilQueryMode === 'month'" v-model="utilMonthDate" type="month"
          placeholder="" size="small" style="width:160px;margin-left:8px;"
          value-format="YYYY-MM" :disabled-date="disabledMonthFuture" @change="fetchUtilData" />
        <div style="flex:1"></div>
        <el-button type="primary" size="small" @click="fetchUtilData">查询</el-button>
      </div>

      <div class="util-top-charts">
        <div class="pie-card">
          <div class="pie-title">总稼动率:</div>
          <div class="pie-canvas-wrap"><canvas ref="utilTotalPieCanvasRef"></canvas></div>
        </div>
        <div class="pie-card">
          <div class="pie-title">当前机台运行状态:</div>
          <div class="pie-canvas-wrap"><canvas ref="utilStatusPieCanvasRef"></canvas></div>
        </div>
        <div class="bar-card">
          <div class="pie-title">异常机台排名:</div>
          <div class="bar-canvas-wrap" style="position:relative;">
            <canvas ref="utilRankCanvasRef" @mousemove="onUtilRankHover" @mouseleave="onUtilRankLeave"></canvas>
            <div v-if="utilRankHover.show" class="rank-tooltip" :style="{ left: utilRankHover.x + 'px', top: utilRankHover.y + 'px' }">
              <div class="rtt-name">{{ utilRankHover.deviceName }}</div>
              <div class="rtt-row"><i class="dot y"></i>待机<span>{{ utilRankHover.s2Label }}</span></div>
              <div class="rtt-row"><i class="dot r"></i>停机<span>{{ utilRankHover.s1Label }}</span></div>
            </div>
          </div>
        </div>
      </div>

      <div class="util-bottom-chart">
        <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-chart canvas-stack-bar" style="position:relative;">
          <canvas ref="utilStackBarCanvasRef" @mousemove="onUtilStackHover" @mouseleave="onUtilStackLeave"></canvas>
          <div v-if="utilStackHover.show" class="stack-tooltip" :style="{ left: utilStackHover.x + 'px', top: utilStackHover.y + 'px' }">
            <div class="stt-name">{{ utilStackHover.deviceName }}</div>
            <div class="stt-row"><i class="dot g"></i>运行<span>{{ utilStackHover.s3Label }}</span></div>
            <div class="stt-row"><i class="dot y"></i>待机<span>{{ utilStackHover.s2Label }}</span></div>
            <div class="stt-row"><i class="dot r"></i>停机<span>{{ utilStackHover.s1Label }}</span></div>
            <div class="stt-row"><i class="dot gy"></i>离线<span>{{ utilStackHover.s0Label }}</span></div>
          </div>
        </div>
      </div>
    </div>

    <!-- ========== 能耗效率:折线图 / 表格 ========== -->
    <div v-else-if="currentStatus === 'efficiency'" class="tab-content eff-view" ref="effWrapRef">
      <div class="eff-toolbar">
        <span class="eff-label">查询方式:</span>
        <el-radio-group v-model="effQueryMode" size="small" @change="onEffModeChange">
          <el-radio-button value="hour">时查询</el-radio-button>
          <el-radio-button value="day">日查询</el-radio-button>
          <el-radio-button value="month">月查询</el-radio-button>
        </el-radio-group>
        <el-date-picker v-if="effQueryMode === 'hour'" v-model="effHourDate" type="date"
          placeholder="" size="small" style="width:160px;margin-left:8px;"
          value-format="YYYY-MM-DD" :disabled-date="disabledDateFuture" @change="() => nextTick(fetchEffData)" />
        <el-date-picker v-if="effQueryMode === 'day'" v-model="effDayDate" type="month"
          placeholder="" size="small" style="width:160px;margin-left:8px;"
          value-format="YYYY-MM" :disabled-date="disabledMonthFuture" @change="() => nextTick(fetchEffData)" />
        <el-date-picker v-if="effQueryMode === 'month'" v-model="effMonthDate" type="year"
          placeholder="" size="small" style="width:120px;margin-left:8px;"
          value-format="YYYY" :disabled-date="disabledYearFuture" @change="() => nextTick(fetchEffData)" />
        <el-select v-model="effDeviceFilter" size="small" style="width:140px;margin-left:8px;" multiple collapse-tags collapse-tags-tooltip :max-collapse-tags="2">
          <el-option v-for="dev in effAllDevices" :key="dev.dtuSn" :label="dev.deviceName || dev.dtuSn" :value="dev.dtuSn" />
        </el-select>
        <el-button type="primary" size="small" @click="fetchEffData" style="margin-left:4px;">查询</el-button>
        <!-- 视图切换图标按钮 -->
        <el-tooltip content="历史数据表格" placement="bottom" :show-after="300">
          <button size="small" :class="['action-btn', 'view-btn', { 'active': effViewMode === 'table' }]"
            @click="toggleEffView('table')" style="border:1px solid #dcdfe6;">
            <svg viewBox="0 0 16 16" width="14" height="14" fill="currentColor">
              <rect x="1.5" y="2.5" width="5" height="4" rx="0.5"/><rect x="9.5" y="2.5" width="5" height="4" rx="0.5"/>
              <rect x="1.5" y="8.5" width="5" height="5" rx="0.5"/><rect x="9.5" y="8.5" width="5" height="5" rx="0.5"/>
            </svg>
          </button>
        </el-tooltip>
        <el-tooltip content="历史数据折线图" placement="bottom" :show-after="300">
          <button size="small" :class="['action-btn', 'view-btn', { 'active': effViewMode === 'chart' }]"
            @click="toggleEffView('chart')" style="border:1px solid #dcdfe6;">
            <svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.3" stroke-linecap="round" stroke-linejoin="round">
              <polyline points="1,13 4,7 8,10 12,3 15,6"/>
            </svg>
          </button>
        </el-tooltip>
      </div>

      <!-- ========== 折线图视图 ========== -->
      <template v-if="effViewMode === 'chart'">
      <!-- 动态图例(可点击筛选) -->
      <div class="eff-legend" v-if="effDeviceList.length > 0">
        <span v-for="(dev, idx) in effDeviceList" :key="dev.dtuSn"
          class="leg-line"
          :class="{ 'leg-dimmed': effHiddenDevices.has(dev.dtuSn) }"
          :style="'--lc:' + EFF_LINE_COLORS[idx % EFF_LINE_COLORS.length]"
          @click="toggleEffDevice(dev.dtuSn)">
          <i></i>{{ dev.deviceName || dev.dtuSn }}
        </span>
      </div>

      <!-- Canvas 折线图 -->
      <div class="eff-chart canvas-eff-chart" style="position:relative;" v-loading="effLoading">
        <canvas ref="effChartCanvasRef" @mousemove="onEffChartHover" @mouseleave="onEffChartLeave"></canvas>
        <div v-if="effHover.show" class="eff-tooltip" :style="{ left: effHover.x + 'px', top: effHover.y + 'px' }">
          <div class="eft-title">{{ effHover.timeLabel }}</div>
          <div v-for="(item, idx) in effHover.devices" :key="idx" class="eft-row">
            <i class="dot" :style="{ background: item.color }"></i>
            <span class="eft-name">{{ item.name }}</span>
            <span class="eft-val">{{ item.value }} kw·h</span>
          </div>
        </div>
      </div>

      <!-- 总用电量统计 -->
      <div class="eff-summary" v-if="effTotalKwh !== null">
        <span class="eff-sum-label">总用电量:</span>
        <span class="eff-sum-val">{{ effTotalKwh.toFixed(2) }} kw·h</span>
        <span class="eff-sum-count">({{ effDeviceList.length }} 台设备)</span>
      </div>
      </template>

      <!-- ========== 表格视图 ========== -->
      <template v-else>
      <div class="eff-table-wrap" v-loading="effLoading">
        <table class="eff-history-table" v-if="effTableColumns.length > 0 && effTableRows.length > 0">
          <thead>
            <tr>
              <th class="col-name">设备名称</th>
              <th v-for="(col, ci) in effTableColumns" :key="ci">{{ col.label }}</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(row, ri) in effTableRows" :key="ri">
              <td class="td-name">{{ row.deviceName }}</td>
              <td v-for="(col, ci) in effTableColumns" :key="ci">{{ row.values[ci] != null ? row.values[ci] : '-' }}</td>
            </tr>
          </tbody>
        </table>
        <div v-else class="eff-table-empty">
          暂无数据
        </div>
      </div>
      </template>
    </div>

    <!-- 能耗报表弹窗 -->
    <EnergyReportDialog
      v-model:visible="dialogVisible.report"
      :device="currentDevice"
    />
    <!-- 用电安全弹窗 -->
    <SafetyDialog
      v-model:visible="dialogVisible.safety"
      :device="currentDevice"
    />
    <!-- 预警设置弹窗 -->
    <WarningSettingDialog
      v-model:visible="dialogVisible.warning"
      :device="currentDevice"
    />
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch, nextTick, onBeforeUnmount } from 'vue'
import { Search, Menu, Document, Lock, Setting, Warning, Histogram } from '@element-plus/icons-vue'
import EnergyReportDialog from '../components/EnergyReportDialog.vue'
import SafetyDialog from '../components/SafetyDialog.vue'
import WarningSettingDialog from '../components/WarningSettingDialog.vue'

const selectedFactory = ref('新建')
const searchKeyword = ref('')
const currentStatus = ref('realtime')
const runStatusFilter = ref('') // runStatus 筛选: ''=全部, '0'=离线, '1'=停机, '2'=待机, '3'=运行

// 各状态数量(接口返回后更新)
const totalCounts = reactive({ all: 0, stop: 0, standby: 0, run: 0, offline: 0 })

// 点击状态筛选
function filterByRunStatus(runStatus) {
  if (runStatusFilter.value === runStatus) return
  runStatusFilter.value = runStatus
  currentPage.value = 1
  fetchDeviceList()
}

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

// 能耗页面4个Tab(第4个是能耗效率,与智能灯不同)
const statusTabs = [
  { key: 'realtime', label: '实时状态' },
  { key: 'timeseries', label: '时序状态' },
  { key: 'utilization', label: '稼动率' },
  { key: 'efficiency', label: '能耗效率' }
]

const deviceList = ref([])
const totalDevices = ref(0)

const PAGE_SIZE = 12
const currentPage = ref(1)
const totalPages = computed(() => Math.ceil(totalDevices.value / PAGE_SIZE) || 1)
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
})
// 服务端分页,pagedDevices 直接使用接口返回的 list
const pagedDevices = computed(() => deviceList.value)

// 获取能耗设备列表
async function fetchDeviceList() {
  try {
    const params = new URLSearchParams({
      pageNo: currentPage.value,
      pageSize: PAGE_SIZE,
      projectState: '1',
    })
    if (searchKeyword.value) params.append('deviceName', searchKeyword.value)
    if (runStatusFilter.value !== '') params.append('runStatus', runStatusFilter.value)

    const res = await fetch(`/api/energy/list?${params}`)
    const data = await res.json()
    deviceList.value = (data.list || []).map(item => ({
      id: item.id,
      name: item.deviceName || item.dtuSn,
      evalue: parseFloat(item.evalue) || 0,
      runStatus: String(item.runStatus ?? '0'),
      duration: item.duration || '0秒',
      _raw: item,
    }))
    totalDevices.value = data.total || 0

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

// 获取运行状态统计
async function fetchStats() {
  try {
    const res = await fetch('/api/energy/stats')
    const data = await res.json()
    totalCounts.all = data.total || 0
    totalCounts.offline = parseInt(data['0']) || 0  // runStatus=0 离线
    totalCounts.stop = parseInt(data['1']) || 0      // runStatus=1 停机
    totalCounts.standby = parseInt(data['2']) || 0   // runStatus=2 待机
    totalCounts.run = parseInt(data['3']) || 0       // runStatus=3 运行
  } catch (err) {
    console.error('获取能耗统计失败:', err)
  }
}

// 页面挂载时加载设备列表
onMounted(() => {
  fetchDeviceList()
})

// runStatus 状态文字映射
const RUN_STATUS_LABELS = { '0': '离线', '1': '停机', '2': '待机', '3': '运行' }
function getRunStatusLabel(runStatus) {
  return RUN_STATUS_LABELS[String(runStatus)] || '未知'
}

const dialogVisible = reactive({
  report: false,
  safety: false,
  param: false,
  warning: false,
  setting: false
})
const currentDevice = ref(null)

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

// ========== 时序状态:Canvas甘特图 ==========
const TS_STATUS_COLORS = { 0: '#909399', 1: '#e74c3c', 2: '#67c23a', 3: '#c5d94e' }
const TS_STATUS_MAP = { 0: '离线', 1: '停机', 2: '运行', 3: '待机' }

const tsQueryMode = ref('day')
const tsSelectedDate = ref(new Date().toISOString().slice(0, 10))
const tsPageNo = ref(1)
const tsPageSize = ref(12)
const tsTotal = ref(0)
const tsLoading = ref(false)
const tsTimelineList = ref([])
// 视图缩放:zoomLevel=1显示24h,越大显示的时间范围越短
const tsZoomLevel = ref(1)
const TS_ZOOM_MIN = 1       // 最小:一屏24h
const TS_ZOOM_MAX = 8       // 最大:一屏约3h
// 视图中心时间点(毫秒),用于鼠标位置为中心的缩放
const tsViewCenterMs = ref(0)

function disabledDateFuture(time) { return time.getTime() > Date.now() }
function onTsModeChange() { fetchTimelineData() }
function tsStatusLabel(s) { return TS_STATUS_MAP[s] || '未知' }
function tsFormatDuration(sec) {
  if (!sec && sec !== 0) return '-'
  sec = Number(sec)
  const h = Math.floor(sec / 3600), m = Math.floor((sec % 3600) / 60), s = sec % 60
  let str = ''
  if (h > 0) str += h + '时'
  if (m > 0) str += m + '分'
  if (s > 0 || !str) str += s + '秒'
  return str
}

// Canvas refs
const tsFixedCanvasRef = ref(null)
const tsGanttCanvasRef = ref(null)
const tsScrollAreaRef = ref(null)
let tsResizeObs = null

// Hover
const tsHover = reactive({ show: false, x: 0, y: 0, rowIdx: -1, segIdx: -1,
  deviceName: '', status: 0, startTime: '', endTime: '', duration: 0 })
let tsHitRects = []

// 布局常量
const TS_ROW_H = 36
const TS_FIXED_W = 220
const TS_AXIS_H = 32

async function fetchTimelineData() {
  tsLoading.value = true
  tsZoomLevel.value = 1
  tsViewCenterMs.value = 0
  try {
    const url = `/api/energy/timelineStatus?date=${tsSelectedDate.value}&pageSize=${tsPageSize.value}&pageNo=${tsPageNo.value}`
    const res = await fetch(url)
    const data = await res.json()
    if (data.code === 200) {
      tsTimelineList.value = data.list || []
      tsTotal.value = data.total || 0
      await nextTick()
      drawTsAll()
    }
  } catch (err) {
    console.error('获取时序状态失败:', err)
  } finally {
    tsLoading.value = false
  }
}

function getDpr() { return window.devicePixelRatio || 1 }

function drawTsAll() { drawTsFixedCol(); drawTsGanttChart(); }

// 左侧固定列绘制
function drawTsFixedCol() {
  const canvas = tsFixedCanvasRef.value; if (!canvas) return
  const list = tsTimelineList.value
  const h = Math.max(TS_AXIS_H + list.length * TS_ROW_H + 8, 80)
  canvas.width = TS_FIXED_W * getDpr(); canvas.height = h * getDpr()
  canvas.style.width = TS_FIXED_W + 'px'; canvas.style.height = h + 'px'
  const ctx = canvas.getContext('2d'); ctx.scale(getDpr(), getDpr())
  ctx.fillStyle = '#fafafa'; ctx.fillRect(0, 0, TS_FIXED_W, h)

  // 表头
  ctx.fillStyle = '#f0f2f5'; ctx.fillRect(0, 0, TS_FIXED_W, TS_AXIS_H)
  ctx.strokeStyle = '#e4e7ed'; ctx.lineWidth = 1
  ctx.beginPath(); ctx.moveTo(0, TS_AXIS_H); ctx.lineTo(TS_FIXED_W, TS_AXIS_H); ctx.stroke()

  ctx.font = 'bold 13px sans-serif'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; ctx.fillStyle = '#333'
  const cW = [TS_FIXED_W * 0.42, TS_FIXED_W * 0.22, TS_FIXED_W * 0.36]
  ctx.fillText('设备名称', cW[0] / 2, TS_AXIS_H / 2)
  ctx.fillText('稼动率', cW[0] + cW[1] / 2, TS_AXIS_H / 2)
  ctx.fillText('用电量', cW[0] + cW[1] + cW[2] / 2, TS_AXIS_H / 2)

  // 列分隔线
  ctx.strokeStyle = '#ebeef5'
  let cx = cW[0]; ctx.beginPath(); ctx.moveTo(cx, 0); ctx.lineTo(cx, h); ctx.stroke()
  cx += cW[1]; ctx.beginPath(); ctx.moveTo(cx, 0); ctx.lineTo(cx, h); ctx.stroke()

  // 数据行
  ctx.font = '12px sans-serif'
  list.forEach((item, i) => {
    const y = TS_AXIS_H + i * TS_ROW_H
    if (i % 2 === 1) { ctx.fillStyle = '#f9f9f9'; ctx.fillRect(0, y, TS_FIXED_W, TS_ROW_H) }
    ctx.strokeStyle = '#f0f0f0'; ctx.beginPath(); ctx.moveTo(0, y + TS_ROW_H); ctx.lineTo(TS_FIXED_W, y + TS_ROW_H); ctx.stroke()
    const cy = y + TS_ROW_H / 2
    ctx.fillStyle = '#303133'; ctx.textAlign = 'left'
    ctx.fillText(item.deviceName || item.dtuSn || '-', 10, cy)
    const ur = item.utilizationRate ?? 0
    ctx.fillStyle = ur >= 30 ? '#67c23a' : ur > 0 ? '#e6a23c' : '#909399'
    ctx.textAlign = 'center'
    ctx.fillText((ur % 1 === 0 ? ur.toFixed(1) : ur.toFixed(2)) + '%', cW[0] + cW[1] / 2, cy)
    ctx.fillStyle = '#303133'; ctx.textAlign = 'right'
    ctx.fillText(String(item.totalKwh ?? 0), cW[0] + cW[1] + cW[2] - 8, cy)
  })
}

// 甘特图绘制(视图缩放:canvas宽度始终=容器宽度,不产生滚动条)
function drawTsGanttChart() {
  const canvas = tsGanttCanvasRef.value; const wrap = tsScrollAreaRef.value
  if (!canvas || !wrap) return
  const list = tsTimelineList.value
  const w = wrap.clientWidth || 800
  const h = Math.max(TS_AXIS_H + list.length * TS_ROW_H + 8, 80)

  canvas.width = w * getDpr(); canvas.height = h * getDpr()
  canvas.style.width = w + 'px'; canvas.style.height = h + 'px'
  const ctx = canvas.getContext('2d'); ctx.scale(getDpr(), getDpr())

  ctx.clearRect(0, 0, w, h)
  tsHitRects = []

  const dateStr = tsSelectedDate.value || new Date().toISOString().slice(0, 10)
  const dayStartMs = new Date(dateStr + 'T00:00:00').getTime()
  const dayEndMs = dayStartMs + 86400000

  // 根据zoomLevel计算可见时间范围(小时)
  const visibleHours = Math.max(24 / tsZoomLevel.value, 3)
  const visibleMs = visibleHours * 3600000

  // 视图中心点,默认为当天中午
  let center = tsViewCenterMs.value || (dayStartMs + 43200000)
  if (tsZoomLevel.value <= 1) center = dayStartMs + 43200000
  const halfVis = visibleMs / 2
  if (center - halfVis < dayStartMs) center = dayStartMs + halfVis
  if (center + halfVis > dayEndMs) center = dayEndMs - halfVis

  const viewStartMs = center - halfVis
  const viewEndMs = center + halfVis
  const viewRangeMs = viewEndMs - viewStartMs

  // 表头背景
  ctx.fillStyle = '#f0f2f5'; ctx.fillRect(0, 0, w, TS_AXIS_H)
  ctx.strokeStyle = '#e4e7ed'; ctx.lineWidth = 1
  ctx.beginPath(); ctx.moveTo(0, TS_AXIS_H); ctx.lineTo(w, TS_AXIS_H); ctx.stroke()

  // 时间刻度(根据可见范围动态调整间隔)
  ctx.font = '11px sans-serif'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; ctx.fillStyle = '#666'
  let stepMinutes = 60
  if (visibleHours <= 4) stepMinutes = 15
  else if (visibleHours <= 8) stepMinutes = 30
  else if (visibleHours <= 16) stepMinutes = 45

  const tickStep = stepMinutes * 60000
  const firstTick = Math.ceil(viewStartMs / tickStep) * tickStep
  for (let t = firstTick; t <= viewEndMs; t += tickStep) {
    const px = ((t - viewStartMs) / viewRangeMs) * w
    ctx.strokeStyle = '#ebeef5'; ctx.lineWidth = 0.5
    ctx.beginPath(); ctx.moveTo(px, TS_AXIS_H); ctx.lineTo(px, h); ctx.stroke()
    const hh = new Date(t).getHours(), mm = new Date(t).getMinutes()
    ctx.fillText(hh.toString().padStart(2,'0')+':'+mm.toString().padStart(2,'0'), px, TS_AXIS_H/2)
  }

  // 数据行条带
  list.forEach((item, rowIdx) => {
    const y = TS_AXIS_H + rowIdx * TS_ROW_H
    const barY = y + TS_ROW_H * 0.15; const barH = TS_ROW_H * 0.7
    if (rowIdx % 2 === 1) { ctx.fillStyle = '#f9f9f9'; ctx.fillRect(0, y, w, TS_ROW_H) }
    ctx.strokeStyle = '#f0f0f0'; ctx.beginPath(); ctx.moveTo(0, y+TS_ROW_H); ctx.lineTo(w, y+TS_ROW_H); ctx.stroke()

    ;(item.timelineList || []).forEach((seg, segIdx) => {
      if (!seg.duration || seg.duration <= 0) return
      const sMs = new Date(seg.startTime).getTime()
      const eMs = seg.endTime ? new Date(seg.endTime).getTime() : sMs + (seg.duration||0)*1000
      const x = ((sMs - viewStartMs) / viewRangeMs) * w
      const sw = Math.max(((eMs - sMs) / viewRangeMs) * w, 2)
      const drawW = Math.max(Math.min(sw, w - x - 1), 0)

      const isHover = (tsHover.show && rowIdx===tsHover.rowIdx && segIdx===tsHover.segIdx)
      ctx.fillStyle = isHover ? (TS_STATUS_COLORS[seg.runStatus]||'#ccc'):(TS_STATUS_COLORS[seg.runStatus]||'#ccc')
      ctx.globalAlpha = isHover?1:0.85
      if(drawW > 0) roundRect(ctx,x,barY,drawW,barH,0);ctx.fill()
      ctx.globalAlpha=1

      if(x+sw>=-50 && x<w+50){
        tsHitRects.push({rowIdx,segIdx,x,y:barY,w:drawW,h:barH,
          ...item,runStatus:seg.runStatus,startTime:seg.startTime,endTime:seg.endTime||'',duration:seg.duration})
      }
    })
  })

  // 当前时间线
  const now=Date.now(),nowPx=((now-viewStartMs)/viewRangeMs)*w
  if(nowPx>=0 && nowPx<=w){ctx.strokeStyle='#e74c3c';ctx.lineWidth=1.5;ctx.setLineDash([4,3])
    ctx.beginPath();ctx.moveTo(nowPx,TS_AXIS_H);ctx.lineTo(nowPx,h);ctx.stroke();ctx.setLineDash([])}
}

// 鼠标滚轮缩放:以鼠标位置为中心放大/缩小可见时间范围(无滚动条)
let tsZoomLock=false
function onTsGanttWheel(e){
  e.preventDefault();if(tsZoomLock)return
  tsZoomLock=true;setTimeout(()=>{tsZoomLock=false},60)

  const delta=e.deltaY>0?-0.25:0.25
  let newL=Math.max(TS_ZOOM_MIN,Math.min(TS_ZOOM_MAX,tsZoomLevel.value+delta))
  if(newL===tsZoomLevel.value)return

  const wrap=tsScrollAreaRef.value,cnv=tsGanttCanvasRef.value
  if(!wrap||!cnv)return
  const rect=cnv.getBoundingClientRect(),mx=e.clientX-rect.left

  const dateStr=tsSelectedDate.value||new Date().toISOString().slice(0,10)
  const dayStartMs=new Date(dateStr+'T00:00:00').getTime()

  const oldVH=Math.max(24/tsZoomLevel.value,3),oldVM=oldVH*3600000
  let center=tsViewCenterMs.value||(dayStartMs+43200000)
  let oldVS=center-oldVM/2;if(oldVS<dayStartMs)oldVS=dayStartMs
  const mouseTimeAt=oldVS+(mx/rect.width)*oldVM

  tsZoomLevel.value=newL
  const newVH=Math.max(24/newL,3),newVM=newVH*3600000
  const newVS=mouseTimeAt-(mx/rect.width)*newVM
  tsViewCenterMs.value=newVS+newVM/2

  drawTsAll()
}

function roundRect(ctx, x, y, w, h, r) {
  if (w < 1 || h < 1) return
  if (r > w / 2) r = w / 2
  if (r > h / 2) r = h / 2
  if (r <= 0) { ctx.fillRect(x, y, w, h); return }
  ctx.beginPath(); ctx.moveTo(x+r, y); ctx.arcTo(x+w, y, x+w, y+h, r)
  ctx.arcTo(x+w, y+h, x, y+h, r); ctx.arcTo(x, y+h, x, y, r); ctx.arcTo(x, y, x+w, y, r); ctx.closePath()
}

// Hover事件
function onTsGanttMouseMove(e) {
  const canvas = tsGanttCanvasRef.value; const wrap = tsScrollAreaRef.value
  if (!canvas || !wrap) return
  const rect = canvas.getBoundingClientRect()
  const mx = e.clientX - rect.left, my = e.clientY - rect.top
  let hit = null
  for (let i = tsHitRects.length - 1; i >= 0; i--) {
    const r = tsHitRects[i]
    if (mx >= r.x && mx <= r.x + r.w && my >= r.y && my <= r.y + r.h) { hit = r; break }
  }
  if (hit) {
    tsHover.rowIdx = hit.rowIdx; tsHover.segIdx = hit.segIdx
    tsHover.deviceName = hit.deviceName || hit.dtuSn || ''
    tsHover.status = hit.runStatus ?? 0
    tsHover.startTime = hit.startTime ? hit.startTime.slice(11, 19) : ''
    tsHover.endTime = hit.endTime ? hit.endTime.slice(11, 19) : ''
    tsHover.duration = hit.duration || 0
    if (!tsHover.show) {
      tsHover.show = true
      let tx = mx + 12, ty = my - 100
      if (tx + 180 > wrap.clientWidth - 20) tx = mx - 190
      if (ty < 10) ty = my + 16
      tsHover.x = tx; tsHover.y = ty
    }
  } else {
    tsHover.show = false
  }
  drawTsGanttChart()
}
function onTsGanttMouseLeave() { tsHover.show = false; drawTsGanttChart() }
function onTsScroll() { drawTsFixedCol() }

// 监听tab切换自动加载
watch(currentStatus, async (val) => {
  if (val === 'timeseries') {
    await nextTick()
    initTsObserver()
    fetchTimelineData()
  } else {
    destroyTsObserver()
  }
})

function initTsObserver() {
  destroyTsObserver()
  tsResizeObs = new ResizeObserver(() => { if (currentStatus.value === 'timeseries') drawTsAll() })
  const el = document.querySelector('.ts-gantt-wrap')
  if (el) tsResizeObs.observe(el)
}
function destroyTsObserver() { if (tsResizeObs) { tsResizeObs.disconnect(); tsResizeObs = null } }
onBeforeUnmount(() => destroyTsObserver())

// ========== 稼动率:Canvas多图表 ==========
const UTIL_COLORS = { 0: '#909399', 1: '#f56c6c', 2: '#e6a23c', 3: '#67c23a' }
const UTIL_STATUS_LABEL = { 0: '离线', 1: '停机', 2: '待机', 3: '运行' }

const utilQueryMode = ref('day')
const utilDayDate = ref(new Date().toISOString().slice(0, 10))
const utilWeekDate = ref(new Date().toISOString().slice(0, 10))
const utilMonthDate = ref(new Date().toISOString().slice(0, 7))
const sortMode = ref('rate')

// Canvas refs
const utilTotalPieCanvasRef = ref(null)
const utilStatusPieCanvasRef = ref(null)
const utilRankCanvasRef = ref(null)
const utilStackBarCanvasRef = ref(null)
let utilResizeObs = null

// 堆积柱状图 hover
const utilStackHover = reactive({ show: false, x: 0, y: 0, deviceName: '', s3Label: '', s2Label: '', s1Label: '', s0Label: '' })
let stackHitRects = []

// 接口数据
const utilData = reactive({
  currentStatus: {},
  deviceList: [],
  summary: {},
  abnormalRanking: []
})

// 异常机台排名 hover 状态
const utilRankHover = reactive({ show: false, x: 0, y: 0, deviceName: '', s1Label: '', s2Label: '' })
let rankHitRects = []

function disabledMonthFuture(time) {
  const now = new Date()
  return time.getFullYear() > now.getFullYear() || (time.getFullYear() === now.getFullYear() && time.getMonth() > now.getMonth())
}

async function fetchUtilData() {
  let startDate, endDate
  if (utilQueryMode.value === 'day') {
    startDate = utilDayDate.value
    endDate = utilDayDate.value
  } else if (utilQueryMode.value === 'week') {
    const d = new Date(utilWeekDate.value)
    const day = d.getDay() || 7
    const mon = new Date(d)
    mon.setDate(d.getDate() - day + 1)
    const sun = new Date(mon)
    sun.setDate(mon.getDate() + 6)
    startDate = mon.toISOString().slice(0, 10)
    endDate = sun.toISOString().slice(0, 10)
  } else {
    startDate = utilMonthDate.value + '-01'
    const [y, m] = utilMonthDate.value.split('-')
    const lastDay = new Date(parseInt(y), parseInt(m), 0).getDate()
    endDate = utilMonthDate.value + '-' + String(lastDay).padStart(2, '0')
  }
  try {
    const res = await fetch(`/api/energy/eqKwhStatistics?startDate=${startDate}&endDate=${endDate}`)
    const result = await res.json()
    if (result.code === 200) {
      const data = result.data || {}
      Object.assign(utilData.currentStatus, data.currentStatus || {})
      utilData.deviceList = data.deviceList || []
      Object.assign(utilData.summary, data.summary || {})
      utilData.abnormalRanking = data.abnormalRanking || []
      await nextTick()
      drawUtilAll()
    }
  } catch (err) {
    console.error('获取稼动率数据失败:', err)
  }
}

function drawUtilAll() { drawUtilTotalPie(); drawUtilStatusPie(); drawUtilRankBar(); drawUtilStackBar(); }

// ---- 总稼动率饼图(普通饼图,不含离线) ----
function drawUtilTotalPie() {
  const canvas = utilTotalPieCanvasRef.value; if (!canvas) return
  const wrap = canvas.parentElement; if (!wrap) return
  const w = wrap.clientWidth, h = wrap.clientHeight || 220
  canvas.width = w * getDpr(); canvas.height = h * getDpr()
  canvas.style.width = w + 'px'; canvas.style.height = h + 'px'
  const ctx = canvas.getContext('2d'); ctx.scale(getDpr(), getDpr())
  ctx.clearRect(0, 0, w, h)

  const summary = utilData.summary
  const totalDur = summary.totalStatusDuration || {}
  const s1 = totalDur.status1?.durationSeconds || 0
  const s2 = totalDur.status2?.durationSeconds || 0
  const s3 = totalDur.status3?.durationSeconds || 0
  const total = s1 + s2 + s3

  // 饼图居中偏左,给右侧图例留空间,半径更大
  const cx = w * 0.4, cy = h / 2, R = Math.min(cx, cy) * 0.85

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

  // 扇区:运行、待机、停机(不含离线)
  const segs = [
    { val: s3, color: UTIL_COLORS[3], label: '运行' },
    { val: s2, color: UTIL_COLORS[2], label: '待机' },
    { val: s1, color: UTIL_COLORS[1], label: '停机' },
  ]

  let startA = -Math.PI / 2
  segs.forEach(seg => {
    const sweep = (seg.val / total) * Math.PI * 2
    if (seg.val > 0 && sweep > 0.02) {
      ctx.beginPath()
      ctx.moveTo(cx, cy)
      ctx.arc(cx, cy, R, startA, startA + sweep)
      ctx.closePath()
      ctx.fillStyle = seg.color; ctx.fill()

      // 标签:百分比 + 状态名:时长(水平居中)
      if (sweep > 0.25 || seg.val / total > 0.15) {
        const midA = startA + sweep / 2
        const lr = R * 0.6
        const tx = cx + Math.cos(midA) * lr, ty = cy + Math.sin(midA) * lr
        const pct = ((seg.val / total) * 100).toFixed(2).replace(/\.?0+$/, '') + '%'
        const durHrs = (seg.val / 3600).toFixed(2).replace(/\.?0+$/, '')
        const durLabel = `${seg.label}:${durHrs}时`
        ctx.fillStyle = '#fff'; ctx.font = 'bold 12px sans-serif'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'
        // 水平显示,不旋转
        ctx.fillText(pct, tx, ty - 7)
        ctx.font = '11px sans-serif'
        ctx.fillText(durLabel, tx, ty + 8)
      }
    } else if (seg.val > 0) {
      ctx.beginPath(); ctx.moveTo(cx, cy)
      ctx.arc(cx, cy, R, startA, startA + sweep)
      ctx.closePath()
      ctx.fillStyle = seg.color; ctx.fill()
    }
    startA += sweep
  })

  // 右侧图例(仅运行/待机/停机),向中间靠拢
  const legX = cx + R + 20, legStartY = cy - 30
  ;segs.map(s => ({ c: s.color, l: s.label })).forEach((leg, i) => {
    const ly = legStartY + i * 24
    ctx.fillStyle = leg.c; roundRect(ctx, legX, ly - 6, 12, 12, 2); ctx.fill()
    ctx.fillStyle = '#666'; ctx.font = '12px sans-serif'; ctx.textAlign = 'left'; ctx.textBaseline = 'middle'
    ctx.fillText(leg.l, legX + 18, ly)
  })
}

function drawUtilLegend(ctx, cx, ly) {
  ctx.textAlign = 'center'
  ;[{ c: UTIL_COLORS[3], l: '运行' }, { c: UTIL_COLORS[2], l: '待机' }, { c: UTIL_COLORS[1], l: '停机' }, { c: UTIL_COLORS[0], l: '离线' }].forEach((leg, i) => {
    const lx = cx - 60 + i * 40
    ctx.fillStyle = leg.c; roundRect(ctx, lx - 4, ly - 4, 10, 10, 2); ctx.fill()
    ctx.fillStyle = '#666'; ctx.font = '11px sans-serif'; ctx.fillText(leg.l, lx + 7, ly + 4)
  })
}

// ---- 当前机台运行状态饼图(普通,图例在右侧) ----
function drawUtilStatusPie() {
  const canvas = utilStatusPieCanvasRef.value; if (!canvas) return
  const wrap = canvas.parentElement; if (!wrap) return
  const w = wrap.clientWidth, h = wrap.clientHeight || 220
  canvas.width = w * getDpr(); canvas.height = h * getDpr()
  canvas.style.width = w + 'px'; canvas.style.height = h + 'px'
  const ctx = canvas.getContext('2d'); ctx.scale(getDpr(), getDpr())
  ctx.clearRect(0, 0, w, h)

  const cs = utilData.currentStatus
  const v3 = parseInt(cs['3']) || 0
  const v2 = parseInt(cs['2']) || 0
  const v1 = parseInt(cs['1']) || 0
  const v0 = parseInt(cs['0']) || 0
  const total = v0 + v1 + v2 + v3

  // 饼图居中偏左,与总稼动率一致的大小和布局
  const cx = w * 0.4, cy = h / 2, R = Math.min(cx, cy) * 0.85

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

  // 全部4个状态
  const segs = [
    { val: v3, color: UTIL_COLORS[3], label: '运行' },
    { val: v2, color: UTIL_COLORS[2], label: '待机' },
    { val: v1, color: UTIL_COLORS[1], label: '停机' },
    { val: v0, color: UTIL_COLORS[0], label: '离线' },
  ]

  let startA = -Math.PI / 2
  segs.forEach(seg => {
    const sweep = (seg.val / total) * Math.PI * 2
    if (seg.val > 0 && sweep > 0.02) {
      ctx.beginPath(); ctx.moveTo(cx, cy); ctx.arc(cx, cy, R, startA, startA + sweep); ctx.closePath()
      ctx.fillStyle = seg.color; ctx.fill()

      // 标签水平显示:状态名X台
      if (sweep > 0.25 || seg.val / total > 0.15) {
        const midA = startA + sweep / 2
        const lr = R * 0.6
        const tx = cx + Math.cos(midA) * lr, ty = cy + Math.sin(midA) * lr
        const labelText = `${seg.label}${seg.val}台`
        ctx.fillStyle = '#fff'; ctx.font = 'bold 12px sans-serif'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'
        ctx.fillText(labelText, tx, ty)
      }
    } else if (seg.val > 0) {
      ctx.beginPath(); ctx.moveTo(cx, cy); ctx.arc(cx, cy, R, startA, startA + sweep); ctx.closePath()
      ctx.fillStyle = seg.color; ctx.fill()
    }
    startA += sweep
  })

  // 右侧图例(全部4项)
  const legX = cx + R + 20, legStartY = cy - 36
  segs.forEach((leg, i) => {
    const ly = legStartY + i * 24
    ctx.fillStyle = leg.color; roundRect(ctx, legX, ly - 6, 12, 12, 2); ctx.fill()
    ctx.fillStyle = '#666'; ctx.font = '12px sans-serif'; ctx.textAlign = 'left'; ctx.textBaseline = 'middle'
    ctx.fillText(leg.label, legX + 18, ly)
  })
}

// ---- 异常机台排名(横向堆叠条形,仅停机+待机) ----
function drawUtilRankBar() {
  const canvas = utilRankCanvasRef.value; if (!canvas) return
  const wrap = canvas.parentElement; if (!wrap) return
  const w = wrap.clientWidth
  // 高度按实际数据行数计算,不留多余空白
  const list = utilData.abnormalRanking
  const rowCount = Math.min(list.length, 6)
  const h = Math.max((rowCount === 0 ? 0 : rowCount * 28 + 12 + 20), 60)
  canvas.width = w * getDpr(); canvas.height = h * getDpr()
  canvas.style.width = w + 'px'; canvas.style.height = h + 'px'
  const ctx = canvas.getContext('2d'); ctx.scale(getDpr(), getDpr())
  ctx.clearRect(0, 0, w, h)

  rankHitRects = []

  if (!list.length) {
    ctx.fillStyle = '#c0c4cc'; ctx.font = '13px sans-serif'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'
    ctx.fillText('暂无数据', w / 2, h / 2); return
  }

  const padL = 100, padT = 12, padB = 20, barH = 22, gap = 6
  const legW = 55 // 右侧图例宽度
  const chartW = w - padL - legW - 10
  const chartH = h - padT - padB

  // X轴基准:取数据中 s1+s2 的最大值,向上取整到漂亮数字
  const rawMaxSec = Math.max(...list.slice(0, 6).map(d =>
    (Number(d.status1?.durationSeconds || 0)) + (Number(d.status2?.durationSeconds || 0))), 1)
  const axisMaxSec = niceAxisMaxHours(rawMaxSec / 3600) * 3600

  // 网格线
  ctx.strokeStyle = '#f0f0f0'; ctx.lineWidth = 1
  for (let g = 1; g <= 5; g++) {
    const gy = padT + chartH * (g / 5)
    ctx.beginPath(); ctx.moveTo(padL, gy); ctx.lineTo(padL + chartW, gy); ctx.stroke()
  }

  list.slice(0, 6).forEach((item, i) => {
    const y = padT + i * (barH + gap)
    // 设备名
    ctx.fillStyle = '#303133'; ctx.font = '11px sans-serif'; ctx.textAlign = 'right'; ctx.textBaseline = 'middle'
    ctx.fillText(item.deviceName || item.dtuSn || '-', padL - 8, y + barH / 2)

    // 背景条(浅灰)
    ctx.fillStyle = '#fafafa'; roundRect(ctx, padL, y, chartW, barH, 2); ctx.fill()

    // 取停机/待机时长(秒)
    const s1 = Number(item.status1?.durationSeconds ?? 0) || 0
    const s2 = Number(item.status2?.durationSeconds ?? 0) || 0

    let px = padL
    const hitInfo = { x: padL, y, w: 0, h: barH, deviceName: item.deviceName || item.dtuSn || '', s1, s2 }
    // 先画待机(橙#e6a23c),再画停机(红#f56c6c)
    ;[[s2, UTIL_COLORS[2]], [s1, UTIL_COLORS[1]]].forEach(([sec, col]) => {
      if (sec <= 0) return
      const sw = Math.max(chartW * (sec / axisMaxSec), 3)
      ctx.fillStyle = col
      roundRect(ctx, px, y, sw, barH, 2)
      ctx.fill()
      px += sw
      hitInfo.w = px - padL
    })

    rankHitRects.push(hitInfo)
  })

  // X轴时间标签(根据实际最大值动态显示)
  for (let t = 0; t <= 4; t++) {
    const valSec = (t / 4) * axisMaxSec
    const gx = padL + (t / 4) * chartW
    ctx.fillStyle = '#909399'; ctx.font = '10px sans-serif'; ctx.textAlign = 'center'; ctx.textBaseline = 'top'
    ctx.fillText(formatHoursShort(valSec), gx, h - padB + 6)
  }

  // 右侧图例(带颜色的方块+文字)
  const legX = padL + chartW + 12, legStartY = padT + 10
  ;[
    { color: UTIL_COLORS[2], label: '待机' },
    { color: UTIL_COLORS[1], label: '停机' },
  ].forEach((leg, i) => {
    const ly = legStartY + i * 22
    ctx.fillStyle = leg.color
    roundRect(ctx, legX, ly - 6, 11, 11, 2)
    ctx.fill()
    ctx.fillStyle = '#606266'
    ctx.font = '12px sans-serif'
    ctx.textAlign = 'left'
    ctx.textBaseline = 'middle'
    ctx.fillText(leg.label, legX + 16, ly)
  })
}

function onUtilRankHover(e) {
  const canvas = utilRankCanvasRef.value; if (!canvas) return
  const rect = canvas.getBoundingClientRect()
  const mx = e.clientX - rect.left, my = e.clientY - rect.top
  let hit = null
  for (const r of rankHitRects) {
    if (mx >= r.x && mx <= r.x + r.w && my >= r.y && my <= r.y + r.h) { hit = r; break }
  }
  if (hit) {
    utilRankHover.deviceName = hit.deviceName
    const totalS12 = hit.s1 + hit.s2
    const s2Pct = totalS12 > 0 ? ((hit.s2 / totalS12) * 100).toFixed(0) : '0'
    const s1Pct = totalS12 > 0 ? ((hit.s1 / totalS12) * 100).toFixed(0) : '0'
    utilRankHover.s2Label = `${tsFormatDuration(hit.s2)}(${s2Pct}%)`
    utilRankHover.s1Label = `${tsFormatDuration(hit.s1)}(${s1Pct}%)`
    if (!utilRankHover.show) {
      utilRankHover.show = true
      let tx = mx + 12, ty = my - 80
      if (tx + 180 > rect.width) tx = mx - 190
      if (ty < 10) ty = my + 16
      utilRankHover.x = tx; utilRankHover.y = ty
    }
  } else {
    utilRankHover.show = false
  }
}
function onUtilRankLeave() { utilRankHover.show = false }

function formatHoursShort(sec) {
  if (!sec) return ''
  sec = Number(sec)
  const h = Math.floor(sec / 3600), m = Math.floor((sec % 3600) / 60)
  if (h > 0) return h + '.' + String(Math.round(m/60*10)) + '时'
  if (m > 0) return m + '分'
  return sec + '秒'
}

// ---- 设备状态时长堆积柱状图 ----
function drawUtilStackBar() {
  const canvas = utilStackBarCanvasRef.value; if (!canvas) return
  const wrap = canvas.parentElement; if (!wrap) return
  const w = wrap.clientWidth, h = wrap.clientHeight || 260
  canvas.width = w * getDpr(); canvas.height = h * getDpr()
  canvas.style.width = w + 'px'; canvas.style.height = h + 'px'
  const ctx = canvas.getContext('2d'); ctx.scale(getDpr(), getDpr())
  ctx.clearRect(0, 0, w, h)

  let list = [...utilData.deviceList]
  if (sortMode.value === 'rate') {
    list.sort((a, b) => (b.availabilityRateValue || 0) - (a.availabilityRateValue || 0))
  } else {
    list.sort((a, b) => ((b.status3?.durationSeconds||0)) - ((a.status3?.durationSeconds||0)))
  }

  stackHitRects = []
  if (!list.length) {
    ctx.fillStyle = '#c0c4cc'; ctx.font = '13px sans-serif'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'
    ctx.fillText('暂无数据', w / 2, h / 2); return
  }

  const padL = 44, padR = 14, padT = 22, padB = 24 // padB给柱子下方设备名留空间
  const chartW = w - padL - padR
  const chartH = h - padT - padB
  const maxCols = Math.min(list.length, 12)
  const barW = Math.min(Math.max(chartW / maxCols * 0.55, 24), 50)
  const totalBarsW = barW * list.length
  const barGap = list.length > 1 ? (chartW - totalBarsW) / (list.length + 1) : chartW / 2 - barW / 2

  // Y轴:自动找合适的最大值和刻度
  const rawMaxHrs = Math.max(...list.map(d => (d.totalDurationSeconds || 0) / 3600), 1)
  const yMax = niceAxisMax(rawMaxHrs)
  const yTicks = 5

  // Y轴网格和刻度
  ctx.strokeStyle = '#ebeef5'; ctx.lineWidth = 1; ctx.font = '10px sans-serif'; ctx.textAlign = 'right'; ctx.textBaseline = 'middle'
  for (let i = 0; i <= yTicks; i++) {
    const vy = padT + chartH - (i / yTicks) * chartH
    const val = (i / yTicks) * yMax
    ctx.beginPath(); ctx.moveTo(padL, vy); ctx.lineTo(w - padR, vy); ctx.stroke()
    ctx.fillStyle = '#999'; ctx.fillText(val >= 1 ? val.toFixed(0) + '时' : (val * 60).toFixed(0) + '分', padL - 5, vy)
  }

  // 基线
  ctx.strokeStyle = '#ddd'; ctx.lineWidth = 1
  ctx.beginPath(); ctx.moveTo(padL, padT + chartH); ctx.lineTo(w - padR, padT + chartH); ctx.stroke()

  const scale = chartH / yMax

  list.forEach((item, i) => {
    const bx = padL + barGap + i * (barW + barGap)
    const s0s = item.status0?.durationSeconds || 0
    const s1s = item.status1?.durationSeconds || 0
    const s2s = item.status2?.durationSeconds || 0
    const s3s = item.status3?.durationSeconds || 0

    let by = padT + chartH
    // 从下到上:运行、待机、停机、离线
    ;[
      { sec: s3s, color: UTIL_COLORS[3] },
      { sec: s2s, color: UTIL_COLORS[2] },
      { sec: s1s, color: UTIL_COLORS[1] },
      { sec: s0s, color: UTIL_COLORS[0] },
    ].reverse().forEach(seg => {
      const sh = seg.sec / 3600 * scale
      by -= sh
      if (sh > 0.5) { ctx.fillStyle = seg.color; roundRect(ctx, bx, by, barW, sh, 0); ctx.fill() }
    })

    // 设备名:水平显示在柱子正下方
    ctx.fillStyle = '#606266'; ctx.font = '10px sans-serif'; ctx.textAlign = 'center'; ctx.textBaseline = 'top'
    const dn = item.deviceName || item.dtuSn || ''
    // 截取后几位,确保不超出柱子宽度
    ctx.fillText(dn.length > 12 ? dn.slice(-12) : dn, bx + barW / 2, padT + chartH + 6)

    // 存储hover区域
    stackHitRects.push({ x: bx, y: padT, w: barW, h: chartH, deviceName: dn, s0: s0s, s1: s1s, s2: s2s, s3: s3s })
  })
}

function onUtilStackHover(e) {
  const canvas = utilStackBarCanvasRef.value; if (!canvas) return
  const rect = canvas.getBoundingClientRect()
  const wrap = canvas.parentElement
  const mx = e.clientX - rect.left, my = e.clientY - rect.top
  let hit = null
  for (const r of stackHitRects) {
    if (mx >= r.x && mx <= r.x + r.w && my >= r.y && my <= r.y + r.h) { hit = r; break }
  }
  if (hit) {
    utilStackHover.deviceName = hit.deviceName
    const total = hit.s0 + hit.s1 + hit.s2 + hit.s3
    utilStackHover.s3Label = `${tsFormatDuration(hit.s3)}${total > 0 ? '(' + ((hit.s3/total)*100).toFixed(1) + '%)' : ''}`
    utilStackHover.s2Label = `${tsFormatDuration(hit.s2)}${total > 0 ? '(' + ((hit.s2/total)*100).toFixed(1) + '%)' : ''}`
    utilStackHover.s1Label = `${tsFormatDuration(hit.s1)}${total > 0 ? '(' + ((hit.s1/total)*100).toFixed(1) + '%)' : ''}`
    utilStackHover.s0Label = `${tsFormatDuration(hit.s0)}${total > 0 ? '(' + ((hit.s0/total)*100).toFixed(1) + '%)' : ''}`
    // 定位:优先显示在柱子上方偏右,超出则改到下方或左侧
    const tipW = 200, tipH = 130
    let tx = mx + 14, ty = my - tipH - 8
    if (tx + tipW > rect.width - 4) tx = mx - tipW - 6
    if (ty < 4) ty = my + 14
    utilStackHover.x = Math.max(4, tx); utilStackHover.y = Math.max(4, ty)
    utilStackHover.show = true
  } else {
    utilStackHover.show = false
  }
}
function onUtilStackLeave() { utilStackHover.show = false }

// 计算合适的Y轴最大值(向上取整到整数,方便展示)
function niceAxisMax(val) {
  if (val <= 0) return 10
  let max = Math.ceil(val)
  if (max <= 1) return 1
  if (max <= 2) return 2
  if (max <= 5) return 5
  if (max <= 10) return 10
  if (max <= 12) return 12
  if (max <= 15) return 15
  if (max <= 20) return 20
  return Math.ceil(max / 5) * 5
}

// X轴小时基准:根据实际最大小时数取整(支持月查询的大数值)
function niceAxisMaxHours(hrs) {
  if (hrs <= 0) return 12
  const m = Math.ceil(hrs)
  if (m <= 6) return 6
  if (m <= 12) return 12
  if (m <= 24) return 24
  if (m <= 48) return 48
  if (m <= 72) return 72
  if (m <= 120) return 120
  if (m <= 168) return 168  // 一周
  if (m <= 336) return 336  // 两周
  if (m <= 720) return 720  // 30天
  return Math.ceil(m / 120) * 120
}

// 稼动率 tab 初始化
watch(currentStatus, async (val) => {
  if (val === 'utilization') {
    await nextTick()
    initUtilObserver()
    fetchUtilData()
  } else {
    destroyUtilObserver()
  }
})

function initUtilObserver() {
  destroyUtilObserver()
  utilResizeObs = new ResizeObserver(() => { if (currentStatus.value === 'utilization') drawUtilAll() })
  const el = document.querySelector('.util-view')
  if (el) utilResizeObs.observe(el)
}
function destroyUtilObserver() { if (utilResizeObs) { utilResizeObs.disconnect(); utilResizeObs = null } }
onBeforeUnmount(() => destroyUtilObserver())

// ========== 能耗效率:Canvas折线图 / 表格 ==========
const EFF_LINE_COLORS = [
  '#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de',
  '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc'
]

// 视图模式:chart(折线图) / table(表格)
const effViewMode = ref('chart')
function toggleEffView(mode) {
  if (effViewMode.value === mode) return
  effViewMode.value = mode
  if (mode === 'chart') nextTick(drawEffChart)
}

const effQueryMode = ref('hour')
const effHourDate = ref(new Date().toISOString().slice(0, 10))
const effDayDate = ref(new Date().toISOString().slice(0, 7))
const effMonthDate = ref(new Date().getFullYear().toString())
const effDeviceFilter = ref([])
const effLoading = ref(false)
const effTotalKwh = ref(null)

// Canvas ref
const effChartCanvasRef = ref(null)
const effWrapRef = ref(null)
let effResizeObs = null

// 接口数据
const effDataList = ref([]) // 原始设备列表
const effAllDevices = computed(() => effDataList.value.map(d => ({ dtuSn: d.dtuSn, deviceName: d.deviceName || d.dtuSn })))
const effDeviceList = computed(() => {
  if (!effDeviceFilter.value.length) return effDataList.value
  return effDataList.value.filter(d => effDeviceFilter.value.includes(d.dtuSn))
})
const effVisibleDevices = computed(() =>
  effDeviceList.value.filter(d => !effHiddenDevices.has(d.dtuSn))
)

// 图例点击筛选:隐藏/显示设备
const effHiddenDevices = reactive(new Set())
function toggleEffDevice(dtuSn) {
  if (effHiddenDevices.has(dtuSn)) {
    effHiddenDevices.delete(dtuSn)
  } else {
    effHiddenDevices.add(dtuSn)
  }
  drawEffChart()
}

// 表格视图:根据查询模式动态生成列和行数据
const effTableColumns = computed(() => {
  const list = effDeviceList.value
  if (!list.length) return []
  if (effQueryMode.value === 'hour') {
    // 时:X轴 = kwhList[].date (如 "1时" ~ "24时")
    if (!list[0].kwhList || !list[0].kwhList.length) return []
    return list[0].kwhList.map((k, i) => ({ label: k.date || '', key: i }))
  } else if (effQueryMode.value === 'day') {
    // 日:X轴 = dailyData[].date → MM-DD
    if (!list[0].dailyData || !list[0].dailyData.length) return []
    return list[0].dailyData.map((d, i) => ({ label: d.date ? d.date.slice(5) : '', key: i }))
  } else {
    // 月:X轴 = monthlyData[].label (如 "1月" ~ "12月")
    if (!list[0].monthlyData || !list[0].monthlyData.length) return []
    return list[0].monthlyData.map((m, i) => ({ label: m.label || '', key: i }))
  }
})

const effTableRows = computed(() => {
  const list = effDeviceList.value
  if (!list.length) return []
  return list.map(dev => {
    let values = []
    if (effQueryMode.value === 'hour') {
      values = (dev.kwhList || []).map(k => Number(k.value) || 0)
    } else if (effQueryMode.value === 'day') {
      values = (dev.dailyData || []).map(d => Number(d.totalKwh) || 0)
    } else {
      values = (dev.monthlyData || []).map(m => Number(m.totalKwh) || 0)
    }
    // 补齐到列数(某些设备可能缺少部分时段/日期的数据)
    while (values.length < effTableColumns.value.length) values.push(null)
    return { deviceName: dev.deviceName || dev.dtuSn, values }
  })
})

// Hover
const effHover = reactive({ show: false, x: 0, y: 0, timeLabel: '', devices: [] })
let effHitAreas = [] // 每个X位置的hover区域

function disabledYearFuture(time) {
  return time.getFullYear() > new Date().getFullYear()
}

function onEffModeChange() { fetchEffData() }

async function fetchEffData() {
  effLoading.value = true
  let startDate, endDate, type

  if (effQueryMode.value === 'hour') {
    type = 1
    startDate = effHourDate.value
    endDate = effHourDate.value
  } else if (effQueryMode.value === 'day') {
    type = 2
    const [y, m] = effDayDate.value.split('-')
    startDate = effDayDate.value + '-01'
    const lastDay = new Date(parseInt(y), parseInt(m), 0).getDate()
    endDate = effDayDate.value + '-' + String(lastDay).padStart(2, '0')
  } else {
    type = 3
    const year = effMonthDate.value
    startDate = year + '-01-01'
    endDate = year + '-12-31'
  }

  try {
    const res = await fetch(`/api/energy/eqKwhByType?startDate=${startDate}&endDate=${endDate}&type=${type}`)
    const data = await res.json()
    if (data.code === 200) {
      effDataList.value = data.list || []
      effTotalKwh.value = data.grandTotalKwh ?? data.totalKwh ?? null
      if (effDeviceFilter.value.length) {
        // 如果有筛选,检查是否还在列表中
        effDeviceFilter.value = effDeviceFilter.value.filter(sn =>
          effDataList.value.some(d => d.dtuSn === sn)
        )
      }
      await nextTick()
      drawEffChart()
    }
  } catch (err) {
    console.error('获取能耗效率数据失败:', err)
  } finally {
    effLoading.value = false
  }
}

function drawEffChart() {
  const canvas = effChartCanvasRef.value; if (!canvas) return
  const wrap = canvas.parentElement; if (!wrap) return
  const w = wrap.clientWidth || 1200
  const h = wrap.clientHeight || 400
  canvas.width = w * getDpr(); canvas.height = h * getDpr()
  canvas.style.width = w + 'px'; canvas.style.height = h + 'px'
  const ctx = canvas.getContext('2d'); ctx.scale(getDpr(), getDpr())
  ctx.clearRect(0, 0, w, h)
  effHitAreas = []

  const list = effDeviceList.value
  if (!list.length) {
    ctx.fillStyle = '#c0c4cc'; ctx.font = '14px sans-serif'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'
    ctx.fillText('暂无数据', w / 2, h / 2); return
  }

  // 布局参数
  const padL = 50, padR = 20, padT = 24, padB = 36
  const chartW = w - padL - padR
  const chartH = h - padT - padB

  // 获取X轴标签和数据点
  let xLabels = [], xDataMap = {} // deviceName -> [values]

  if (effQueryMode.value === 'hour') {
    // 时查询: kwhList 的 date 字段作为X轴标签
    if (list[0].kwhList && list[0].kwhList.length) {
      xLabels = list[0].kwhList.map(k => k.date || '')
    }
    list.forEach(dev => {
      const vals = (dev.kwhList || []).map(k => Number(k.value) || 0)
      xDataMap[dev.dtuSn] = vals
    })
  } else if (effQueryMode.value === 'day') {
    // 日查询: dailyData 的 date 字段
    if (list[0].dailyData && list[0].dailyData.length) {
      xLabels = list[0].dailyData.map(d => d.date ? d.date.slice(5) : '') // MM-DD
    }
    list.forEach(dev => {
      const vals = (dev.dailyData || []).map(d => Number(d.totalKwh) || 0)
      xDataMap[dev.dtuSn] = vals
    })
  } else {
    // 月查询(monthlyData): label作为X轴标签(如"1月","2月")
    if (list[0].monthlyData && list[0].monthlyData.length) {
      xLabels = list[0].monthlyData.map(m => m.label || '')
    }
    list.forEach(dev => {
      const vals = (dev.monthlyData || []).map(m => Number(m.totalKwh) || 0)
      xDataMap[dev.dtuSn] = vals
    })
  }

  const pointCount = xLabels.length
  if (pointCount === 0) {
    ctx.fillStyle = '#c0c4cc'; ctx.font = '14px sans-serif'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'
    ctx.fillText('暂无数据', w / 2, h / 2); return
  }

  // Y轴最大值计算
  let maxYVal = 1
  list.forEach(dev => {
    const vals = xDataMap[dev.dtuSn] || []
    vals.forEach(v => { if (v > maxYVal) maxYVal = v })
  })
  const yMax = niceEffYMax(maxYVal)
  const yTicks = 5

  // 绘制Y轴网格线和刻度
  ctx.strokeStyle = '#ebeef5'; ctx.lineWidth = 1; ctx.font = '11px sans-serif'; ctx.textAlign = 'right'; ctx.textBaseline = 'middle'
  for (let i = 0; i <= yTicks; i++) {
    const vy = padT + chartH - (i / yTicks) * chartH
    const val = (i / yTicks) * yMax
    ctx.beginPath(); ctx.moveTo(padL, vy); ctx.lineTo(w - padR, vy); ctx.stroke()
    ctx.fillStyle = '#999'
    ctx.fillText(val >= 1 ? val.toFixed(0) : val.toFixed(1), padL - 8, vy)
  }

  // X轴线
  ctx.strokeStyle = '#ddd'; ctx.lineWidth = 1.5
  ctx.beginPath(); ctx.moveTo(padL, padT + chartH); ctx.lineTo(w - padR, padT + chartH); ctx.stroke()

  // Y轴线
  ctx.beginPath(); ctx.moveTo(padL, padT); ctx.lineTo(padL, padT + chartH); ctx.stroke()

  // 计算X轴间距
  const stepX = chartW / Math.max(pointCount - 1, 1)

  // 绘制X轴标签(根据点数量动态调整显示间隔)
  ctx.fillStyle = '#666'; ctx.font = '10px sans-serif'; ctx.textAlign = 'center'; ctx.textBaseline = 'top'
  const xLabelStep = pointCount > 20 ? Math.ceil(pointCount / 12) : 1
  xLabels.forEach((lbl, i) => {
    if (i % xLabelStep === 0 || i === pointCount - 1) {
      const px = padL + i * stepX
      ctx.fillText(lbl, px, padT + chartH + 10)
    }
  })

  // 存储每个X位置用于hover检测
  for (let i = 0; i < pointCount; i++) {
    effHitAreas.push({ x: padL + i * stepX - stepX / 2, w: stepX, index: i, label: xLabels[i] })
  }

  // 绘制每条折线(平滑曲线)
  const yScale = chartH / yMax
  // 用于存储每个设备的点坐标,供hover垂直线绘制圆点
  const devPointsMap = {} // dtuSn -> [{x, y}]

  list.forEach((dev, devIdx) => {
    const color = EFF_LINE_COLORS[devIdx % EFF_LINE_COLORS.length]
    const vals = xDataMap[dev.dtuSn] || []
    const points = []
    vals.forEach((v, i) => {
      points.push({
        x: padL + i * stepX,
        y: padT + chartH - (Number(v) || 0) * yScale
      })
    })
    devPointsMap[dev.dtuSn] = points

    // 初始化该设备在各X位置的hover数据
    for (let i = 0; i < pointCount; i++) {
      if (!effHitAreas[i].devs) effHitAreas[i].devs = []
      effHitAreas[i].devs.push({
        name: dev.deviceName || dev.dtuSn,
        value: i < vals.length ? (Number(vals[i]) || 0) : 0,
        color
      })
    }

    if (points.length === 0) return

    // 绘制单调三次样条曲线(Monotone Cubic,不会过冲)
    ctx.beginPath(); ctx.strokeStyle = color; ctx.lineWidth = 2; ctx.lineJoin = 'round'
    ctx.moveTo(points[0].x, points[0].y)

    if (points.length === 2) {
      // 两点:直接连线
      ctx.lineTo(points[1].x, points[1].y)
    } else if (points.length > 2) {
      const n = points.length
      // 计算各点斜率(中心差分 + 边界单侧差分)
      const slopes = new Array(n)
      for (let i = 1; i < n - 1; i++) {
        slopes[i] = (points[i + 1].y - points[i - 1].y) / (points[i + 1].x - points[i - 1].x)
      }
      slopes[0] = (points[1].y - points[0].y) / (points[1].x - points[0].x)
      slopes[n - 1] = (points[n - 1].y - points[n - 2].y) / (points[n - 1].x - points[n - 2].x)

      // Fritsch-Carlson 单调性修正:确保斜率不导致过冲
      for (let i = 0; i < n - 1; i++) {
        const dx = points[i + 1].x - points[i].x
        const dy = points[i + 1].y - points[i].y
        if (Math.abs(dy) < 1e-8) {
          // 相邻两点Y相同 → 斜率归零(直线)
          slopes[i] = 0; slopes[i + 1] = 0
        } else {
          const s = dy / dx
          // α, β: 斜率与割线的比值
          const alpha = Math.abs(slopes[i] / s)
          const beta = Math.abs(slopes[i + 1] / s)
          const ab = alpha * beta
          if (ab > 3) { // 会过冲 → 缩小斜率
            const tau = 3.0 / Math.sqrt(ab)
            slopes[i] *= Math.min(tau, 1)
            slopes[i + 1] *= Math.min(tau, 1)
          }
        }
      }

      // 用 Hermite 形式绘制每段 Bezier 曲线(控制点 Y 钳位防过冲)
      for (let i = 0; i < n - 1; i++) {
        const dx = points[i + 1].x - points[i].x
        const y0 = points[i].y, y1 = points[i + 1].y
        const cp1x = points[i].x + dx / 3
        let cp1y = points[i].y + slopes[i] * (dx / 3)
        const cp2x = points[i + 1].x - dx / 3
        let cp2y = points[i + 1].y - slopes[i + 1] * (dx / 3)
        // 将控制点 Y 钳位到两端点之间,彻底杜绝过冲/下冲
        const lo = Math.min(y0, y1), hi = Math.max(y0, y1)
        cp1y = Math.max(lo, Math.min(hi, cp1y))
        cp2y = Math.max(lo, Math.min(hi, cp2y))
        ctx.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, points[i + 1].x, points[i + 1].y)
      }
    }
    ctx.stroke()

    // 绘制数据点圆圈
    points.forEach(p => {
      ctx.fillStyle = '#fff'
      ctx.beginPath(); ctx.arc(p.x, p.y, 3.5, 0, Math.PI * 2); ctx.fill()
      ctx.strokeStyle = color; ctx.lineWidth = 1.5
      ctx.beginPath(); ctx.arc(p.x, p.y, 3.5, 0, Math.PI * 2); ctx.stroke()
    })
  })

  // Hover 垂直虚线 + 高亮圆点
  if (effHover.show && effHover.hoverPx !== undefined && !isNaN(effHover.hoverPx)) {
    const hx = effHover.hoverPx
    ctx.strokeStyle = '#c0c4cc'; ctx.lineWidth = 1; ctx.setLineDash([4, 3])
    ctx.beginPath(); ctx.moveTo(hx, padT); ctx.lineTo(hx, padT + chartH); ctx.stroke()
    ctx.setLineDash([])

    // 在垂直线位置重绘高亮圆点(略大)
    list.forEach((dev, devIdx) => {
      const color = EFF_LINE_COLORS[devIdx % EFF_LINE_COLORS.length]
      const pts = devPointsMap[dev.dtuSn] || []
      // 找最近的点
      let bestP = null, bestD = Infinity
      pts.forEach(p => { const d = Math.abs(p.x - hx); if (d < bestD) { bestD = d; bestP = p } })
      if (bestP && bestD < stepX / 2 + 2) {
        ctx.fillStyle = '#fff'
        ctx.beginPath(); ctx.arc(bestP.x, bestP.y, 5, 0, Math.PI * 2); ctx.fill()
        ctx.strokeStyle = color; ctx.lineWidth = 2
        ctx.beginPath(); ctx.arc(bestP.x, bestP.y, 5, 0, Math.PI * 2); ctx.stroke()
      }
    })
  }
}

// Y轴取整函数
function niceEffYMax(val) {
  if (val <= 0) return 10
  if (val <= 5) return 5
  if (val <= 10) return 10
  if (val <= 20) return 20
  if (val <= 30) return 30
  if (val <= 50) return 50
  if (val <= 70) return 70
  if (val <= 100) return 100
  if (val <= 200) return 200
  if (val <= 500) return 500
  return Math.ceil(val / 100) * 100
}

function onEffChartHover(e) {
  const canvas = effChartCanvasRef.value; if (!canvas) return
  const rect = canvas.getBoundingClientRect()
  const mx = e.clientX - rect.left, my = e.clientY - rect.top

  // 始终更新hoverPx和tooltip位置,用于垂直虚线定位
  effHover.hoverPx = mx

  let hit = null
  for (const area of effHitAreas) {
    if (mx >= area.x && mx <= area.x + area.w) { hit = area; break }
  }

  if (hit && hit.devs && hit.devs.length > 0) {
    effHover.timeLabel = hit.label || ''
    effHover.devices = [...hit.devs]
    effHover.show = true
    const tipW = 180, tipH = 40 + hit.devs.length * 28
    let tx = mx + 12, ty = my - tipH - 8
    if (tx + tipW > rect.width - 4) tx = mx - tipW - 6
    if (ty < 4) ty = my + 14
    effHover.x = Math.max(4, tx)
    effHover.y = Math.max(4, ty)
  } else {
    effHover.show = false
  }

  // 重绘以更新垂直虚线和高亮圆点
  drawEffChart()
}

function onEffChartLeave() { effHover.show = false; effHover.hoverPx = undefined; drawEffChart() }

// 能耗效率 tab 初始化
watch(currentStatus, async (val) => {
  if (val === 'efficiency') {
    await nextTick()
    initEffObserver()
    fetchEffData()
  } else {
    destroyEffObserver()
  }
})

function initEffObserver() {
  destroyEffObserver()
  effResizeObs = new ResizeObserver(() => { if (currentStatus.value === 'efficiency') drawEffChart() })
  const el = document.querySelector('.eff-view')
  if (el) effResizeObs.observe(el)
}
function destroyEffObserver() { if (effResizeObs) { effResizeObs.disconnect(); effResizeObs = null } }
onBeforeUnmount(() => destroyEffObserver())
</script>

<style scoped>
.energy-page {
  min-height: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f0f2f5;
  overflow: hidden;
  min-width: 1200px;
}
.device-grid {
  flex: 1;
  overflow-x: auto;
  overflow-y: auto;
  padding: 16px 20px;
}
.device-grid .grid-inner {
  display: grid;
  grid-template-columns: repeat(6, 270px);
  gap: 16px;
}
.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;
  transition: all 0.2s;
}
.tag-item:hover {
  opacity: 0.8;
}
.tag-item.active {
  font-weight: bold;
}
.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.green i { background: #67c23a; }
.tag-item.blue i { background: #409eff; }
.tag-item.gray i { background: #909399; }

.energy-card {
  min-width: 270px;
  height: 340px;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 16px rgba(0,0,0,0.15);
  transition: transform 0.2s;
  display: flex;
  flex-direction: column;
}
/* runStatus 状态背景色 */
.energy-card.status-0 { background: linear-gradient(145deg, #b8b8b8 0%, #999 100%); }
.energy-card.status-1 { background: linear-gradient(145deg, #f56c6c 0%, #e74c3c 100%); }
.energy-card.status-2 { background: linear-gradient(145deg, #7ec87e 0%, #5cb85c 100%); }
.energy-card.status-3 { background: linear-gradient(145deg, #32a756 0%, #289048 100%); }
.energy-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(0,0,0,0.25);
}
.card-header {
  color: #fff;
  padding: 12px 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
  font-weight: bold;
  flex-shrink: 0;
}
.menu-icon {
  cursor: pointer;
  color: #aaa;
}
.card-body {
  padding: 10px 16px;
  text-align: center;
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
.energy-icon {
  width: 56px;
  height: 56px;
  margin-bottom: 12px;
}
.lightning-icon svg {
  width: 100%;
  height: 100%;
  filter: drop-shadow(0 0 12px rgba(255,200,0,0.5));
}
.info-list {
  text-align: center;
  color: #fff;
  font-size: 13px;
  line-height: 2;
}
.info-item span {
  color: #fff;
  font-weight: 500;
}
.value-highlight {
  color: #f5a623 !important;
  font-weight: bold;
}
.card-footer {
  padding: 8px 12px;
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 6px;
  border-top: 1px solid rgba(255,255,255,0.15);
  flex-shrink: 0;
}
.action-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
  padding: 6px 6px;
  border: 1px solid rgba(255,255,255,0.35);
  border-radius: 5px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.2s;
  color: #fff;
  background: rgba(0,0,0,0.15);
}
.action-btn:hover {
  opacity: 0.8;
  transform: scale(1.02);
}
.action-btn.primary { border-color: rgba(64,158,255,0.5); }
.action-btn.danger { border-color: rgba(245,108,108,0.5); }
.action-btn.info { border-color: rgba(144,147,153,0.45); }
.action-btn.setting { border-color: rgba(144,147,153,0.45); }
/* ========== 自定义分页 ========== */
.pagination-wrapper {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  padding: 8px 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;
  min-height: 0;
}

/* ========== 时序状态 ========== */
.timeseries-view {
  background: #f5f7fa;
}
.ts-toolbar {
  background: #fff;
  padding: 8px 20px;
  display: flex;
  align-items: center;
  gap: 10px;
  border-bottom: 1px solid #e8e8e8;
}
.ts-label {
  font-size: 13px; color: #666; font-weight: bold;
}
.ts-table-wrap {
  flex: 1;
  overflow: auto;
  background: #fff;
  margin: 12px 20px;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
}
.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-sub-col2 { 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甘特图 ========== */
.ts-gantt-wrap {
  flex: 1;
  display: flex;
  min-height: 0;
  overflow: auto;
  background: #fff;
  margin: 8px 20px 0;
  border: 1px solid #e8e8e8;
  position: relative;
}
.ts-fixed-col {
  width: 220px;
  flex-shrink: 0;
}
.ts-fixed-col canvas { display: block; }
.ts-scroll-area {
  flex: 1;
  overflow-x: hidden;
  overflow-y: auto;
  position: relative;
}
.ts-scroll-area canvas { display: block; }

/* Tooltip - 相对于 ts-scroll-area 定位 */
.gantt-tooltip {
  position: absolute;
  background: rgba(30,40,55,0.95);
  border-radius: 6px;
  padding: 8px 14px;
  min-width: 180px;
  z-index: 200;
  pointer-events: none;
  box-shadow: 0 4px 16px rgba(0,0,0,0.25);
}
.gtt-title {
  font-size: 12px; font-weight:bold; color:#eef1f7; margin-bottom:6px; padding-bottom:6px; border-bottom:1px solid rgba(255,255,255,0.1);
}
.gtt-row {
  display:flex; align-items:center; justify-content:space-between; gap:12px; line-height:2; font-size:12px;
}
.gtt-label { color:#aab2c0; flex-shrink:0; }
.gtt-val { color:#eef1f7; font-weight:500; display:flex; align-items:center; gap:4px; }
.gtt-highlight { font-weight:bold; }

/* 异常机台排名 hover tooltip */
.rank-tooltip {
  position: absolute;
  background: #fff;
  border-radius: 6px;
  padding: 10px 14px;
  min-width: 160px;
  z-index: 200;
  pointer-events: none;
  box-shadow: 0 4px 16px rgba(0,0,0,0.15);
  border: 1px solid #ebeef5;
}
.rtt-name {
  font-size: 13px; font-weight:bold; color:#303133; margin-bottom:6px; padding-bottom:6px; border-bottom:1px solid #ebeef5;
}
.rtt-row {
  display:flex; align-items:center; gap:8px; line-height:1.8; font-size:12px; color:#606266;
}
.rtt-row i { width:8px; height:8px; border-radius:2px; flex-shrink:0; }
.rtt-row .dot.y { background:#e6a23c; }
.rtt-row .dot.r { background:#f56c6c; }
.rtt-row span { margin-left:auto; color:#f56c6c; font-weight:500; }
.rtt-row span:first-of-type { color:#67c23a; }

/* 堆积柱状图 hover tooltip */
.stack-tooltip {
  position: absolute;
  background: #fff;
  border-radius: 6px;
  padding: 10px 14px;
  min-width: 180px;
  z-index: 200;
  pointer-events: none;
  box-shadow: 0 4px 16px rgba(0,0,0,0.15);
  border: 1px solid #ebeef5;
}
.stt-name {
  font-size: 13px; font-weight:bold; color:#303133; margin-bottom:6px; padding-bottom:6px; border-bottom:1px solid #ebeef5;
}
.stt-row {
  display:flex; align-items:center; gap:8px; line-height:1.8; font-size:12px; color:#606266;
}
.stt-row i { width:8px; height:8px; border-radius:2px; flex-shrink:0; }
.stt-row .dot.g { background:#67c23a; }
.stt-row .dot.y { background:#e6a23c; }
.stt-row .dot.r { background:#f56c6c; }
.stt-row .dot.gy { background:#909399; }
.stt-row span { margin-left:auto; color:#303133; font-weight:500; }

/* ========== 稼动率 ========== */
.util-view {
  background: #f5f7fa;
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
  overflow: hidden;
}
.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(3, 1fr);
  gap: 14px;
  padding: 14px 20px;
  flex-shrink: 0;
}
.pie-card, .bar-card {
  background: #fff;
  box-shadow: 0 1px 4px rgba(0,0,0,0.06);
  padding: 14px;
  display: flex;
  flex-direction: column;
  min-height: 0;
  max-height: 280px;
  overflow: hidden;
}
.pie-title {
  font-size: 13px;
  font-weight: bold;
  color: #333;
  margin-bottom: 10px;
  flex-shrink: 0;
}
.pie-canvas-wrap {
  flex: 1;
  min-height: 0;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}
.pie-canvas-wrap canvas {
  display: block;
  max-width: 100%;
}
.bar-canvas-wrap {
  flex: 1;
  min-height: 0;
  position: relative;
}
.bar-canvas-wrap canvas {
  display: block;
  width: 100%;
}

.abn-legend {
  margin-top: 4px;
  font-size: 11px;
  color: #999;
  display: flex;
  gap: 10px;
  justify-content: flex-end;
}

.rank-leg-inline {
  display:flex; align-items:center; gap:8px; font-size:11px; color:#666; font-weight:normal;
}
.rank-leg-inline i { width:10px;height:10px;border-radius:2px;display:inline-block; }

.util-bottom-chart {
  margin: 0 20px 14px;
  background: #fff;
  box-shadow: 0 1px 4px rgba(0,0,0,0.06);
  padding: 14px;
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
  overflow: visible;
}
.stack-bar-toolbar {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
  font-size: 13px;
  color: #666;
  flex-shrink: 0;
}
.stack-bar-legend {
  display: flex;
  gap: 18px;
  margin-bottom: 8px;
  font-size: 12px;
  color: #666;
  flex-shrink: 0;
}
.leg-item { display:flex; align-items:center; gap:4px; }
.leg-item i { width:10px; height:10px; border-radius:2px; display:inline-block; }
.leg-item .dot.g { background:#67c23a; }
.leg-item .dot.y { background:#e6a23c; }
.leg-item .dot.r { background:#f56c6c; }
.leg-item .dot.gy { background:#909399; }
.stack-bar-chart.canvas-stack-bar {
  flex: 1;
  min-height: 0;
  overflow: visible;
}
.stack-bar-chart canvas {
  display: block;
  width: 100%;
}

/* ========== 能耗效率 ========== */
.eff-view {
  background: #f5f7fa;
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
  overflow-y: auto;
}
.eff-toolbar {
  background: #fff;
  padding: 10px 20px;
  display: flex;
  align-items: center;
  gap: 10px;
  border-bottom: 1px solid #e8e8e8;
  flex-shrink: 0;
}
.eff-label {
  font-size: 13px; color: #666; font-weight: bold;
}
.eff-legend {
  padding: 8px 24px;
  font-size: 12px;
  color: #666;
  display: flex;
  align-items: center;
  gap: 20px;
  flex-wrap: wrap;
  flex-shrink: 0;
  background: #fff;
  border-bottom: 1px solid #ebeef5;
}
.leg-line {
  display: inline-flex;
  align-items: center;
  gap: 5px;
  cursor: pointer;
  transition: opacity 0.2s;
}
.leg-line:hover { opacity: 0.7; }
.leg-line.leg-dimmed { opacity: 0.35; }
.leg-line i {
  display: inline-block;
  width: 16px;
  height: 3px;
  border-radius: 2px;
  background: var(--lc);
}
.eff-chart.canvas-eff-chart {
  margin: 0 20px 14px;
  background: #fff;
  border-radius: 6px;
  box-shadow: 0 1px 4px rgba(0,0,0,0.06);
  padding: 16px 14px 14px;
  flex: 1;
  min-height: 380px;
  overflow: visible;
  position: relative;
}
.eff-chart canvas {
  display: block;
  width: 100%;
}

/* 能耗效率 tooltip */
.eff-tooltip {
  position: absolute;
  background: rgba(30,40,55,0.95);
  border-radius: 6px;
  padding: 10px 14px;
  min-width: 160px;
  z-index: 200;
  pointer-events: none;
  box-shadow: 0 4px 16px rgba(0,0,0,0.25);
}
.eft-title {
  font-size: 12px; font-weight:bold; color:#eef1f7; margin-bottom:6px; padding-bottom:6px; border-bottom:1px solid rgba(255,255,255,0.12);
}
.eft-row {
  display:flex; align-items:center; justify-content:space-between; gap:12px; line-height:2.2; font-size:12px;
}
.eft-row .dot { width:8px; height:8px; border-radius:50%; flex-shrink:0; }
.eft-name { color:#aab2c0; }
.eft-val { color:#eef1f7; font-weight:500; }

/* 总用电量统计 */
.eff-summary {
  padding: 8px 24px 14px;
  font-size: 13px;
  color: #666;
  background: #fff;
  border-top: 1px solid #ebeef5;
  text-align: center;
  flex-shrink: 0;
}
.eff-sum-label { color: #909399; margin-right: 4px; }
.eff-sum-val { color: #409eff; font-weight:bold; font-size:15px; margin-right: 6px; }
.eff-sum-count { color: #999; font-size:12px; }

/* 视图切换图标按钮 */
.view-btn {
  width: 30px;
  height: 30px;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s;
  color: #606266;
  background: #fff;
}
.view-btn:hover { color: #409eff; border-color: #409eff !important; }
.view-btn.active { color: #409eff; border-color: #409eff !important; }

/* 历史数据表格(简洁风格) */
.eff-table-wrap {
  flex: 1;
  overflow: auto;
  background: #fff;
  margin: 8px 20px 14px;
  border: 1px solid #ebeef5;
}
.eff-history-table {
  width: 100%;
  border-collapse: collapse;
  table-layout: auto;
}
.eff-history-table th,
.eff-history-table td {
  padding: 8px 12px;
  text-align: center;
  font-size: 13px;
  border-right: 1px solid #ebeef5;
  white-space: nowrap;
  line-height: 1.8;
}
.eff-history-table th {
  background: #fff;
  font-weight: 600;
  color: #333;
  position: sticky;
  top: 0;
  z-index: 2;
  border-bottom: 1px solid #ddd;
}
.eff-history-table td {
  color: #555;
  border-bottom: 1px solid #ebeef5;
}
.eff-history-table tbody tr:last-child td { border-bottom: 1px solid #ebeef5; }
.eff-history-table .col-name,
.eff-history-table .td-name {
  position: sticky;
  left: 0;
  z-index: 1;
  text-align: left !important;
  font-weight: 500;
  width: 120px;
  border-left: none !important;
}
.eff-history-table .td-name { background: #fff; }
.eff-history-table tbody tr:hover .td-name,
.eff-history-table tbody tr:hover { background: #fafafa; }
.eff-table-empty {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 160px;
  font-size: 13px;
  color: #909399;
}
</style>