import {FC, useEffect, useState} from "react";
import {View} from "@tarojs/components";
import {publicApi} from "@/api";
import Spin from "@/components/spinner";
import ArticlesBox from "@/components/articlesBox/articlesBox";
import {useReachBottom} from "@tarojs/taro";
import PageScript from "@/components/pageScript/pageScript";
import Empty from "@/components/empty/empty";

const JumpArticlesConfig: FC = () => {
  const [page, setPage] = useState(1)
  const [total, setTotal] = useState(0)
  const [enable, setEnable] = useState(true)
  const [data, setData] = useState<Articles[]>([])

  useEffect(() => {
    publicApi.articlesPush(page, 10).then(res => {
      setTotal(res.total)
      const result = res.list.reduce((pre, cur) => {
        const index = pre.findIndex(d => d.id === cur.id)
        if (index === -1) {
          pre.push(cur)
        } else {
          pre.splice(index, 1, cur)
        }
        return pre
      }, data)
      setData(result)
    }).finally(() => {
      setEnable(false)
    })
  }, [page])

  useReachBottom(() => {
    if (data.length < total) {
      setPage(page + 1)
    }
  })


  return (
    <View>
      <Spin enable={enable} overlay/>
      <View className='bg-white rounded-20 clip m-3 px-3'>
        {
          data.length > 0
            ?data.map(d => <ArticlesBox data={d}/>)
            :<Empty name='暂无更多文章'/>
        }
      </View>
      <PageScript/>
    </View>
  )
}

export default JumpArticlesConfig
