-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathSearchAggregation.vue
More file actions
1985 lines (1745 loc) · 60.9 KB
/
SearchAggregation.vue
File metadata and controls
1985 lines (1745 loc) · 60.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<template>
<div class="search-aggregation">
<!-- 顶部Header已移至全局Header组件 -->
<!-- 主要内容区域 -->
<div class="search-content">
<!-- 最近搜索记录(仅在搜索前显示,有记录时) -->
<div v-if="!hasSearched && recentSearches.length > 0" class="recent-search-floating">
<div class="recent-search-section">
<div class="section-header">
<h3 class="section-title">
<icon-history class="title-icon"/>
最近搜索记录
</h3>
<a-button type="text" size="small" class="refresh-btn" @click="clearRecentSearches">
<template #icon>
<icon-delete/>
</template>
清空
</a-button>
</div>
<div class="recent-search-tags">
<a-tag
v-for="tag in recentSearches"
:key="tag"
class="recent-tag"
@click="searchRecentTag(tag)"
>
{{ tag }}
</a-tag>
</div>
</div>
</div>
<!-- 搜索前的状态:建议+热门 -->
<div v-if="!hasSearched" class="search-home">
<!-- 猜你想搜(有输入草稿时显示) -->
<div v-if="suggestions.length > 0" class="search-suggestions">
<div class="section-header">
<h3 class="section-title">
<icon-bulb class="title-icon"/>
猜你想搜
</h3>
</div>
<div class="suggestions-tags">
<a-tag
v-for="suggestion in suggestions"
:key="suggestion"
class="suggestion-tag"
@click="searchSuggestion(suggestion)"
>
{{ suggestion }}
</a-tag>
</div>
</div>
<!-- 热门搜索 -->
<div class="hot-search-section">
<div class="section-header">
<h3 class="section-title">
<icon-fire class="title-icon"/>
热门搜索
</h3>
<a-button
type="text"
size="small"
@click="randomizeHotSearchTags"
class="refresh-btn"
>
<template #icon>
<icon-refresh/>
</template>
换一批
</a-button>
</div>
<div class="hot-search-tags">
<a-tag
v-for="tag in hotSearchTags"
:key="tag"
class="hot-tag"
@click="searchHotTag(tag)"
>
{{ tag }}
</a-tag>
</div>
</div>
</div>
<!-- 搜索结果页面 -->
<div v-if="hasSearched" class="search-results">
<div class="results-layout">
<!-- 左侧源分组 -->
<div class="sources-sidebar">
<div class="sources-header">
<h4>搜索源</h4>
<span class="sources-count">({{ searchStats.completed }}/{{ searchStats.total }})</span>
<span class="sources-result-tag" v-if="searchStats.withData > 0">{{ searchStats.withData }}</span>
<span class="sources-time-tag" v-if="searchTotalTime > 0">{{ searchTotalTime.toFixed(2) }}s</span>
</div>
<div class="sources-list">
<div
v-for="source in sourcesWithResults"
:key="source.key"
class="source-item"
:class="{ active: activeSource === source.key }"
@click="selectSource(source.key)"
>
<div class="source-info">
<span class="source-name">{{ source.name }}</span>
<span class="source-count" v-if="searchResults[source.key]">
({{ searchResults[source.key].length }})
</span>
</div>
<div class="source-status">
<a-spin v-if="loadingStates[source.key]" :size="14"/>
<icon-check-circle
v-else-if="searchResults[source.key]"
class="status-success"
/>
<icon-close-circle
v-else-if="errorStates[source.key]"
class="status-error"
/>
</div>
</div>
</div>
</div>
<!-- 右侧搜索结果 -->
<div class="results-content">
<div v-if="activeSource && searchResults[activeSource]" class="results-list">
<div class="results-header">
<h4>{{ getSourceName(activeSource) }} 搜索结果</h4>
<span class="results-count">
共 {{ searchResults[activeSource].length }} 条结果
</span>
</div>
<a-scrollbar
ref="scrollbarRef"
@scroll="handleScroll"
class="search-scroll-container"
:style="'height:' + scrollAreaHeight + 'px; overflow: auto;'"
>
<!-- 搜索结果网格 -->
<a-grid
v-if="searchResults[activeSource] && searchResults[activeSource].length > 0"
:cols="{ xs: 2, sm: 3, md: 4, lg: 5, xl: 6, xxl: 8 }"
:rowGap="16"
:colGap="12"
class="video-grid"
>
<a-grid-item
v-for="(video, index) in displayedResults"
:key="video.vod_id || index"
class="video-card-item"
>
<div class="video-card" @click="handleVideoClick(video)">
<div class="video-poster">
<!-- 优先显示vod_pic图片,如果有值的话 -->
<img
v-if="video.vod_pic && video.vod_pic.trim() !== ''"
class="video-poster-img"
:src="video.vod_pic"
:alt="video.vod_name"
@error="handleImageError"
/>
<!-- 文件夹图标 (当vod_pic为空且是文件夹时) -->
<div v-else-if="isFolder(video)" class="folder-icon-container">
<i class="iconfont icon-wenjianjia folder-icon"></i>
</div>
<!-- 文件类型图标 (当vod_pic为空且是目录模式下的非文件夹项目时) -->
<div v-else-if="isDirectoryFile(video)" class="file-icon-container">
<svg style="width:30%">
<use :href="`#${getFileTypeIcon(video.vod_name)}`"></use>
</svg>
</div>
<!-- 默认图片 (当vod_pic为空且没有特殊标识时) -->
<img
v-else
class="video-poster-img"
:src="video.vod_pic || '/default-poster.svg'"
:alt="video.vod_name"
@error="handleImageError"
/>
<!-- Action标识 -->
<div v-if="video.vod_tag === 'action'" class="action-badge">
<icon-thunderbolt />
</div>
<!-- 播放按钮覆盖层 -->
<div class="play-overlay">
<icon-play-arrow-fill />
</div>
<!-- vod_remarks 浮层 -->
<div v-if="video.vod_remarks" class="video-remarks-overlay" v-html="video.vod_remarks">
</div>
</div>
<div class="video-info">
<h3 class="video-title" :title="video.vod_name">{{ video.vod_name }}</h3>
<div class="video-meta">
<span v-if="video.vod_year" class="video-year">{{ video.vod_year }}</span>
<span v-if="video.vod_area" class="video-area">{{ video.vod_area }}</span>
</div>
</div>
</div>
</a-grid-item>
</a-grid>
<!-- 加载更多 -->
<div v-if="loadingMore" class="loading-container">
<a-spin />
<div class="loading-text">加载更多...</div>
</div>
<!-- 没有更多数据提示 -->
<div v-else-if="!hasMoreData && searchResults[activeSource] && searchResults[activeSource].length > 0" class="no-more-data">
没有更多数据了
</div>
<!-- 底部间距 -->
<div class="bottom-spacer"></div>
</a-scrollbar>
</div>
<!-- 加载状态 -->
<div v-else-if="activeSource && loadingStates[activeSource]" class="loading-state">
<a-spin :size="32"/>
<p>正在搜索 {{ getSourceName(activeSource) }}...</p>
</div>
<!-- 错误状态 -->
<div v-else-if="activeSource && errorStates[activeSource]" class="error-state">
<icon-exclamation-circle class="error-icon"/>
<p>{{ getSourceName(activeSource) }} 搜索失败</p>
<a-button @click="retrySearch(activeSource)">重试</a-button>
</div>
<!-- 空状态 -->
<div v-else-if="activeSource" class="empty-state">
<icon-empty class="empty-icon"/>
<p>{{ getSourceName(activeSource) }} 暂无搜索结果</p>
</div>
</div>
<!-- ActionRenderer组件 -->
<ActionRenderer
v-if="showActionRenderer"
:action-data="currentActionData"
@close="handleActionClose"
/>
</div>
</div>
</div>
<!-- 搜索设置弹窗 -->
<SearchSettingsModal
v-model:visible="showSearchSettings"
@confirm="onSearchSettingsConfirm"
/>
</div>
</template>
<script>
import { defineComponent, ref, computed, onMounted, onUnmounted, onBeforeUnmount, watch, nextTick } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { Message } from '@arco-design/web-vue';
import {
IconHistory,
IconBulb,
IconFire,
IconRefresh,
IconCheckCircle,
IconCloseCircle,
IconExclamationCircle,
IconEmpty,
IconDelete
} from '@arco-design/web-vue/es/icon';
import SearchSettingsModal from '@/components/SearchSettingsModal.vue';
import ActionRenderer from '@/components/actions/ActionRenderer.vue';
import { getFileTypeIcon, isFolder, isDirectoryFile } from '@/utils/fileTypeUtils';
import { usePaginationStore } from '@/stores/paginationStore';
import { usePageStateStore } from '@/stores/pageStateStore';
import { useVisitedStore } from '@/stores/visitedStore';
import siteService from '@/api/services/site';
import videoService from '@/api/services/video';
export default defineComponent({
name: 'SearchAggregation',
components: {
SearchSettingsModal,
ActionRenderer,
IconHistory,
IconBulb,
IconFire,
IconRefresh,
IconCheckCircle,
IconCloseCircle,
IconExclamationCircle,
IconEmpty,
IconDelete
},
setup() {
const route = useRoute();
const router = useRouter();
// Stores
const paginationStore = usePaginationStore();
const pageStateStore = usePageStateStore();
const visitedStore = useVisitedStore();
// 搜索相关状态
const searchKeyword = ref('');
const hasSearched = ref(false);
const showSearchSettings = ref(false);
const recentSearches = ref([]);
// 搜索源和结果
const searchSources = ref([]);
const searchResults = ref({});
const loadingStates = ref({});
const errorStates = ref({});
const activeSource = ref('');
// 滚动翻页相关
const scrollbarRef = ref(null);
const scrollAreaHeight = ref(600);
const displayedCount = ref(20); // 当前显示的结果数量
const pageSize = ref(20); // 每次加载的数量
const loadingMore = ref(false);
// 分页状态管理
const currentPages = ref({}); // 每个源的当前页码
const hasMorePages = ref({}); // 每个源是否还有更多页面
// 搜索完成时间戳记录
const searchCompletedTimes = ref({}); // 记录每个源完成搜索的时间戳
// 搜索耗时记录
const searchStartTime = ref(0); // 搜索开始时间戳
const searchTotalTime = ref(0); // 搜索总耗时(秒)
// ActionRenderer相关
const showActionRenderer = ref(false);
const currentActionData = ref(null);
// 所有热门搜索标签
const allHotSearchTags = [
'最新电影', '热门电视剧', '经典动漫', '综艺节目', '纪录片',
'科幻大片', '动作电影', '喜剧片', '爱情剧', '悬疑剧',
'国产剧', '韩剧', '日剧', '美剧', '港剧',
'2024新片', '高分电影', '经典老片', '院线大片', '网络电影',
'武侠片', '古装剧', '现代剧', '都市剧', '农村剧',
'青春剧', '校园剧', '职场剧', '医疗剧', '律政剧'
];
// 当前显示的热门搜索标签
const hotSearchTags = ref([]);
// 搜索建议
const suggestions = ref([]);
// 计算属性
const displayedResults = computed(() => {
if (!activeSource.value || !searchResults.value[activeSource.value]) {
return [];
}
return searchResults.value[activeSource.value].slice(0, displayedCount.value);
});
const hasMoreData = computed(() => {
if (!activeSource.value) {
return false;
}
// 检查是否还有更多页面可以加载,或者当前显示的数量少于已加载的数据
const hasMoreFromServer = hasMorePages.value[activeSource.value] || false;
const hasMoreFromLocal = searchResults.value[activeSource.value] &&
displayedCount.value < searchResults.value[activeSource.value].length;
return hasMoreFromServer || hasMoreFromLocal;
});
// 过滤有结果的搜索源,并按搜索完成时间排序
const sourcesWithResults = computed(() => {
const sourcesWithData = searchSources.value.filter(source => {
const results = searchResults.value[source.key];
// 严格只显示有结果的源
return results && results.length > 0;
});
// 按搜索完成时间排序,先完成的排在前面
const sortedSources = sourcesWithData.sort((a, b) => {
const timeA = searchCompletedTimes.value[a.key] || 0;
const timeB = searchCompletedTimes.value[b.key] || 0;
return timeA - timeB; // 升序排列,时间戳小的(先完成的)排在前面
});
console.log('搜索源排序结果:', sortedSources.map(s => ({
name: s.name,
key: s.key,
completedTime: searchCompletedTimes.value[s.key]
})));
return sortedSources;
});
// 搜索统计计算属性
const searchStats = computed(() => {
const totalSources = searchSources.value.length;
let completedSources = 0;
let sourcesWithData = 0;
let sourcesWithoutData = 0;
// 计算已完成搜索的源数量(包括成功和失败的)
searchSources.value.forEach(source => {
const isLoading = loadingStates.value[source.key];
const hasResults = searchResults.value[source.key] !== undefined;
const hasError = errorStates.value[source.key] !== undefined;
const resultCount = searchResults.value[source.key]?.length || 0;
// 如果不在加载中,且有结果或有错误,则认为已完成
if (!isLoading && (hasResults || hasError)) {
completedSources++;
// 区分有数据和无数据的源
if (resultCount > 0) {
sourcesWithData++;
} else {
sourcesWithoutData++;
}
}
});
return {
completed: completedSources,
total: totalSources,
withData: sourcesWithData,
withoutData: sourcesWithoutData
};
});
// 方法
const loadSearchSources = () => {
try {
const allSites = siteService.getAllSites();
// 获取用户配置的搜索源
const searchSettings = getSearchSettings();
// 过滤出可搜索的源
const availableSources = allSites.filter(site =>
site.searchable && site.searchable !== 0
);
// 根据用户设置过滤
searchSources.value = availableSources.filter(site =>
searchSettings.selectedSources.includes(site.key)
);
// 如果没有配置,默认选择所有可搜索的源
if (searchSources.value.length === 0) {
searchSources.value = availableSources;
}
} catch (error) {
console.error('加载搜索源失败:', error);
Message.error('加载搜索源失败');
}
};
const getSearchSettings = () => {
try {
const settings = localStorage.getItem('searchAggregationSettings');
if (settings) {
const parsed = JSON.parse(settings);
// 验证设置格式
if (parsed && Array.isArray(parsed.selectedSources)) {
console.log('已加载搜索设置:', parsed);
return parsed;
} else {
console.warn('搜索设置格式无效,使用默认配置');
}
} else {
console.log('未找到搜索设置,使用默认配置');
}
} catch (error) {
console.error('获取搜索设置失败:', error);
}
return { selectedSources: [] };
};
const performSearch = async (keyword) => {
console.log('🔍 [performSearch] 方法被调用:', {
keyword,
currentKeyword: searchKeyword.value,
hasSearched: hasSearched.value,
currentResults: Object.keys(searchResults.value).length
});
if (!keyword || !keyword.trim()) {
Message.warning('请输入搜索关键词');
return;
}
const trimmedKeyword = keyword.trim();
console.log('🔍 [performSearch] 开始执行搜索:', { trimmedKeyword });
// 记录搜索开始时间
searchStartTime.value = Date.now();
searchKeyword.value = trimmedKeyword;
hasSearched.value = true;
// 重置状态
console.log('🔍 [performSearch] 重置搜索状态...');
searchResults.value = {};
loadingStates.value = {};
errorStates.value = {};
currentPages.value = {};
hasMorePages.value = {};
searchCompletedTimes.value = {}; // 清空搜索完成时间戳
searchTotalTime.value = 0; // 重置搜索总耗时
displayedCount.value = pageSize.value;
console.log('🔍 [performSearch] 状态重置完成:', {
searchResults: Object.keys(searchResults.value).length,
loadingStates: Object.keys(loadingStates.value).length,
hasSearched: hasSearched.value
});
// 重置活跃源,让自动激活逻辑来处理
activeSource.value = '';
// 并行搜索所有源
const searchPromises = searchSources.value.map(source =>
searchSource(source, keyword.trim())
);
await Promise.allSettled(searchPromises);
// 计算搜索总耗时
const searchEndTime = Date.now();
searchTotalTime.value = (searchEndTime - searchStartTime.value) / 1000; // 转换为秒
console.log('🔍 [performSearch] 搜索完成,总耗时:', searchTotalTime.value.toFixed(2) + 's');
// 记录最近搜索
try {
const HISTORY_KEY = 'drplayer_search_history';
const stored = localStorage.getItem(HISTORY_KEY);
let history = [];
try { history = stored ? JSON.parse(stored) : []; } catch { history = []; }
const k = searchKeyword.value;
// 过滤空字符串和无效值
if (k && k.trim()) {
const idx = history.findIndex(item => item === k);
if (idx !== -1) history.splice(idx, 1);
history.unshift(k);
// 过滤历史记录中的空字符串
history = history.filter(item => item && item.trim());
if (history.length > 10) history = history.slice(0, 10);
localStorage.setItem(HISTORY_KEY, JSON.stringify(history));
// console.log('保存搜索历史记录:',history);
// 直接更新最近搜索记录
recentSearches.value = [...history];
}
} catch (e) {
console.error('保存搜索历史失败:', e);
}
};
const searchSource = async (source, keyword, page = 1) => {
loadingStates.value[source.key] = true;
try {
const searchData = await videoService.searchVideo(source.key, {
keyword: keyword,
page: page,
extend: source.ext,
apiUrl: source.api
});
const newVideos = searchData.videos || [];
if (page === 1) {
// 第一页,直接设置结果
searchResults.value[source.key] = newVideos;
currentPages.value[source.key] = 1;
} else {
// 后续页面,追加到现有结果
if (!searchResults.value[source.key]) {
searchResults.value[source.key] = [];
}
// 过滤重复数据
const existingIds = new Set(searchResults.value[source.key].map(v => v.vod_id));
const uniqueNewVideos = newVideos.filter(video =>
!existingIds.has(video.vod_id) &&
video.vod_id !== 'no_data' &&
video.vod_name !== 'no_data'
);
searchResults.value[source.key] = [...searchResults.value[source.key], ...uniqueNewVideos];
currentPages.value[source.key] = page;
}
// 更新分页状态
hasMorePages.value[source.key] = searchData.pagination?.hasNext !== false;
// 记录搜索完成时间戳(仅在第一页时记录)
if (page === 1) {
searchCompletedTimes.value[source.key] = Date.now();
console.log(`搜索源 ${source.name} 完成搜索,时间戳: ${searchCompletedTimes.value[source.key]}`);
// 搜索完成后实时保存状态
debouncedSavePageState();
console.log('🔄 [状态保存] 搜索完成,触发状态保存:', source.name);
}
delete errorStates.value[source.key];
} catch (error) {
console.error(`搜索源 ${source.name} 失败:`, error);
errorStates.value[source.key] = error.message || '搜索失败';
if (page === 1) {
searchResults.value[source.key] = [];
currentPages.value[source.key] = 1;
hasMorePages.value[source.key] = false;
}
} finally {
loadingStates.value[source.key] = false;
}
};
const selectSource = (sourceKey) => {
activeSource.value = sourceKey;
displayedCount.value = pageSize.value; // 重置显示数量
updateScrollAreaHeight();
updateGlobalStats();
// 切换搜索源后实时保存状态
debouncedSavePageState();
console.log('🔄 [状态保存] 切换搜索源,触发状态保存:', sourceKey);
};
// 滚动位置保存的防抖定时器
let scrollSaveTimer = null;
// 滚动事件处理
const handleScroll = (e) => {
// 获取真正的滚动容器(arco-scrollbar内部容器)
const rawTarget = e?.target || e?.srcElement;
const container = rawTarget?.closest ? rawTarget.closest('.arco-scrollbar-container') : rawTarget;
if (!container) return;
const scrollHeight = container.scrollHeight - container.clientHeight;
const scrollTop = container.scrollTop;
// 实时更新滚动位置
scrollPosition.value = scrollTop;
// 防抖保存滚动位置(使用更长的延迟避免过于频繁)
if (scrollSaveTimer) {
clearTimeout(scrollSaveTimer);
}
scrollSaveTimer = setTimeout(() => {
if (hasSearched.value && searchKeyword.value) {
debouncedSavePageState();
console.log('🔄 [状态保存] 滚动位置变化,触发状态保存:', scrollTop);
}
}, 1000); // 1秒防抖延迟,避免滚动时过于频繁保存
// 当滚动到距离底部50px以内时触发加载
if (scrollHeight - scrollTop < 50 && hasMoreData.value && !loadingMore.value) {
loadMore();
}
};
// 加载更多数据
const loadMore = async () => {
if (!hasMoreData.value || loadingMore.value || !activeSource.value) return;
loadingMore.value = true;
try {
// 检查是否需要从服务器加载更多数据
const currentResults = searchResults.value[activeSource.value] || [];
const needMoreFromServer = hasMorePages.value[activeSource.value] &&
displayedCount.value >= currentResults.length;
if (needMoreFromServer) {
// 从服务器加载下一页
const currentPage = currentPages.value[activeSource.value] || 1;
const nextPage = currentPage + 1;
const activeSourceObj = searchSources.value.find(s => s.key === activeSource.value);
if (activeSourceObj && searchKeyword.value) {
await searchSource(activeSourceObj, searchKeyword.value, nextPage);
}
}
// 增加显示数量
displayedCount.value += pageSize.value;
updateGlobalStats();
// 加载更多后实时保存状态
debouncedSavePageState();
console.log('🔄 [状态保存] 加载更多数据,触发状态保存');
} catch (error) {
console.error('加载更多数据失败:', error);
Message.error('加载更多数据失败');
} finally {
loadingMore.value = false;
}
};
// 动态计算滚动区域高度
const updateScrollAreaHeight = () => {
// 计算可用高度:总高度减去头部和其他固定元素
const availableHeight = window.innerHeight - 112; // 减去导航栏等固定高度
scrollAreaHeight.value = Math.max(availableHeight - 120, 400); // 减去results-header等,最小400px
};
// 新的视频点击处理方法,支持action类型
const handleVideoClick = (video) => {
if (video && video.vod_id) {
// 检查是否为action类型
if (video.vod_tag === 'action') {
try {
// 尝试解析vod_id中的JSON字符串获取action配置
const actionConfig = JSON.parse(video.vod_id);
console.log('SearchAggregation解析action配置:', actionConfig);
// 传递解析后的action配置给ActionRenderer
currentActionData.value = actionConfig;
showActionRenderer.value = true;
return;
} catch (error) {
console.log('SearchAggregation vod_id不是JSON格式,作为普通文本处理:', video.vod_id);
// 如果解析失败,说明vod_id是普通文本,显示Toast提示
Message.info({
content: video.vod_id,
duration: 3000,
closable: true
});
return;
}
}
// 记录最后点击的视频
visitedStore.setLastClicked(video.vod_id, video.name);
// 获取当前源信息
const currentSource = searchSources.value.find(s => s.key === activeSource.value);
console.log('🎬 [搜索聚合] 点击视频跳转详情页:', {
videoName: video.name,
videoId: video.vod_id,
activeSource: activeSource.value,
currentSource: currentSource,
sourceInfo: {
key: currentSource?.key,
name: currentSource?.name,
api: currentSource?.api,
ext: currentSource?.ext
}
});
// 跳转到视频详情页面
if (currentSource) {
router.push({
name: 'VideoDetail',
params: { id: video.vod_id },
query: {
name: video.name,
pic: video.pic,
year: video.year,
area: video.area,
type: video.type,
remarks: video.note,
content: video.content,
actor: video.actor,
director: video.director,
tempSiteKey: currentSource.key,
tempSiteApi: currentSource.api,
tempSiteName: currentSource.name,
tempSiteExt: currentSource.ext,
fromSpecialAction: 'true',
from: 'search-aggregation',
// 添加来源页面信息,用于返回时恢复状态
sourceRouteName: 'SearchAggregation',
sourceRouteParams: JSON.stringify({}),
sourceRouteQuery: JSON.stringify({
keyword: searchKeyword.value
}),
// 添加来源图片信息,用于详情页图片备用
sourcePic: video.pic
}
});
}
}
};
// 更新全局统计信息
const updateGlobalStats = () => {
console.log('[updateGlobalStats] 更新全局统计信息');
if (!activeSource.value || !searchResults.value[activeSource.value]) {
paginationStore.updateStats('');
return;
}
const totalResults = searchResults.value[activeSource.value].length;
const displayedResults = Math.min(displayedCount.value, totalResults);
const sourceName = getSourceName(activeSource.value);
let statsText = `搜索"${searchKeyword.value}":${sourceName} - 已显示${displayedResults}条,共${totalResults}条`;
// 检查是否还有更多数据可以加载
const hasMore = hasMoreData.value;
if (hasMore) {
statsText += ',可继续加载';
} else if (totalResults > 0) {
statsText += ',已全部加载';
}
console.log('[updateGlobalStats] <statsText>:', statsText);
paginationStore.updateStats(statsText);
};
// ActionRenderer相关方法
const handleActionClose = () => {
showActionRenderer.value = false;
currentActionData.value = null;
};
const getSourceName = (sourceKey) => {
const source = searchSources.value.find(s => s.key === sourceKey);
return source ? source.name : sourceKey;
};
const retrySearch = (sourceKey) => {
const source = searchSources.value.find(s => s.key === sourceKey);
if (source && searchKeyword.value) {
searchSource(source, searchKeyword.value);
}
};
const onSearchInput = (value) => {
if (value && value.trim()) {
// 生成搜索建议
generateSuggestions(value.trim());
} else {
suggestions.value = [];
}
};
const generateSuggestions = (keyword) => {
if (!keyword || keyword.length < 1) {
suggestions.value = [];
return;
}
// 基础建议模板
const suggestionTemplates = [
`${keyword} 电影`,
`${keyword} 电视剧`,
`${keyword} 动漫`,
`${keyword} 纪录片`,
`${keyword} 综艺`,
`最新 ${keyword}`,
`${keyword} 高清`,
`${keyword} 完整版`,
`${keyword} 免费观看`,
`${keyword} 在线播放`
];
// 热门关键词联想
const popularKeywords = [
'2024', '最新', '高清', '免费', '完整版', '在线',
'国产', '日本', '韩国', '美国', '欧美', '港台',
'爱情', '动作', '喜剧', '科幻', '悬疑', '恐怖', '战争', '历史'
];
// 根据关键词长度和内容生成不同的建议
let suggestions_list = [];
if (keyword.length === 1) {
// 单字符时提供更多类型建议
suggestions_list = [
`${keyword}开头的电影`,
`${keyword}字电视剧`,
`${keyword}相关动漫`,
`${keyword}类纪录片`
];
} else if (keyword.length <= 3) {
// 短关键词时提供基础建议
suggestions_list = suggestionTemplates.slice(0, 6);
} else {
// 长关键词时提供更精确的建议
suggestions_list = suggestionTemplates.slice(0, 4);
// 添加一些智能联想
popularKeywords.forEach(popular => {
if (keyword.toLowerCase().includes(popular.toLowerCase()) === false) {
suggestions_list.push(`${keyword} ${popular}`);
}
});
}
// 去重并限制数量
suggestions.value = [...new Set(suggestions_list)].slice(0, 8);
};
const searchHotTag = (tag) => {
router.push({
name: 'SearchAggregation',
query: { keyword: tag }
});
};
const searchSuggestion = (suggestion) => {
router.push({
name: 'SearchAggregation',
query: { keyword: suggestion }
});
};
const searchRecentTag = (tag) => {
router.push({
name: 'SearchAggregation',
query: { keyword: tag }
});
};
const onSearchSettingsConfirm = (settings) => {
// 保存搜索设置
localStorage.setItem('searchAggregationSettings', JSON.stringify(settings));
// 重新加载搜索源
loadSearchSources();
Message.success('搜索设置已保存');
};
const playVideo = (video) => {
// 跳转到视频详情页面
const currentSource = searchSources.value.find(s => s.key === activeSource.value);
if (currentSource && video.vod_id) {
router.push({
name: 'VideoDetail',
params: { id: video.vod_id },
query: {
site: currentSource.key,
api: currentSource.api,
ext: currentSource.ext,
from: 'search'
}
});
} else {
Message.warning('无法播放该视频');
}
};
const handleImageError = (event) => {
event.target.style.display = 'none';
};
// 随机化热门搜索标签
const randomizeHotSearchTags = () => {
const shuffled = [...allHotSearchTags].sort(() => 0.5 - Math.random());
hotSearchTags.value = shuffled.slice(0, 12); // 显示12个标签
};
// 最近搜索读取与清空
const loadRecentSearches = () => {
try {
const HISTORY_KEY = 'drplayer_search_history';
const stored = localStorage.getItem(HISTORY_KEY);
let history = stored ? JSON.parse(stored) : [];
if (!Array.isArray(history)) history = [];
// 过滤空字符串和无效值
recentSearches.value = history.filter(item => item && item.trim());
// 如果过滤后的数据与原数据不同,更新localStorage
if (recentSearches.value.length !== history.length) {
localStorage.setItem(HISTORY_KEY, JSON.stringify(recentSearches.value));
}
} catch {
recentSearches.value = [];
}
};
const clearRecentSearches = () => {
localStorage.removeItem('drplayer_search_history');
recentSearches.value = [];
Message.success('已清空最近搜索记录');
};
// 监听路由参数 - 监听整个query对象以确保时间戳参数变化时也能触发
watch(() => route.query, (newQuery, oldQuery) => {
const keyword = newQuery.keyword;
const oldKeyword = oldQuery?.keyword;
const isReturnFromDetail = newQuery._returnFromDetail === 'true';
const newTimestamp = newQuery._t;
const oldTimestamp = oldQuery?._t;