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

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_SHARE_LIST, method: 'get', payload: { personId: PersonId, 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 MyShare'>

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

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

        </view>
      </ScrollView>

    </view>
  )
})
