import { useState, useEffect } from 'react'
import { ScrollView } from '@tarojs/components'
import { useSelector } from 'react-redux'
import { fetch } from '@/utils/request'
import { API_ITEMS_LIST } from '@/constants/api'
import './index.scss'
import MyShareListItem from '../MyShareListItem/index'

export default function MyCollectForBuilding () {
  
  const user = useSelector(state => state.user)
  const [PersonId, setPersonId] = useState(null)
  const [pageNumber, setPageNumber] = useState(null)
  const [pageSize] = useState(10)
  const [HasNextPage, setHasNextPage] = useState(true)
  const [PageList, setPageList] = useState([])
  const [IsPull, setPull] = useState(false)
  const [PullTimer, setPullTimer] = useState(null)

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

  useEffect(() => {
    if(PersonId) {
      setPageNumber(1)
    }
  }, [PersonId])

  useEffect(() => {
    if(pageNumber && HasNextPage) {
      fetch({ url: API_ITEMS_LIST, method: 'get', payload: { mine: true, pageNumber, pageSize } }).then((res) => {
        setPageList(res.records || [])
        setHasNextPage(res.current < res.pages)
      })
    }
  }, [pageNumber])

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

  useEffect(() => { // 下拉刷新触发
    if (IsPull) {
      clearTimeout(PullTimer)
      setPullTimer(setTimeout(() => {
        setPull(false)
      }, 2000))
    }
  }, [IsPull])

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

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