function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

function _extends() { _extends = Object.assign || 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 ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

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; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

import React from 'react';
import { findDOMNode } from 'react-dom';
import PropTypes from 'prop-types';
import { dom } from '../util';
import VirtualBody from './virtual/body';
import { statics } from './util';

var noop = function noop() {};

export default function virtual(BaseComponent) {
  var VirtualTable =
  /*#__PURE__*/
  function (_React$Component) {
    _inherits(VirtualTable, _React$Component);

    function VirtualTable() {
      var _getPrototypeOf2;

      var _this;

      _classCallCheck(this, VirtualTable);

      for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
        args[_key] = arguments[_key];
      }

      _this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(VirtualTable)).call.apply(_getPrototypeOf2, [this].concat(args)));

      _defineProperty(_assertThisInitialized(_this), "state", {
        rowHeight: _this.props.rowHeight,
        scrollToRow: _this.props.scrollToRow,
        height: _this.props.maxBodyHeight
      });

      _defineProperty(_assertThisInitialized(_this), "onScroll", function () {
        // 避免横向滚动带来的性能问题
        var scrollTop = _this.bodyNode.scrollTop;

        if (scrollTop === _this.lastScrollTop) {
          return;
        }

        var start = _this.computeScrollToRow(scrollTop);

        if (!('scrollToRow' in _this.props)) {
          _this.setState({
            scrollToRow: start
          });
        }

        _this.props.onBodyScroll(start);

        _this.lastScrollTop = scrollTop;
      });

      _defineProperty(_assertThisInitialized(_this), "getBodyNode", function (node, lockType) {
        lockType = lockType ? lockType.charAt(0).toUpperCase() + lockType.substr(1) : '';
        _this["body".concat(lockType, "Node")] = node;
      });

      _defineProperty(_assertThisInitialized(_this), "getTableInstance", function (type, instance) {
        type = type ? type.charAt(0).toUpperCase() + type.substr(1) : '';
        _this["table".concat(type, "Inc")] = instance;
      });

      return _this;
    }

    _createClass(VirtualTable, [{
      key: "getChildContext",
      value: function getChildContext() {
        return {
          onVirtualScroll: this.onScroll,
          bodyHeight: this.computeBodyHeight(),
          innerTop: this.computeInnerTop(),
          getBodyNode: this.getBodyNode,
          getTableInstanceForVirtual: this.getTableInstance,
          rowSelection: this.rowSelection
        };
      }
    }, {
      key: "UNSAFE_componentWillMount",
      value: function UNSAFE_componentWillMount() {
        var _this$props = this.props,
            useVirtual = _this$props.useVirtual,
            dataSource = _this$props.dataSource;
        this.hasVirtualData = useVirtual && dataSource && dataSource.length > 0;
      }
    }, {
      key: "componentDidMount",
      value: function componentDidMount() {
        if (this.hasVirtualData) {
          this.lastScrollTop = this.bodyNode.scrollTop;
        }

        this.adjustScrollTop();
        this.adjustSize();
        this.reComputeSize();
      }
    }, {
      key: "UNSAFE_componentWillReceiveProps",
      value: function UNSAFE_componentWillReceiveProps(nextProps) {
        var useVirtual = nextProps.useVirtual,
            dataSource = nextProps.dataSource;
        this.hasVirtualData = useVirtual && dataSource && dataSource.length > 0;

        if ('maxBodyHeight' in nextProps) {
          if (this.state.height !== nextProps.maxBodyHeight) {
            this.setState({
              height: nextProps.maxBodyHeight
            });
          }
        }

        if ('scrollToRow' in nextProps) {
          this.setState({
            scrollToRow: nextProps.scrollToRow
          });
        }

        if (this.state.rowHeight && 'rowHeight' in nextProps) {
          var row = this.getRowNode();
          var rowClientHeight = row && row.clientHeight;

          if (rowClientHeight && rowClientHeight !== this.state.rowHeight) {
            this.setState({
              rowHeight: rowClientHeight
            });
          }
        }
      }
    }, {
      key: "componentDidUpdate",
      value: function componentDidUpdate() {
        this.adjustScrollTop();
        this.adjustSize();
        this.reComputeSize();
      }
    }, {
      key: "reComputeSize",
      value: function reComputeSize() {
        var rowHeight = this.state.rowHeight;

        if (typeof rowHeight === 'function' && this.hasVirtualData) {
          var row = this.getRowNode();
          var rowClientHeight = row && row.clientHeight;

          if (rowClientHeight !== this.state.rowHeight) {
            this.setState({
              rowHeight: rowClientHeight
            });
          }
        }
      }
    }, {
      key: "computeBodyHeight",
      value: function computeBodyHeight() {
        var rowHeight = this.state.rowHeight;
        var dataSource = this.props.dataSource;

        if (typeof rowHeight === 'function') {
          return 0;
        }

        return dataSource.length * rowHeight;
      }
    }, {
      key: "computeInnerTop",
      value: function computeInnerTop() {
        var rowHeight = this.state.rowHeight;

        if (typeof rowHeight === 'function') {
          return 0;
        }

        return this.start * rowHeight;
      }
    }, {
      key: "getVisibleRange",
      value: function getVisibleRange(ExpectStart) {
        var _this$state = this.state,
            height = _this$state.height,
            rowHeight = _this$state.rowHeight;
        var len = this.props.dataSource.length;
        var end;
        var visibleCount = 0;
        var start = 0;

        if (typeof rowHeight === 'function') {
          // try get cell height;
          end = 1;
        } else {
          visibleCount = parseInt(height / rowHeight, 10);

          if (typeof ExpectStart === 'number') {
            start = ExpectStart < len ? ExpectStart : 0;
          }

          end = Math.min(+start + 1 + visibleCount + 10, len);
        }

        this.end = end;
        this.visibleCount = visibleCount;
        return {
          start: start,
          end: end
        };
      }
    }, {
      key: "adjustScrollTop",
      value: function adjustScrollTop() {
        if (this.hasVirtualData) {
          this.bodyNode.scrollTop = this.lastScrollTop % this.state.rowHeight + this.state.rowHeight * this.state.scrollToRow;
        }
      }
    }, {
      key: "adjustSize",
      value: function adjustSize() {
        if (this.hasVirtualData) {
          var body = this.bodyNode;
          var virtualScrollNode = body.querySelector('div');
          var clientHeight = body.clientHeight,
              clientWidth = body.clientWidth;
          var tableInc = this.tableInc;
          var tableNode = findDOMNode(tableInc);
          var prefix = this.props.prefix;
          var headerNode = tableNode.querySelector(".".concat(prefix, "table-header table"));
          var headerClientWidth = headerNode && headerNode.clientWidth;

          if (clientWidth < headerClientWidth) {
            dom.setStyle(virtualScrollNode, 'min-width', headerClientWidth);
            var leftNode = this.bodyLeftNode;
            var rightNode = this.bodyRightNode;
            leftNode && dom.setStyle(leftNode, 'max-height', clientHeight);
            rightNode && dom.setStyle(rightNode, 'max-height', clientHeight);
            this.hasScrollbar = true;
          } else {
            dom.setStyle(virtualScrollNode, 'min-width', 'auto');
            this.hasScrollbar = false;
          }
        }
      }
    }, {
      key: "computeScrollToRow",
      value: function computeScrollToRow(offset) {
        var rowHeight = this.state.rowHeight;
        var start = parseInt(offset / rowHeight);
        this.start = start;
        return start;
      }
    }, {
      key: "getRowNode",
      value: function getRowNode() {
        try {
          // in case of finding an unmounted component due to cached data
          // need to clear refs of this.tableInc when dataSource Changed
          // use try catch for temporary
          return findDOMNode(this.tableInc.getRowRef(0));
        } catch (error) {
          return null;
        }
      }
    }, {
      key: "render",
      value: function render() {
        /* eslint-disable no-unused-vars, prefer-const */
        var _this$props2 = this.props,
            useVirtual = _this$props2.useVirtual,
            components = _this$props2.components,
            dataSource = _this$props2.dataSource,
            fixedHeader = _this$props2.fixedHeader,
            rowHeight = _this$props2.rowHeight,
            scrollToRow = _this$props2.scrollToRow,
            onBodyScroll = _this$props2.onBodyScroll,
            others = _objectWithoutProperties(_this$props2, ["useVirtual", "components", "dataSource", "fixedHeader", "rowHeight", "scrollToRow", "onBodyScroll"]);

        var entireDataSource = dataSource;
        this.rowSelection = this.props.rowSelection;

        if (this.hasVirtualData) {
          components = _objectSpread({}, components);

          var _this$getVisibleRange = this.getVisibleRange(this.state.scrollToRow),
              start = _this$getVisibleRange.start,
              end = _this$getVisibleRange.end;

          dataSource = dataSource.slice(start, end);

          if (!components.Body) {
            components.Body = VirtualBody;
          }

          fixedHeader = true;
        }

        return React.createElement(BaseComponent, _extends({}, others, {
          dataSource: dataSource,
          entireDataSource: entireDataSource,
          components: components,
          fixedHeader: fixedHeader
        }));
      }
    }]);

    return VirtualTable;
  }(React.Component);

  _defineProperty(VirtualTable, "VirtualBody", VirtualBody);

  _defineProperty(VirtualTable, "propTypes", _objectSpread({
    /**
     * 是否开启虚拟滚动
     */
    useVirtual: PropTypes.bool,

    /**
     * 设置行高
     */
    rowHeight: PropTypes.oneOfType([PropTypes.number, PropTypes.func]),
    maxBodyHeight: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
    primaryKey: PropTypes.string,
    dataSource: PropTypes.array,

    /**
     * 在内容区域滚动的时候触发的函数
     */
    onBodyScroll: PropTypes.func
  }, BaseComponent.propTypes));

  _defineProperty(VirtualTable, "defaultProps", _objectSpread({}, BaseComponent.defaultProps, {
    primaryKey: 'id',
    rowHeight: noop,
    maxBodyHeight: 200,
    components: {},
    prefix: 'next-',
    onBodyScroll: noop
  }));

  _defineProperty(VirtualTable, "childContextTypes", {
    onVirtualScroll: PropTypes.func,
    bodyHeight: PropTypes.number,
    innerTop: PropTypes.number,
    getBodyNode: PropTypes.func,
    getTableInstanceForVirtual: PropTypes.func,
    rowSelection: PropTypes.object
  });

  statics(VirtualTable, BaseComponent);
  return VirtualTable;
}