import React from 'react';
import Taro from '@tarojs/taro';
import { View } from '@tarojs/components';
import { PowerScrollView } from '@antmjs/vantui';
import useShow from '@/layouts/hooks/useShow';

export default React.forwardRef((props, ref) => {
  const { request, params, renderItem, onLoadingChange, onDataChange } = props;

  const pageSize = 20;
  const pageNumRef = React.useRef(1);
  const listRef = React.useRef([]);
  const [loading, setLoading] = React.useState(false);
  const [list, setList] = React.useState([]);
  const [finished, setFinished] = React.useState(true);
  listRef.current = list;

  const changeLoading = (val) => {
    setLoading(val);
    if (onLoadingChange) {
      onLoadingChange(val);
    }
  }

  const queryData = React.useCallback((options = {}) => {
    return new Promise((resolve, reject) => {
      changeLoading(true);
      request({
        pageSize,
        ...(params || {}),
        ...options
      }).then((res) => {
        const { records, current, pages } = res;

        let dataset = current == 1 ? records || [] : listRef.current.concat(records || [])
        if (onDataChange) {
          dataset = onDataChange(dataset)
        }
        setList(dataset);

        setFinished(current >= pages);
        changeLoading(false);
        resolve();
      }).catch((err) => {
        changeLoading(false);
        reject(err);
      });
    });
  }, [request, params]);

  const refresh = React.useCallback(() => {
    pageNumRef.current = 1;
    queryData({pageNum : pageNumRef.current});
  }, [queryData]);

  const onScrollToLower = React.useCallback((event = 0, isRefresh = false) => {
    pageNumRef.current += 1;
    return queryData({pageNum : pageNumRef.current});
  }, [queryData]);

  // React.useEffect(() => {
  //   refresh();
  // }, [refresh]);

  React.useImperativeHandle(ref, () => ({
    refresh,
    updateData: (dt) => setList(dt),
  }));

  useShow(() => {
    refresh();
  }, [refresh]);
  
  return (
    <PowerScrollView
      scrollY
      finishedText="没有更多了"
      refresherEnabled={false}
      current={list.length}
      pageSize={pageSize}
      finished={finished}
      onScrollToLower={onScrollToLower}
      style={{ height: '100%', overflowY: 'auto' }}
    >
      {
        list.map(renderItem)
      }
    </PowerScrollView>
  )
})
