import {FC, useCallback, useEffect, useState} from "react";
import {View} from "@tarojs/components";
import styles from './index.module.scss'
import Taro, {useReachBottom, useRouter} from "@tarojs/taro";
import Empty from "@/components/empty/empty";
import Spinner from "@/components/spinner";
import Img from "@/components/image/image";
import { SearchApi } from "@/api/search";

const SearchList: FC = () => {
  const {name} = useRouter().params as unknown as { name: string}
  const [page, setPage] = useState(1)
  const [brands, setBrands] = useState<any[]>([])
  const [total, setTotal] = useState(0)
  const [text, setText] = useState('')
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    getData()
  }, [page,name])

  const getData = useCallback(async () => {
    try {
      const data = await SearchApi.list(page, 10,name)
      if (page === 1) {
        if (data.data.length < 10) {
          setText('没有更多了~')
        } else {
          setText('上拉加载更多~')
        }
      }
      setTotal(data.total)
      setBrands([
        ...brands,
        ...data.data
      ])
    } catch (e) {
    }
    setLoading(false)
  }, [page])


  function jumpInfo(id: number,type:string) {
    console.log(type,'type')
    let url = ''
    switch (type){
      case 'brand':
        url = '/pages/preview/brand/info/info';
        break;
      case 'illness':
        url = '/pages/preview/illness/list/list';
        break;
      case 'article':
        url = '/pages/preview/illness/article/article'
        break
      case 'video_record':
        url = '/pages/preview/videoFull/videoFull'
        break
    }
    Taro.navigateTo({url: `${url}?id=${id}`})

  }

  useReachBottom(useCallback(() => {
    if (brands?.length < total) {
      setPage(page + 1)
    } else {
      setText('没有更多了~')
    }
  }, [total, brands]))


  return (
    <View className='p-2'>
      <Spinner enable={loading} overlay/>
      {
        brands.length ?
          <>
            {brands.map((d) => <View onClick={() => jumpInfo(d.data.id,d.data.table)} className={styles.box} key={d.data.id}>
              <Img width={128} height={128} src={d.data['@data'].logo} mode='aspectFill' className={styles.image}/>
              <View className={styles.rightBox}>
                <View className='font-weight mb-2 font-28'>{d.data.title}</View>
                <View className={styles.desc}>{d.graphic_introduction}</View>
              </View>
            </View>)
            }
            <View style={{width: '710rpx', textAlign: 'center', color: '#999'}} className="font-28 mt-3">{text}</View>
          </> : <Empty name='空空如也'/>
      }
    </View>
  )
}

export default SearchList

