import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { ScrollView } from '@tarojs/components';
import Taro from '@tarojs/taro';

export default (props) => {
  const {
    render,
    request,
    params,
    pageSize = 10,
    onError,
    onDataChange,
    ...leftProps
  } = props

  const loadingRef = useRef(false)
  const [payload, setPayload] = useState({})
  const [list, setList] = useState([])
  const pageRef = useRef({ current: 1, pages: 0 })
  const hasMore = pageRef.current.current < pageRef.current.pages

  // 滚动
  const handleScrollToLower = (e) => {
    const loading = loadingRef.current

    if (!loading && hasMore) {
      setPayload({
        ...payload,
        pageNum: pageRef.current.current + 1
      })
    }
  }

  const fetchList = (queryParams) => {
    if (!request) return;

    Taro.showLoading()
    loadingRef.current = true
    request(queryParams).then((res) => {
      const { records, ...pageInfo } = res || {}
      const lst = pageInfo.current === 1 ? records || [] : list.concat(records || [])
      setList(lst)
      if (onDataChange) {
        onDataChange(lst)
      }

      pageRef.current = pageInfo
      loadingRef.current = false
      Taro.hideLoading()
    }).catch((err) => {
      loadingRef.current = false
      console.error(err)
      Taro.hideLoading()
      if (onError) {
        onError(err)
      }
    })
  }

  const fetchRef = useRef()
  fetchRef.current = fetchList

  // 联动状态, 设置查询参数
  useEffect(() => {
    setPayload({
      ...params || {},
      pageNum: 1,
      pageSize,
    })
  }, [pageSize, params])

  // 请求数据
  useEffect(() => {
    fetchRef.current(payload)
  }, [payload])

  return (
    <ScrollView
      scrollY
      onScrollToLower={handleScrollToLower}
      {...leftProps}
    >
      {!render
        ? props.children
        : list.map((item, index) => render({ item, index }))
      }
      <view className='botton' style={{ display: hasMore ? 'none' : '' }}>已经到底了~</view>
    </ScrollView>
  )
}
