app.js 86.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912
/**
 * 主应用逻辑
 */

const App = {
    currentPage: 'dashboard',
    currentTaskNo: null,
    
    // 配件汇总表排序状态
    partSummarySort: {
        sortBy: 'total_suggest_amount',
        sortOrder: 'desc'
    },

    // 配件汇总表筛选状态
    partSummaryFilters: {
        page: 1,
        page_size: 50,
        part_code: '',
        priority: ''
    },

    // 侧边栏折叠状态
    isSidebarCollapsed: localStorage.getItem('sidebar-collapsed') === 'true',

    /**
     * 切换侧边栏折叠状态
     */
    toggleSidebarCollapse() {
        this.isSidebarCollapsed = !this.isSidebarCollapsed;
        localStorage.setItem('sidebar-collapsed', this.isSidebarCollapsed);
        this.applySidebarState();
    },

    /**
     * 应用侧边栏状态
     */
    applySidebarState() {
        const sidebar = document.querySelector('.sidebar');
        // 主内容区通过 CSS 选择器 .sidebar.collapsed + ... .main-content 自动调整
        // 或者我们需要手动给 main-content 加类,但 CSS 中用了兄弟选择器,
        // 不过兄弟选择器在这里可能不生效,因为中间隔了 .sidebar-overlay
        // 让我们看看 index.html 结构: sidebar, sidebar-overlay, main-content
        // CSS 选择器是 .sidebar.collapsed + .sidebar-overlay + .main-content
        // 这样是可以的。
        
        if (this.isSidebarCollapsed) {
            sidebar.classList.add('collapsed');
        } else {
            sidebar.classList.remove('collapsed');
        }
        
        // 触发 icon 刷新以确保显示正确(虽然 CSS 旋转已处理)
        lucide.createIcons();
    },

    /**
     * 切换侧边栏显示状态(移动端)
     */
    toggleSidebar(show) {
        const sidebar = document.querySelector('.sidebar');
        const overlay = document.getElementById('sidebar-overlay');
        
        if (show) {
            sidebar.classList.add('visible');
            overlay.classList.add('active');
        } else {
            sidebar.classList.remove('visible');
            overlay.classList.remove('active');
        }
    },

    /**
     * 应用配件筛选
     */
    applyPartFilters() {
        const partCode = document.getElementById('filter-part-code')?.value || '';
        const priorityElement = document.getElementById('filter-priority');
        const priority = priorityElement ? priorityElement.value : '';
        
        this.partSummaryFilters.part_code = partCode;
        this.partSummaryFilters.priority = priority;
        this.partSummaryFilters.page = 1; // 重置到第一页
        
        this.loadPartSummaries();
    },

    /**
     * 重置配件筛选
     */
    resetPartFilters() {
        this.partSummaryFilters.part_code = '';
        this.partSummaryFilters.priority = '';
        this.partSummaryFilters.page = 1;
        
        this.loadPartSummaries();
    },


    /**
     * 渲染分析报告标签页(四大板块:库存概览/销量分析/健康度/补货建议)
     */
    async renderReportTab(container, taskNo) {
        container.innerHTML = '<div class="loading-shops">加载分析报告...</div>';
        
        try {
            const report = await API.getAnalysisReport(taskNo);
            
            if (!report) {
                container.innerHTML = `
                    <div class="card">
                        ${Components.renderEmptyState('file-x', '暂无分析报告', '该任务尚未生成分析报告')}
                    </div>
                `;
                return;
            }

            container.innerHTML = `
                <div id="report-inventory-overview" class="report-module"></div>
                <div id="report-sales-analysis" class="report-module"></div>
                <div id="report-inventory-health" class="report-module"></div>
                <div id="report-replenishment-summary" class="report-module"></div>
            `;

            this.renderInventoryOverview(
                document.getElementById('report-inventory-overview'),
                report.inventory_overview
            );
            this.renderSalesAnalysis(
                document.getElementById('report-sales-analysis'),
                report.sales_analysis
            );
            this.renderInventoryHealth(
                document.getElementById('report-inventory-health'),
                report.inventory_health
            );
            this.renderReplenishmentSummary(
                document.getElementById('report-replenishment-summary'),
                report.replenishment_summary
            );
            
            lucide.createIcons();
        } catch (error) {
            container.innerHTML = `
                <div class="card" style="text-align: center; color: var(--color-danger);">
                    <i data-lucide="alert-circle" style="width: 48px; height: 48px; margin-bottom: 1rem;"></i>
                    <p>加载报告失败: ${error.message}</p>
                </div>
            `;
            lucide.createIcons();
        }
    },

    /**
     * 渲染库存概览板块
     */
    renderInventoryOverview(container, data) {
        if (!data) {
            container.innerHTML = '';
            return;
        }
        const stats = data.stats || {};
        const analysis = data.llm_analysis || {};
        
        // 兼容新旧数据结构
        const conclusion = analysis.conclusion || analysis;
        const process = analysis.analysis_process || null;

        const ratio = stats.overall_ratio;
        const ratioDisplay = (ratio === 999 || ratio === null || ratio === undefined) ? '无销量' : Components.formatNumber(ratio);

        // LLM 分析文本渲染
        let analysisHtml = '';
        if (analysis.error) {
            analysisHtml = `<div class="report-analysis-text"><span style="color:var(--color-warning);">分析生成失败: ${analysis.error}</span></div>`;
        } else {
            const sections = [];
            
            // 季节信息(如果有)
            if (process && process.seasonal_analysis) {
                const sa = process.seasonal_analysis;
                sections.push(`<div class="analysis-block">
                    <div class="analysis-block-title"><i data-lucide="sun"></i> 季节性分析 <span class="season-tag"><i data-lucide="calendar"></i>${sa.current_season || ''}</span></div>
                    <p>${sa.season_demand_feature || ''}</p>
                    <p>${sa.inventory_fitness || ''}</p>
                    ${sa.upcoming_season_preparation ? `<p>下季准备: ${sa.upcoming_season_preparation}</p>` : ''}
                </div>`);
            }
            
            if (conclusion.capital_assessment) {
                const ca = conclusion.capital_assessment;
                sections.push(`<div class="analysis-block">
                    <div class="analysis-block-title"><i data-lucide="wallet"></i> 资金占用评估 <span class="risk-tag risk-tag-${ca.risk_level || 'medium'}">${ca.risk_level === 'high' ? '高风险' : ca.risk_level === 'low' ? '低风险' : '中风险'}</span></div>
                    <p>${ca.total_evaluation || ''}</p>
                    <p>${ca.structure_ratio || ''}</p>
                </div>`);
            }
            if (conclusion.ratio_diagnosis) {
                const rd = conclusion.ratio_diagnosis;
                sections.push(`<div class="analysis-block">
                    <div class="analysis-block-title"><i data-lucide="gauge"></i> 库销比诊断 — ${rd.level || ''}</div>
                    <p>${rd.analysis || ''}</p>
                    <p class="analysis-benchmark">${rd.benchmark || ''}</p>
                </div>`);
            }
            if (conclusion.recommendations && conclusion.recommendations.length > 0) {
                const recHtml = conclusion.recommendations.map(r => {
                    if (typeof r === 'object') {
                        return `<li><strong>${r.action || ''}</strong>${r.reason ? ` - ${r.reason}` : ''}${r.expected_effect ? `<br><small>预期效果: ${r.expected_effect}</small>` : ''}</li>`;
                    }
                    return `<li>${r}</li>`;
                }).join('');
                sections.push(`<div class="analysis-block">
                    <div class="analysis-block-title"><i data-lucide="lightbulb"></i> 库存结构建议</div>
                    <ul class="analysis-rec-list">${recHtml}</ul>
                </div>`);
            }
            
            // 推理过程(可折叠)
            let processHtml = '';
            if (process) {
                processHtml = this._renderAnalysisProcess(process, 'inventory-overview');
            }
            
            analysisHtml = sections.length > 0 ? `<div class="report-analysis-text">${sections.join('')}${processHtml}</div>` : '';
        }

        container.innerHTML = `
            <div class="report-section-title">
                <i data-lucide="warehouse"></i>
                库存总体概览
            </div>
            <div class="report-stat-cards">
                <div class="report-stat-card">
                    <div class="report-stat-label">有效库存总数量</div>
                    <div class="report-stat-value">${Components.formatNumber(stats.total_valid_storage_cnt)}</div>
                </div>
                <div class="report-stat-card">
                    <div class="report-stat-label">资金占用(总金额)</div>
                    <div class="report-stat-value">${Components.formatAmount(stats.total_valid_storage_amount)}</div>
                </div>
                <div class="report-stat-card">
                    <div class="report-stat-label">整体库销比</div>
                    <div class="report-stat-value">${ratioDisplay}</div>
                </div>
                <div class="report-stat-card">
                    <div class="report-stat-label">配件种类数</div>
                    <div class="report-stat-value">${stats.part_count || 0}</div>
                </div>
            </div>
            <div class="report-detail-table">
                <table>
                    <thead>
                        <tr>
                            <th>构成项</th>
                            <th>数量</th>
                            <th>金额</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td>在库未锁</td>
                            <td>${Components.formatNumber(stats.total_in_stock_unlocked_cnt)}</td>
                            <td>${Components.formatAmount(stats.total_in_stock_unlocked_amount)}</td>
                        </tr>
                        <tr>
                            <td>在途</td>
                            <td>${Components.formatNumber(stats.total_on_the_way_cnt)}</td>
                            <td>${Components.formatAmount(stats.total_on_the_way_amount)}</td>
                        </tr>
                        <tr>
                            <td>计划数</td>
                            <td>${Components.formatNumber(stats.total_has_plan_cnt)}</td>
                            <td>${Components.formatAmount(stats.total_has_plan_amount)}</td>
                        </tr>
                    </tbody>
                </table>
            </div>
            ${analysisHtml}
        `;
        
        // 绑定折叠事件
        this._bindProcessToggle(container);
    },

    /**
     * 渲染销量分析板块
     */
    renderSalesAnalysis(container, data) {
        if (!data) {
            container.innerHTML = '';
            return;
        }
        const stats = data.stats || {};
        const analysis = data.llm_analysis || {};
        
        // 兼容新旧数据结构
        const conclusion = analysis.conclusion || analysis;
        const process = analysis.analysis_process || null;

        // LLM 分析文本
        let analysisHtml = '';
        if (analysis.error) {
            analysisHtml = `<div class="report-analysis-text"><span style="color:var(--color-warning);">分析生成失败: ${analysis.error}</span></div>`;
        } else {
            const sections = [];
            
            // 季节信息(如果有)
            if (process && process.seasonal_analysis) {
                const sa = process.seasonal_analysis;
                sections.push(`<div class="analysis-block">
                    <div class="analysis-block-title"><i data-lucide="sun"></i> 季节性分析 <span class="season-tag"><i data-lucide="calendar"></i>${sa.current_season || ''}</span></div>
                    <p>${sa.expected_performance || ''}</p>
                    <p>${sa.actual_vs_expected || ''}</p>
                    ${sa.seasonal_items_status ? `<p>${sa.seasonal_items_status}</p>` : ''}
                </div>`);
            }
            
            if (conclusion.composition_analysis) {
                const ca = conclusion.composition_analysis;
                sections.push(`<div class="analysis-block">
                    <div class="analysis-block-title"><i data-lucide="pie-chart"></i> 销量构成解读</div>
                    <p>${ca.main_driver || ''}</p>
                    <p>${ca.pending_orders_impact || ''}</p>
                    <p>${ca.booking_trend || ''}</p>
                </div>`);
            }
            if (conclusion.activity_assessment) {
                const aa = conclusion.activity_assessment;
                sections.push(`<div class="analysis-block">
                    <div class="analysis-block-title"><i data-lucide="activity"></i> 销售活跃度</div>
                    <p>${aa.active_ratio || ''}</p>
                    <p>${aa.optimization_suggestion || ''}</p>
                </div>`);
            }
            if (conclusion.demand_trend) {
                const dt = conclusion.demand_trend;
                const dirIcon = dt.direction === '上升' ? 'trending-up' : dt.direction === '下降' ? 'trending-down' : 'minus';
                sections.push(`<div class="analysis-block">
                    <div class="analysis-block-title"><i data-lucide="${dirIcon}"></i> 需求趋势 — ${dt.direction || ''}</div>
                    <p>${dt.evidence || ''}</p>
                    ${dt.seasonal_factor ? `<p>季节因素: ${dt.seasonal_factor}</p>` : ''}
                    <p>${dt.forecast || ''}</p>
                </div>`);
            }
            
            // 推理过程(可折叠)
            let processHtml = '';
            if (process) {
                processHtml = this._renderAnalysisProcess(process, 'sales-analysis');
            }
            
            analysisHtml = sections.length > 0 ? `<div class="report-analysis-text">${sections.join('')}${processHtml}</div>` : '';
        }

        const totalParts = (stats.has_sales_part_count || 0) + (stats.no_sales_part_count || 0);

        container.innerHTML = `
            <div class="report-section-title">
                <i data-lucide="bar-chart-3"></i>
                销量分析
            </div>
            <div class="report-stat-cards">
                <div class="report-stat-card">
                    <div class="report-stat-label">月均销量总数量</div>
                    <div class="report-stat-value">${Components.formatNumber(stats.total_avg_sales_cnt)}</div>
                </div>
                <div class="report-stat-card">
                    <div class="report-stat-label">月均销量总金额</div>
                    <div class="report-stat-value">${Components.formatAmount(stats.total_avg_sales_amount)}</div>
                </div>
                <div class="report-stat-card">
                    <div class="report-stat-label">有销量配件</div>
                    <div class="report-stat-value">${stats.has_sales_part_count || 0} <span class="report-stat-sub">/ ${totalParts}</span></div>
                </div>
                <div class="report-stat-card">
                    <div class="report-stat-label">无销量配件</div>
                    <div class="report-stat-value">${stats.no_sales_part_count || 0} <span class="report-stat-sub">/ ${totalParts}</span></div>
                </div>
            </div>
            <div class="report-detail-table">
                <table>
                    <thead>
                        <tr>
                            <th>构成项</th>
                            <th>总量</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td>90天出库数</td>
                            <td>${Components.formatNumber(stats.total_out_stock_cnt)}</td>
                        </tr>
                        <tr>
                            <td>未关单已锁</td>
                            <td>${Components.formatNumber(stats.total_storage_locked_cnt)}</td>
                        </tr>
                        <tr>
                            <td>未关单出库</td>
                            <td>${Components.formatNumber(stats.total_out_stock_ongoing_cnt)}</td>
                        </tr>
                        <tr>
                            <td>订件</td>
                            <td>${Components.formatNumber(stats.total_buy_cnt)}</td>
                        </tr>
                    </tbody>
                </table>
            </div>
            ${analysisHtml}
        `;
        
        // 绑定折叠事件
        this._bindProcessToggle(container);
    },

    /**
     * 渲染库存健康度板块(含 Chart.js 环形图)
     */
    renderInventoryHealth(container, data) {
        if (!data) {
            container.innerHTML = '';
            return;
        }
        const stats = data.stats || {};
        const chartData = data.chart_data || {};
        const analysis = data.llm_analysis || {};
        
        // 兼容新旧数据结构
        const conclusion = analysis.conclusion || analysis;
        const process = analysis.analysis_process || null;

        const shortage = stats.shortage || {};
        const stagnant = stats.stagnant || {};
        const low_freq = stats.low_freq || {};
        const normal = stats.normal || {};

        // LLM 分析文本
        let analysisHtml = '';
        if (analysis.error) {
            analysisHtml = `<div class="report-analysis-text"><span style="color:var(--color-warning);">分析生成失败: ${analysis.error}</span></div>`;
        } else {
            const sections = [];
            
            // 季节信息(如果有)
            if (process && process.seasonal_analysis) {
                const sa = process.seasonal_analysis;
                sections.push(`<div class="analysis-block">
                    <div class="analysis-block-title"><i data-lucide="sun"></i> 季节性分析 <span class="season-tag"><i data-lucide="calendar"></i>${sa.current_season || ''}</span></div>
                    ${sa.seasonal_stagnant_items ? `<p>${sa.seasonal_stagnant_items}</p>` : ''}
                    ${sa.seasonal_shortage_risk ? `<p>${sa.seasonal_shortage_risk}</p>` : ''}
                    ${sa.upcoming_season_alert ? `<p>下季关注: ${sa.upcoming_season_alert}</p>` : ''}
                </div>`);
            }
            
            if (conclusion.health_score) {
                const hs = conclusion.health_score;
                sections.push(`<div class="analysis-block">
                    <div class="analysis-block-title"><i data-lucide="heart-pulse"></i> 健康度评分 — ${hs.score || ''}</div>
                    <p>${hs.normal_ratio_evaluation || ''}</p>
                </div>`);
            }
            if (conclusion.problem_diagnosis) {
                const pd = conclusion.problem_diagnosis;
                sections.push(`<div class="analysis-block">
                    <div class="analysis-block-title"><i data-lucide="stethoscope"></i> 问题诊断</div>
                    ${pd.stagnant_analysis ? `<p>呆滞件: ${pd.stagnant_analysis}</p>` : ''}
                    ${pd.shortage_analysis ? `<p>缺货件: ${pd.shortage_analysis}</p>` : ''}
                    ${pd.low_freq_analysis ? `<p>低频件: ${pd.low_freq_analysis}</p>` : ''}
                </div>`);
            }
            if (conclusion.capital_release) {
                const cr = conclusion.capital_release;
                sections.push(`<div class="analysis-block">
                    <div class="analysis-block-title"><i data-lucide="banknote"></i> 资金释放机会</div>
                    ${cr.stagnant_releasable ? `<p>呆滞件可释放: ${cr.stagnant_releasable}</p>` : ''}
                    ${cr.low_freq_releasable ? `<p>低频件可释放: ${cr.low_freq_releasable}</p>` : ''}
                    ${cr.action_plan ? `<p>${cr.action_plan}</p>` : ''}
                </div>`);
            }
            if (conclusion.priority_actions && conclusion.priority_actions.length > 0) {
                const actHtml = conclusion.priority_actions.map(a => {
                    if (typeof a === 'object') {
                        return `<li><strong>${a.action || ''}</strong>${a.reason ? ` - ${a.reason}` : ''}${a.expected_effect ? `<br><small>预期效果: ${a.expected_effect}</small>` : ''}</li>`;
                    }
                    return `<li>${a}</li>`;
                }).join('');
                sections.push(`<div class="analysis-block">
                    <div class="analysis-block-title"><i data-lucide="list-ordered"></i> 改善优先级</div>
                    <ol class="analysis-rec-list">${actHtml}</ol>
                </div>`);
            }
            
            // 推理过程(可折叠)
            let processHtml = '';
            if (process) {
                processHtml = this._renderAnalysisProcess(process, 'inventory-health');
            }
            
            analysisHtml = sections.length > 0 ? `<div class="report-analysis-text">${sections.join('')}${processHtml}</div>` : '';
        }

        container.innerHTML = `
            <div class="report-section-title">
                <i data-lucide="heart-pulse"></i>
                库存构成健康度
            </div>
            <div class="report-stat-cards report-stat-cards-4">
                <div class="report-stat-card report-stat-card-danger">
                    <div class="report-stat-label">缺货件</div>
                    <div class="report-stat-value">${shortage.count || 0}</div>
                    <div class="report-stat-pct">${Components.formatNumber(shortage.count_pct)}% · ${Components.formatAmount(shortage.amount)}</div>
                </div>
                <div class="report-stat-card report-stat-card-warning">
                    <div class="report-stat-label">呆滞件</div>
                    <div class="report-stat-value">${stagnant.count || 0}</div>
                    <div class="report-stat-pct">${Components.formatNumber(stagnant.count_pct)}% · ${Components.formatAmount(stagnant.amount)}</div>
                </div>
                <div class="report-stat-card report-stat-card-info">
                    <div class="report-stat-label">低频件</div>
                    <div class="report-stat-value">${low_freq.count || 0}</div>
                    <div class="report-stat-pct">${Components.formatNumber(low_freq.count_pct)}% · ${Components.formatAmount(low_freq.amount)}</div>
                </div>
                <div class="report-stat-card report-stat-card-success">
                    <div class="report-stat-label">正常件</div>
                    <div class="report-stat-value">${normal.count || 0}</div>
                    <div class="report-stat-pct">${Components.formatNumber(normal.count_pct)}% · ${Components.formatAmount(normal.amount)}</div>
                </div>
            </div>
            <div class="report-charts-row">
                <div class="report-chart-container">
                    <div class="report-chart-title">数量占比</div>
                    <canvas id="health-count-chart"></canvas>
                </div>
                <div class="report-chart-container">
                    <div class="report-chart-title">金额占比</div>
                    <canvas id="health-amount-chart"></canvas>
                </div>
            </div>
            ${analysisHtml}
        `;

        // 渲染 Chart.js 环形图
        this._renderHealthCharts(chartData);
        
        // 绑定折叠事件
        this._bindProcessToggle(container);
    },

    /**
     * 渲染健康度环形图
     */
    _renderHealthCharts(chartData) {
        if (!chartData || !chartData.labels) return;
        if (typeof Chart === 'undefined') return;

        const colors = ['#ef4444', '#f59e0b', '#3b82f6', '#10b981'];
        const borderColors = ['#dc2626', '#d97706', '#2563eb', '#059669'];

        const chartOptions = {
            responsive: true,
            maintainAspectRatio: true,
            plugins: {
                legend: {
                    position: 'bottom',
                    labels: {
                        color: '#94a3b8',
                        padding: 16,
                        usePointStyle: true,
                        pointStyleWidth: 10,
                        font: { size: 12 }
                    }
                },
                tooltip: {
                    backgroundColor: '#1e293b',
                    titleColor: '#f8fafc',
                    bodyColor: '#94a3b8',
                    borderColor: 'rgba(148,163,184,0.2)',
                    borderWidth: 1
                }
            },
            cutout: '60%'
        };

        // 数量占比图
        const countCtx = document.getElementById('health-count-chart');
        if (countCtx) {
            new Chart(countCtx, {
                type: 'doughnut',
                data: {
                    labels: chartData.labels,
                    datasets: [{
                        data: chartData.count_values,
                        backgroundColor: colors,
                        borderColor: borderColors,
                        borderWidth: 2
                    }]
                },
                options: chartOptions
            });
        }

        // 金额占比图
        const amountCtx = document.getElementById('health-amount-chart');
        if (amountCtx) {
            new Chart(amountCtx, {
                type: 'doughnut',
                data: {
                    labels: chartData.labels,
                    datasets: [{
                        data: chartData.amount_values,
                        backgroundColor: colors,
                        borderColor: borderColors,
                        borderWidth: 2
                    }]
                },
                options: {
                    ...chartOptions,
                    plugins: {
                        ...chartOptions.plugins,
                        tooltip: {
                            ...chartOptions.plugins.tooltip,
                            callbacks: {
                                label: function(context) {
                                    const value = context.parsed;
                                    return ` ${context.label}: ¥${Number(value).toLocaleString('zh-CN', {minimumFractionDigits: 2})}`;
                                }
                            }
                        }
                    }
                }
            });
        }
    },

    /**
     * 渲染补货建议板块
     */
    renderReplenishmentSummary(container, data) {
        if (!data) {
            container.innerHTML = '';
            return;
        }
        const stats = data.stats || {};
        const analysis = data.llm_analysis || {};
        
        // 兼容新旧数据结构
        const conclusion = analysis.conclusion || analysis;
        const process = analysis.analysis_process || null;

        const urgent = stats.urgent || {};
        const suggested = stats.suggested || {};
        const optional = stats.optional || {};

        // LLM 分析文本
        let analysisHtml = '';
        if (analysis.error) {
            analysisHtml = `<div class="report-analysis-text"><span style="color:var(--color-warning);">分析生成失败: ${analysis.error}</span></div>`;
        } else {
            const sections = [];
            
            // 季节信息(如果有)
            if (process && process.seasonal_analysis) {
                const sa = process.seasonal_analysis;
                sections.push(`<div class="analysis-block">
                    <div class="analysis-block-title"><i data-lucide="sun"></i> 季节性分析 <span class="season-tag"><i data-lucide="calendar"></i>${sa.current_season || ''}</span></div>
                    ${sa.seasonal_priority_items ? `<p>${sa.seasonal_priority_items}</p>` : ''}
                    ${sa.timeline_adjustment ? `<p>${sa.timeline_adjustment}</p>` : ''}
                    ${sa.next_season_preparation ? `<p>下季准备: ${sa.next_season_preparation}</p>` : ''}
                </div>`);
            }
            
            if (conclusion.urgency_assessment) {
                const ua = conclusion.urgency_assessment;
                const riskTag = ua.risk_level === 'high' ? '高风险' : ua.risk_level === 'low' ? '低风险' : '中风险';
                sections.push(`<div class="analysis-block">
                    <div class="analysis-block-title"><i data-lucide="alert-triangle"></i> 紧迫度评估 <span class="risk-tag risk-tag-${ua.risk_level || 'medium'}">${riskTag}</span></div>
                    <p>${ua.urgent_ratio_evaluation || ''}</p>
                    ${ua.immediate_action_needed ? '<p style="color:var(--color-danger);font-weight:600;">需要立即采取行动</p>' : ''}
                </div>`);
            }
            if (conclusion.budget_allocation) {
                const ba = conclusion.budget_allocation;
                sections.push(`<div class="analysis-block">
                    <div class="analysis-block-title"><i data-lucide="wallet"></i> 资金分配建议</div>
                    <p>${ba.recommended_order || ''}</p>
                    ${ba.urgent_budget ? `<p>急需补货预算: ${ba.urgent_budget}</p>` : ''}
                    ${ba.suggested_budget ? `<p>建议补货预算: ${ba.suggested_budget}</p>` : ''}
                    ${ba.optional_budget ? `<p>可选补货预算: ${ba.optional_budget}</p>` : ''}
                </div>`);
            }
            if (conclusion.execution_plan) {
                const ep = conclusion.execution_plan;
                sections.push(`<div class="analysis-block">
                    <div class="analysis-block-title"><i data-lucide="calendar-clock"></i> 执行节奏建议</div>
                    ${ep.urgent_timeline ? `<p>急需: ${ep.urgent_timeline}</p>` : ''}
                    ${ep.suggested_timeline ? `<p>建议: ${ep.suggested_timeline}</p>` : ''}
                    ${ep.optional_timeline ? `<p>可选: ${ep.optional_timeline}</p>` : ''}
                </div>`);
            }
            if (conclusion.risk_warnings && conclusion.risk_warnings.length > 0) {
                const warnHtml = conclusion.risk_warnings.map(w => {
                    if (typeof w === 'object') {
                        return `<li><strong>${w.risk_type || ''}</strong>: ${w.description || ''}${w.mitigation ? `<br><small>应对: ${w.mitigation}</small>` : ''}</li>`;
                    }
                    return `<li>${w}</li>`;
                }).join('');
                sections.push(`<div class="analysis-block">
                    <div class="analysis-block-title"><i data-lucide="shield-alert"></i> 风险提示</div>
                    <ul class="analysis-rec-list">${warnHtml}</ul>
                </div>`);
            }
            
            // 推理过程(可折叠)
            let processHtml = '';
            if (process) {
                processHtml = this._renderAnalysisProcess(process, 'replenishment-summary');
            }
            
            analysisHtml = sections.length > 0 ? `<div class="report-analysis-text">${sections.join('')}${processHtml}</div>` : '';
        }

        container.innerHTML = `
            <div class="report-section-title">
                <i data-lucide="shopping-cart"></i>
                补货建议生成情况
            </div>
            <div class="report-detail-table">
                <table>
                    <thead>
                        <tr>
                            <th>优先级</th>
                            <th>配件种类数</th>
                            <th>建议补货金额</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td><span class="priority-badge priority-high">急需补货</span></td>
                            <td>${urgent.count || 0}</td>
                            <td class="table-cell-amount">${Components.formatAmount(urgent.amount)}</td>
                        </tr>
                        <tr>
                            <td><span class="priority-badge priority-medium">建议补货</span></td>
                            <td>${suggested.count || 0}</td>
                            <td class="table-cell-amount">${Components.formatAmount(suggested.amount)}</td>
                        </tr>
                        <tr>
                            <td><span class="priority-badge priority-low">可选补货</span></td>
                            <td>${optional.count || 0}</td>
                            <td class="table-cell-amount">${Components.formatAmount(optional.amount)}</td>
                        </tr>
                        <tr style="font-weight:600; border-top: 2px solid var(--border-color-light);">
                            <td>合计</td>
                            <td>${stats.total_count || 0}</td>
                            <td class="table-cell-amount">${Components.formatAmount(stats.total_amount)}</td>
                        </tr>
                    </tbody>
                </table>
            </div>
            ${analysisHtml}
        `;
        
        // 绑定折叠事件
        this._bindProcessToggle(container);
    },

    /**
     * 渲染推理过程(可折叠)
     */
    _renderAnalysisProcess(process, moduleId) {
        if (!process) return '';
        
        const sections = [];
        
        // 计算指标
        if (process.calculated_metrics) {
            const items = Object.entries(process.calculated_metrics)
                .filter(([k, v]) => v && v !== '')
                .map(([k, v]) => `<div class="process-item"><span class="process-item-label">${this._formatProcessKey(k)}</span><span class="process-item-value">${v}</span></div>`)
                .join('');
            if (items) {
                sections.push(`<div class="process-section"><div class="process-section-title">计算指标</div>${items}</div>`);
            }
        }
        
        // 库销比诊断
        if (process.ratio_diagnosis) {
            const rd = process.ratio_diagnosis;
            const items = [];
            if (rd.current_value) items.push(`<div class="process-item"><span class="process-item-label">当前值</span><span class="process-item-value highlight">${rd.current_value}</span></div>`);
            if (rd.level) items.push(`<div class="process-item"><span class="process-item-label">判断等级</span><span class="process-item-value highlight">${rd.level}</span></div>`);
            if (rd.reasoning) items.push(`<div class="process-item"><span class="process-item-label">判断依据</span><span class="process-item-value">${rd.reasoning}</span></div>`);
            if (rd.benchmark_comparison) items.push(`<div class="process-item"><span class="process-item-label">行业对比</span><span class="process-item-value">${rd.benchmark_comparison}</span></div>`);
            if (items.length > 0) {
                sections.push(`<div class="process-section"><div class="process-section-title">库销比诊断</div>${items.join('')}</div>`);
            }
        }
        
        // 结构分析
        if (process.structure_analysis) {
            const sa = process.structure_analysis;
            const items = [];
            if (sa.in_stock_evaluation) items.push(`<div class="process-item"><span class="process-item-label">在库未锁</span><span class="process-item-value">${sa.in_stock_evaluation}</span></div>`);
            if (sa.on_way_evaluation) items.push(`<div class="process-item"><span class="process-item-label">在途</span><span class="process-item-value">${sa.on_way_evaluation}</span></div>`);
            if (sa.plan_evaluation) items.push(`<div class="process-item"><span class="process-item-label">计划数</span><span class="process-item-value">${sa.plan_evaluation}</span></div>`);
            if (sa.abnormal_items && sa.abnormal_items.length > 0) {
                items.push(`<div class="process-item"><span class="process-item-label">异常项</span><span class="process-item-value">${sa.abnormal_items.join('; ')}</span></div>`);
            }
            if (items.length > 0) {
                sections.push(`<div class="process-section"><div class="process-section-title">结构分析</div>${items.join('')}</div>`);
            }
        }
        
        // 构成诊断(销量分析)
        if (process.composition_diagnosis) {
            const cd = process.composition_diagnosis;
            const items = [];
            if (cd.out_stock_evaluation) items.push(`<div class="process-item"><span class="process-item-label">90天出库</span><span class="process-item-value">${cd.out_stock_evaluation}</span></div>`);
            if (cd.locked_evaluation) items.push(`<div class="process-item"><span class="process-item-label">未关单已锁</span><span class="process-item-value">${cd.locked_evaluation}</span></div>`);
            if (cd.ongoing_evaluation) items.push(`<div class="process-item"><span class="process-item-label">未关单出库</span><span class="process-item-value">${cd.ongoing_evaluation}</span></div>`);
            if (cd.buy_evaluation) items.push(`<div class="process-item"><span class="process-item-label">订件</span><span class="process-item-value">${cd.buy_evaluation}</span></div>`);
            if (items.length > 0) {
                sections.push(`<div class="process-section"><div class="process-section-title">构成诊断</div>${items.join('')}</div>`);
            }
        }
        
        // 活跃度诊断
        if (process.activity_diagnosis) {
            const ad = process.activity_diagnosis;
            const items = [];
            if (ad.current_rate) items.push(`<div class="process-item"><span class="process-item-label">当前活跃率</span><span class="process-item-value highlight">${ad.current_rate}</span></div>`);
            if (ad.level) items.push(`<div class="process-item"><span class="process-item-label">判断等级</span><span class="process-item-value highlight">${ad.level}</span></div>`);
            if (ad.reasoning) items.push(`<div class="process-item"><span class="process-item-label">判断依据</span><span class="process-item-value">${ad.reasoning}</span></div>`);
            if (items.length > 0) {
                sections.push(`<div class="process-section"><div class="process-section-title">活跃度诊断</div>${items.join('')}</div>`);
            }
        }
        
        // 趋势诊断
        if (process.trend_diagnosis) {
            const td = process.trend_diagnosis;
            const items = [];
            if (td.signals && td.signals.length > 0) items.push(`<div class="process-item"><span class="process-item-label">趋势信号</span><span class="process-item-value">${td.signals.join('; ')}</span></div>`);
            if (td.reasoning) items.push(`<div class="process-item"><span class="process-item-label">判断依据</span><span class="process-item-value">${td.reasoning}</span></div>`);
            if (items.length > 0) {
                sections.push(`<div class="process-section"><div class="process-section-title">趋势诊断</div>${items.join('')}</div>`);
            }
        }
        
        // 健康度诊断
        if (process.health_score_diagnosis) {
            const hsd = process.health_score_diagnosis;
            const items = [];
            if (hsd.normal_ratio) items.push(`<div class="process-item"><span class="process-item-label">正常件占比</span><span class="process-item-value highlight">${hsd.normal_ratio}</span></div>`);
            if (hsd.score) items.push(`<div class="process-item"><span class="process-item-label">健康度评分</span><span class="process-item-value highlight">${hsd.score}</span></div>`);
            if (hsd.reasoning) items.push(`<div class="process-item"><span class="process-item-label">判断依据</span><span class="process-item-value">${hsd.reasoning}</span></div>`);
            if (items.length > 0) {
                sections.push(`<div class="process-section"><div class="process-section-title">健康度诊断</div>${items.join('')}</div>`);
            }
        }
        
        // 问题诊断(健康度)
        if (process.problem_diagnosis) {
            const pd = process.problem_diagnosis;
            const items = [];
            ['shortage', 'stagnant', 'low_freq'].forEach(key => {
                const item = pd[key];
                if (item) {
                    const label = key === 'shortage' ? '缺货件' : key === 'stagnant' ? '呆滞件' : '低频件';
                    if (item.threshold_comparison) items.push(`<div class="process-item"><span class="process-item-label">${label}</span><span class="process-item-value">${item.threshold_comparison}</span></div>`);
                }
            });
            if (items.length > 0) {
                sections.push(`<div class="process-section"><div class="process-section-title">问题诊断</div>${items.join('')}</div>`);
            }
        }
        
        // 资金释放计算
        if (process.capital_release_calculation) {
            const crc = process.capital_release_calculation;
            const items = [];
            if (crc.stagnant_calculation) items.push(`<div class="process-item"><span class="process-item-label">呆滞件</span><span class="process-item-value">${crc.stagnant_calculation}</span></div>`);
            if (crc.low_freq_calculation) items.push(`<div class="process-item"><span class="process-item-label">低频件</span><span class="process-item-value">${crc.low_freq_calculation}</span></div>`);
            if (crc.total_releasable) items.push(`<div class="process-item"><span class="process-item-label">总可释放</span><span class="process-item-value highlight">${crc.total_releasable}</span></div>`);
            if (items.length > 0) {
                sections.push(`<div class="process-section"><div class="process-section-title">资金释放计算</div>${items.join('')}</div>`);
            }
        }
        
        // 紧迫度诊断(补货建议)
        if (process.urgency_diagnosis) {
            const ud = process.urgency_diagnosis;
            const items = [];
            if (ud.urgent_ratio) items.push(`<div class="process-item"><span class="process-item-label">急需占比</span><span class="process-item-value highlight">${ud.urgent_ratio}</span></div>`);
            if (ud.level) items.push(`<div class="process-item"><span class="process-item-label">紧迫等级</span><span class="process-item-value highlight">${ud.level}</span></div>`);
            if (ud.reasoning) items.push(`<div class="process-item"><span class="process-item-label">判断依据</span><span class="process-item-value">${ud.reasoning}</span></div>`);
            if (items.length > 0) {
                sections.push(`<div class="process-section"><div class="process-section-title">紧迫度诊断</div>${items.join('')}</div>`);
            }
        }
        
        // 预算分析
        if (process.budget_analysis) {
            const ba = process.budget_analysis;
            const items = [];
            if (ba.current_distribution) items.push(`<div class="process-item"><span class="process-item-label">当前分布</span><span class="process-item-value">${ba.current_distribution}</span></div>`);
            if (ba.comparison_with_standard) items.push(`<div class="process-item"><span class="process-item-label">标准对比</span><span class="process-item-value">${ba.comparison_with_standard}</span></div>`);
            if (ba.adjustment_needed) items.push(`<div class="process-item"><span class="process-item-label">调整建议</span><span class="process-item-value">${ba.adjustment_needed}</span></div>`);
            if (items.length > 0) {
                sections.push(`<div class="process-section"><div class="process-section-title">预算分析</div>${items.join('')}</div>`);
            }
        }
        
        // 风险识别
        if (process.risk_identification) {
            const ri = process.risk_identification;
            const items = [];
            if (ri.capital_pressure_check) items.push(`<div class="process-item"><span class="process-item-label">资金压力</span><span class="process-item-value">${ri.capital_pressure_check}</span></div>`);
            if (ri.over_replenishment_check) items.push(`<div class="process-item"><span class="process-item-label">过度补货</span><span class="process-item-value">${ri.over_replenishment_check}</span></div>`);
            if (ri.identified_risks && ri.identified_risks.length > 0) {
                items.push(`<div class="process-item"><span class="process-item-label">识别风险</span><span class="process-item-value">${ri.identified_risks.join('; ')}</span></div>`);
            }
            if (items.length > 0) {
                sections.push(`<div class="process-section"><div class="process-section-title">风险识别</div>${items.join('')}</div>`);
            }
        }
        
        if (sections.length === 0) return '';
        
        return `
            <div class="analysis-process-toggle" data-target="${moduleId}-process">
                <i data-lucide="chevron-down"></i>
                <span>查看分析推理过程</span>
            </div>
            <div class="analysis-process-content" id="${moduleId}-process">
                ${sections.join('')}
            </div>
        `;
    },
    
    /**
     * 格式化推理过程的key名称
     */
    _formatProcessKey(key) {
        const keyMap = {
            'in_stock_ratio': '在库未锁占比',
            'on_way_ratio': '在途占比',
            'plan_ratio': '计划数占比',
            'avg_cost': '平均成本',
            'out_stock_ratio': '90天出库占比',
            'locked_ratio': '未关单已锁占比',
            'ongoing_ratio': '未关单出库占比',
            'buy_ratio': '订件占比',
            'sku_active_rate': 'SKU活跃率',
            'avg_sales_price': '平均销售金额',
            'urgent_count_ratio': '急需数量占比',
            'urgent_amount_ratio': '急需金额占比',
            'suggested_count_ratio': '建议数量占比',
            'suggested_amount_ratio': '建议金额占比',
            'optional_count_ratio': '可选数量占比',
            'optional_amount_ratio': '可选金额占比',
        };
        return keyMap[key] || key;
    },
    
    /**
     * 绑定推理过程折叠事件
     */
    _bindProcessToggle(container) {
        const toggles = container.querySelectorAll('.analysis-process-toggle');
        toggles.forEach(toggle => {
            toggle.addEventListener('click', () => {
                const targetId = toggle.dataset.target;
                const content = document.getElementById(targetId);
                if (content) {
                    toggle.classList.toggle('expanded');
                    content.classList.toggle('expanded');
                    lucide.createIcons();
                }
            });
        });
    },

    /**
     * 初始化应用
     */
    init() {
        this.bindEvents();
        this.handleRoute();
        this.applySidebarState(); // 初始化侧边栏状态
        window.addEventListener('hashchange', () => this.handleRoute());
        lucide.createIcons();
    },

    /**
     * 绑定全局事件
     */
    bindEvents() {
        // 刷新按钮
        document.getElementById('refresh-btn').addEventListener('click', () => {
            this.handleRoute();
        });

        // 模态框关闭
        document.getElementById('modal-close').addEventListener('click', () => {
            Components.closeModal();
        });
        document.getElementById('modal-overlay').addEventListener('click', (e) => {
            if (e.target.id === 'modal-overlay') {
                Components.closeModal();
            }
        });

        // 侧边栏切换
        const menuToggle = document.getElementById('menu-toggle');
        const sidebarOverlay = document.getElementById('sidebar-overlay');
        
        if (menuToggle) {
            menuToggle.addEventListener('click', () => {
                this.toggleSidebar(true);
            });
        }
        
        if (sidebarOverlay) {
            sidebarOverlay.addEventListener('click', () => {
                this.toggleSidebar(false);
            });
        }

        // 桌面端侧边栏折叠按钮
        const collapseBtn = document.getElementById('sidebar-collapse-btn');
        if (collapseBtn) {
            collapseBtn.addEventListener('click', () => {
                this.toggleSidebarCollapse();
            });
        }

        // 导航点击自动关闭侧边栏(移动端)
        document.querySelectorAll('.nav-item').forEach(item => {
            item.addEventListener('click', () => {
                if (window.innerWidth <= 1024) {
                    this.toggleSidebar(false);
                }
            });
        });
    },

    /**
     * 路由处理
     */
    handleRoute() {
        const hash = window.location.hash || '#/';
        const [, path, param] = hash.match(/#\/([^/]*)(?:\/(.*))?/) || [, '', ''];

        // 更新导航状态
        document.querySelectorAll('.nav-item').forEach(item => {
            item.classList.remove('active');
            if (item.dataset.page === (path || 'dashboard')) {
                item.classList.add('active');
            }
        });

        // 路由分发
        switch (path) {
            case 'tasks':
                if (param) {
                    this.showTaskDetail(param);
                } else {
                    this.showTaskList();
                }
                break;
            case '':
            default:
                this.showDashboard();
                break;
        }
    },

    /**
     * 更新面包屑
     */
    updateBreadcrumb(items) {
        const breadcrumb = document.getElementById('breadcrumb');
        breadcrumb.innerHTML = items.map((item, index) => {
            if (item.href) {
                return `<span class="breadcrumb-item"><a href="${item.href}">${item.text}</a></span>`;
            }
            return `<span class="breadcrumb-item">${item.text}</span>`;
        }).join('');
    },

    /**
     * 显示概览页面
     */
    async showDashboard() {
        this.currentPage = 'dashboard';
        this.updateBreadcrumb([{ text: '概览' }]);

        const container = document.getElementById('page-container');
        container.innerHTML = '<div class="stats-grid" id="stats-grid"></div><div id="recent-tasks"></div>';

        try {
            // 获取统计数据
            const [stats, tasksData] = await Promise.all([
                API.getStatsSummary().catch(() => ({})),
                API.getTasks({ page: 1, page_size: 5 }).catch(() => ({ items: [] })),
            ]);

            // 渲染统计卡片
            const statsGrid = document.getElementById('stats-grid');
            statsGrid.innerHTML = `
                ${Components.renderStatCard('list-checks', '总任务数', stats.total_tasks || 0, 'primary')}
                ${Components.renderStatCard('check-circle', '成功任务', stats.success_tasks || 0, 'success')}
                ${Components.renderStatCard('x-circle', '失败任务', stats.failed_tasks || 0, 'danger')}
                ${Components.renderStatCard('package', '建议配件', stats.total_parts || 0, 'info')}
                ${Components.renderStatCard('dollar-sign', '建议金额', Components.formatAmount(stats.total_suggest_amount), 'warning')}
            `;

            // 渲染最近任务
            this.renderRecentTasks(tasksData.items || []);

            lucide.createIcons();
        } catch (error) {
            Components.showToast('加载数据失败: ' + error.message, 'error');
        }
    },

    /**
     * 渲染最近任务
     */
    renderRecentTasks(tasks) {
        const container = document.getElementById('recent-tasks');
        
        if (!tasks.length) {
            container.innerHTML = `
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i data-lucide="clock"></i>
                            最近任务
                        </h3>
                    </div>
                    ${Components.renderEmptyState('inbox', '暂无任务', '还没有执行过任何补货建议任务')}
                </div>
            `;
            return;
        }

        container.innerHTML = `
            <div class="table-container">
                <div class="table-header">
                    <h3 class="table-title">最近任务</h3>
                    <a href="#/tasks" class="btn btn-secondary btn-sm">
                        查看全部
                        <i data-lucide="arrow-right"></i>
                    </a>
                </div>
                <div class="table-wrapper">
                    <table>
                        <thead>
                            <tr>
                                <th>任务编号</th>
                                <th>商家组合</th>
                                <th>状态</th>
                                <th>配件数</th>
                                <th>建议金额</th>
                                <th>执行时间</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${tasks.map(task => `
                                <tr>
                                    <td>
                                        <a href="#/tasks/${task.task_no}" class="table-cell-link table-cell-mono">
                                            ${task.task_no}
                                        </a>
                                    </td>
                                    <td>${task.dealer_grouping_name || '-'}</td>
                                    <td>${Components.getStatusBadge(task.status, task.status_text)}</td>
                                    <td>${task.part_count}</td>
                                    <td class="table-cell-amount">${Components.formatAmount(task.actual_amount)}</td>
                                    <td class="table-cell-secondary">${Components.formatDuration(task.duration_seconds)}</td>
                                </tr>
                            `).join('')}
                        </tbody>
                    </table>
                </div>
            </div>
        `;
    },

    /**
     * 显示任务列表页面
     */
    async showTaskList(page = 1) {
        this.currentPage = 'tasks';
        this.updateBreadcrumb([{ text: '任务列表' }]);

        const container = document.getElementById('page-container');
        container.innerHTML = '<div id="task-list-container"></div>';

        try {
            Components.showLoading();
            const data = await API.getTasks({ page, page_size: 20 });
            Components.hideLoading();

            this.renderTaskList(data);
            lucide.createIcons();
        } catch (error) {
            Components.hideLoading();
            Components.showToast('加载任务列表失败: ' + error.message, 'error');
        }
    },

    /**
     * 渲染任务列表
     */
    renderTaskList(data) {
        const container = document.getElementById('task-list-container');
        const { items, total, page, page_size } = data;

        if (!items.length) {
            container.innerHTML = `
                <div class="card">
                    ${Components.renderEmptyState('inbox', '暂无任务', '还没有执行过任何补货建议任务')}
                </div>
            `;
            return;
        }

        container.innerHTML = `
            <div class="table-container">
                <div class="table-header">
                    <h3 class="table-title">任务列表 (${total})</h3>
                </div>
                <div class="table-wrapper">
                    <table>
                        <thead>
                            <tr>
                                <th>任务编号</th>
                                <th>商家组合</th>
                                <th>状态</th>
                                <th>配件数</th>
                                <th>建议金额</th>
                                <th>基准库销比</th>
                                <th>统计日期</th>
                                <th>执行时长</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${items.map(task => `
                                <tr>
                                    <td>
                                        <span class="table-cell-mono">${task.task_no}</span>
                                    </td>
                                    <td>${task.dealer_grouping_name || '-'}</td>
                                    <td>${Components.getStatusBadge(task.status, task.status_text)}</td>
                                    <td>${task.part_count}</td>
                                    <td class="table-cell-amount">${Components.formatAmount(task.actual_amount)}</td>
                                    <td>${Components.formatRatio(task.base_ratio)}</td>
                                    <td>${task.statistics_date || '-'}</td>
                                    <td class="table-cell-secondary">${Components.formatDuration(task.duration_seconds)}</td>
                                    <td>
                                        <a href="#/tasks/${task.task_no}" class="btn btn-ghost btn-sm">
                                            <i data-lucide="eye"></i>
                                            查看
                                        </a>
                                    </td>
                                </tr>
                            `).join('')}
                        </tbody>
                    </table>
                </div>
                <div id="pagination-container"></div>
            </div>
        `;

        // 渲染分页
        const paginationContainer = document.getElementById('pagination-container');
        paginationContainer.innerHTML = Components.renderPagination(page, total, page_size);

        // 绑定分页事件
        paginationContainer.querySelectorAll('.pagination-btn[data-page]').forEach(btn => {
            btn.addEventListener('click', () => {
                const targetPage = parseInt(btn.dataset.page);
                if (targetPage && targetPage !== page) {
                    this.showTaskList(targetPage);
                }
            });
        });

        lucide.createIcons();
    },

    /**
     * 显示任务详情页面
     */
    async showTaskDetail(taskNo) {
        this.currentPage = 'task-detail';
        this.currentTaskNo = taskNo;
        this.updateBreadcrumb([
            { text: '任务列表', href: '#/tasks' },
            { text: taskNo },
        ]);

        const container = document.getElementById('page-container');
        container.innerHTML = '<div id="task-detail-container"></div>';

        try {
            Components.showLoading();
            
            const [task, partSummaries, logs] = await Promise.all([
                API.getTask(taskNo),
                API.getPartSummaries(taskNo, { page: 1, page_size: 100 }).catch(() => ({ items: [], total: 0 })),
                API.getTaskLogs(taskNo).catch(() => ({ items: [] })),
            ]);
            
            Components.hideLoading();
            this.renderTaskDetail(task, partSummaries, logs);
            lucide.createIcons();
        } catch (error) {
            Components.hideLoading();
            Components.showToast('加载任务详情失败: ' + error.message, 'error');
        }
    },

    /**
     * 渲染任务详情
     */
    renderTaskDetail(task, partSummaries, logs) {
        this._currentLogs = logs;
        this._partSummaries = partSummaries;
        const container = document.getElementById('task-detail-container');

        container.innerHTML = `
            <!-- 返回链接 -->
            <a href="#/tasks" class="back-link">
                <i data-lucide="arrow-left"></i>
                返回任务列表
            </a>

            <!-- 任务头部 -->
            <div class="detail-header">
                <div>
                    <h1 class="detail-title">
                        ${task.task_no}
                        ${Components.getStatusBadge(task.status, task.status_text)}
                    </h1>
                    <div class="detail-meta">
                        <span class="detail-meta-item">
                            <i data-lucide="building-2"></i>
                            ${task.dealer_grouping_name || '未知商家组合'}
                        </span>
                        <span class="detail-meta-item">
                            <i data-lucide="calendar"></i>
                            ${task.statistics_date || '-'}
                        </span>
                        <span class="detail-meta-item">
                            <i data-lucide="clock"></i>
                            ${Components.formatDuration(task.duration_seconds)}
                        </span>
                    </div>
                </div>
            </div>

            <!-- 统计卡片 -->
            <div class="stats-grid">
                ${Components.renderStatCard('package', '建议配件数', task.part_count, 'primary')}
                ${Components.renderStatCard('dollar-sign', '建议金额', Components.formatAmount(task.actual_amount), 'success')}
                ${Components.renderStatCard('percent', '基准库销比', Components.formatRatio(task.base_ratio), 'info')}
                ${Components.renderStatCard('cpu', 'LLM Tokens', task.llm_total_tokens || 0, 'warning')}
            </div>

            <!-- 标签页 -->
            <div class="tabs" id="detail-tabs">
                <button class="tab active" data-tab="details">
                    <i data-lucide="list"></i>
                    配件明细
                </button>
                <button class="tab" data-tab="report">
                    <i data-lucide="file-text"></i>
                    分析报告
                </button>
                <button class="tab" data-tab="logs">
                    <i data-lucide="activity"></i>
                    执行日志
                </button>
                <button class="tab" data-tab="info">
                    <i data-lucide="info"></i>
                    任务信息
                </button>
            </div>

            <!-- 标签页内容 -->
            <div id="tab-content" class="report-container"></div>
        `;

        // 绑定标签页事件
        const tabs = container.querySelectorAll('.tab');
        tabs.forEach(tab => {
            tab.addEventListener('click', () => {
                tabs.forEach(t => t.classList.remove('active'));
                tab.classList.add('active');
                this.renderTabContent(tab.dataset.tab, task, partSummaries);
            });
        });

        // 默认显示配件汇总
        this.renderTabContent('details', task, partSummaries);
    },

    /**
     * 渲染标签页内容
     */
    renderTabContent(tabName, task, details) {
        const container = document.getElementById('tab-content');

        switch (tabName) {
            case 'details':
                this.renderDetailsTab(container, details);
                break;

            case 'logs':
                this.renderLogsTab(container, this._currentLogs);
                break;
            case 'report':
                this.renderReportTab(container, task.task_no);
                break;
            case 'info':
                this.renderInfoTab(container, task);
                break;
        }

        lucide.createIcons();
    },

    /**
     * 加载配件汇总数据(支持排序和筛选)
     */
    async loadPartSummaries() {
        if (!this.currentTaskNo) return;
        
        try {
            const params = {
                page: this.partSummaryFilters.page,
                page_size: this.partSummaryFilters.page_size,
                sort_by: this.partSummarySort.sortBy,
                sort_order: this.partSummarySort.sortOrder,
                part_code: this.partSummaryFilters.part_code,
                priority: this.partSummaryFilters.priority
            };
            
            // 移除空值参数
            Object.keys(params).forEach(key => {
                if (params[key] === '' || params[key] === null || params[key] === undefined) {
                    delete params[key];
                }
            });

            const data = await API.getPartSummaries(this.currentTaskNo, params);
            this._partSummaries = data;
            
            const container = document.getElementById('tab-content');
            if (container) {
                this.renderDetailsTab(container, data);
                lucide.createIcons();
            }
        } catch (error) {
            Components.showToast('加载配件数据失败: ' + error.message, 'error');
        }
    },

    /**
     * 切换配件汇总排序
     */
    togglePartSummarySort(field) {
        if (this.partSummarySort.sortBy === field) {
            this.partSummarySort.sortOrder = this.partSummarySort.sortOrder === 'desc' ? 'asc' : 'desc';
        } else {
            this.partSummarySort.sortBy = field;
            this.partSummarySort.sortOrder = 'desc';
        }
        this.loadPartSummaries();
    },

    /**
     * 获取排序图标
     */
    getSortIcon(field) {
        if (this.partSummarySort.sortBy !== field) {
            return '<i data-lucide="arrow-up-down" class="sort-icon sort-icon-inactive"></i>';
        }
        if (this.partSummarySort.sortOrder === 'desc') {
            return '<i data-lucide="arrow-down" class="sort-icon sort-icon-active"></i>';
        }
        return '<i data-lucide="arrow-up" class="sort-icon sort-icon-active"></i>';
    },

    /**
     * 渲染配件明细标签页
     */
    renderDetailsTab(container, partSummaries) {
        const items = partSummaries.items || [];
        const { total, page, page_size } = partSummaries;

        container.innerHTML = `
            <div class="table-container">
                <div class="table-header" style="flex-wrap: wrap; gap: 1rem; height: auto;">
                    <div style="display: flex; align-items: center; gap: 1rem; flex: 1;">
                        <h3 class="table-title">配件补货建议 (商家组合维度) - ${total}个配件</h3>
                        <div class="table-header-hint">
                            <i data-lucide="info" style="width:14px;height:14px;"></i>
                            <span>点击表头可排序</span>
                        </div>
                    </div>
                    
                    <div class="filter-toolbar" style="display: flex; gap: 0.5rem; align-items: center;">
                        <input type="text" 
                            id="filter-part-code" 
                            class="input input-sm" 
                            placeholder="搜索配件编码..." 
                            value="${this.partSummaryFilters.part_code || ''}"
                            style="width: 150px;"
                        >
                        <select id="filter-priority" class="input input-sm" style="width: 120px;">
                            <option value="">所有优先级</option>
                            <option value="1" ${this.partSummaryFilters.priority == 1 ? 'selected' : ''}>急需补货</option>
                            <option value="2" ${this.partSummaryFilters.priority == 2 ? 'selected' : ''}>建议补货</option>
                            <option value="3" ${this.partSummaryFilters.priority == 3 ? 'selected' : ''}>可选补货</option>
                            <option value="0" ${this.partSummaryFilters.priority === '0' || this.partSummaryFilters.priority === 0 ? 'selected' : ''}>无需补货</option>
                        </select>
                        <button class="btn btn-secondary btn-sm" onclick="App.applyPartFilters()">
                            <i data-lucide="search" style="width: 14px; height: 14px; margin-right: 4px;"></i>
                            查询
                        </button>
                        <button class="btn btn-ghost btn-sm" onclick="App.resetPartFilters()">
                            重置
                        </button>
                    </div>
                </div>
                <div class="table-wrapper">
                    <table>
                        <thead>
                            <tr>
                                <th style="width: 40px;"></th>
                                <th class="sortable-th" onclick="App.togglePartSummarySort('part_code')">
                                    配件编码 ${this.getSortIcon('part_code')}
                                </th>
                                <th>配件名称</th>
                                <th class="sortable-th" onclick="App.togglePartSummarySort('cost_price')">
                                    成本价 ${this.getSortIcon('cost_price')}
                                </th>
                                <th class="sortable-th" onclick="App.togglePartSummarySort('total_storage_cnt')">
                                    总库存 ${this.getSortIcon('total_storage_cnt')}
                                </th>
                                <th class="sortable-th" onclick="App.togglePartSummarySort('total_avg_sales_cnt')">
                                    总销量 ${this.getSortIcon('total_avg_sales_cnt')}
                                </th>
                                <th class="sortable-th" onclick="App.togglePartSummarySort('group_current_ratio')">
                                    商家组合库销比 ${this.getSortIcon('group_current_ratio')}
                                </th>
                                <th class="sortable-th" onclick="App.togglePartSummarySort('group_post_plan_ratio')">
                                    计划后库销比 ${this.getSortIcon('group_post_plan_ratio')}
                                </th>
                                <th class="sortable-th" onclick="App.togglePartSummarySort('shop_count')">
                                    门店数 ${this.getSortIcon('shop_count')}
                                </th>
                                <th class="sortable-th" onclick="App.togglePartSummarySort('need_replenishment_shop_count')">
                                    需补货门店 ${this.getSortIcon('need_replenishment_shop_count')}
                                </th>
                                <th class="sortable-th" onclick="App.togglePartSummarySort('total_suggest_cnt')">
                                    总建议数量 ${this.getSortIcon('total_suggest_cnt')}
                                </th>
                                <th class="sortable-th" onclick="App.togglePartSummarySort('total_suggest_amount')">
                                    总建议金额 ${this.getSortIcon('total_suggest_amount')}
                                </th>
                            </tr>
                        </thead>
                        <tbody>
                            ${items.length > 0 ? items.map((item, index) => `
                                <tr class="part-summary-row" data-part-code="${item.part_code}" data-index="${index}">
                                    <td>
                                        <button class="btn btn-ghost btn-sm expand-btn" onclick="App.togglePartShops('${item.part_code}', ${index})">
                                            <i data-lucide="chevron-right" class="expand-icon"></i>
                                        </button>
                                    </td>
                                    <td class="table-cell-mono">${item.part_code}</td>
                                    <td>${item.part_name || '-'}</td>
                                    <td>${Components.formatAmount(item.cost_price)}</td>
                                    <td>${Components.formatNumber(item.total_storage_cnt)}</td>
                                    <td>${Components.formatNumber(item.total_avg_sales_cnt)}</td>
                                    <td>${Components.getRatioIndicator(item.group_current_ratio, 1.1)}</td>
                                    <td>${Components.formatRatio(item.group_post_plan_ratio)}</td>
                                    <td>${item.shop_count}</td>
                                    <td><strong style="color: var(--color-warning);">${item.need_replenishment_shop_count}</strong></td>
                                    <td><strong>${item.total_suggest_cnt}</strong></td>
                                    <td class="table-cell-amount">${Components.formatAmount(item.total_suggest_amount)}</td>
                                </tr>
                                <tr class="part-shops-row" id="shops-${index}" style="display: none;">
                                    <td colspan="12" style="padding: 0;">
                                        <div class="shops-container" id="shops-container-${index}">
                                            <div class="loading-shops">加载中...</div>
                                        </div>
                                    </td>
                                </tr>
                            `).join('') : `
                                <tr>
                                    <td colspan="12" style="text-align: center; padding: 2rem; color: var(--text-muted);">
                                        暂无符合条件的配件建议
                                    </td>
                                </tr>
                            `}
                        </tbody>
                    </table>
                </div>
                <div id="part-summary-pagination"></div>
            </div>

            <style>
                .part-summary-row { cursor: pointer; }
                .part-summary-row:hover { background: var(--bg-hover); }
                .expand-icon { transition: transform 0.2s; }
                .expand-icon.expanded { transform: rotate(90deg); }
                .shops-container { 
                    background: var(--bg-elevated); 
                    padding: var(--spacing-md); 
                    border-left: 3px solid var(--color-primary);
                    margin-left: var(--spacing-lg);
                }
                .loading-shops { 
                    color: var(--text-muted); 
                    padding: var(--spacing-sm); 
                }
                .shop-items-table {
                    width: 100%;
                    font-size: 0.875rem;
                }
                .shop-items-table th { 
                    background: var(--bg-subtle); 
                    font-weight: 600;
                    padding: var(--spacing-xs) var(--spacing-sm);
                }
                .shop-items-table td { 
                    padding: var(--spacing-xs) var(--spacing-sm); 
                }
                .part-decision-reason {
                    margin-bottom: var(--spacing-sm);
                    padding: var(--spacing-sm);
                    background: var(--bg-subtle);
                    border-radius: var(--radius-sm);
                    font-size: 0.875rem;
                    color: var(--text-secondary);
                }
            </style>
        `;

        // 渲染分页
        const paginationContainer = document.getElementById('part-summary-pagination');
        if (paginationContainer) {
            paginationContainer.innerHTML = Components.renderPagination(page, total, page_size);
            
            // 绑定分页事件
            paginationContainer.querySelectorAll('.pagination-btn[data-page]').forEach(btn => {
                btn.addEventListener('click', () => {
                    const targetPage = parseInt(btn.dataset.page);
                    if (targetPage && targetPage !== page) {
                        this.partSummaryFilters.page = targetPage;
                        this.loadPartSummaries();
                    }
                });
            });
        }
        
        // 绑定搜索框回车事件
        const partCodeInput = document.getElementById('filter-part-code');
        if (partCodeInput) {
            partCodeInput.addEventListener('keypress', (e) => {
                if (e.key === 'Enter') {
                    App.applyPartFilters();
                }
            });
        }
    },

    /**
     * 切换配件门店展开/收起
     */
    async togglePartShops(partCode, index) {
        const row = document.getElementById(`shops-${index}`);
        const container = document.getElementById(`shops-container-${index}`);
        const btn = document.querySelector(`tr[data-index="${index}"] .expand-icon`);
        
        if (row.style.display === 'none') {
            row.style.display = 'table-row';
            btn.classList.add('expanded');
            
            try {
                const data = await API.getPartShopDetails(this.currentTaskNo, partCode);
                const partSummary = this._partSummaries.items.find(p => p.part_code === partCode);
                this.renderPartShops(container, data.items, partSummary);
                lucide.createIcons();
            } catch (error) {
                container.innerHTML = `<div class="error-text">加载失败: ${error.message}</div>`;
            }
        } else {
            row.style.display = 'none';
            btn.classList.remove('expanded');
        }
    },

    /**
     * 渲染配件门店明细
     */
    renderPartShops(container, shops, partSummary) {
        if (!shops || shops.length === 0) {
            container.innerHTML = '<div class="text-muted">无门店建议数据</div>';
            return;
        }

        container.innerHTML = `
            ${partSummary && partSummary.part_decision_reason ? `
                <div class="part-decision-reason">
                    <strong><i data-lucide="message-square" style="width:14px;height:14px;"></i> 配件补货理由:</strong>
                    ${partSummary.part_decision_reason}
                </div>
            ` : ''}
            <table class="shop-items-table">
                <thead>
                    <tr>
                        <th>库房</th>
                        <th>有效库存</th>
                        <th>月均销量</th>
                        <th>当前库销比</th>
                        <th>计划后库销比</th>
                        <th>建议数量</th>
                        <th>建议金额</th>
                        <th>建议理由</th>
                    </tr>
                </thead>
                <tbody>
                    ${shops.map(shop => `
                        <tr>
                            <td>${shop.shop_name || '-'}</td>
                            <td>${Components.formatNumber(shop.valid_storage_cnt)}</td>
                            <td>${Components.formatNumber(shop.avg_sales_cnt)}</td>
                            <td>${Components.getRatioIndicator(shop.current_ratio, shop.base_ratio)}</td>
                            <td>${Components.formatRatio(shop.post_plan_ratio)}</td>
                            <td><strong>${shop.suggest_cnt}</strong></td>
                            <td class="table-cell-amount">${Components.formatAmount(shop.suggest_amount)}</td>
                            <td style="min-width: 200px;">
                                ${shop.suggestion_reason || '-'}
                            </td>
                        </tr>
                    `).join('')}
                </tbody>
            </table>
        `;
    },

    /**
     * 渲染执行日志标签页
     */
    renderLogsTab(container, logs) {
        if (!logs || !logs.items || logs.items.length === 0) {
            container.innerHTML = `
                <div class="card">
                    ${Components.renderEmptyState('activity', '暂无执行日志', '该任务没有执行日志记录')}
                </div>
            `;
            return;
        }

        const items = logs.items;
        const totalTokens = items.reduce((sum, item) => sum + (item.llm_tokens || 0), 0);
        const totalTime = items.reduce((sum, item) => sum + (item.execution_time_ms || 0), 0);

        container.innerHTML = `
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">
                        <i data-lucide="activity"></i>
                        执行日志时间线
                    </h3>
                    <div class="card-actions">
                        <span class="text-muted">总耗时: ${Components.formatDuration(totalTime / 1000)} | Tokens: ${totalTokens}</span>
                    </div>
                </div>
                <div class="timeline">
                    ${items.map((log, index) => `
                        <div class="timeline-item ${log.status === 2 ? 'timeline-item-error' : 'timeline-item-success'}">
                            <div class="timeline-marker">
                                <div class="timeline-icon">
                                    ${log.status === 1 ? '<i data-lucide="check-circle"></i>' : 
                                      log.status === 2 ? '<i data-lucide="x-circle"></i>' : 
                                      '<i data-lucide="loader"></i>'}
                                </div>
                                ${index < items.length - 1 ? '<div class="timeline-line"></div>' : ''}
                            </div>
                            <div class="timeline-content">
                                <div class="timeline-header">
                                    <span class="timeline-title">${Components.getStepNameDisplay(log.step_name)}</span>
                                    ${Components.getLogStatusBadge(log.status)}
                                </div>
                                <div class="timeline-meta">
                                    <span class="meta-item">
                                        <i data-lucide="clock"></i>
                                        ${log.execution_time_ms ? Components.formatDuration(log.execution_time_ms / 1000) : '-'}
                                    </span>
                                    ${log.llm_tokens > 0 ? `
                                        <span class="meta-item">
                                            <i data-lucide="cpu"></i>
                                            ${log.llm_tokens} tokens
                                        </span>
                                    ` : ''}
                                    ${log.retry_count > 0 ? `
                                        <span class="meta-item meta-warning">
                                            <i data-lucide="refresh-cw"></i>
                                            重试 ${log.retry_count} 
                                        </span>
                                    ` : ''}
                                </div>
                                ${log.error_message ? `
                                    <div class="timeline-error">
                                        <i data-lucide="alert-triangle"></i>
                                        ${log.error_message}
                                    </div>
                                ` : ''}
                            </div>
                        </div>
                    `).join('')}
                </div>
            </div>
        `;
    },

    /**
     * 渲染任务信息标签页
     */
    renderInfoTab(container, task) {
        container.innerHTML = `
            <div class="detail-grid">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i data-lucide="info"></i>
                            基本信息
                        </h3>
                    </div>
                    <div class="info-list">
                        ${Components.renderInfoItem('任务编号', task.task_no)}
                        ${Components.renderInfoItem('集团ID', task.group_id)}
                        ${Components.renderInfoItem('商家组合ID', task.dealer_grouping_id)}
                        ${Components.renderInfoItem('商家组合名称', task.dealer_grouping_name)}
                        ${Components.renderInfoItem('品牌组合ID', task.brand_grouping_id)}
                        ${Components.renderInfoItem('统计日期', task.statistics_date)}
                    </div>
                </div>
                
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i data-lucide="activity"></i>
                            执行信息
                        </h3>
                    </div>
                    <div class="info-list">
                        ${Components.renderInfoItem('状态', Components.getStatusBadge(task.status, task.status_text))}
                        ${Components.renderInfoItem('开始时间', task.start_time)}
                        ${Components.renderInfoItem('结束时间', task.end_time)}
                        ${Components.renderInfoItem('执行时长', Components.formatDuration(task.duration_seconds))}
                        ${Components.renderInfoItem('创建时间', task.create_time)}
                    </div>
                </div>
                
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i data-lucide="cpu"></i>
                            LLM 信息
                        </h3>
                    </div>
                    <div class="info-list">
                        ${Components.renderInfoItem('LLM 提供商', task.llm_provider || '-')}
                        ${Components.renderInfoItem('模型名称', task.llm_model || '-')}
                        ${Components.renderInfoItem('Token 消耗', task.llm_total_tokens)}
                    </div>
                </div>
                
                ${task.error_message ? `
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title" style="color: var(--color-danger)">
                            <i data-lucide="alert-triangle"></i>
                            错误信息
                        </h3>
                    </div>
                    <pre style="background: var(--bg-elevated); padding: var(--spacing-md); border-radius: var(--radius-md); overflow-x: auto; color: var(--color-danger-light);">${task.error_message}</pre>
                </div>
                ` : ''}
            </div>
        `;
    },
};

// DOM 加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    App.init();
});

// 导出到全局
window.App = App;