analysis.html
42.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
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
<!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;
}
.preview-sheet-tabs {
display: flex;
flex-wrap: wrap;
gap: 6px;
padding: 8px 16px;
border-bottom: 1px solid #e8e8e8;
background: #fafafa;
}
.preview-sheet-tab {
padding: 4px 12px;
font-size: 12px;
cursor: pointer;
border-radius: 4px;
border: 1px solid #d9d9d9;
background: #fff;
color: #555;
}
.preview-sheet-tab.active {
background: #1890ff;
border-color: #1890ff;
color: #fff;
}
.preview-sheet-tab.ecology:not(.active) { border-color: #91d5ff; color: #1890ff; }
.preview-sheet-tab.nature:not(.active) { border-color: #b7eb8f; color: #52c41a; }
@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="./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">
<!-- 步骤1: 门店列表 -->
<div class="step-card" id="step1-card">
<div class="step-title">① 步骤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()">
📁 <span id="store-file-name">点击上传门店列表文件</span>
</div>
<a class="btn-download-tpl" href="./api/analysis/template/store">📥 模板</a>
</div>
<button class="btn-save-batch" id="btn-save-store" style="display:none;" onclick="saveBatch('store')">💾 保存为历史批次</button>
</div>
<!-- 步骤2: 主机厂数据(单文件多 Sheet,按 sheet 名区分生态月/自然月) -->
<div class="step-card" id="step2-card">
<div class="step-title">② 步骤2: 主机厂数据(含生态月+自然月)</div>
<div class="step-row">
<select class="step-select" id="factory-batch-select" onchange="onFactoryBatchSelect()">
<option value="">-- 选择历史批次 --</option>
</select>
</div>
<div class="step-row">
<span class="step-or">或</span>
<div class="step-upload-zone" id="factory-drop-zone" onclick="document.getElementById('factory-file-input').click()">
<input type="file" id="factory-file-input" style="display:none;" accept=".xlsx,.xls" onchange="onFactoryFileChange()">
📁 <span id="factory-file-name">点击上传主机厂数据(含生态月+自然月 sheet)</span>
</div>
<a class="btn-download-tpl" href="./api/analysis/template/factory">📥 模板</a>
</div>
<div class="step-date-row">
<span style="font-size:11px;color:#999;">生态月:</span>
<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>
<div class="step-date-row">
<span style="font-size:11px;color:#999;">自然月:</span>
<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>
<p style="font-size:11px;color:#999;margin-top:4px;">上传一份含多 Sheet 的主机厂 Excel,系统按 Sheet 名日期自动识别生态月/自然月;右侧预览可切换 Sheet</p>
<button class="btn-save-batch" id="btn-save-factory" style="display:none;" onclick="saveBatch('factory')">💾 保存为历史批次</button>
</div>
<!-- 生成按钮 -->
<div style="text-align:center; margin-top:4px;">
<button class="btn-generate" id="btn-generate-report">
🚀 开始生成分析报表
</button>
<p style="font-size:11px;color:#999;margin-top:4px;">上传一份主机厂数据(含多 Sheet),系统按 Sheet 名自动拆分生态月/自然月,按兜底截止日期分组门店</p>
</div>
<!-- 生成结果 -->
<div class="result-box" id="analysis-result">
<h3 style="color:#52c41a;margin:0 0 6px;">✅ 报表生成成功</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="#">📥 下载分析报表</a>
</div>
<div class="result-box" id="analysis-error">
<h3 style="color:#f5222d;margin:0 0 6px;">❌ 报表生成失败</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">📊 数据预览</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="preview-sheet-tabs" id="preview-sheet-tabs" 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>
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: 主机厂数据(单文件多 Sheet) ==========
window.onFactoryBatchSelect = async function() {
const sel = document.getElementById('factory-batch-select');
if (!sel.value) return;
highlightStep('step2-card');
document.getElementById('factory-file-input').value = '';
document.getElementById('factory-file-name').textContent = '点击上传主机厂数据(含生态月+自然月 sheet)';
document.getElementById('factory-drop-zone').classList.remove('has-file');
const opt = sel.options[sel.selectedIndex];
const ps = opt.dataset.periodStart || '';
const pe = opt.dataset.periodEnd || '';
const pt = opt.dataset.periodType || '';
const periodLabel = pt === 'ecology' ? '生态月'
: pt === 'nature' ? '自然月'
: pt === 'mixed' ? '生态月+自然月' : '';
await loadBatchPreview(sel.value, '主机厂数据 - 历史批次', {
type: '主机厂交付数据',
periodType: periodLabel,
period: ps ? `${ps} ~ ${pe}` : '',
source: opt.textContent.split(' [')[0],
applyFactoryDates: true,
});
};
window.onFactoryFileChange = async function() {
const input = document.getElementById('factory-file-input');
if (!input.files.length) return;
const name = input.files[0].name;
document.getElementById('factory-file-name').textContent = '\u2705 ' + name;
document.getElementById('factory-drop-zone').classList.add('has-file');
document.getElementById('factory-batch-select').value = '';
highlightStep('step2-card');
document.getElementById('btn-save-factory').style.display = 'block';
const formData = new FormData();
formData.append('file_type', 'factory');
formData.append('file', input.files[0]);
await previewFile(formData, '主机厂数据 - ' + name, {
type: '主机厂交付数据',
source: 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 factoryInput = document.getElementById('factory-file-input');
const storeBatchSel = document.getElementById('store-batch-select');
const factoryBatchSel = document.getElementById('factory-batch-select');
const hasStoreFile = storeInput && storeInput.files.length > 0;
const hasFactoryFile = factoryInput && factoryInput.files.length > 0;
const hasStoreBatch = storeBatchSel && storeBatchSel.value;
const hasFactoryBatch = factoryBatchSel && factoryBatchSel.value;
if (!hasFactoryFile && !hasFactoryBatch) {
alert('请上传或选择主机厂数据(步骤2)');
return;
}
btnGenerate.disabled = true;
btnGenerate.textContent = '\u23f3 正在生成报表...';
try {
const uploadForm = new FormData();
if (hasStoreFile) uploadForm.append('store_file', storeInput.files[0]);
if (hasFactoryFile) uploadForm.append('factory_file', factoryInput.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 || hasFactoryFile;
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 (hasFactoryBatch) genForm.append('factory_batch_no', factoryBatchSel.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, facRes] = 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')
]);
const storeData = await storeRes.json();
const facData = await facRes.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.dataset.periodType = periodTypeOfRow(r);
const pt = periodTypeOfRow(r);
const tag = pt === 'ecology' ? '生态月'
: pt === 'nature' ? '自然月'
: pt === 'mixed' ? '生态+自然'
: '主机厂';
opt.textContent = `[${tag}] ${r.file_name || r.batch_no} [${r.data_period_start}~${r.data_period_end}]`;
sel.appendChild(opt);
});
}
function periodTypeOfRow(r) {
const pt = (r.period_type || '').toLowerCase();
if (pt === 'ecology' || pt === 'nature' || pt === 'mixed') return pt;
const day = parseInt((r.data_period_start || '').slice(8, 10), 10);
return day >= 20 ? 'ecology' : 'nature';
}
if (storeData.status === 'success') {
fillSelect('store-batch-select', storeData.data);
}
if (facData.status === 'success') {
fillSelect('factory-batch-select', facData.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') {
const batchMeta = { ...(meta || {}) };
const d = data.data;
if (d.period_type === 'ecology') batchMeta.periodType = '生态月';
else if (d.period_type === 'nature') batchMeta.periodType = '自然月';
else if (d.period_type === 'mixed' || (d.has_ecology && d.has_nature)) {
batchMeta.periodType = '生态月+自然月';
}
if (!batchMeta.period && d.data_period_start) {
batchMeta.period = `${d.data_period_start} ~ ${d.data_period_end}`;
}
if (meta && meta.applyFactoryDates) {
applyFactoryDatesFromBatch(d);
}
renderPreviewTable(d, title, batchMeta);
} else {
showPreviewError(data.detail || '加载失败');
}
} catch (e) {
console.error('加载批次数据失败:', e);
showPreviewError('加载失败: ' + e.message);
}
}
function applyFactoryDatesFromBatch(data) {
const metas = data.sheet_metas || [];
if (metas.length) {
metas.forEach(s => {
const start = s.data_period_start || '';
const end = s.data_period_end || '';
if (!start || !end) return;
if (s.period_type === 'ecology') {
document.getElementById('ecology-start-date').value = start;
document.getElementById('ecology-end-date').value = end;
} else if (s.period_type === 'nature') {
document.getElementById('nature-start-date').value = start;
document.getElementById('nature-end-date').value = end;
}
});
return;
}
const ps = data.data_period_start || '';
const pe = data.data_period_end || '';
const pt = (data.period_type || '').toLowerCase();
if (!ps || !pe) return;
if (pt === 'ecology') {
document.getElementById('ecology-start-date').value = ps;
document.getElementById('ecology-end-date').value = pe;
} else if (pt === 'nature') {
document.getElementById('nature-start-date').value = ps;
document.getElementById('nature-end-date').value = pe;
} else {
document.getElementById('ecology-start-date').value = ps;
document.getElementById('ecology-end-date').value = pe;
}
}
let _previewSheetsCache = null;
let _previewSheetMetas = {};
let _previewActiveSheet = null;
let _previewMetaCache = null;
function hidePreviewSheetTabs() {
const tabs = document.getElementById('preview-sheet-tabs');
tabs.style.display = 'none';
tabs.innerHTML = '';
_previewSheetsCache = null;
_previewSheetMetas = {};
_previewActiveSheet = null;
}
function sheetPeriodTypeOf(sheetName) {
const m = _previewSheetMetas[sheetName];
if (m && m.period_type) return m.period_type;
return inferSheetPeriodType(sheetName);
}
function inferSheetPeriodType(sheetName) {
const s = String(sheetName || '').trim().replace(/[()()]/g, '');
const m = s.match(/(\d{3,4})\s*[-~]\s*(\d{3,4})/);
if (!m) {
const m2 = s.match(/(\d{1,2})\.(\d{1,2})\s*[-~]\s*(\d{1,2})\.(\d{1,2})/);
if (!m2) return '';
const day = parseInt(m2[2], 10);
return day >= 20 ? 'ecology' : 'nature';
}
const token = m[1];
let day;
if (token.length === 3) day = parseInt(token.slice(1), 10);
else day = parseInt(token.slice(2), 10);
if (Number.isNaN(day)) return '';
return day >= 20 ? 'ecology' : 'nature';
}
function sheetPeriodLabel(sheetName) {
const pt = sheetPeriodTypeOf(sheetName);
if (pt === 'ecology') return '生态月';
if (pt === 'nature') return '自然月';
return '';
}
function formatSheetTabLabel(sheetName) {
const label = sheetPeriodLabel(sheetName);
return label ? `${sheetName} (${label})` : sheetName;
}
async function previewFile(formData, title, meta) {
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, meta);
} else {
showPreviewError(data.detail || '解析失败');
}
} catch (e) {
console.error('预览文件失败:', e);
showPreviewError('预览失败: ' + e.message);
}
}
function renderPreviewSheetTabs(sheetNames) {
const tabs = document.getElementById('preview-sheet-tabs');
tabs.innerHTML = '';
sheetNames.forEach((name, idx) => {
const btn = document.createElement('button');
btn.type = 'button';
const pt = sheetPeriodTypeOf(name);
btn.className = 'preview-sheet-tab' + (idx === 0 ? ' active' : '') + (pt ? ' ' + pt : '');
btn.textContent = formatSheetTabLabel(name);
btn.dataset.sheet = name;
btn.onclick = () => switchPreviewSheet(name);
tabs.appendChild(btn);
});
tabs.style.display = 'flex';
}
window.switchPreviewSheet = function(sheetName) {
if (!_previewSheetsCache || !_previewSheetsCache[sheetName]) return;
_previewActiveSheet = sheetName;
document.querySelectorAll('.preview-sheet-tab').forEach(tab => {
tab.classList.toggle('active', tab.dataset.sheet === sheetName);
});
const sheet = _previewSheetsCache[sheetName];
const ptLabel = sheetPeriodLabel(sheetName);
document.getElementById('preview-count').textContent =
'当前 Sheet「' + sheetName + '」' + (ptLabel ? '(' + ptLabel + ')' : '') + ' 共 ' + sheet.total + ' 条';
if (_previewMetaCache) {
const meta = { ..._previewMetaCache, periodType: ptLabel || _previewMetaCache.periodType };
renderPreviewMeta(meta, sheet.total);
}
renderPreviewTableBody(sheet);
};
function renderPreviewTableBody(tableData) {
const { columns, rows } = tableData;
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;
}
function showPreviewLoading(title) {
document.getElementById('preview-title').textContent = '\u23f3 ' + title;
document.getElementById('preview-count').textContent = '加载中...';
document.getElementById('preview-meta').style.display = 'none';
hidePreviewSheetTabs();
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';
hidePreviewSheetTabs();
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;
_previewMetaCache = meta || null;
if (data.sheets && data.sheet_names && data.sheet_names.length) {
_previewSheetsCache = data.sheets;
_previewSheetMetas = {};
(data.sheet_metas || []).forEach(s => { if (s && s.name) _previewSheetMetas[s.name] = s; });
_previewActiveSheet = data.sheet_names[0];
const first = data.sheets[_previewActiveSheet];
const totalAll = data.sheet_names.reduce((sum, n) => sum + (data.sheets[n].total || 0), 0);
const ecoCount = data.sheet_names.filter(n => sheetPeriodTypeOf(n) === 'ecology').length;
const natCount = data.sheet_names.filter(n => sheetPeriodTypeOf(n) === 'nature').length;
let countText = data.sheet_names.length > 1
? `${data.sheet_names.length} 个 Sheet,合计 ${totalAll} 条`
: '共 ' + first.total + ' 条';
if (ecoCount || natCount) {
countText += `(生态月 ${ecoCount} / 自然月 ${natCount})`;
}
document.getElementById('preview-count').textContent = countText;
const sheetMeta = { ...(meta || {}), periodType: sheetPeriodLabel(_previewActiveSheet) };
renderPreviewMeta(sheetMeta, first.total);
renderPreviewSheetTabs(data.sheet_names);
renderPreviewTableBody(first);
return;
}
hidePreviewSheetTabs();
document.getElementById('preview-count').textContent = '共 ' + (data.total || 0) + ' 条';
renderPreviewMeta(meta, data.total || 0);
renderPreviewTableBody(data);
}
function renderPreviewMeta(meta, 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">${total}</span></span>`;
metaDiv.innerHTML = html;
metaDiv.style.display = 'flex';
} else {
metaDiv.style.display = 'none';
}
}
async function saveBatch(fileType) {
const config = {
store: { inputId: 'store-file-input', btnId: 'btn-save-store' },
factory: {
inputId: 'factory-file-input',
btnId: 'btn-save-factory',
startId: 'ecology-start-date',
endId: 'ecology-end-date',
},
};
const cfg = config[fileType];
if (!cfg) return;
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.startId) {
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>