"use client"; import { faSearch } from "@fortawesome/free-solid-svg-icons"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import clsx from "clsx"; import { useEffect, useMemo, useState } from "react"; import Logo from "./Logo"; import { useRequest } from "ahooks"; import { getSearchTypeList, getSearchWayList, SearchWayItemType } from "../_lib/data/search"; import { doSearch } from "../_lib/utils"; const defaultSearchEngine: SearchWayItemType = { _id: 'default', label: '站内', value: '/search?wd=%s', fullName: '站内', } export default function Search() { const { data: searchWayList = [] } = useRequest(() => getSearchWayList({ page: 1, pageSize: 9999 }).then(res => [defaultSearchEngine, ...res.list])) const { data: searchTypeList = [] } = useRequest(() => getSearchTypeList({ page: 1, pageSize: 9999 }).then(res => res.list.map((val, idx) => { if (idx === 0) { return { ...val, includes: ['default', ...val.includes] } } return val }))) const [selectKey, setSelectKey] = useState(null) const [activeSearchKey, setActiveSearchKey] = useState(null) const [inputStr, setInputStr] = useState('') const nowSelectConfig = useMemo(() => { const idx = searchTypeList.findIndex(val => val._id === selectKey) if (idx !== -1) return searchTypeList[idx] else return null }, [selectKey, searchTypeList]) const filterSeachList = useMemo(() => { return searchWayList.filter(val => nowSelectConfig?.includes.includes(val._id)) }, [searchWayList, nowSelectConfig]) const activeSearch = useMemo(() => { const idx = searchWayList.findIndex(val => val._id === activeSearchKey) if (idx !== -1) { return searchWayList[idx] } else { return null } }, [activeSearchKey, searchWayList]) useEffect(() => { if (searchTypeList.length > 0) { setSelectKey(searchTypeList[0]._id) } }, [searchTypeList]) useEffect(() => { if (filterSeachList.length > 0) { setActiveSearchKey(filterSeachList[0]._id) } }, [filterSeachList, selectKey]) return (
{ searchTypeList.map((item, idx) => (
{ setSelectKey(item._id) }} className={clsx(item._id === selectKey || (idx === 0 && selectKey === 'default') ? "text-[#333]" : "text-[#999] cursor-pointer")}> {item.name}
)) }
{ if (!activeSearch?.value) return if (e.key === 'Enter') { doSearch(activeSearch?.value, inputStr) } }} type="text" onChange={e => { setInputStr(e.target.value) }} placeholder={`${activeSearch?.label || ' '}搜索`} className="w-full bg-[#C4C2C6] px-4 h-[50px] rounded-3xl outline-none" />
{ filterSeachList.map(item => (
{ setActiveSearchKey(item._id) }} className={clsx(activeSearchKey === item._id ? "text-[#333]" : "text-[#999] cursor-pointer")}>{item.label}
)) }
); }