"use client" import type React from "react" import { useState, useEffect } from "react" import { Button } from "@/components/ui/button" import { Search, X } from "lucide-react" import { useRouter, useSearchParams } from "next/navigation" import { CommandDialog, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, } from "@/components/ui/command" import { fetchWithAuth } from "@/lib/api" interface SearchResult { bookId: number title: string author: string[] price: number coverImage?: string } export function SearchBar() { const [searchTerm, setSearchTerm] = useState("") const [isLoading, setIsLoading] = useState(false) const [open, setOpen] = useState(false) const [results, setResults] = useState([]) const router = useRouter() const searchParams = useSearchParams() // 从 URL 参数中获取搜索词 useEffect(() => { const query = searchParams?.get("search") if (query) { setSearchTerm(query) } }, [searchParams]) // 监听快捷键打开搜索 useEffect(() => { const down = (e: KeyboardEvent) => { if (e.key === "k" && (e.metaKey || e.ctrlKey)) { e.preventDefault() setOpen((open) => !open) } } document.addEventListener("keydown", down) return () => document.removeEventListener("keydown", down) }, []) // 当搜索对话框打开时执行搜索 useEffect(() => { if (open && searchTerm.trim().length > 0) { performSearch(searchTerm) } }, [open, searchTerm]) const performSearch = async (term: string) => { if (!term.trim()) return setIsLoading(true) try { const response = await fetchWithAuth(`book/search/title?title=${encodeURIComponent(term)}&pageNum=1&pageSize=5`) const result = await response.json() if (result.code === 0) { setResults( result.data.data.map((book: any) => ({ bookId: book.bookId, title: book.title, author: book.author, price: book.price, coverImage: book.coverImage, })), ) } else { setResults([]) } } catch (error) { console.error("搜索失败", error) setResults([]) } finally { setIsLoading(false) } } const handleSearch = (e: React.FormEvent) => { e.preventDefault() if (searchTerm.trim()) { router.push(`/books?search=${encodeURIComponent(searchTerm)}`) setOpen(false) } } const handleSelectResult = (bookId: number) => { router.push(`/books/${bookId}`) setOpen(false) } const clearSearch = () => { setSearchTerm("") } return ( <>
{searchTerm && ( )}
{isLoading ? (
正在搜索...
) : ( <> 未找到相关图书 {results.map((book) => ( handleSelectResult(book.bookId)} className="flex items-center gap-2 py-2" >
{book.title}

{book.title}

{book.author.join(", ")} · ¥{book.price.toFixed(2)}

))}
{searchTerm.trim() && ( { router.push(`/books?search=${encodeURIComponent(searchTerm)}`) setOpen(false) }} className="justify-center font-medium" > 查看所有 "{searchTerm}" 的搜索结果 )} )}
) }