Files
ai_dianshang/miniprogram/pages/goods/search/index.js

300 lines
6.7 KiB
JavaScript
Raw Normal View History

2025-11-17 14:11:46 +08:00
import {
getSearchHistory,
getSearchPopular,
} from '../../../services/good/fetchSearchHistory';
Page({
data: {
historyWords: [],
popularWords: [],
searchValue: '',
searchSuggestions: [],
showSuggestions: false,
dialog: {
title: '确认删除当前历史记录',
showCancelButton: true,
message: '',
},
dialogShow: false,
},
deleteType: 0,
deleteIndex: '',
searchTimer: null,
onShow() {
this.loadLocalHistory();
this.queryPopular();
},
onLoad() {
this.loadLocalHistory();
},
// 加载本地历史记录
loadLocalHistory() {
try {
const historyWords = wx.getStorageSync('searchHistory') || [];
this.setData({
historyWords: historyWords.slice(0, 10), // 最多显示10条历史记录
});
} catch (error) {
console.error('加载搜索历史失败:', error);
}
},
// 保存搜索历史到本地
saveSearchHistory(keyword) {
try {
let historyWords = wx.getStorageSync('searchHistory') || [];
// 移除重复项
historyWords = historyWords.filter(item => item !== keyword);
// 添加到开头
historyWords.unshift(keyword);
// 限制历史记录数量
historyWords = historyWords.slice(0, 20);
wx.setStorageSync('searchHistory', historyWords);
this.setData({
historyWords: historyWords.slice(0, 10),
});
} catch (error) {
console.error('保存搜索历史失败:', error);
}
},
// 清空本地历史记录
clearLocalHistory() {
try {
wx.removeStorageSync('searchHistory');
this.setData({
historyWords: [],
});
} catch (error) {
console.error('清空搜索历史失败:', error);
}
},
// 删除单条历史记录
deleteHistoryItem(index) {
try {
let historyWords = wx.getStorageSync('searchHistory') || [];
historyWords.splice(index, 1);
wx.setStorageSync('searchHistory', historyWords);
this.setData({
historyWords: historyWords.slice(0, 10),
});
} catch (error) {
console.error('删除历史记录失败:', error);
}
},
async queryHistory() {
try {
const data = await getSearchHistory();
const code = 'Success';
if (String(code).toUpperCase() === 'SUCCESS') {
const { historyWords = [] } = data;
this.setData({
historyWords,
});
}
} catch (error) {
console.error(error);
}
},
async queryPopular() {
try {
const data = await getSearchPopular();
const code = 'Success';
if (String(code).toUpperCase() === 'SUCCESS') {
const { popularWords = [] } = data;
this.setData({
popularWords,
});
}
} catch (error) {
console.error(error);
}
},
// 搜索输入处理
onSearchInput(e) {
const value = e.detail.value || '';
this.setData({
searchValue: value,
});
// 清除之前的定时器
if (this.searchTimer) {
clearTimeout(this.searchTimer);
}
if (value.trim()) {
// 延迟搜索建议
this.searchTimer = setTimeout(() => {
this.getSearchSuggestions(value.trim());
}, 300);
} else {
this.setData({
showSuggestions: false,
searchSuggestions: [],
});
}
},
// 获取搜索建议
getSearchSuggestions(keyword) {
const { historyWords, popularWords } = this.data;
const allWords = [...historyWords, ...popularWords];
// 过滤出包含关键词的建议
const suggestions = allWords
.filter(word => word.toLowerCase().includes(keyword.toLowerCase()))
.filter((word, index, arr) => arr.indexOf(word) === index) // 去重
.slice(0, 8); // 最多显示8条建议
this.setData({
searchSuggestions: suggestions,
showSuggestions: suggestions.length > 0,
});
},
// 点击搜索建议
onSuggestionTap(e) {
const { suggestion } = e.currentTarget.dataset;
this.performSearch(suggestion);
},
// 清空搜索输入
onSearchClear() {
this.setData({
searchValue: '',
showSuggestions: false,
searchSuggestions: [],
});
},
// 搜索输入获得焦点
onSearchFocus() {
const { searchValue } = this.data;
if (searchValue.trim()) {
this.getSearchSuggestions(searchValue.trim());
}
},
// 搜索输入失去焦点
onSearchBlur() {
// 延迟隐藏建议,让点击事件能够触发
setTimeout(() => {
this.setData({
showSuggestions: false,
});
}, 200);
},
confirm() {
if (this.deleteType === 0) {
// 清空所有历史记录
this.clearLocalHistory();
} else {
// 删除单条历史记录
this.deleteHistoryItem(this.deleteIndex);
}
this.setData({
dialogShow: false,
});
},
close() {
this.setData({ dialogShow: false });
},
handleClearHistory() {
const { dialog } = this.data;
this.deleteType = 1;
this.setData({
dialog: {
...dialog,
message: '确认删除所有历史记录',
},
dialogShow: true,
});
},
deleteCurr(e) {
const { index } = e.currentTarget.dataset;
this.deleteIndex = index;
this.deleteType = 1;
this.setData({
dialogShow: true,
'dialog.message': '确认删除这条搜索记录?',
});
},
handleHistoryTap(e) {
const { historyWords } = this.data;
const { dataset } = e.currentTarget;
const _searchValue = historyWords[dataset.index || 0] || '';
if (_searchValue) {
this.performSearch(_searchValue);
}
},
handlePopularTap(e) {
const { popularword } = e.currentTarget.dataset;
this.performSearch(popularword);
},
// 执行搜索
performSearch(keyword) {
if (!keyword || !keyword.trim()) {
wx.showToast({
title: '请输入搜索关键词',
icon: 'none',
});
return;
}
const searchValue = keyword.trim();
// 保存到搜索历史
this.saveSearchHistory(searchValue);
// 跳转到搜索结果页
wx.navigateTo({
url: `/pages/goods/result/index?searchValue=${encodeURIComponent(searchValue)}`,
});
},
handleSubmit(e) {
// 安全地获取搜索值
const value = e?.detail?.value || this.data.searchValue;
// 确保value是字符串类型
const searchValue = typeof value === 'string' ? value.trim() : '';
// 使用统一的搜索方法
this.performSearch(searchValue);
},
// 分享功能
onShareAppMessage() {
return {
title: '商品搜索 - 查找你想要的商品',
path: '/pages/goods/search/index'
};
},
// 分享到朋友圈
onShareTimeline() {
return {
title: '商品搜索 - 查找你想要的商品'
};
}
});