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";
import useHide from "@/layouts/hooks/useHide";
import { throttle } from "@/utils/tools";

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

  const pageSize = React.useMemo(() => params?.pageSize || 5, [params]);
  const pageShowRef = React.useRef(true);
  const [loading, setLoading] = React.useState(false);
  const [list, setList] = React.useState([]);
  const [finished, setFinished] = React.useState(true);
  const listRef = React.useRef([]);
  listRef.current = list;

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

  const queryData = React.useMemo(() => throttle(
    (options = {}) => {
      return new Promise((resolve, reject) => {
        changeLoading(true);

        const queryParams = {
          pageSize,
          ...options,
        }

        request(queryParams)
          .then((res) => {
            const { records, current, total } = res;

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

            setFinished(dataset.length >= total);
            changeLoading(false);
            resolve();

            // 写入缓存
            Taro.setStorage({
              key: `list-${sid}`,
              data: JSON.stringify({
                params: queryParams,
              }),
            })

          })
          .catch((err) => {
            changeLoading(false);
            reject(err);
          });
      });
    }),
    []
  );

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

  const onScrollToLower = React.useCallback(
    (page) => {
      const currentPage = Math.ceil(page / pageSize);
      queryData({ pageNum: currentPage + 1, ...(params || {}) });
    },
    [params]
  );

  useShow(() => {
    pageShowRef.current = true;

    const paramStr = Taro.getStorageSync(`list-${sid}`);
    const finalParams = paramStr ? JSON.parse(paramStr).params : { ...params || {} };

    // 如果已经加载多页数据
    // 那么需要重新加载
    if (finalParams.pageNum && finalParams.pageNum > 1) {
      finalParams.pageSize = finalParams.pageNum * finalParams.pageSize;
      finalParams.pageNum = 1;
    }

    refresh(finalParams);
  });

  useHide(() => {
    pageShowRef.current = false;
  });
  
  React.useEffect(() => {
    if (pageShowRef.current) {
      refresh(params);
    }
  }, [params, sid]);

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

  React.useEffect(() => {
    return () => {
      Taro.removeStorageSync(`list-${sid}`);
    }
  }, [sid]);
 
  return (
    <PowerScrollView
      scrollY
      finishedText="没有更多了"
      refresherEnabled={false}
      current={list.length}
      pageSize={pageSize}
      finished={finished}
      onScrollToLower={onScrollToLower}
      style={{ height: "100%", overflowY: "auto" }}
      renderLoading={loading ? <view>加载中...</view> : <view></view>}
    >
      {list.map(renderItem)}
    </PowerScrollView>
  );
});
