index.vue 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. <template>
  2. <view class="page">
  3. <!-- 搜索栏 -->
  4. <view class="search-bar">
  5. <input
  6. v-model="searchQuery"
  7. class="search-input"
  8. placeholder="搜索音频..."
  9. @confirm="handleSearch"
  10. />
  11. <button class="search-btn" @click="handleSearch">搜索</button>
  12. </view>
  13. <!-- 骨架屏加载状态 -->
  14. <scroll-view scroll-y class="results" v-if="loading" :scroll-top="scrollTop">
  15. <SkeletonList layout="search-result" :count="5" />
  16. </scroll-view>
  17. <!-- 搜索结果 -->
  18. <scroll-view scroll-y class="results" v-else-if="searchResults.length > 0" :scroll-top="scrollTop">
  19. <view class="result-list">
  20. <view
  21. v-for="item in searchResults"
  22. :key="item.id"
  23. class="result-item"
  24. @click="playAudio(item)"
  25. >
  26. <view class="result-cover" :style="{ background: getCoverGradient(item.voiceId) }">
  27. <text class="cover-icon">🎵</text>
  28. </view>
  29. <view class="result-info">
  30. <text class="result-title" v-html="highlightText(item.title, searchQuery)"></text>
  31. <text class="result-desc" v-if="item.description" v-html="highlightText(item.description.slice(0, 50) + '...', searchQuery)"></text>
  32. <text class="result-meta">{{ item.wordCount || 0 }}字</text>
  33. </view>
  34. </view>
  35. </view>
  36. </scroll-view>
  37. <!-- 无结果 -->
  38. <view v-else-if="hasSearched && searchResults.length === 0" class="no-result">
  39. <text class="no-result-icon">🔍</text>
  40. <text class="no-result-text">未找到相关音频</text>
  41. </view>
  42. <!-- 初始状态:搜索历史 + 热门推荐 -->
  43. <view v-else class="initial-state">
  44. <!-- 搜索历史 -->
  45. <view class="section" v-if="searchHistory.length > 0">
  46. <view class="section-header">
  47. <text class="section-title">搜索历史</text>
  48. <text class="clear-btn" @click="clearHistory">清空</text>
  49. </view>
  50. <view class="tag-list">
  51. <view
  52. v-for="(item, index) in searchHistory"
  53. :key="index"
  54. class="tag history-tag"
  55. @click="clickHistory(item.keyword)"
  56. >
  57. <text class="tag-text">{{ item.keyword }}</text>
  58. <text class="delete-icon" @click.stop="deleteHistoryItem(item.keyword)">×</text>
  59. </view>
  60. </view>
  61. </view>
  62. <!-- 热门推荐 -->
  63. <view class="section" v-if="hotSearches.length > 0">
  64. <view class="section-header">
  65. <text class="section-title">🔥 热门推荐</text>
  66. </view>
  67. <view class="tag-list">
  68. <view
  69. v-for="(item, index) in hotSearches"
  70. :key="item.id"
  71. class="tag hot-tag"
  72. @click="clickHotSearch(item.keyword)"
  73. >
  74. <text class="tag-rank">{{ index + 1 }}</text>
  75. <text class="tag-text">{{ item.keyword }}</text>
  76. </view>
  77. </view>
  78. </view>
  79. <!-- 空状态提示 -->
  80. <view v-if="searchHistory.length === 0 && hotSearches.length === 0" class="empty-hint">
  81. <text class="hint-text">输入关键词搜索音频</text>
  82. </view>
  83. </view>
  84. </view>
  85. </template>
  86. <script setup lang="ts">
  87. import { ref, onMounted } from 'vue';
  88. import { onLoad } from '@dcloudio/uni-app';
  89. import { useAudioStore } from '../../store/audio';
  90. import { get, post } from '../../utils/request';
  91. import type { AudioItem } from '../../types';
  92. import SkeletonList from '../../components/SkeletonList.vue';
  93. // 缓存键名
  94. const HOT_SEARCH_CACHE_KEY = 'hot_search_cache';
  95. // scroll-top 用于避免 scrollTop 错误
  96. const scrollTop = ref(0);
  97. const audioStore = useAudioStore();
  98. const searchQuery = ref('');
  99. const searchResults = ref<AudioItem[]>([]);
  100. const hasSearched = ref(false);
  101. const loading = ref(false);
  102. const searchHistory = ref<{ keyword: string }[]>([]);
  103. const hotSearches = ref<{ id: number; keyword: string; count: number }[]>([]);
  104. // 音色封面颜色映射
  105. const voiceColors: Record<string, string[]> = {
  106. cherry: ['#667eea', '#764ba2'],
  107. ethan: ['#f093fb', '#f5576c'],
  108. serena: ['#4facfe', '#00f2fe'],
  109. chelsie: ['#43e97b', '#38f9d7'],
  110. momo: ['#fa709a', '#fee140'],
  111. vivian: ['#a8edea', '#fed6e3'],
  112. moon: ['#5ee7df', '#b490ca'],
  113. maia: ['#d299c2', '#fef9d7'],
  114. kai: ['#89f7fe', '#66a6ff'],
  115. nofish: ['#cd9cf2', '#f6f3ff'],
  116. };
  117. function getCoverGradient(voiceId: string): string {
  118. const colors = voiceColors[voiceId] || ['#667eea', '#764ba2'];
  119. return `linear-gradient(135deg, ${colors[0]} 0%, ${colors[1]} 100%)`;
  120. }
  121. // 高亮搜索关键词
  122. function highlightText(text: string, keyword: string): string {
  123. if (!keyword || !text) return text;
  124. const regex = new RegExp(`(${escapeRegExp(keyword)})`, 'gi');
  125. return text.replace(regex, '<span class="highlight">$1</span>');
  126. }
  127. // 转义正则特殊字符
  128. function escapeRegExp(str: string): string {
  129. return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  130. }
  131. // 缓存热词
  132. function cacheHotSearches(hotList: { id: number; keyword: string; count: number }[]) {
  133. try {
  134. uni.setStorageSync(HOT_SEARCH_CACHE_KEY, hotList);
  135. } catch (e) {
  136. console.error('缓存热词失败:', e);
  137. }
  138. }
  139. // 读取缓存热词
  140. function getCachedHotSearches(): { id: number; keyword: string; count: number }[] {
  141. try {
  142. return uni.getStorageSync(HOT_SEARCH_CACHE_KEY) || [];
  143. } catch (e) {
  144. console.error('读取热词缓存失败:', e);
  145. return [];
  146. }
  147. }
  148. // 加载搜索历史和热门推荐
  149. async function loadSearchContext() {
  150. try {
  151. // 获取搜索历史(用户ID固定为1,用于开发阶段)
  152. const userId = 1;
  153. const [historyRes, hotRes] = await Promise.all([
  154. get<{ keyword: string }[]>('/search/history', { userId, limit: 5 }),
  155. get<{ id: number; keyword: string; count: number }[]>('/search/hot', { limit: 10 }),
  156. ]);
  157. searchHistory.value = historyRes || [];
  158. hotSearches.value = hotRes || [];
  159. // 更新热词缓存
  160. if (hotRes && hotRes.length > 0) {
  161. cacheHotSearches(hotRes);
  162. }
  163. } catch (error) {
  164. console.error('加载搜索上下文失败:', error);
  165. searchHistory.value = [];
  166. // 读取缓存热词
  167. hotSearches.value = getCachedHotSearches();
  168. }
  169. }
  170. // 点击历史标签
  171. function clickHistory(keyword: string) {
  172. searchQuery.value = keyword;
  173. handleSearch();
  174. }
  175. // 点击热搜词
  176. function clickHotSearch(keyword: string) {
  177. searchQuery.value = keyword;
  178. handleSearch();
  179. }
  180. // 删除单条历史
  181. async function deleteHistoryItem(keyword: string) {
  182. try {
  183. const userId = 1;
  184. await get('/search/history', { userId, keyword } as any);
  185. await loadSearchContext();
  186. } catch (error) {
  187. console.error('删除历史失败:', error);
  188. }
  189. }
  190. // 清空历史
  191. async function clearHistory() {
  192. try {
  193. const userId = 1;
  194. await get('/search/history/all', { userId } as any);
  195. searchHistory.value = [];
  196. } catch (error) {
  197. console.error('清空历史失败:', error);
  198. }
  199. }
  200. async function handleSearch() {
  201. if (!searchQuery.value.trim()) return;
  202. hasSearched.value = true;
  203. loading.value = true;
  204. try {
  205. // 保存搜索历史
  206. const userId = 1;
  207. await post('/search/history', { userId, keyword: searchQuery.value });
  208. const result = await get<AudioItem[]>('/search', { q: searchQuery.value });
  209. searchResults.value = result || [];
  210. // 更新热词缓存(搜索结果返回后更新)
  211. if (hotSearches.value.length > 0) {
  212. cacheHotSearches(hotSearches.value);
  213. }
  214. // 刷新历史记录
  215. await loadSearchContext();
  216. } catch (error) {
  217. console.error('搜索失败:', error);
  218. searchResults.value = [];
  219. } finally {
  220. loading.value = false;
  221. }
  222. }
  223. function playAudio(item: AudioItem) {
  224. // 搜索结果是书籍,跳转到书籍详情页(专辑页)
  225. uni.navigateTo({ url: `/pages/album/index?id=${item.id}` });
  226. }
  227. onMounted(() => {
  228. loadSearchContext();
  229. });
  230. </script>
  231. <style scoped>
  232. .page {
  233. min-height: 100vh;
  234. background: #f5f5f5;
  235. padding-top: 44rpx;
  236. }
  237. .search-bar {
  238. display: flex;
  239. gap: 16rpx;
  240. padding: 24rpx 32rpx;
  241. background: #ffffff;
  242. }
  243. .search-input {
  244. flex: 1;
  245. height: 72rpx;
  246. background: #f5f5f5;
  247. border-radius: 36rpx;
  248. padding: 0 32rpx;
  249. font-size: 28rpx;
  250. }
  251. .search-btn {
  252. width: 120rpx;
  253. height: 72rpx;
  254. background: #4f46e5;
  255. color: #ffffff;
  256. border-radius: 36rpx;
  257. font-size: 28rpx;
  258. display: flex;
  259. align-items: center;
  260. justify-content: center;
  261. }
  262. .search-btn::after {
  263. border: none;
  264. }
  265. .results {
  266. height: calc(100vh - 140rpx);
  267. }
  268. .result-list {
  269. padding: 24rpx;
  270. }
  271. .result-item {
  272. display: flex;
  273. gap: 20rpx;
  274. padding: 20rpx;
  275. background: #ffffff;
  276. border-radius: 16rpx;
  277. margin-bottom: 16rpx;
  278. }
  279. .result-cover {
  280. width: 100rpx;
  281. height: 100rpx;
  282. border-radius: 12rpx;
  283. display: flex;
  284. align-items: center;
  285. justify-content: center;
  286. flex-shrink: 0;
  287. }
  288. .cover-icon {
  289. font-size: 40rpx;
  290. opacity: 0.6;
  291. }
  292. .result-info {
  293. flex: 1;
  294. display: flex;
  295. flex-direction: column;
  296. justify-content: center;
  297. }
  298. .result-title {
  299. font-size: 28rpx;
  300. color: #1f2937;
  301. margin-bottom: 8rpx;
  302. }
  303. .result-meta {
  304. font-size: 24rpx;
  305. color: #9ca3af;
  306. }
  307. .result-desc {
  308. font-size: 24rpx;
  309. color: #6b7280;
  310. margin-bottom: 4rpx;
  311. overflow: hidden;
  312. text-overflow: ellipsis;
  313. white-space: nowrap;
  314. }
  315. :deep(.highlight) {
  316. background: linear-gradient(135deg, #fef08a 0%, #fde047 100%);
  317. color: #92400e;
  318. padding: 0 4rpx;
  319. border-radius: 4rpx;
  320. }
  321. .no-result {
  322. display: flex;
  323. flex-direction: column;
  324. align-items: center;
  325. justify-content: center;
  326. padding: 200rpx 0;
  327. }
  328. .no-result-icon {
  329. font-size: 80rpx;
  330. margin-bottom: 24rpx;
  331. }
  332. .no-result-text {
  333. font-size: 28rpx;
  334. color: #6b7280;
  335. }
  336. .initial-state {
  337. padding: 24rpx 32rpx;
  338. }
  339. .section {
  340. margin-bottom: 32rpx;
  341. }
  342. .section-header {
  343. display: flex;
  344. justify-content: space-between;
  345. align-items: center;
  346. margin-bottom: 20rpx;
  347. }
  348. .section-title {
  349. font-size: 28rpx;
  350. font-weight: 600;
  351. color: #1f2937;
  352. }
  353. .clear-btn {
  354. font-size: 24rpx;
  355. color: #9ca3af;
  356. }
  357. .tag-list {
  358. display: flex;
  359. flex-wrap: wrap;
  360. gap: 16rpx;
  361. }
  362. .tag {
  363. display: inline-flex;
  364. align-items: center;
  365. gap: 8rpx;
  366. padding: 12rpx 20rpx;
  367. background: #ffffff;
  368. border-radius: 32rpx;
  369. font-size: 26rpx;
  370. }
  371. .history-tag {
  372. color: #4b5563;
  373. }
  374. .delete-icon {
  375. font-size: 28rpx;
  376. color: #9ca3af;
  377. margin-left: 4rpx;
  378. }
  379. .hot-tag {
  380. background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
  381. color: #92400e;
  382. }
  383. .tag-rank {
  384. font-weight: 600;
  385. color: #dc2626;
  386. margin-right: 4rpx;
  387. }
  388. .tag-text {
  389. max-width: 300rpx;
  390. overflow: hidden;
  391. text-overflow: ellipsis;
  392. white-space: nowrap;
  393. }
  394. .empty-hint {
  395. display: flex;
  396. flex-direction: column;
  397. align-items: center;
  398. justify-content: center;
  399. padding: 200rpx 0;
  400. }
  401. .hint-text {
  402. font-size: 28rpx;
  403. color: #9ca3af;
  404. }
  405. </style>