import {FC, useCallback, useEffect, useState} from "react";
import {View} from "@tarojs/components";
import Taro, {useReachBottom, useRouter} from "@tarojs/taro";
import {illnessApi} from "@/api/illness";
import Empty from "@/components/empty/empty";
import Spin from "@/components/spinner";
import ArticlesBox from "@/components/articlesBox/articlesBox";

const BrandList: FC = () => {
  const params = useRouter().params as unknown as { id: number }
  const [page, setPage] = useState(1)
  const [articles, setArticles] = useState<any[]>([])
  const [total, setTotal] = useState(0)
  const [fetchDone, setFetchDone] = useState(false)
  const [enable, setEnable] = useState(true)

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

  const getData = useCallback(async () => {
    try {
      const data = await illnessApi.articleInfo(params.id, page, 20)
      Taro.setNavigationBarTitle({title: data?.illness?.name || '暂无文章'})
      setTotal(data.list.total)
      setArticles([...articles, ...data.list.list])
    } catch (e) {
    }
    setEnable(false)
    setFetchDone(true)
    Taro.hideLoading()
  }, [page])

  useReachBottom(useCallback(() => {
    if (articles?.length < total) {
      setPage(page + 1)
    }
  }, [total, articles]))


  return (
    <View style={{display: fetchDone ? 'block' : 'none'}} className='px-3 mt-3'>
      <Spin enable={enable} overlay/>
      {
        articles.length > 0 ?
          <>
            <View className='bg-white rounded-20 clip px-3'>
              {
                articles.map(d => <ArticlesBox data={d}/>)
              }
            </View>

          </>
          : <Empty name='暂无文章'/>
      }
    </View>
  )
}

export default BrandList
