import React, { useState, useEffect } from 'react' import { View, Text, ScrollView } from '@tarojs/components' import Taro from '@tarojs/taro' import { Navbar } from '@/components/ui/navbar' import TDesignSearch from '@/components/tdesign/search' import './index.css' // 本地存储搜索历史 const SEARCH_HISTORY_KEY = 'search_history' const SearchPage: React.FC = () => { const [searchValue, setSearchValue] = useState('') const [historyWords, setHistoryWords] = useState([]) const [popularWords, setPopularWords] = useState([]) // 获取搜索历史 const getSearchHistory = (): string[] => { try { const history = Taro.getStorageSync(SEARCH_HISTORY_KEY) return Array.isArray(history) ? history : [] } catch (error) { console.error('获取搜索历史失败:', error) return [] } } // 保存搜索历史 const saveSearchHistory = (keyword: string) => { try { const history = getSearchHistory() // 移除重复的关键词 const filteredHistory = history.filter(word => word !== keyword) // 将新关键词添加到前面 const newHistory = [keyword, ...filteredHistory] // 限制历史记录数量 const limitedHistory = newHistory.slice(0, 10) Taro.setStorageSync(SEARCH_HISTORY_KEY, limitedHistory) setHistoryWords(limitedHistory) } catch (error) { console.error('保存搜索历史失败:', error) } } // 清空搜索历史 const clearSearchHistory = () => { try { Taro.removeStorageSync(SEARCH_HISTORY_KEY) setHistoryWords([]) } catch (error) { console.error('清空搜索历史失败:', error) } } // 获取热门搜索词(模拟数据) const getPopularSearchWords = (): string[] => { return [ '手机', '笔记本电脑', '耳机', '智能手表', '平板电脑', '数码相机', '游戏机', '智能家居' ] } // 页面显示时加载数据 useEffect(() => { setHistoryWords(getSearchHistory()) setPopularWords(getPopularSearchWords()) }, []) // 处理搜索提交 const handleSubmit = (value: string) => { if (!value.trim()) return // 保存搜索历史 saveSearchHistory(value.trim()) // 跳转到搜索结果页面 Taro.navigateTo({ url: `/pages/search-result/index?keyword=${encodeURIComponent(value)}` }) } // 点击历史搜索项 const handleHistoryTap = (word: string) => { setSearchValue(word) // 保存搜索历史 saveSearchHistory(word) Taro.navigateTo({ url: `/pages/search-result/index?keyword=${encodeURIComponent(word)}` }) } // 点击热门搜索项 const handlePopularTap = (word: string) => { setSearchValue(word) // 保存搜索历史 saveSearchHistory(word) Taro.navigateTo({ url: `/pages/search-result/index?keyword=${encodeURIComponent(word)}` }) } // 清空搜索历史 const handleClearHistory = () => { clearSearchHistory() } return ( Taro.navigateBack()} className="bg-white" /> {/* 搜索栏 */} setSearchValue(value)} onSubmit={() => handleSubmit(searchValue)} onClear={() => setSearchValue('')} /> {/* 搜索历史 */} {historyWords.length > 0 && ( 搜索历史 清空 {historyWords.map((word: string, index: number) => ( handleHistoryTap(word)} data-testid="history-item" > {word} ))} )} {/* 热门搜索 */} {popularWords.length > 0 && ( 热门搜索 {popularWords.map((word: string, index: number) => ( handlePopularTap(word)} data-testid="popular-item" > {word} ))} )} {/* 空状态 */} {historyWords.length === 0 && popularWords.length === 0 && ( 暂无搜索记录 输入关键词搜索商品 )} ) } export default SearchPage