-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
2762 lines (2452 loc) · 113 KB
/
Copy pathscript.js
File metadata and controls
2762 lines (2452 loc) · 113 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ========== 配置区域 ==========
// ========== API 配置区域 ==========
// 从 api.config.js 导入配置
let API_KEY = '';
let ENDPOINT = '';
let MODEL = '';
let AUTH_TYPE = '';
let TEMPERATURE = 0.7;
let MAX_TOKENS = 6000;
// 尝试加载用户配置
try {
// 从 api.config.js 中获取配置
if (typeof API_CONFIG !== 'undefined') {
API_KEY = API_CONFIG.API_KEY || '';
ENDPOINT = API_CONFIG.ENDPOINT;
MODEL = API_CONFIG.MODEL;
AUTH_TYPE = API_CONFIG.AUTH_TYPE;
TEMPERATURE = API_CONFIG.TEMPERATURE || 0.7;
MAX_TOKENS = API_CONFIG.MAX_TOKENS || 6000;
}
// 检查配置是否有效
if (!API_KEY || API_KEY === 'your_api_key_here') {
console.warn('❌ API 密钥未配置!请修改 api.config.js 文件。');
}
} catch (error) {
console.error('❌ 加载 API 配置失败:', error);
}
// ========== 全局变量 ==========
let selectedIngredients = []; // 已选主要食材
let selectedSeasonings = []; // 已选调料
let currentRecipeId = ''; // 当前评价的菜谱ID
let starScore = 0; // 星级评分
let commonIngredientGroups = JSON.parse(localStorage.getItem('commonIngredientGroups')) || []; // 常用食材组合
let historyRecipes = JSON.parse(localStorage.getItem('historyRecipes')) || []; // 生成历史
let collectRecipes = JSON.parse(localStorage.getItem('collectRecipes')) || []; // 收藏菜谱
let tryRecipes = JSON.parse(localStorage.getItem('tryRecipes')) || {}; // 已尝试菜谱
let currentDisplayedRecipes = []; // 当前显示的菜谱列表
let editingGroupIndex = -1; // 当前编辑的组合索引
let isGeneratingFlow = false; // 是否处于生成菜谱流程中
let isEditingGroupFlow = false; // 是否处于编辑常用组合流程中
let editingGroupForFlow = -1; // 编辑流程中的组合索引
// ========== DOM元素获取 ==========
// 筛选相关
const cuisineFilter = document.getElementById('cuisineFilter');
const tasteFilter = document.getElementById('tasteFilter');
const timeFilter = document.getElementById('timeFilter');
const levelFilter = document.getElementById('levelFilter');
// 食材相关
const categoryTabs = document.querySelectorAll('.category-tab');
const ingredientSearch = document.getElementById('ingredientSearch');
const ingredientList = document.getElementById('ingredientList');
const ingredientItems = document.querySelectorAll('.ingredient-item[data-type="ingredient"]');
const customIngredient = document.getElementById('customIngredient');
const addIngredientBtn = document.getElementById('addIngredientBtn');
const selectedIngredientsEl = document.getElementById('selectedIngredients');
// 调料相关
const seasoningSearch = document.getElementById('seasoningSearch');
const seasoningList = document.getElementById('seasoningList');
const seasoningItems = document.querySelectorAll('.ingredient-item[data-type="seasoning"]');
const customSeasoning = document.getElementById('customSeasoning');
const addSeasoningBtn = document.getElementById('addSeasoningBtn');
const selectedSeasoningsEl = document.getElementById('selectedSeasonings');
// 保存/管理
const saveGroupBtn = document.getElementById('saveGroupBtn');
const manageGroupBtn = document.getElementById('manageGroupBtn');
// 生成相关
const generateBtn = document.getElementById('generateBtn');
const loading = document.getElementById('loading');
const recipeList = document.getElementById('recipeList');
const emptyTip = document.getElementById('emptyTip');
// 购物清单
const shoppingList = []; // 购物清单数组
const shoppingModal = document.getElementById('shoppingModal');
const shoppingLoadingModal = document.getElementById('shoppingLoadingModal');
const shoppingContent = document.getElementById('shoppingContent');
const closeShoppingModal = document.getElementById('closeShoppingModal');
const cancelShoppingModal = document.getElementById('cancelShoppingModal');
const clearShoppingBtn = document.getElementById('clearShoppingBtn');
const exportShoppingBtn = document.getElementById('exportShoppingBtn');
// 历史/收藏相关
const historyCard = document.getElementById('historyCard');
const historyModal = document.getElementById('historyModal');
const closeHistoryModal = document.getElementById('closeHistoryModal');
const cancelHistoryModal = document.getElementById('cancelHistoryModal');
const historyContent = document.getElementById('historyContent');
const historyCountDisplay = document.getElementById('historyCountDisplay');
const clearHistoryBtn = document.getElementById('clearHistoryBtn');
const collectCard = document.getElementById('collectCard');
const collectModal = document.getElementById('collectModal');
const closeCollectModal = document.getElementById('closeCollectModal');
const cancelCollectModal = document.getElementById('cancelCollectModal');
const collectContent = document.getElementById('collectContent');
const collectCountDisplay = document.getElementById('collectCountDisplay');
const clearCollectBtn = document.getElementById('clearCollectBtn');
// 常用组合管理相关
const groupModal = document.getElementById('groupModal');
const closeGroupModal = document.getElementById('closeGroupModal');
const cancelGroupModal = document.getElementById('cancelGroupModal');
const groupContent = document.getElementById('groupContent');
// 评价弹窗
const evaluateModal = document.getElementById('evaluateModal');
const starRating = document.getElementById('starRating');
const commentInput = document.getElementById('commentInput');
const cancelEvaluate = document.getElementById('cancelEvaluate');
const confirmEvaluate = document.getElementById('confirmEvaluate');
// 食材/调料模态窗口
const ingredientCard = document.getElementById('ingredientCard');
const ingredientModal = document.getElementById('ingredientModal');
const closeIngredientModal = document.getElementById('closeIngredientModal');
const cancelIngredientModal = document.getElementById('cancelIngredientModal');
const confirmIngredientModal = document.getElementById('confirmIngredientModal');
const clearAllIngredientsBtn = document.getElementById('clearAllIngredientsBtn');
const ingredientCount = document.getElementById('ingredientCount');
const seasoningCard = document.getElementById('seasoningCard');
const seasoningModal = document.getElementById('seasoningModal');
const closeSeasoningModal = document.getElementById('closeSeasoningModal');
const cancelSeasoningModal = document.getElementById('cancelSeasoningModal');
const confirmSeasoningModal = document.getElementById('confirmSeasoningModal');
const clearAllSeasoningsBtn = document.getElementById('clearAllSeasoningsBtn');
const seasoningCount = document.getElementById('seasoningCount');
// 菜谱详情弹窗
const recipeDetailModal = document.getElementById('recipeDetailModal');
const closeRecipeDetailModal = document.getElementById('closeRecipeDetailModal');
const cancelRecipeDetailModal = document.getElementById('cancelRecipeDetailModal');
const recipeDetailContent = document.getElementById('recipeDetailContent');
// ========== 初始化函数 ==========
/**
* 初始化应用程序,设置初始状态并绑定事件
*/
function init() {
renderSelectedIngredients();
renderSelectedSeasonings();
updateIngredientCount();
updateSeasoningCount();
updateHistoryCount();
updateCollectCount();
updateSaveButtonState();
updateSaveButtonText();
generateBtn.disabled = false;
renderHistory();
renderCollect();
bindEvents();
}
// ========== 事件绑定 ==========
/**
* 绑定所有DOM事件监听器
*/
function bindEvents() {
// 食材卡片点击事件
ingredientCard.addEventListener('click', () => {
ingredientModal.classList.add('active');
});
// 关闭食材选择模态窗口
closeIngredientModal.addEventListener('click', () => {
ingredientModal.classList.remove('active');
if (isGeneratingFlow) {
isGeneratingFlow = false;
updateModalButtons();
}
});
cancelIngredientModal.addEventListener('click', () => {
ingredientModal.classList.remove('active');
if (isGeneratingFlow) {
isGeneratingFlow = false;
updateModalButtons();
}
});
confirmIngredientModal.addEventListener('click', () => {
if (isGeneratingFlow) {
if (selectedIngredients.length === 0) {
alert('请至少选择一种食材!');
return;
}
ingredientModal.classList.remove('active');
seasoningModal.classList.add('active');
updateModalButtons();
} else if (isEditingGroupFlow) {
if (selectedIngredients.length === 0) {
alert('请至少选择一种食材!');
return;
}
ingredientModal.classList.remove('active');
seasoningModal.classList.add('active');
updateModalButtons();
} else {
ingredientModal.classList.remove('active');
updateIngredientCount();
}
});
// 一键清空食材
clearAllIngredientsBtn.addEventListener('click', () => {
if (selectedIngredients.length === 0) return;
if (confirm('确定要清空所有已选食材吗?')) {
ingredientItems.forEach(item => item.classList.remove('selected'));
selectedIngredients = [];
renderSelectedIngredients();
updateIngredientCount();
}
});
// 打开调料选择模态窗口
seasoningCard.addEventListener('click', () => {
seasoningModal.classList.add('active');
});
// 关闭调料选择模态窗口
closeSeasoningModal.addEventListener('click', () => {
seasoningModal.classList.remove('active');
if (isGeneratingFlow) {
isGeneratingFlow = false;
updateModalButtons();
} else if (isEditingGroupFlow) {
isEditingGroupFlow = false;
editingGroupForFlow = -1;
updateModalButtons();
}
});
cancelSeasoningModal.addEventListener('click', () => {
seasoningModal.classList.remove('active');
if (isGeneratingFlow) {
ingredientModal.classList.add('active');
updateModalButtons();
} else if (isEditingGroupFlow) {
ingredientModal.classList.add('active');
updateModalButtons();
}
});
confirmSeasoningModal.addEventListener('click', async () => {
if (isGeneratingFlow) {
seasoningModal.classList.remove('active');
isGeneratingFlow = false;
updateModalButtons();
await handleGenerateRecipe();
} else if (isEditingGroupFlow) {
if (selectedIngredients.length === 0 || selectedSeasonings.length === 0) {
alert('请先选择食材和调料!');
return;
}
const group = commonIngredientGroups[editingGroupForFlow];
const oldName = group.name;
const groupName = prompt('请输入常用组合名称:', oldName);
if (!groupName) return;
commonIngredientGroups[editingGroupForFlow] = {
name: groupName,
ingredients: [...selectedIngredients],
seasonings: [...selectedSeasonings],
createTime: group.createTime,
updateTime: new Date().toLocaleString()
};
localStorage.setItem('commonIngredientGroups', JSON.stringify(commonIngredientGroups));
seasoningModal.classList.remove('active');
isEditingGroupFlow = false;
editingGroupForFlow = -1;
updateModalButtons();
alert('常用食材组合已更新!');
renderGroupList();
} else {
seasoningModal.classList.remove('active');
updateSeasoningCount();
}
});
// 一键清空调料
clearAllSeasoningsBtn.addEventListener('click', () => {
if (selectedSeasonings.length === 0) return;
if (confirm('确定要清空所有已选调料吗?')) {
seasoningItems.forEach(item => item.classList.remove('selected'));
selectedSeasonings = [];
renderSelectedSeasonings();
updateSeasoningCount();
}
});
// 点击模态窗口背景关闭
ingredientModal.addEventListener('click', (e) => {
if (e.target === ingredientModal) {
ingredientModal.classList.remove('active');
}
});
seasoningModal.addEventListener('click', (e) => {
if (e.target === seasoningModal) {
seasoningModal.classList.remove('active');
}
});
// 食材分类标签切换
categoryTabs.forEach(tab => {
tab.addEventListener('click', () => {
const type = tab.dataset.type;
document.querySelectorAll(`.category-tab[data-type="${type}"]`).forEach(t => t.classList.remove('active'));
tab.classList.add('active');
const category = tab.dataset.category;
if (type === 'ingredient') {
document.querySelectorAll('.subcategory-container[data-type="ingredient"]').forEach(container => {
container.classList.remove('active');
});
if (category !== 'all') {
const subcategoryContainer = document.getElementById(`${category}-subcategory`);
if (subcategoryContainer) {
subcategoryContainer.classList.add('active');
}
}
filterIngredientsByCategory(category);
} else if (type === 'seasoning') {
filterSeasoningsByCategory(category);
}
});
});
// 子分类标签切换
const subcategoryTabs = document.querySelectorAll('.subcategory-tab');
subcategoryTabs.forEach(tab => {
tab.addEventListener('click', () => {
const type = tab.dataset.type;
const category = tab.dataset.category;
const subcategory = tab.dataset.subcategory;
document.querySelectorAll(`.subcategory-tab[data-category="${category}"][data-type="${type}"]`).forEach(t => t.classList.remove('active'));
tab.classList.add('active');
if (type === 'ingredient') {
filterIngredientsBySubcategory(category, subcategory);
}
});
});
// 食材搜索
ingredientSearch.addEventListener('input', (e) => {
const keyword = e.target.value.trim().toLowerCase();
filterIngredientsBySearch(keyword);
});
// 调料搜索
seasoningSearch.addEventListener('input', (e) => {
const keyword = e.target.value.trim().toLowerCase();
filterSeasoningsBySearch(keyword);
});
// 食材项点击选择
ingredientItems.forEach(item => {
item.addEventListener('click', () => {
item.classList.toggle('selected');
const ingredient = item.textContent.trim();
if (item.classList.contains('selected')) {
if (!selectedIngredients.some(i => i.name === ingredient)) {
selectedIngredients.push({ name: ingredient, quantity: '' });
}
} else {
selectedIngredients = selectedIngredients.filter(i => i.name !== ingredient);
}
renderSelectedIngredients();
updateIngredientCount();
});
});
// 调料项点击选择
seasoningItems.forEach(item => {
item.addEventListener('click', () => {
item.classList.toggle('selected');
const seasoning = item.textContent.trim();
if (item.classList.contains('selected')) {
if (!selectedSeasonings.includes(seasoning)) {
selectedSeasonings.push(seasoning);
}
} else {
selectedSeasonings = selectedSeasonings.filter(i => i !== seasoning);
}
renderSelectedSeasonings();
updateSeasoningCount();
});
});
// 自定义添加食材
addIngredientBtn.addEventListener('click', () => {
const input = customIngredient.value.trim();
if (!input) {
alert('请输入食材名称!');
return;
}
let name = input;
let quantity = '';
const match = input.match(/^(.+?)(\d+[^\d\s]+)$/);
if (match) {
name = match[1].trim();
quantity = match[2].trim();
}
if (selectedIngredients.some(i => i.name === name)) {
alert('该食材已添加!');
customIngredient.value = '';
return;
}
selectedIngredients.push({ name: name, quantity: quantity });
customIngredient.value = '';
renderSelectedIngredients();
updateIngredientCount();
});
// 自定义添加调料
addSeasoningBtn.addEventListener('click', () => {
const seasoning = customSeasoning.value.trim();
if (!seasoning) {
alert('请输入调料名称!');
return;
}
if (selectedSeasonings.includes(seasoning)) {
alert('该调料已添加!');
customSeasoning.value = '';
return;
}
selectedSeasonings.push(seasoning);
customSeasoning.value = '';
renderSelectedSeasonings();
updateSeasoningCount();
});
// 保存常用食材组合
saveGroupBtn.addEventListener('click', () => {
if (selectedIngredients.length === 0 && selectedSeasonings.length === 0) {
alert('请先选择/添加食材或调料!');
return;
}
if (editingGroupIndex >= 0) {
const oldName = commonIngredientGroups[editingGroupIndex].name;
const groupName = prompt('请输入常用组合名称:', oldName);
if (!groupName) return;
commonIngredientGroups[editingGroupIndex] = {
name: groupName,
ingredients: [...selectedIngredients],
seasonings: [...selectedSeasonings],
createTime: commonIngredientGroups[editingGroupIndex].createTime,
updateTime: new Date().toLocaleString()
};
localStorage.setItem('commonIngredientGroups', JSON.stringify(commonIngredientGroups));
alert('常用食材组合更新成功!');
editingGroupIndex = -1;
updateSaveButtonText();
} else {
const groupName = prompt('请输入常用组合名称:', '我的家常菜组合');
if (!groupName) return;
const group = {
name: groupName,
ingredients: [...selectedIngredients],
seasonings: [...selectedSeasonings],
createTime: new Date().toLocaleString()
};
commonIngredientGroups.push(group);
localStorage.setItem('commonIngredientGroups', JSON.stringify(commonIngredientGroups));
alert('常用食材组合保存成功!');
}
});
// 管理常用食材组合(加载/删除)
manageGroupBtn.addEventListener('click', () => {
if (commonIngredientGroups.length === 0) {
alert('暂无保存的常用食材组合!');
return;
}
groupModal.classList.add('active');
renderGroupList();
});
// 生成食谱按钮
generateBtn.addEventListener('click', async () => {
if (selectedIngredients.length === 0) {
alert('请先添加至少一种食材!');
return;
}
if (selectedSeasonings.length === 0) {
alert('请先添加至少一种调料!');
return;
}
await handleGenerateRecipe();
});
// 清空购物清单
clearShoppingBtn.addEventListener('click', () => {
shoppingContent.innerHTML = '';
shoppingList.classList.remove('active');
localStorage.removeItem('shoppingList');
});
// 导出购物清单
const exportShoppingBtn = document.getElementById('exportShoppingBtn');
exportShoppingBtn.addEventListener('click', () => {
exportShoppingList();
});
// 打开生成历史模态窗口
historyCard.addEventListener('click', () => {
historyModal.classList.add('active');
renderHistory();
});
// 关闭生成历史模态窗口
closeHistoryModal.addEventListener('click', () => {
historyModal.classList.remove('active');
});
cancelHistoryModal.addEventListener('click', () => {
historyModal.classList.remove('active');
});
// 点击模态窗口背景关闭
historyModal.addEventListener('click', (e) => {
if (e.target === historyModal) {
historyModal.classList.remove('active');
}
});
// 一键清空历史记录
clearHistoryBtn.addEventListener('click', () => {
if (historyRecipes.length === 0) {
alert('暂无历史记录!');
return;
}
if (confirm(`确定要清空所有历史记录吗?\n\n共 ${historyRecipes.length} 条记录将被永久删除,此操作不可恢复!`)) {
historyRecipes = [];
localStorage.setItem('historyRecipes', JSON.stringify(historyRecipes));
renderHistory();
updateHistoryCount();
alert('历史记录已清空!');
}
});
// 打开我的收藏模态窗口
collectCard.addEventListener('click', () => {
collectModal.classList.add('active');
renderCollect();
});
// 关闭我的收藏模态窗口
closeCollectModal.addEventListener('click', () => {
collectModal.classList.remove('active');
});
cancelCollectModal.addEventListener('click', () => {
collectModal.classList.remove('active');
});
// 点击模态窗口背景关闭
collectModal.addEventListener('click', (e) => {
if (e.target === collectModal) {
collectModal.classList.remove('active');
}
});
// 一键清空收藏
clearCollectBtn.addEventListener('click', () => {
if (collectRecipes.length === 0) {
alert('暂无收藏记录!');
return;
}
if (confirm(`确定要清空所有收藏吗?\n\n共 ${collectRecipes.length} 条收藏将被永久删除,此操作不可恢复!`)) {
collectRecipes = [];
localStorage.setItem('collectRecipes', JSON.stringify(collectRecipes));
renderCollect();
updateCollectCount();
alert('收藏已清空!');
}
});
// 打开常用组合管理模态窗口(通过加载按钮)
// 关闭常用组合管理模态窗口
closeGroupModal.addEventListener('click', () => {
groupModal.classList.remove('active');
});
cancelGroupModal.addEventListener('click', () => {
groupModal.classList.remove('active');
});
// 一键删除常用组合
const bulkDeleteGroupBtn = document.getElementById('bulkDeleteGroupBtn');
bulkDeleteGroupBtn.addEventListener('click', () => {
const checkboxes = document.querySelectorAll('.group-checkbox:checked');
if (checkboxes.length === 0) {
alert('请先选择要删除的常用组合!');
return;
}
if (confirm(`确定要删除选中的 ${checkboxes.length} 个常用组合吗?此操作不可恢复!`)) {
const indicesToDelete = Array.from(checkboxes)
.map(cb => parseInt(cb.dataset.index))
.sort((a, b) => b - a);
indicesToDelete.forEach(index => {
commonIngredientGroups.splice(index, 1);
});
localStorage.setItem('commonIngredientGroups', JSON.stringify(commonIngredientGroups));
renderGroupList();
alert(`已成功删除 ${checkboxes.length} 个常用组合!`);
}
});
// 点击模态窗口背景关闭
groupModal.addEventListener('click', (e) => {
if (e.target === groupModal) {
groupModal.classList.remove('active');
}
});
// 星级评分
const stars = starRating.querySelectorAll('.star');
stars.forEach((star, index) => {
star.addEventListener('click', () => {
starScore = index + 1;
stars.forEach((s, i) => {
if (i < starScore) {
s.classList.add('active');
} else {
s.classList.remove('active');
}
});
});
});
// 取消评价
cancelEvaluate.addEventListener('click', () => {
closeEvaluateModal();
});
// 确认评价
confirmEvaluate.addEventListener('click', () => {
const comment = commentInput.value.trim();
tryRecipes[currentRecipeId] = {
score: starScore,
comment: comment
};
localStorage.setItem('tryRecipes', JSON.stringify(tryRecipes));
closeEvaluateModal();
renderHistory();
renderCollect();
if (currentDisplayedRecipes.length > 0) {
renderRecipeList(currentDisplayedRecipes);
}
const detailModal = document.getElementById('recipeDetailModal');
if (detailModal.classList.contains('active')) {
let targetRecipe = null;
const historyItem = historyRecipes.find(h => h.id === currentRecipeId);
if (historyItem) targetRecipe = historyItem.recipe;
if (!targetRecipe) {
targetRecipe = collectRecipes.find(r => r.id === currentRecipeId);
}
if (!targetRecipe) {
targetRecipe = currentDisplayedRecipes.find(r => r.id === currentRecipeId);
}
if (targetRecipe) {
showRecipeDetail(targetRecipe);
}
}
});
// 点击空白处关闭弹窗
window.addEventListener('click', (e) => {
if (e.target === evaluateModal) {
closeEvaluateModal();
}
});
// 关闭菜谱详情弹窗
closeRecipeDetailModal.addEventListener('click', () => {
recipeDetailModal.classList.remove('active');
});
cancelRecipeDetailModal.addEventListener('click', () => {
recipeDetailModal.classList.remove('active');
});
// 点击模态窗口背景关闭
recipeDetailModal.addEventListener('click', (e) => {
if (e.target === recipeDetailModal) {
recipeDetailModal.classList.remove('active');
}
});
closeShoppingModal.addEventListener('click', () => {
shoppingModal.classList.remove('active');
});
cancelShoppingModal.addEventListener('click', () => {
shoppingModal.classList.remove('active');
});
shoppingModal.addEventListener('click', (e) => {
if (e.target === shoppingModal) {
shoppingModal.classList.remove('active');
}
});
clearShoppingBtn.addEventListener('click', () => {
if(confirm('确定要清空购物清单吗?')) {
shoppingContent.innerHTML = '<div class="empty-tip" style="margin-top:20px;">购物清单已清空</div>';
localStorage.removeItem('shoppingList');
}
});
exportShoppingBtn.addEventListener('click', () => {
exportShoppingList();
});
}
// ========== 食材筛选相关 ==========
/**
* 按分类筛选食材
* @param {string} category - 食材分类
*/
function filterIngredientsByCategory(category) {
ingredientItems.forEach(item => {
if (category === 'all' || item.dataset.category === category) {
item.style.display = 'inline-block';
} else {
item.style.display = 'none';
}
});
}
/**
* 按子分类筛选食材
* @param {string} category - 主分类
* @param {string} subcategory - 子分类
*/
function filterIngredientsBySubcategory(category, subcategory) {
ingredientItems.forEach(item => {
if (subcategory === 'all') {
if (item.dataset.category === category) {
item.style.display = 'inline-block';
} else {
item.style.display = 'none';
}
} else {
if (item.dataset.category === category && item.dataset.subcategory === subcategory) {
item.style.display = 'inline-block';
} else {
item.style.display = 'none';
}
}
});
}
/**
* 按搜索关键词筛选食材
* @param {string} keyword - 搜索关键词
*/
function filterIngredientsBySearch(keyword) {
if (!keyword) {
const activeCategory = document.querySelector('.category-tab[data-type="ingredient"].active')?.dataset.category || 'all';
const activeSubcategory = document.querySelector('.subcategory-tab.active[data-type="ingredient"]')?.dataset.subcategory;
if (activeSubcategory && activeCategory !== 'all') {
filterIngredientsBySubcategory(activeCategory, activeSubcategory);
} else {
filterIngredientsByCategory(activeCategory);
}
return;
}
ingredientItems.forEach(item => {
const text = item.textContent.trim().toLowerCase();
if (text.includes(keyword)) {
item.style.display = 'inline-block';
} else {
item.style.display = 'none';
}
});
}
/**
* 按分类筛选调料
* @param {string} category - 调料分类
*/
function filterSeasoningsByCategory(category) {
seasoningItems.forEach(item => {
if (category === 'all' || item.dataset.category === category) {
item.style.display = 'inline-block';
} else {
item.style.display = 'none';
}
});
}
/**
* 按搜索关键词筛选调料
* @param {string} keyword - 搜索关键词
*/
function filterSeasoningsBySearch(keyword) {
if (!keyword) {
const activeCategory = document.querySelector('.category-tab[data-type="seasoning"].active')?.dataset.category || 'all';
filterSeasoningsByCategory(activeCategory);
return;
}
seasoningItems.forEach(item => {
const text = item.textContent.trim().toLowerCase();
if (text.includes(keyword)) {
item.style.display = 'inline-block';
} else {
item.style.display = 'none';
}
});
}
/**
* 渲染已选食材到界面
*/
function renderSelectedIngredients() {
selectedIngredientsEl.innerHTML = '';
if (selectedIngredients.length === 0) {
selectedIngredientsEl.innerHTML = '<span style="color:#999;font-size:14px">没有你需要的食材吗?那就在上方的自定义添加栏那里添加吧!</span>';
if (selectedSeasonings.length === 0 && editingGroupIndex >= 0) {
editingGroupIndex = -1;
updateSaveButtonText();
}
checkGenerateButton();
updateSaveButtonState();
return;
}
selectedIngredients.forEach((ingredient, index) => {
const item = document.createElement('div');
item.className = 'selected-item';
item.innerHTML = `
<span>${ingredient.name}</span>
<input type="text" class="quantity-input" placeholder="如:200g" value="${ingredient.quantity || ''}" data-index="${index}">
<span class="close-icon" data-ingredient="${ingredient.name}">×</span>
`;
selectedIngredientsEl.appendChild(item);
const quantityInput = item.querySelector('.quantity-input');
quantityInput.addEventListener('input', (e) => {
const idx = parseInt(e.target.dataset.index);
selectedIngredients[idx].quantity = e.target.value.trim();
});
item.querySelector('.close-icon').addEventListener('click', (e) => {
const delIngredient = e.target.dataset.ingredient;
selectedIngredients = selectedIngredients.filter(i => i.name !== delIngredient);
ingredientItems.forEach(i => {
if (i.textContent.trim() === delIngredient) {
i.classList.remove('selected');
}
});
renderSelectedIngredients();
updateIngredientCount();
});
});
checkGenerateButton();
updateIngredientCount();
updateSaveButtonState();
}
/**
* 渲染已选调料到界面
*/
function renderSelectedSeasonings() {
selectedSeasoningsEl.innerHTML = '';
if (selectedSeasonings.length === 0) {
selectedSeasoningsEl.innerHTML = '<span style="color:#999;font-size:14px">没有你需要的调料吗?那就在上方的自定义添加栏那里添加吧!</span>';
if (selectedIngredients.length === 0 && editingGroupIndex >= 0) {
editingGroupIndex = -1;
updateSaveButtonText();
}
updateSaveButtonState();
return;
}
selectedSeasonings.forEach(seasoning => {
const item = document.createElement('div');
item.className = 'selected-item';
item.innerHTML = `
<span>${seasoning}</span>
<span class="close-icon" data-seasoning="${seasoning}">×</span>
`;
selectedSeasoningsEl.appendChild(item);
item.querySelector('.close-icon').addEventListener('click', (e) => {
const delSeasoning = e.target.dataset.seasoning;
selectedSeasonings = selectedSeasonings.filter(i => i !== delSeasoning);
seasoningItems.forEach(i => {
if (i.textContent.trim() === delSeasoning) {
i.classList.remove('selected');
}
});
renderSelectedSeasonings();
updateSeasoningCount();
});
});
updateSeasoningCount();
updateSaveButtonState();
}
/**
* 检查生成按钮状态
*/
function checkGenerateButton() {
generateBtn.disabled = false;
}
/**
* 更新食材卡片计数显示
*/
function updateIngredientCount() {
ingredientCount.textContent = `已选 ${selectedIngredients.length} 种`;
}
/**
* 更新调料卡片计数显示
*/
function updateSeasoningCount() {
seasoningCount.textContent = `已选 ${selectedSeasonings.length} 种`;
}
/**
* 更新模态窗口按钮文本(根据流程模式)
*/
function updateModalButtons() {
if (isGeneratingFlow) {
confirmIngredientModal.textContent = '下一步';
confirmSeasoningModal.textContent = '生成菜谱';
cancelSeasoningModal.textContent = '上一步';
} else if (isEditingGroupFlow) {
confirmIngredientModal.textContent = '下一步';
confirmSeasoningModal.textContent = '保存';
cancelSeasoningModal.textContent = '上一步';
} else {
confirmIngredientModal.textContent = '确认';
confirmSeasoningModal.textContent = '确认';
cancelSeasoningModal.textContent = '取消';
}
}
/**
* 更新历史卡片计数显示
*/
function updateHistoryCount() {
historyCountDisplay.textContent = `共 ${historyRecipes.length} 条`;
}
/**
* 更新收藏卡片计数显示
*/
function updateCollectCount() {
collectCountDisplay.textContent = `共 ${collectRecipes.length} 条`;
}
/**
* 更新保存常用组合按钮状态
*/
function updateSaveButtonState() {
if (selectedIngredients.length > 0 && selectedSeasonings.length > 0) {
saveGroupBtn.disabled = false;
} else {
saveGroupBtn.disabled = true;
}
}
/**
* 更新保存按钮文本(根据编辑模式)
*/
function updateSaveButtonText() {
if (editingGroupIndex >= 0) {
saveGroupBtn.innerHTML = '<i class="fas fa-edit"></i> 更新常用组合';
} else {
saveGroupBtn.innerHTML = '<i class="fas fa-save"></i> 保存常用组合';
}
}
/**
* 设置全选/反选逻辑
* @param {string} itemCheckboxSelector - 单项复选框选择器
* @param {string} selectAllCheckboxId - 全选复选框ID
*/
function setupSelectAllLogic(itemCheckboxSelector, selectAllCheckboxId) {
const selectAllCheckbox = document.getElementById(selectAllCheckboxId);
if (!selectAllCheckbox) return;
const itemCheckboxes = document.querySelectorAll(itemCheckboxSelector);
selectAllCheckbox.addEventListener('change', (e) => {