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

export default function MyCollectForCourse () {
  
  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_MY_COLLECT_COURSE_LIST, method: 'get', payload: { pageNum: 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='components MyCollectForCourse'>
      <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) => (
                <MyCourseListItem Data={item} key={`MyCourseListItem-${index}`}></MyCourseListItem>
              ))
            }
          </view>

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