import { useState, useEffect } from 'react'
import { useSelector } from 'react-redux'
import withLayout from '@/layout'
import { ScrollView } from '@tarojs/components'
import '@/assets/css/iconfont.css'
import { fetch } from '@/utils/request'
import { API_NEWS_LIST } from '@/constants/api'
import './index.scss'
import NewsListItem from '../components/NewsListItem/index'

export default withLayout(() => {
  
  const user = useSelector(state => state.user)
  const [PageList, setPageList] = useState([])
  const [IsPull, setPull] = useState(false)
  const [PersonId, setPersonId] = useState(null)
  const [pageNumber, setPageNumber] = useState(1)
  const [HasNextPage, setHasNextPage] = useState(true)

  useEffect(() => {
    if(user?.userInfo?.person?.personId) {
      setPersonId(user.userInfo.person.personId)
    }
  }, [user])

  useEffect(() => {
    if(PersonId) {
      GetPageList()
    }
  }, [pageNumber, PersonId])

  const PageRefresh = () => { // 页面下拉刷新回调
    setPull(true)
  }

  const GetPageList = () => {
    setHasNextPage(false)
    fetch({ url: API_NEWS_LIST, method: 'get', payload: { pageNumber, pageSize: 10 } }).then((res) => {
      setPageList(pageNumber === 1 ? res.records || [] : PageList.concat(res.records || []))
      setHasNextPage(res.current < res.pages)
      setPull(false)
    })
  }

  const PageLoadMore = () => { // 页面上拉加载更多
    if(HasNextPage) {
      setPageNumber(pageNumber + 1)
    }
  }

  useEffect(() => { // 下拉刷新触发
    if (IsPull) {
      if(pageNumber === 1) {
        GetPageList()
      } else {
        setPageNumber(1)
      }
    }
  }, [IsPull])

  return (
    <view className='Page newsList'>
      <ScrollView
        scroll-y
        refresher-enabled
        refresher-triggered={IsPull}
        onrefresherrefresh={PageRefresh}
        refresher-background='#fff'
        onscrolltolower={PageLoadMore}
      >
        <view className='PageContent'>
          {PageList.map((item, index) => (
            <NewsListItem data={item} key={`ListItem-${index}`}></NewsListItem>
          ))}

          {/* bottom */}
          <view className='PageBottom'>
            <text>已经到底了~</text>
          </view>
        </view>
      </ScrollView>
    </view>
  );
});
