analysis.html 36.5 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
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>问界生态系数分析 - 问界门店运营数据分析平台</title>
    <link rel="stylesheet" href="./static/css/style.css">
    <style>
        .analysis-layout {
            display: flex;
            gap: 16px;
            height: calc(100vh - 160px);
            min-height: 600px;
            align-items: flex-start;
            overflow: hidden;
        }
        .left-panel {
            width: 420px;
            min-width: 380px;
            height: 100%;
            overflow-y: auto;
            scrollbar-width: none;        /* Firefox 隐藏滚动条 */
            -ms-overflow-style: none;     /* IE/Edge 隐藏滚动条 */
            display: flex;
            flex-direction: column;
            gap: 10px;
        }
        .left-panel::-webkit-scrollbar {
            display: none;                /* Chrome/Safari 隐藏滚动条 */
        }
        .right-panel {
            flex: 1;
            height: 100%;
            overflow: hidden;
            border: 1px solid #e8e8e8;
            border-radius: 6px;
            background: #fff;
            display: flex;
            flex-direction: column;
        }
        .right-panel-header {
            padding: 10px 16px;
            border-bottom: 1px solid #e8e8e8;
            background: #fafafa;
            font-size: 13px;
            color: #666;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        .right-panel-body {
            flex: 1;
            overflow: auto;
            padding: 0;
        }
        .right-panel-meta {
            padding: 6px 16px;
            border-bottom: 1px solid #e8e8e8;
            background: #f0f7ff;
            font-size: 12px;
            color: #555;
            display: flex;
            flex-wrap: wrap;
            gap: 4px 16px;
        }
        .right-panel-meta .meta-item {
            white-space: nowrap;
        }
        .right-panel-meta .meta-label {
            color: #999;
        }
        .right-panel-meta .meta-value {
            color: #333;
            font-weight: 500;
        }
        .right-panel-empty {
            display: flex;
            align-items: center;
            justify-content: center;
            height: 100%;
            color: #bbb;
            font-size: 14px;
        }
        .step-card {
            background: #f8f9fa;
            padding: 10px 14px;
            border-radius: 6px;
            border: 1px solid #e8e8e8;
        }
        .step-card.active {
            border-color: #1890ff;
            background: #f0f5ff;
        }
        .step-title {
            font-size: 14px;
            font-weight: 600;
            color: #333;
            margin-bottom: 8px;
            display: flex;
            align-items: center;
            gap: 6px;
        }
        .step-row {
            display: flex;
            align-items: center;
            gap: 8px;
            margin-bottom: 6px;
        }
        .step-row:last-child { margin-bottom: 0; }
        .step-select {
            flex: 1;
            padding: 5px 8px;
            border: 1px solid #d9d9d9;
            border-radius: 4px;
            font-size: 12px;
            background: #fff;
            color: #333;
        }
        .btn-save-batch {
            margin-top: 6px;
            padding: 4px 12px;
            border: 1px solid #1890ff;
            border-radius: 4px;
            background: #e6f7ff;
            color: #1890ff;
            font-size: 12px;
            cursor: pointer;
            width: 100%;
        }
        .btn-save-batch:hover { background: #bae7ff; }
        .btn-save-batch:disabled { opacity: 0.5; cursor: not-allowed; }
        .step-or {
            font-size: 11px;
            color: #999;
            white-space: nowrap;
        }
        .step-upload-zone {
            flex: 1;
            border: 1px dashed #d9d9d9;
            padding: 5px 10px;
            border-radius: 4px;
            cursor: pointer;
            background: #fff;
            font-size: 12px;
            color: #999;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            display: flex;
            align-items: center;
            gap: 4px;
        }
        .step-upload-zone.has-file {
            color: #52c41a;
            border-color: #52c41a;
            background: #f6ffed;
        }
        .step-date-row {
            display: flex;
            align-items: center;
            gap: 6px;
            margin-top: 6px;
        }
        .step-date-row input[type="date"] {
            width: 130px;
            padding: 4px 6px;
            border: 1px solid #d9d9d9;
            border-radius: 4px;
            font-size: 12px;
        }
        .btn-download-tpl {
            font-size: 11px;
            color: #1890ff;
            text-decoration: none;
            white-space: nowrap;
            cursor: pointer;
        }
        .btn-download-tpl:hover { text-decoration: underline; }
        .btn-generate {
            padding: 12px 48px;
            background: #1890ff;
            color: white;
            border: none;
            border-radius: 6px;
            font-size: 16px;
            cursor: pointer;
            transition: all 0.3s;
            width: 100%;
        }
        .btn-generate:hover { background: #40a9ff; }
        .btn-generate:disabled { background: #d9d9d9; cursor: not-allowed; }

        /* Preview Table */
        .preview-table {
            width: 100%;
            border-collapse: collapse;
            font-size: 12px;
            white-space: nowrap;
        }
        .preview-table thead {
            position: sticky;
            top: 0;
            z-index: 2;
        }
        .preview-table th {
            background: #fafafa;
            padding: 6px 10px;
            border-bottom: 2px solid #e8e8e8;
            text-align: left;
            font-weight: 600;
            color: #333;
            position: sticky;
            top: 0;
        }
        .preview-table td {
            padding: 5px 10px;
            border-bottom: 1px solid #f0f0f0;
            color: #555;
            max-width: 200px;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        .preview-table tr:hover td {
            background: #e6f7ff;
        }

        /* Result */
        .result-box {
            padding: 16px;
            border-radius: 8px;
            text-align: center;
            display: none;
        }
        .result-box.success {
            display: block;
            background: #f6ffed;
            border: 1px solid #b7eb8f;
        }
        .result-box.error {
            display: block;
            background: #fff2f0;
            border: 1px solid #ffccc7;
        }
        .btn-download {
            display: inline-block;
            padding: 10px 32px;
            background: #52c41a;
            color: white;
            border: none;
            border-radius: 4px;
            font-size: 14px;
            text-decoration: none;
            cursor: pointer;
            margin-top: 10px;
        }

        @media (max-width: 900px) {
            .analysis-layout { flex-direction: column; height: auto; }
            .left-panel { width: 100%; min-width: 0; }
            .right-panel { min-height: 400px; }
        }
    </style>
</head>
<body>
    <header>
        <div class="logo">问界运营分析平台</div>
        <nav class="nav-links">
            <a class="nav-item" href="./">首页</a>
            <a class="nav-item" href="./ods">ODS 同步任务</a>
            <a class="nav-item" href="./dw">DWS/DWM/DWA 任务</a>
            <a class="nav-item active" href="./analysis">问界生态系数分析</a>
            <a class="nav-item" href="./harmony">鸿蒙生态分析</a>
            <a class="nav-item" href="./strategy">策略效果盯防(开发中)</a>
        </nav>
        <div class="user-info" id="user-info">管理员</div>
    </header>

    <main>
        <section id="content-area">
            <div class="card">
                <h2 id="content-title">问界生态系数分析</h2>
                <div id="content-body">
                    <div class="analysis-layout">

                        <!-- ============ 左侧表单 ============ -->
                        <div class="left-panel">
                            <!-- 步骤1: 门店列表 -->
                            <div class="step-card" id="step1-card">
                                <div class="step-title">&#9312; 步骤1: 门店列表</div>
                                <div class="step-row">
                                    <select class="step-select" id="store-batch-select" onchange="onStoreBatchSelect()">
                                        <option value="">-- 选择历史批次 --</option>
                                    </select>
                                </div>
                                <div class="step-row">
                                    <span class="step-or">或</span>
                                    <div class="step-upload-zone" id="store-drop-zone" onclick="document.getElementById('store-file-input').click()">
                                        <input type="file" id="store-file-input" style="display:none;" accept=".xlsx,.xls" onchange="onStoreFileChange()">
                                        &#x1f4c1; <span id="store-file-name">点击上传门店列表文件</span>
                                    </div>
                                    <a class="btn-download-tpl" href="./api/analysis/template/store">&#x1f4e5; 模板</a>
                                </div>
                                <button class="btn-save-batch" id="btn-save-store" style="display:none;" onclick="saveBatch('store')">&#x1f4be; 保存为历史批次</button>
                            </div>

                            <!-- 步骤2: 生态(26日) -->
                            <div class="step-card" id="step2-card">
                                <div class="step-title">&#9313; 步骤2: 生态(26日)</div>
                                <div class="step-row">
                                    <select class="step-select" id="ecology-batch-select" onchange="onFactoryBatchSelect('ecology')">
                                        <option value="">-- 选择历史批次 --</option>
                                    </select>
                                </div>
                                <div class="step-row">
                                    <span class="step-or">或</span>
                                    <div class="step-upload-zone" id="ecology-drop-zone" onclick="document.getElementById('ecology-factory-input').click()">
                                        <input type="file" id="ecology-factory-input" style="display:none;" accept=".xlsx,.xls" onchange="onFactoryFileChange('ecology')">
                                        &#x1f4c1; <span id="ecology-file-name">点击上传生态主机厂数据</span>
                                    </div>
                                    <a class="btn-download-tpl" href="./api/analysis/template/factory">&#x1f4e5; 模板</a>
                                </div>
                                <div class="step-date-row">
                                    <input type="date" id="ecology-start-date" title="开始日期">
                                    <span style="font-size:12px;color:#999;">~</span>
                                    <input type="date" id="ecology-end-date" title="结束日期">
                                </div>
                                <button class="btn-save-batch" id="btn-save-ecology" style="display:none;" onclick="saveBatch('ecology')">&#x1f4be; 保存为历史批次</button>
                            </div>

                            <!-- 步骤3: 自然月(1日) -->
                            <div class="step-card" id="step3-card">
                                <div class="step-title">&#9314; 步骤3: 自然月(1日)</div>
                                <div class="step-row">
                                    <select class="step-select" id="nature-batch-select" onchange="onFactoryBatchSelect('nature')">
                                        <option value="">-- 选择历史批次 --</option>
                                    </select>
                                </div>
                                <div class="step-row">
                                    <span class="step-or">或</span>
                                    <div class="step-upload-zone" id="nature-drop-zone" onclick="document.getElementById('nature-factory-input').click()">
                                        <input type="file" id="nature-factory-input" style="display:none;" accept=".xlsx,.xls" onchange="onFactoryFileChange('nature')">
                                        &#x1f4c1; <span id="nature-file-name">点击上传自然月主机厂数据</span>
                                    </div>
                                    <a class="btn-download-tpl" href="./api/analysis/template/factory">&#x1f4e5; 模板</a>
                                </div>
                                <div class="step-date-row">
                                    <input type="date" id="nature-start-date" title="开始日期">
                                    <span style="font-size:12px;color:#999;">~</span>
                                    <input type="date" id="nature-end-date" title="结束日期">
                                </div>
                                <button class="btn-save-batch" id="btn-save-nature" style="display:none;" onclick="saveBatch('nature')">&#x1f4be; 保存为历史批次</button>
                            </div>

                            <!-- 生成按钮 -->
                            <div style="text-align:center; margin-top:4px;">
                                <button class="btn-generate" id="btn-generate-report">
                                    &#x1f680; 开始生成分析报表
                                </button>
                                <p style="font-size:11px;color:#999;margin-top:4px;">门店按兜底截止日期分组:月底/25日→生态数据sheet,其余→自然月sheet</p>
                            </div>

                            <!-- 生成结果 -->
                            <div class="result-box" id="analysis-result">
                                <h3 style="color:#52c41a;margin:0 0 6px;">&#x2705; 报表生成成功</h3>
                                <div style="font-size:12px;color:#666;margin-bottom:10px;" id="analysis-result-info"></div>
                                <a class="btn-download" id="btn-download-report" href="#">&#x1f4e5; 下载分析报表</a>
                            </div>
                            <div class="result-box" id="analysis-error">
                                <h3 style="color:#f5222d;margin:0 0 6px;">&#x274c; 报表生成失败</h3>
                                <p style="margin:0;color:#666;font-size:12px;" id="analysis-error-msg"></p>
                            </div>
                        </div>

                        <!-- ============ 右侧预览 ============ -->
                        <div class="right-panel">
                            <div class="right-panel-header">
                                <span id="preview-title">&#x1f4ca; 数据预览</span>
                                <span id="preview-count" style="font-size:11px;color:#999;"></span>
                            </div>
                            <div class="right-panel-meta" id="preview-meta" style="display:none;"></div>
                            <div class="right-panel-body" id="preview-body">
                                <div class="right-panel-empty" id="preview-empty">
                                    请在左侧选择历史批次或上传文件,数据将在此处预览
                                </div>
                            </div>
                        </div>

                    </div>
                </div>
            </div>
        </section>
    </main>

    <script>
    (function(){var p=window.location.pathname;if(p.endsWith('/'))p=p.slice(0,-1);var i=p.lastIndexOf('/');window.API_BASE=p.substring(0,i)+'/api';})();

    document.addEventListener('DOMContentLoaded', () => {
        const fmt = d => `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`;
        const now = new Date();
        const todayStr = fmt(now);
        const yesterday = new Date(now);
        yesterday.setDate(yesterday.getDate() - 1);
        const yesterdayStr = fmt(yesterday);
        const lastMonth26 = new Date(now.getFullYear(), now.getMonth()-1, 26);
        const startStr = fmt(lastMonth26);
        const firstOfMonth = fmt(new Date(now.getFullYear(), now.getMonth(), 1));

        // 默认日期
        const ecoStart = document.getElementById('ecology-start-date');
        const ecoEnd = document.getElementById('ecology-end-date');
        if (ecoStart && !ecoStart.value) ecoStart.value = startStr;
        if (ecoEnd && !ecoEnd.value) ecoEnd.value = yesterdayStr;
        const natStart = document.getElementById('nature-start-date');
        const natEnd = document.getElementById('nature-end-date');
        if (natStart && !natStart.value) natStart.value = firstOfMonth;
        if (natEnd && !natEnd.value) natEnd.value = yesterdayStr;

        // 加载历史批次下拉
        loadBatchOptions();

        // ========== 步骤1: 门店列表 ==========
        window.onStoreBatchSelect = async function() {
            const sel = document.getElementById('store-batch-select');
            if (!sel.value) return;
            highlightStep('step1-card');
            const opt = sel.options[sel.selectedIndex];
            await loadBatchPreview(sel.value, '门店列表 - 历史批次', {
                type: '门店兜底配置',
                period: opt.dataset.periodStart ? `${opt.dataset.periodStart} ~ ${opt.dataset.periodEnd}` : '',
                source: opt.textContent.split(' [')[0],
            });
        };

        window.onStoreFileChange = async function() {
            const input = document.getElementById('store-file-input');
            if (!input.files.length) return;
            const name = input.files[0].name;
            document.getElementById('store-file-name').textContent = '\u2705 ' + name;
            document.getElementById('store-drop-zone').classList.add('has-file');
            document.getElementById('store-batch-select').value = '';
            highlightStep('step1-card');
            document.getElementById('btn-save-store').style.display = 'block';

            const formData = new FormData();
            formData.append('file_type', 'store');
            formData.append('file', input.files[0]);
            await previewFile(formData, '门店列表 - ' + name);
        };

        // ========== 步骤2/3: 主机厂数据 ==========
        window.onFactoryBatchSelect = async function(type) {
            const prefix = type === 'ecology' ? 'ecology' : 'nature';
            const sel = document.getElementById(prefix + '-batch-select');
            if (!sel.value) return;
            const cardId = type === 'ecology' ? 'step2-card' : 'step3-card';
            highlightStep(cardId);
            const label = type === 'ecology' ? '生态(26日)' : '自然月(1日)';

            // 同步日期
            const opt = sel.options[sel.selectedIndex];
            if (opt.dataset.periodStart) document.getElementById(prefix + '-start-date').value = opt.dataset.periodStart;
            if (opt.dataset.periodEnd) document.getElementById(prefix + '-end-date').value = opt.dataset.periodEnd;

            await loadBatchPreview(sel.value, label + ' - 历史批次', {
                type: '主机厂交付数据',
                period: opt.dataset.periodStart ? `${opt.dataset.periodStart} ~ ${opt.dataset.periodEnd}` : '',
                source: opt.textContent.split(' [')[0],
                periodType: label,
            });
        };

        window.onFactoryFileChange = async function(type) {
            const inputId = type === 'ecology' ? 'ecology-factory-input' : 'nature-factory-input';
            const zoneId = type === 'ecology' ? 'ecology-drop-zone' : 'nature-drop-zone';
            const nameId = type === 'ecology' ? 'ecology-file-name' : 'nature-file-name';
            const selId = type === 'ecology' ? 'ecology-batch-select' : 'nature-batch-select';
            const cardId = type === 'ecology' ? 'step2-card' : 'step3-card';
            const btnId = type === 'ecology' ? 'btn-save-ecology' : 'btn-save-nature';

            const input = document.getElementById(inputId);
            if (!input.files.length) return;
            const name = input.files[0].name;
            document.getElementById(nameId).textContent = '\u2705 ' + name;
            document.getElementById(zoneId).classList.add('has-file');
            document.getElementById(selId).value = '';
            highlightStep(cardId);
            document.getElementById(btnId).style.display = 'block';

            const label = type === 'ecology' ? '生态(26日)' : '自然月(1日)';
            const formData = new FormData();
            formData.append('file_type', 'factory');
            formData.append('file', input.files[0]);
            await previewFile(formData, label + ' - ' + name);
        };

        // ========== 生成报表 ==========
        const btnGenerate = document.getElementById('btn-generate-report');
        if (btnGenerate) {
            btnGenerate.addEventListener('click', async () => {
                document.getElementById('analysis-result').className = 'result-box';
                document.getElementById('analysis-error').className = 'result-box';

                const storeInput = document.getElementById('store-file-input');
                const ecoInput = document.getElementById('ecology-factory-input');
                const natInput = document.getElementById('nature-factory-input');
                const storeBatchSel = document.getElementById('store-batch-select');
                const ecoBatchSel = document.getElementById('ecology-batch-select');
                const natBatchSel = document.getElementById('nature-batch-select');

                const hasStoreFile = storeInput && storeInput.files.length > 0;
                const hasEcoFile = ecoInput && ecoInput.files.length > 0;
                const hasNatFile = natInput && natInput.files.length > 0;
                const hasEcoBatch = ecoBatchSel && ecoBatchSel.value;
                const hasNatBatch = natBatchSel && natBatchSel.value;
                const hasStoreBatch = storeBatchSel && storeBatchSel.value;

                const hasEco = hasEcoFile || hasEcoBatch;
                const hasNat = hasNatFile || hasNatBatch;

                if (!hasEco && !hasNat) {
                    alert('请至少上传或选择一个主机厂数据(步骤2或步骤3)');
                    return;
                }

                btnGenerate.disabled = true;
                btnGenerate.textContent = '\u23f3 正在生成报表...';

                try {
                    const uploadForm = new FormData();
                    if (hasStoreFile) uploadForm.append('store_file', storeInput.files[0]);
                    if (hasEcoFile) uploadForm.append('ecology_factory_file', ecoInput.files[0]);
                    if (hasNatFile) uploadForm.append('nature_factory_file', natInput.files[0]);
                    // 传日期范围用于文件命名
                    const eS2 = document.getElementById('ecology-start-date').value;
                    const eE2 = document.getElementById('ecology-end-date').value;
                    const nS2 = document.getElementById('nature-start-date').value;
                    const nE2 = document.getElementById('nature-end-date').value;
                    if (eS2) uploadForm.append('ecology_start_date', eS2);
                    if (eE2) uploadForm.append('ecology_end_date', eE2);
                    if (nS2) uploadForm.append('nature_start_date', nS2);
                    if (nE2) uploadForm.append('nature_end_date', nE2);

                    const anyFile = hasStoreFile || hasEcoFile || hasNatFile;
                    if (anyFile) {
                        const uploadRes = await fetch(window.API_BASE + '/analysis/upload', { method: 'POST', body: uploadForm });
                        const uploadData = await uploadRes.json();
                        if (uploadData.status !== 'success') throw new Error(uploadData.detail || '文件上传失败');
                    }

                    btnGenerate.textContent = '\u23f3 正在分析计算...';

                    const genForm = new FormData();
                    const eS = document.getElementById('ecology-start-date').value;
                    const eE = document.getElementById('ecology-end-date').value;
                    const nS = document.getElementById('nature-start-date').value;
                    const nE = document.getElementById('nature-end-date').value;
                    if (eS) genForm.append('ecology_start_date', eS);
                    if (eE) genForm.append('ecology_end_date', eE);
                    if (nS) genForm.append('nature_start_date', nS);
                    if (nE) genForm.append('nature_end_date', nE);
                    // 传递批次号
                    if (hasStoreBatch) genForm.append('store_batch_no', storeBatchSel.value);
                    if (hasEcoBatch) genForm.append('ecology_batch_no', ecoBatchSel.value);
                    if (hasNatBatch) genForm.append('nature_batch_no', natBatchSel.value);

                    const genRes = await fetch(window.API_BASE + '/analysis/generate', { method: 'POST', body: genForm });
                    const genData = await genRes.json();

                    if (genData.status === 'success') {
                        document.getElementById('analysis-result').className = 'result-box success';
                        document.getElementById('analysis-result-info').innerHTML =
                            '生态数据门店: <strong>' + genData.ecology_store_count + '</strong> 家 | ' +
                            '自然月门店: <strong>' + genData.nature_store_count + '</strong> 家';
                        document.getElementById('btn-download-report').href = genData.download_url;
                    } else {
                        throw new Error(genData.detail || '报表生成失败');
                    }
                } catch (err) {
                    console.error('分析失败:', err);
                    document.getElementById('analysis-error').className = 'result-box error';
                    document.getElementById('analysis-error-msg').textContent = err.message || '未知错误';
                } finally {
                    btnGenerate.disabled = false;
                    btnGenerate.textContent = '\u{1f680} 开始生成分析报表';
                }
            });
        }
    });

    // ========== 辅助函数 ==========

    function highlightStep(cardId) {
        document.querySelectorAll('.step-card').forEach(c => c.classList.remove('active'));
        const card = document.getElementById(cardId);
        if (card) card.classList.add('active');
    }

    async function loadBatchOptions() {
        try {
            const [storeRes, ecoRes, natRes] = await Promise.all([
                fetch(window.API_BASE + '/data-import/history?brand=问界&data_type=store_guarantee'),
                fetch(window.API_BASE + '/data-import/history?brand=问界&data_type=oem_delivery&period_type=ecology'),
                fetch(window.API_BASE + '/data-import/history?brand=问界&data_type=oem_delivery&period_type=nature')
            ]);
            const storeData = await storeRes.json();
            const ecoData = await ecoRes.json();
            const natData = await natRes.json();

            function fillSelect(selId, rows) {
                const sel = document.getElementById(selId);
                if (!sel) return;
                // 清空已有选项,仅保留第一条占位项
                while (sel.options.length > 1) sel.remove(1);
                (rows || []).forEach(r => {
                    const opt = document.createElement('option');
                    opt.value = r.batch_no;
                    opt.dataset.periodStart = r.data_period_start || '';
                    opt.dataset.periodEnd = r.data_period_end || '';
                    opt.textContent = `${r.file_name || r.batch_no} [${r.data_period_start}~${r.data_period_end}]`;
                    sel.appendChild(opt);
                });
            }

            if (storeData.status === 'success') {
                fillSelect('store-batch-select', storeData.data);
            }
            if (ecoData.status === 'success') {
                fillSelect('ecology-batch-select', ecoData.data);
            }
            if (natData.status === 'success') {
                fillSelect('nature-batch-select', natData.data);
            }
        } catch (e) {
            console.error('加载历史批次失败:', e);
        }
    }

    async function loadBatchPreview(batchNo, title, meta) {
        showPreviewLoading(title);
        document.getElementById('preview-meta').style.display = 'none';
        try {
            const res = await fetch(window.API_BASE + '/analysis/batch-data?batch_no=' + encodeURIComponent(batchNo));
            const data = await res.json();
            if (data.status === 'success') {
                renderPreviewTable(data.data, title, meta);
            } else {
                showPreviewError(data.detail || '加载失败');
            }
        } catch (e) {
            console.error('加载批次数据失败:', e);
            showPreviewError('加载失败: ' + e.message);
        }
    }

    async function previewFile(formData, title) {
        showPreviewLoading(title);
        try {
            const res = await fetch(window.API_BASE + '/analysis/preview-file', { method: 'POST', body: formData });
            const data = await res.json();
            if (data.status === 'success') {
                renderPreviewTable(data.data, title);
            } else {
                showPreviewError(data.detail || '解析失败');
            }
        } catch (e) {
            console.error('预览文件失败:', e);
            showPreviewError('预览失败: ' + e.message);
        }
    }

    function showPreviewLoading(title) {
        document.getElementById('preview-title').textContent = '\u23f3 ' + title;
        document.getElementById('preview-count').textContent = '加载中...';
        document.getElementById('preview-meta').style.display = 'none';
        document.getElementById('preview-body').innerHTML =
            '<div class="right-panel-empty">正在解析数据...</div>';
    }

    function showPreviewError(msg) {
        document.getElementById('preview-title').textContent = '\u274c 加载失败';
        document.getElementById('preview-count').textContent = '';
        document.getElementById('preview-meta').style.display = 'none';
        document.getElementById('preview-body').innerHTML =
            '<div class="right-panel-empty" style="color:#f5222d;">' + msg + '</div>';
    }

    function renderPreviewTable(data, title, meta) {
        document.getElementById('preview-title').textContent = '\u{1f4ca} ' + title;
        document.getElementById('preview-count').textContent = '共 ' + data.total + ' 条';

        // 渲染批次元信息
        const metaDiv = document.getElementById('preview-meta');
        if (meta) {
            let html = '';
            if (meta.type) html += `<span class="meta-item"><span class="meta-label">数据类型:</span><span class="meta-value">${escapeHtml(meta.type)}</span></span>`;
            if (meta.periodType) html += `<span class="meta-item"><span class="meta-label">周期类型:</span><span class="meta-value">${escapeHtml(meta.periodType)}</span></span>`;
            if (meta.period) html += `<span class="meta-item"><span class="meta-label">时间范围:</span><span class="meta-value">${escapeHtml(meta.period)}</span></span>`;
            if (meta.source) html += `<span class="meta-item"><span class="meta-label">来源:</span><span class="meta-value">${escapeHtml(meta.source)}</span></span>`;
            html += `<span class="meta-item"><span class="meta-label">数据行数:</span><span class="meta-value">${data.total}</span></span>`;
            metaDiv.innerHTML = html;
            metaDiv.style.display = 'flex';
        } else {
            metaDiv.style.display = 'none';
        }

        const { columns, rows } = data;
        if (!columns.length || !rows.length) {
            document.getElementById('preview-body').innerHTML =
                '<div class="right-panel-empty">无数据</div>';
            return;
        }

        let html = '<table class="preview-table"><thead><tr>';
        html += '<th style="width:40px;text-align:center;">#</th>';
        columns.forEach(c => {
            html += '<th>' + escapeHtml(String(c)) + '</th>';
        });
        html += '</tr></thead><tbody>';

        rows.forEach((row, i) => {
            html += '<tr>';
            html += '<td style="text-align:center;color:#999;">' + (i + 1) + '</td>';
            columns.forEach(c => {
                const val = row[c] !== undefined && row[c] !== null ? String(row[c]) : '';
                html += '<td>' + escapeHtml(val) + '</td>';
            });
            html += '</tr>';
        });

        html += '</tbody></table>';
        document.getElementById('preview-body').innerHTML = html;
    }

    async function saveBatch(fileType) {
        const config = {
            store: { inputId: 'store-file-input', btnId: 'btn-save-store' },
            ecology: { inputId: 'ecology-factory-input', btnId: 'btn-save-ecology', startId: 'ecology-start-date', endId: 'ecology-end-date', periodType: 'ecology' },
            nature: { inputId: 'nature-factory-input', btnId: 'btn-save-nature', startId: 'nature-start-date', endId: 'nature-end-date', periodType: 'nature' },
        };
        const cfg = config[fileType];
        const input = document.getElementById(cfg.inputId);
        if (!input || !input.files.length) { alert('请先上传文件'); return; }

        const btn = document.getElementById(cfg.btnId);
        btn.disabled = true;
        btn.textContent = '\u23f3 保存中...';

        const formData = new FormData();
        formData.append('file_type', fileType);
        formData.append('file', input.files[0]);
        if (cfg.periodType) {
            formData.append('period_type', cfg.periodType);
            formData.append('period_start', document.getElementById(cfg.startId).value || '');
            formData.append('period_end', document.getElementById(cfg.endId).value || '');
        }

        try {
            const res = await fetch(window.API_BASE + '/analysis/save-batch', { method: 'POST', body: formData });
            const data = await res.json();
            if (data.status === 'success') {
                btn.textContent = '\u2705 已保存 (' + (data.data.batch_no || '') + ')';
                btn.style.background = '#f6ffed';
                btn.style.borderColor = '#b7eb8f';
                btn.style.color = '#52c41a';
                // 刷新下拉列表
                loadBatchOptions();
            } else {
                throw new Error(data.detail || '保存失败');
            }
        } catch (e) {
            console.error('保存批次失败:', e);
            btn.textContent = '\u274c 保存失败';
            btn.style.background = '#fff2f0';
            btn.style.borderColor = '#ffccc7';
            btn.style.color = '#f5222d';
            btn.disabled = false;
        }
    }

    function escapeHtml(str) {
        const div = document.createElement('div');
        div.textContent = str;
        return div.innerHTML;
    }
    </script>
    <script src="./static/js/auth.js"></script>
</body>
</html>