function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
var _excluded = ["virtual", "onTopRefresh", "onBottomRefresh", "allowClear", "multiple", "value", "onChange", "onScroll", "wrapper", "layout", "checkable", "checkbox", "checkboxProps", "checkboxPosition", "prepend", "list", "append", "children"];
function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
import React, { useRef, useMemo, useState, useEffect, forwardRef, useImperativeHandle } from 'react';
import _ from 'lodash';
import constant from "./constant";
import flattenList from "./flattenList";
import getVisibleItems from "./getVisibleItems";
import List from "./List";

// 内库使用-start
import Layout from "./../../../Layout";
// 内库使用-end

/* 测试使用-start
import { Layout } from 'seedsui-react'
测试使用-end */

// 列表
var VirtualList = function VirtualList(_ref, ref) {
  var virtual = _ref.virtual,
    onTopRefresh = _ref.onTopRefresh,
    onBottomRefresh = _ref.onBottomRefresh,
    allowClear = _ref.allowClear,
    multiple = _ref.multiple,
    value = _ref.value,
    onChange = _ref.onChange,
    onScroll = _ref.onScroll,
    wrapper = _ref.wrapper,
    layout = _ref.layout,
    checkable = _ref.checkable,
    checkbox = _ref.checkbox,
    checkboxProps = _ref.checkboxProps,
    checkboxPosition = _ref.checkboxPosition,
    prepend = _ref.prepend,
    list = _ref.list,
    append = _ref.append,
    children = _ref.children,
    props = _objectWithoutProperties(_ref, _excluded);
  var rootRef = useRef(null);
  var listRef = useRef(null);

  // 拉平数据, And set virtualData.type
  var items = useMemo(function () {
    return flattenList(list);
  }, [list]);

  // 计算每一项的高度并缓存
  var itemHeights = useMemo(function () {
    if (Array.isArray(items) && items.length) {
      return items.map(virtual.getItemHeight);
    }
    return [];
    // eslint-disable-next-line
  }, [list]);

  // 计算总高度
  var totalHeight = itemHeights.reduce(function (sum, h) {
    return sum + h;
  }, 0);

  // Visible Items and set virtualData style
  var _useState = useState(null),
    _useState2 = _slicedToArray(_useState, 2),
    visibleItems = _useState2[0],
    setVisibleItems = _useState2[1];

  // Expose
  useImperativeHandle(ref, function () {
    return _objectSpread(_objectSpread({}, rootRef.current), {}, {
      getAnchors: function getAnchors() {
        if (!Array.isArray(items) || !items.length) {
          return [];
        }
        var anchorsMap = {};
        var anchors = [];
        var _iterator = _createForOfIteratorHelper(items),
          _step;
        try {
          for (_iterator.s(); !(_step = _iterator.n()).done;) {
            var item = _step.value;
            if (item.anchor) {
              if (!anchorsMap[item.anchor]) anchors.push(item.anchor);
              anchorsMap[item.anchor] = 1;
            }
          }
        } catch (err) {
          _iterator.e(err);
        } finally {
          _iterator.f();
        }
        return anchors;
      },
      scrollToAnchor: function scrollToAnchor(anchor) {
        var _iterator2 = _createForOfIteratorHelper(items),
          _step2;
        try {
          for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
            var item = _step2.value;
            if (item.anchor === anchor) {
              if (typeof (item === null || item === void 0 ? void 0 : item.virtualData.top) === 'number') {
                rootRef.current.rootDOM.scrollTop = item === null || item === void 0 ? void 0 : item.virtualData.top;
                return;
              }
            }
          }
        } catch (err) {
          _iterator2.e(err);
        } finally {
          _iterator2.f();
        }
      }
    });
  });

  // 初始化完成时更新显示容器
  useEffect(function () {
    if (Array.isArray(list) && list.length) {
      // 列表更新, 底部自定义区域超过一屏高度, 即使列表高度增加, 也会一直保持在底部, 需要滚动到列表可视区域, 避免一直底部刷新
      if (_.isEmpty(visibleItems) && totalHeight > constant.startBuffer) {
        var _rootRef$current;
        var appendHeight = rootRef.current.rootDOM.scrollHeight - (listRef.current.offsetTop + listRef.current.offsetHeight);
        if (appendHeight > ((_rootRef$current = rootRef.current) === null || _rootRef$current === void 0 ? void 0 : _rootRef$current.rootDOM.clientHeight)) {
          rootRef.current.rootDOM.scrollTop = rootRef.current.rootDOM.scrollTop - appendHeight - constant.startBuffer;
        }
      }

      // 更新显示容器
      updateVisibleItems();
    } else {
      setVisibleItems(null);
    }
    // eslint-disable-next-line
  }, [list]);

  // 更新显示容器
  function updateVisibleItems() {
    var _rootRef$current2, _listRef$current;
    if (!((_rootRef$current2 = rootRef.current) !== null && _rootRef$current2 !== void 0 && _rootRef$current2.rootDOM)) return;
    var prependHeight = (_listRef$current = listRef.current) === null || _listRef$current === void 0 ? void 0 : _listRef$current.offsetTop;
    requestAnimationFrame(function () {
      var _rootRef$current3, _rootRef$current4;
      var newVisibleItems = getVisibleItems({
        prependHeight: prependHeight || 0,
        items: items,
        itemHeights: itemHeights,
        scrollTop: (_rootRef$current3 = rootRef.current) === null || _rootRef$current3 === void 0 || (_rootRef$current3 = _rootRef$current3.rootDOM) === null || _rootRef$current3 === void 0 ? void 0 : _rootRef$current3.scrollTop,
        containerHeight: ((_rootRef$current4 = rootRef.current) === null || _rootRef$current4 === void 0 || (_rootRef$current4 = _rootRef$current4.rootDOM) === null || _rootRef$current4 === void 0 ? void 0 : _rootRef$current4.clientHeight) || 0
      });
      setVisibleItems(newVisibleItems);
    });
  }

  // 滚动
  function handleScroll(e) {
    // Set visible items and set virtualData
    updateVisibleItems();
    onScroll && onScroll(e);
  }
  return /*#__PURE__*/React.createElement(Layout.Main, _extends({}, props, {
    ref: rootRef,
    className: "list-main".concat(props.className ? ' ' + props.className : ''),
    onTopRefresh: onTopRefresh,
    onBottomRefresh: onBottomRefresh,
    onScroll: handleScroll
  }), typeof prepend === 'function' ? prepend({
    list: list,
    value: value,
    onChange: onChange
  }) : null, /*#__PURE__*/React.createElement(List, {
    ref: listRef,
    allowClear: allowClear,
    multiple: multiple,
    value: value,
    list: visibleItems,
    onChange: onChange
    // List config
    ,
    wrapper: wrapper,
    layout: layout,
    checkable: checkable,
    checkbox: checkbox,
    checkboxProps: checkboxProps,
    checkboxPosition: checkboxPosition
    // virtual config
    ,
    height: totalHeight
  }), typeof append === 'function' ? append({
    list: list,
    value: value,
    onChange: onChange
  }) : null, children);
};
export default /*#__PURE__*/forwardRef(VirtualList);