harmony_sub_brand.html 27.7 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
<!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; -ms-overflow-style: none;
            display: flex; flex-direction: column; gap: 10px;
        }
        .left-panel::-webkit-scrollbar { display: none; }
        .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-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-label { color: #999; }
        .right-panel-meta .meta-value { color: #333; font-weight: 500; }
        .right-panel-body { flex: 1; overflow: auto; padding: 0; }
        .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; }
        .step-row { display: flex; align-items: center; gap: 8px; margin-bottom: 6px; }
        .step-select {
            flex: 1; padding: 5px 8px; border: 1px solid #d9d9d9;
            border-radius: 4px; font-size: 12px; background: #fff;
        }
        .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; overflow: hidden; text-overflow: ellipsis;
            white-space: nowrap;
        }
        .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; }
        .btn-save-batch {
            margin-top: 6px; padding: 6px 12px; width: 100%;
            background: #e6f7ff; color: #1890ff; border: 1px solid #91d5ff;
            border-radius: 4px; font-size: 12px; cursor: pointer;
        }
        .btn-save-batch:hover { background: #bae7ff; }
        .btn-save-batch:disabled { opacity: 0.5; cursor: not-allowed; }
        .btn-generate {
            padding: 12px 48px; background: #1890ff; color: white;
            border: none; border-radius: 6px; font-size: 16px;
            cursor: pointer; width: 100%;
        }
        .btn-generate:hover { background: #40a9ff; }
        .btn-generate:disabled { background: #d9d9d9; cursor: not-allowed; }
        .brand-filter {
            padding: 8px 16px; border-bottom: 1px solid #e8e8e8;
            display: flex; flex-wrap: wrap; gap: 6px; background: #fafafa;
        }
        .brand-chip {
            padding: 2px 10px; border-radius: 12px; font-size: 11px;
            border: 1px solid #d9d9d9; background: #fff; cursor: pointer; color: #666;
        }
        .brand-chip.active { background: #1890ff; color: #fff; border-color: #1890ff; }
        .summary-table { width: 100%; border-collapse: collapse; font-size: 11px; margin-bottom: 0; }
        .summary-table th, .summary-table td {
            padding: 4px 8px; border-bottom: 1px solid #e8e8e8; text-align: center;
        }
        .summary-table th { background: #e6f7ff; font-weight: 600; }
        .summary-wrap { padding: 8px 12px; border-bottom: 1px solid #e8e8e8; background: #fafffe; }
        .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;
        }
        .preview-table td {
            padding: 5px 10px; border-bottom: 1px solid #f0f0f0;
            max-width: 220px; overflow: hidden; text-overflow: ellipsis;
        }
        .preview-table tr:hover td { background: #e6f7ff; }
        .preview-table tr.summary-row td { background: #f6ffed; font-weight: 600; color: #389e0d; }
        .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-radius: 4px; font-size: 14px; text-decoration: none; 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" href="../analysis">问界生态系数分析</a>
            <a class="nav-item" href="../harmony">鸿蒙生态分析</a>
            <a class="nav-item active" href="../harmony/sub-brand">鸿蒙子品牌分析</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">
                            <div class="step-card" id="sb-step-store">
                                <div class="step-title">&#9312; 门店兜底配置(可选)</div>
                                <div class="step-row">
                                    <select class="step-select" id="sb-store-batch-select" onchange="onSbStoreBatchSelect()">
                                        <option value="">-- 选择历史批次 --</option>
                                    </select>
                                </div>
                                <span style="font-size:11px;color:#999;">用于关联兜底指标;不选则自动取最新鸿蒙门店配置</span>
                            </div>

                            <div class="step-card active" id="sb-step-oem">
                                <div class="step-title">&#9313; 主机厂子品牌数据</div>
                                <div class="step-row">
                                    <select class="step-select" id="sb-oem-batch-select" onchange="onSbOemBatchSelect()">
                                        <option value="">-- 选择历史批次 --</option>
                                    </select>
                                </div>
                                <div class="step-row">
                                    <span class="step-or">或</span>
                                    <div class="step-upload-zone" id="sb-drop-zone" onclick="document.getElementById('sb-file-input').click()">
                                        <input type="file" id="sb-file-input" style="display:none;" accept=".xlsx,.xls" onchange="onSubBrandFileChange()">
                                        &#x1f4c1; <span id="sb-file-name">上传主机厂子品牌数据</span>
                                    </div>
                                    <a class="btn-download-tpl" id="sb-tpl-input" href="#">输入</a>
                                    <a class="btn-download-tpl" id="sb-tpl-output" href="#">输出</a>
                                </div>
                                <div class="step-date-row">
                                    <input type="date" id="sb-start-date" title="开始日期">
                                    <span style="font-size:12px;color:#999;">~</span>
                                    <input type="date" id="sb-end-date" title="结束日期">
                                </div>
                                <button class="btn-save-batch" id="btn-save-sb-batch" style="display:none;"
                                    onclick="saveSubBrandBatch()">&#x1f4be; 保存为历史批次</button>
                            </div>

                            <div style="background:#e6f7ff;padding:6px 14px;border-radius:6px;border:1px solid #91d5ff;font-size:12px;color:#666;">
                                上传「主机厂数据-鸿蒙子品牌-模板001.xlsx」,按尊界/尚界/智界/享界拆分;产值数据按子品牌从数据库查询,输出对齐「输出模板-鸿蒙子品牌-模板003.xlsx」(19列 + 顶部汇总行)。
                            </div>

                            <div style="text-align:center;">
                                <button class="btn-generate" id="btn-generate-sb-report">&#x1f680; 生成鸿蒙子品牌分析报表</button>
                                <p style="font-size:11px;color:#999;margin-top:4px;">输出模板-鸿蒙子品牌-模板003.xlsx</p>
                            </div>

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

                        <div class="right-panel">
                            <div class="right-panel-header">
                                <span id="sb-preview-title">&#x1f4ca; 子品牌数据预览</span>
                                <span id="sb-preview-count" style="font-size:11px;color:#999;"></span>
                            </div>
                            <div class="right-panel-meta" id="sb-preview-meta" style="display:none;"></div>
                            <div class="brand-filter" id="sb-brand-filter" style="display:none;"></div>
                            <div class="right-panel-body" id="sb-preview-body">
                                <div class="right-panel-empty">请选择历史批次或上传主机厂子品牌数据</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </section>
    </main>

    <script src="../static/js/api-base.js"></script>
    <script>
    let sbPreviewCache = null;
    let sbActiveBrand = '全部';

    function escapeHtml(str) {
        const div = document.createElement('div');
        div.textContent = str;
        return div.innerHTML;
    }

    function tplUrl(type) {
        return (window.APP_ROOT || '') + '/api/harmony/sub-brand/template/' + type;
    }

    function getSbDates() {
        return {
            start: document.getElementById('sb-start-date').value,
            end: document.getElementById('sb-end-date').value,
        };
    }

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

    function renderSbMeta(data, extra) {
        const meta = document.getElementById('sb-preview-meta');
        const parts = [];
        if (data.period) parts.push('<span><span class="meta-label">周期:</span><span class="meta-value">' + escapeHtml(data.period) + '</span></span>');
        if (extra && extra.source) parts.push('<span><span class="meta-label">来源:</span><span class="meta-value">' + escapeHtml(extra.source) + '</span></span>');
        parts.push('<span><span class="meta-label">明细行:</span><span class="meta-value">' + (data.total || 0) + '</span></span>');
        if (data.matched_guarantee != null) {
            parts.push('<span><span class="meta-label">已关联兜底:</span><span class="meta-value">' + data.matched_guarantee + ' 行</span></span>');
        }
        meta.innerHTML = parts.join('');
        meta.style.display = parts.length ? 'flex' : 'none';
    }

    function renderSbBrandFilter(data) {
        const wrap = document.getElementById('sb-brand-filter');
        const counts = data.brand_counts || {};
        const chips = ['全部', '四界', '尊界', '尚界', '智界', '享界'];
        let html = '';
        chips.forEach(b => {
            const cnt = b === '全部' ? (data.total || 0) : (b === '四界' ? (data.total || 0) : (counts[b] || 0));
            const active = sbActiveBrand === b ? ' active' : '';
            html += '<span class="brand-chip' + active + '" data-brand="' + escapeHtml(b) + '">' +
                escapeHtml(b) + (cnt ? ' (' + cnt + ')' : '') + '</span>';
        });
        wrap.innerHTML = html;
        wrap.style.display = 'flex';
        wrap.querySelectorAll('.brand-chip').forEach(el => {
            el.addEventListener('click', () => {
                sbActiveBrand = el.dataset.brand;
                renderSbBrandFilter(data);
                renderSbPreviewBody(data);
            });
        });
    }

    function renderSbSummaryTable(summary) {
        if (!summary || !summary.length) return '';
        const cols = ['品牌', '主机厂交付数', '产值表交付数', '触客数', '整车延保成交数'];
        let html = '<div class="summary-wrap"><table class="summary-table"><thead><tr>';
        cols.forEach(c => { html += '<th>' + escapeHtml(c) + '</th>'; });
        html += '</tr></thead><tbody>';
        summary.forEach(row => {
            html += '<tr class="summary-row">';
            cols.forEach(c => {
                html += '<td>' + escapeHtml(String(row[c] != null ? row[c] : '')) + '</td>';
            });
            html += '</tr>';
        });
        html += '</tbody></table></div>';
        return html;
    }

    function renderSbPreviewBody(data) {
        const columns = data.columns || [];
        let rows = data.rows || [];
        if (sbActiveBrand && sbActiveBrand !== '全部' && sbActiveBrand !== '四界') {
            rows = rows.filter(r => String(r['品牌'] || '') === sbActiveBrand);
        }
        if (!columns.length) {
            document.getElementById('sb-preview-body').innerHTML = '<div class="right-panel-empty">无数据</div>';
            return;
        }
        let html = renderSbSummaryTable(data.summary);
        html += '<table class="preview-table"><thead><tr><th>#</th>';
        columns.forEach(c => { html += '<th>' + escapeHtml(String(c)) + '</th>'; });
        html += '</tr></thead><tbody>';
        rows.forEach((row, i) => {
            html += '<tr><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('sb-preview-body').innerHTML = html;
    }

    function renderSubBrandPreview(data, extra) {
        sbPreviewCache = data;
        document.getElementById('sb-preview-title').textContent = '\u{1f4ca} 子品牌数据预览';
        document.getElementById('sb-preview-count').textContent =
            sbActiveBrand === '全部' ? '共 ' + (data.total || 0) + ' 条' : '筛选 ' + sbActiveBrand;
        renderSbMeta(data, extra);
        renderSbBrandFilter(data);
        renderSbPreviewBody(data);
    }

    async function loadSbBatchOptions() {
        try {
            const [storeRes, oemRes] = 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=harmony_sub_brand_oem'),
            ]);
            const storeData = await storeRes.json();
            const oemData = await oemRes.json();
            function fill(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.textContent = (r.file_name || r.batch_no) + ' [' + (r.data_period_start || '') + '~' + (r.data_period_end || '') + ']';
                    sel.appendChild(opt);
                });
            }
            if (storeData.status === 'success') fill('sb-store-batch-select', storeData.data);
            if (oemData.status === 'success') fill('sb-oem-batch-select', oemData.data);
        } catch (e) {
            console.error('加载批次失败:', e);
        }
    }

    window.onSbStoreBatchSelect = async function() {
        highlightSbStep('sb-step-store');
        const batchNo = document.getElementById('sb-store-batch-select').value;
        if (!batchNo) return;
        try {
            const res = await fetch(window.API_BASE + '/analysis/batch-data?batch_no=' + encodeURIComponent(batchNo));
            const data = await res.json();
            if (data.status === 'success') {
                renderSubBrandPreview(data.data, { source: '门店兜底批次 ' + batchNo });
            }
        } catch (e) {
            console.error(e);
        }
        if (sbPreviewCache && document.getElementById('sb-oem-batch-select').value) {
            onSbOemBatchSelect();
        }
    };

    window.onSbOemBatchSelect = async function() {
        highlightSbStep('sb-step-oem');
        const batchNo = document.getElementById('sb-oem-batch-select').value;
        if (!batchNo) return;
        const dates = getSbDates();
        const storeBatch = document.getElementById('sb-store-batch-select').value;
        let url = window.API_BASE + '/harmony/sub-brand/batch-data?batch_no=' + encodeURIComponent(batchNo);
        if (storeBatch) url += '&store_batch_no=' + encodeURIComponent(storeBatch);
        if (dates.start) url += '&start_date=' + encodeURIComponent(dates.start);
        if (dates.end) url += '&end_date=' + encodeURIComponent(dates.end);
        document.getElementById('sb-preview-body').innerHTML = '<div class="right-panel-empty">正在加载批次...</div>';
        try {
            const res = await fetch(url);
            const data = await res.json();
            if (data.status !== 'success') throw new Error(data.detail || '加载失败');
            sbActiveBrand = '全部';
            renderSubBrandPreview(data.data, { source: '子品牌 OEM 批次 ' + batchNo });
            document.getElementById('sb-file-name').textContent = '\u2705 ' + (data.data.file_name || batchNo);
            document.getElementById('sb-drop-zone').classList.add('has-file');
        } catch (e) {
            document.getElementById('sb-preview-body').innerHTML =
                '<div class="right-panel-empty" style="color:#f5222d;">' + escapeHtml(e.message) + '</div>';
        }
    };

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

        const formData = new FormData();
        formData.append('data_file', file);
        const dates = getSbDates();
        const storeBatch = document.getElementById('sb-store-batch-select').value;
        if (dates.start) formData.append('start_date', dates.start);
        if (dates.end) formData.append('end_date', dates.end);
        if (storeBatch) formData.append('store_batch_no', storeBatch);

        document.getElementById('sb-preview-body').innerHTML = '<div class="right-panel-empty">正在解析...</div>';
        try {
            const res = await fetch(window.API_BASE + '/harmony/sub-brand/upload', { method: 'POST', body: formData });
            const data = await res.json();
            if (data.status !== 'success') throw new Error(data.detail || '上传失败');
            sbActiveBrand = '全部';
            renderSubBrandPreview(data.data, { source: file.name });
        } catch (e) {
            document.getElementById('sb-preview-body').innerHTML =
                '<div class="right-panel-empty" style="color:#f5222d;">' + escapeHtml(e.message) + '</div>';
        }
    };

    window.saveSubBrandBatch = async function() {
        const input = document.getElementById('sb-file-input');
        if (!input || !input.files.length) { alert('请先上传文件'); return; }
        const btn = document.getElementById('btn-save-sb-batch');
        btn.disabled = true;
        btn.textContent = '\u23f3 保存中...';
        const formData = new FormData();
        formData.append('data_file', input.files[0]);
        const dates = getSbDates();
        if (dates.start) formData.append('start_date', dates.start);
        if (dates.end) formData.append('end_date', dates.end);
        try {
            const res = await fetch(window.API_BASE + '/harmony/sub-brand/save-batch', { method: 'POST', body: formData });
            const data = await res.json();
            if (data.status !== 'success') throw new Error(data.detail || '保存失败');
            btn.textContent = '\u2705 已保存 (' + (data.data.batch_no || '') + ')';
            loadSbBatchOptions();
        } catch (e) {
            alert(e.message);
            btn.disabled = false;
            btn.textContent = '\u{1f4be} 保存为历史批次';
        }
    };

    document.addEventListener('DOMContentLoaded', () => {
        document.getElementById('sb-tpl-input').href = tplUrl('input');
        document.getElementById('sb-tpl-output').href = tplUrl('output');
        loadSbBatchOptions();

        const fmt = d => `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`;
        const now = new Date();
        const yesterday = new Date(now); yesterday.setDate(yesterday.getDate() - 1);
        const sbStart = document.getElementById('sb-start-date');
        const sbEnd = document.getElementById('sb-end-date');
        if (sbStart && !sbStart.value) sbStart.value = fmt(new Date(now.getFullYear(), now.getMonth(), 1));
        if (sbEnd && !sbEnd.value) sbEnd.value = fmt(yesterday);

        document.getElementById('btn-generate-sb-report').addEventListener('click', async () => {
            document.getElementById('sb-analysis-result').className = 'result-box';
            document.getElementById('sb-analysis-error').className = 'result-box';

            const oemBatch = document.getElementById('sb-oem-batch-select').value;
            const hasFile = document.getElementById('sb-file-input').files.length > 0;
            if (!oemBatch && !hasFile) {
                document.getElementById('sb-analysis-error').className = 'result-box error';
                document.getElementById('sb-analysis-error-msg').textContent = '请先上传或选择主机厂子品牌数据';
                return;
            }

            const btn = document.getElementById('btn-generate-sb-report');
            btn.disabled = true;
            btn.textContent = '\u23f3 正在生成...';
            const dates = getSbDates();
            const storeBatch = document.getElementById('sb-store-batch-select').value;

            try {
                if (hasFile && !oemBatch) {
                    const uploadForm = new FormData();
                    uploadForm.append('data_file', document.getElementById('sb-file-input').files[0]);
                    if (dates.start) uploadForm.append('start_date', dates.start);
                    if (dates.end) uploadForm.append('end_date', dates.end);
                    if (storeBatch) uploadForm.append('store_batch_no', storeBatch);
                    const upRes = await fetch(window.API_BASE + '/harmony/sub-brand/upload', { method: 'POST', body: uploadForm });
                    const upData = await upRes.json();
                    if (upData.status !== 'success') throw new Error(upData.detail || '上传失败');
                }

                const genForm = new FormData();
                if (dates.start) genForm.append('start_date', dates.start);
                if (dates.end) genForm.append('end_date', dates.end);
                if (storeBatch) genForm.append('store_batch_no', storeBatch);
                if (oemBatch) genForm.append('oem_batch_no', oemBatch);

                const genRes = await fetch(window.API_BASE + '/harmony/sub-brand/generate', { method: 'POST', body: genForm });
                const genData = await genRes.json();
                if (genData.status !== 'success') throw new Error(genData.detail || '生成失败');

                document.getElementById('sb-analysis-result').className = 'result-box success';
                const info = [];
                if (genData.detail_rows) info.push('明细 ' + genData.detail_rows + ' 行');
                info.push('含汇总行 5 行');
                info.push('文件: ' + (genData.file_path || ''));
                document.getElementById('sb-analysis-result-info').innerHTML = info.join(' · ');
                document.getElementById('btn-download-sb-report').href =
                    (window.APP_ROOT || '') + (genData.download_url || '');
            } catch (e) {
                document.getElementById('sb-analysis-error').className = 'result-box error';
                document.getElementById('sb-analysis-error-msg').textContent = e.message || '未知错误';
            } finally {
                btn.disabled = false;
                btn.textContent = '\u{1f680} 生成鸿蒙子品牌分析报表';
            }
        });
    });
    </script>
    <script src="../static/js/auth.js"></script>
</body>
</html>