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 Img from "@/components/image/image";
import {beforeTime} from "@/utils/time";

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().then()
  }, [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])

  function jump(data: any, index: number) {
    Taro.navigateTo({url: '/pages/preview/brand/article/article?id=' + data.id})
    const oldArticles: any[] = JSON.parse(JSON.stringify(articles))
    oldArticles.splice(index, 1, {
      ...data,
      page_view: data.page_view + 1
    })
    setArticles(oldArticles)
  }


  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 rounded-20 clip'>
              {
                articles.map((d, i) => <View className='p-3 relative' onClick={() => jump(d, i)}>
                  {i > 0 && <View className='absolute top left right divided ml-3 mr-3'/>}
                  <View className="font-34 text-black">{d.title}</View>
                  {(d.intro || '').length > 40 && (<View className='flex mt-1'>
                    <View className="flex-1 font-24 lh1_5">{d.intro}</View>
                    {d.cover && <Img className='ml-l' width={140} height={100} src={d.cover} errorType="acquiesce"/>}
                  </View>)}
                  <View className="flex mt-3 justify-between font-24 text-muted">
                    <View>{beforeTime(d.created_at)}</View>
                    <View>阅读 {d.page_view || 0}</View>
                  </View>
                </View>)
              }
            </View>
            <View className='text-center font-24 text-dark mt-3'>暂无更多</View>
          </>
          : <Empty name='暂无文章'/>
      }
    </View>
  )
}

export default BrandList
