import { useState, useEffect } from 'react'
import { ScrollView } from '@tarojs/components'
import { fetch } from '@/utils/request'
import { API_CUSTOMER_LIST } from '@/constants/api'
import './index.scss'
import StatCustomerListItem from '../StatCustomerListItem/index'

export default function TransactedCustomer () {
  const [PageList, setPageList] = useState([])
  const [IsPull, setPull] = useState(false)
  const [pageNumber, setPageNumber] = useState(1)
  const [HasNextPage, setHasNextPage] = useState(true)

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

  const GetPageList = () => {
    setHasNextPage(false)
    fetch({ url: `${API_CUSTOMER_LIST}/clinch`, 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 PageRefresh = () => { // 页面下拉刷新回调
    setPull(true)
  }

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

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

  return (
    <view className='components TransactedCustomer'>
      <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) => (
                <StatCustomerListItem key={`ListItem-${index}`} data={item}></StatCustomerListItem>
              ))
            }
          </view>

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

        </view>
      </ScrollView>
    </view>
  )
}
