app.js 52.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
/**
 * 主应用逻辑
 */

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 class="report-module">
                    <div class="report-section-title">
                        <i data-lucide="layout-dashboard"></i>
                        核心经营综述
                    </div>
                    <div class="report-grid">
                        ${this.renderOverallAssessment(report.replenishment_insights)}
                    </div>
                </div>

                <div class="report-module">
                    <div class="report-section-title">
                        <i data-lucide="alert-triangle"></i>
                        风险管控预警
                    </div>
                    <div class="report-grid">
                        ${this.renderRiskAlerts(report.urgency_assessment)}
                    </div>
                </div>

                <div class="report-module">
                    <div class="report-section-title">
                        <i data-lucide="target"></i>
                        补货策略建议
                    </div>
                    <div class="report-grid">
                        ${this.renderStrategy(report.strategy_recommendations)}
                    </div>
                </div>

                <div class="report-module">
                    <div class="report-section-title">
                        <i data-lucide="trending-up"></i>
                        效果预期与建议
                    </div>
                    <div class="report-grid">
                        ${this.renderExpectedImpact(report.expected_outcomes)}
                    </div>
                </div>
            `;
            
            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();
        }
    },

    renderOverallAssessment(insights) {
        if (!insights) return '';
        
        let heroHtml = '';
        
        // Scale (Hero Main)
        if (insights.scale_evaluation) {
            heroHtml += `
            <div class="assessment-item">
                <div class="assessment-label">补货规模</div>
                <div class="assessment-main">${insights.scale_evaluation.current_vs_historical || '-'}</div>
                <div class="assessment-sub">${insights.scale_evaluation.possible_reasons || ''}</div>
            </div>`;
        }
        
        // Structure (Hero Middle)
        if (insights.structure_analysis) {
            const data = insights.structure_analysis;
            const details = [
                data.category_distribution ? `• ${data.category_distribution}` : '',
                data.price_range_distribution ? `• ${data.price_range_distribution}` : '',
                data.turnover_distribution ? `• ${data.turnover_distribution}` : ''
            ].filter(Boolean).join('<br>');

            heroHtml += `
            <div class="assessment-item">
                <div class="assessment-label">结构特征</div>
                <div class="assessment-main">${data.imbalance_warning || '结构均衡'}</div>
                <div class="assessment-sub">${details}</div>
            </div>`;
        }
        
        // Timing (Hero End)
        if (insights.timing_judgment) {
            const data = insights.timing_judgment;
            const isPos = data.is_favorable;
            heroHtml += `
            <div class="assessment-item">
                <div class="assessment-label">时机判断</div>
                <div class="assessment-main" style="color:${isPos ? 'var(--color-success)' : 'var(--color-warning)'}">
                    ${isPos ? '有利时机' : '建议观望'}
                </div>
                <div class="assessment-sub">
                    ${data.recommendation}<br>
                    <span style="opacity:0.7;font-size:0.85em;display:block;margin-top:4px;">${data.timing_factors || ''}</span>
                </div>
            </div>`;
        }
        
        return `<div class="assessment-grid">${heroHtml}</div>`;
    },

    renderRiskAlerts(risks) {
        if (!risks) return '';
        
        let feedHtml = '<div class="risk-feed">';
        
        const addRiskItem = (level, type, desc, action) => {
            let icon = 'alert-circle';
            if (level === 'high') icon = 'alert-octagon';
            if (level === 'low') icon = 'info';
            
            feedHtml += `
            <div class="risk-item ${level}">
                <div class="risk-icon">
                    <i data-lucide="${icon}"></i>
                </div>
                <div class="risk-content">
                    <div class="risk-title">
                        ${type}
                        <span class="badgex">${level.toUpperCase()}</span>
                    </div>
                    <div class="risk-desc">${desc}</div>
                    ${action ? `<div class="risk-action"><i data-lucide="arrow-right-circle" style="width:14px;"></i> ${action}</div>` : ''}
                </div>
            </div>`;
        };
        
        // Supply Risks
        if (risks.supply_risks && Array.isArray(risks.supply_risks)) {
            risks.supply_risks.forEach(r => addRiskItem(
                r.likelihood === '高' ? 'high' : 'medium',
                r.risk_type || '供应风险',
                r.affected_scope,
                r.mitigation
            ));
        }
        
        // Capital Risks
        if (risks.capital_risks) {
            const data = risks.capital_risks;
            addRiskItem('medium', '资金风险', data.cash_flow_pressure, data.recommendation);
        }

        // Market Risks
        if (risks.market_risks && Array.isArray(risks.market_risks)) {
            risks.market_risks.forEach(r => addRiskItem('medium', '市场风险', r.risk_description, r.recommendation));
        }
        
        // Execution
        if (risks.execution_anomalies && Array.isArray(risks.execution_anomalies)) {
             risks.execution_anomalies.forEach(a => addRiskItem('high', a.anomaly_type || '执行异常', a.description, a.review_suggestion));
        }
        
        feedHtml += '</div>';
        return feedHtml;
    },

    renderStrategy(strategy) {
        if (!strategy) return '';
        
        let html = '<div class="strategy-steps">';
        
        const addStep = (num, title, items) => {
            const listItems = Array.isArray(items) ? items : [items];
            const listHtml = listItems.map(i => `<li>${i}</li>`).join('');
            html += `
            <div class="strategy-step">
                <div class="strategy-number">0${num}</div>
                <div class="strategy-title">${title}</div>
                <ul class="strategy-list">${listHtml}</ul>
            </div>`;
        };
        
        // 1. Priority
        if (strategy.priority_principle) {
            const p = strategy.priority_principle;
            addStep(1, '优先级排序', [
                `<strong style="color:var(--color-danger)">P1:</strong> ${p.tier1_criteria}`,
                `<strong style="color:var(--color-warning)">P2:</strong> ${p.tier2_criteria}`,
                `<span style="opacity:0.7">P3: ${p.tier3_criteria}</span>`
            ]);
        }
        
        // 2. Phased
        if (strategy.phased_procurement) {
            addStep(2, '分批节奏', [
                `节奏: ${strategy.phased_procurement.suggested_rhythm}`,
                `范围: ${strategy.phased_procurement.recommended_parts}`
            ]);
        }

        // 3. Coordination
        if (strategy.supplier_coordination) {
            addStep(3, '供应商协同', [
                strategy.supplier_coordination.key_communications,
                `时机: ${strategy.supplier_coordination.timing_suggestions}`
            ]);
        }
        
        html += '</div>';
        return html;
    },

    renderExpectedImpact(impact) {
        if (!impact) return '';
        
        let html = '<div class="impact-panel">';
        
        // Inventory
        if (impact.inventory_health) {
            html += `
            <div class="kpi-item">
                <div class="kpi-label">库存健康度</div>
                <div class="kpi-value">${Components.formatAmount(impact.inventory_health.shortage_reduction || 0)}</div>
                <div class="kpi-desc">${impact.inventory_health.structure_improvement}</div>
            </div>`;
        }
        
        // Efficiency
        if (impact.capital_efficiency) {
            html += `
            <div class="kpi-item">
                <div class="kpi-label">资金效率</div>
                <div class="kpi-value">${Components.formatAmount(impact.capital_efficiency.investment_amount)}</div>
                <div class="kpi-desc">${impact.capital_efficiency.expected_return}</div>
            </div>`;
        }

        // Next
        if (impact.follow_up_actions) {
            html += `
            <div class="kpi-item">
                <div class="kpi-label">下一步关注</div>
                <div class="kpi-value" style="font-size:1.5rem;background:none;-webkit-text-fill-color:var(--text-primary);">Key Actions</div>
                <div class="kpi-desc" style="text-align:left;display:inline-block;">${impact.follow_up_actions.next_steps}</div>
            </div>`;
        }
        
        html += '</div>';
        return html;
    },

    // 辅助方法:renderReportCard, renderRiskCard, renderImpactCard 已被新的独立渲染逻辑取代,保留为空或删除
    renderReportCard(title, data) { return ''; },
    renderRiskCard(title, data, level) { return ''; },
    renderImpactCard(title, data) { return ''; },

    /**
     * 初始化应用
     */
    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;