import {FC, useCallback, useEffect, useState} from "react";
import {View} from "@tarojs/components";
import styles from './list.module.scss'
import Taro, {useReachBottom, useRouter} from "@tarojs/taro";
import {illnessApi} from "@/api/illness";
import Empty from "@/components/empty/empty";
import Spin from "@/components/spinner";

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

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

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

  function jump(id: number) {
    Taro.navigateTo({url: '/pages/preview/illness/article/article?id=' + id})
  }


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


  return (
    <View style={{display: fetchDone ? 'block' : 'none'}} className='px-2 mt-2'>
      <Spin enable={enable} overlay/>
      {
        articles.length > 0 ?
          <>
            <View className='bg-white'>
              {
                articles.map((d, index) => <View key={d.id} className={styles.articles} onClick={() => jump(d.id)}>
                  {index + 1} . {d.title}
                </View>)
              }
            </View>
            <View className='text-center font-24 text-dark mt-3'>暂无更多</View>
          </>
          : <Empty name='暂无文章'/>
      }
    </View>
  )
}

export default BrandList
