"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault")["default"];

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard")["default"];

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;

var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));

var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));

var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));

var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));

var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof"));

var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));

var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));

var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));

var _assertThisInitialized2 = _interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized"));

var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));

var _createSuper2 = _interopRequireDefault(require("@babel/runtime/helpers/createSuper"));

var _tslib = require("tslib");

var _react = _interopRequireWildcard(require("react"));

var _classnames = _interopRequireDefault(require("classnames"));

var _mobx = require("mobx");

var _mobxReact = require("mobx-react");

var _omit = _interopRequireDefault(require("lodash/omit"));

var _noop = _interopRequireDefault(require("lodash/noop"));

var _pagination = _interopRequireDefault(require("../../pro/lib/pagination"));

var _checkBox = _interopRequireDefault(require("../../pro/lib/check-box"));

var _autobind = _interopRequireDefault(require("../../pro/lib/_util/autobind"));

var _enum = require("../../pro/lib/data-set/enum");

var _util = require("../../pro/lib/tree/util");

var _spin = _interopRequireDefault(require("../spin"));

var _LocaleReceiver = _interopRequireDefault(require("../locale-provider/LocaleReceiver"));

var _default2 = _interopRequireDefault(require("../locale-provider/default"));

var _enum2 = require("../_util/enum");

var _grid = require("../grid");

var _Item = _interopRequireDefault(require("./Item"));

var _ListContext = require("./ListContext");

var _ConfigContext = _interopRequireDefault(require("../config-provider/ConfigContext"));

var _excluded = ["pageSize"],
    _excluded2 = ["bordered", "split", "className", "children", "itemLayout", "loadMore", "pagination", "grid", "dataSource", "size", "header", "footer", "empty", "loading", "rowPrefixCls", "spinPrefixCls", "dataSet"];

var List = /*#__PURE__*/function (_Component) {
  (0, _inherits2["default"])(List, _Component);

  var _super = (0, _createSuper2["default"])(List);

  function List() {
    var _this;

    (0, _classCallCheck2["default"])(this, List);
    _this = _super.apply(this, arguments);
    _this.defaultPaginationProps = {
      page: 1,
      pageSize: 10,
      onChange: function onChange(page, pageSize) {
        var pagination = _this.props.pagination;
        _this.paginationCurrent = page;

        if (pagination && pagination.onChange) {
          pagination.onChange(page, pageSize);
        }
      },
      total: 0
    };
    _this.keys = {};

    _this.renderItem = function (item, index) {
      var _this$props = _this.props,
          renderItem = _this$props.renderItem,
          rowKey = _this$props.rowKey,
          dataSet = _this$props.dataSet;
      var key;

      if (typeof rowKey === 'function') {
        key = rowKey(item);
      } else if (typeof rowKey === 'string') {
        key = dataSet ? item.get(rowKey) : item[rowKey];
      } else {
        key = item.key;
      }

      if (!key) {
        key = "list-item-".concat(index);
      }

      _this.keys[index] = key;

      if (dataSet) {
        return renderItem({
          dataSet: dataSet,
          record: item,
          index: dataSet.indexOf(item)
        });
      }

      return renderItem(item, index);
    };

    _this.renderEmpty = function (contextLocale) {
      var _assertThisInitialize = (0, _assertThisInitialized2["default"])(_this),
          props = _assertThisInitialize.props;

      var locale = (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, contextLocale), props.locale);
      return /*#__PURE__*/_react["default"].createElement("div", {
        className: "".concat(_this.getPrefixCls(), "-empty-text")
      }, locale.emptyText);
    };

    return _this;
  }

  (0, _createClass2["default"])(List, [{
    key: "rowSelectionKeys",
    get: function get() {
      var rowSelection = this.props.rowSelection;

      if (rowSelection && (0, _typeof2["default"])(rowSelection) === 'object') {
        var selectedRowKeys = rowSelection.selectedRowKeys,
            defaultSelectedRowKeys = rowSelection.defaultSelectedRowKeys;
        return selectedRowKeys || defaultSelectedRowKeys;
      }
    }
  }, {
    key: "checkedKeys",
    get: function get() {
      var dataSet = this.props.dataSet;

      if (dataSet) {
        var _dataSet$props = dataSet.props,
            checkField = _dataSet$props.checkField,
            primaryKey = _dataSet$props.primaryKey;

        if (checkField) {
          var keys = [];
          var field = dataSet.getField(checkField);
          dataSet.forEach(function (record) {
            var key = (0, _util.getKey)(record, primaryKey);

            if (record.get(checkField) === (field ? field.get(_enum.BooleanValue.trueValue, record) : true)) {
              keys.push(key);
            }
          });
          return keys;
        }

        return dataSet.selected.map(function (selected) {
          return String(primaryKey ? selected.get(primaryKey) : selected.id);
        });
      }

      return this.rowSelectionKeys || this.stateCheckedKeys || [];
    }
  }, {
    key: "paginationProps",
    get: function get() {
      var _this$props2 = this.props,
          dataSet = _this$props2.dataSet,
          dataSource = _this$props2.dataSource,
          pagination = _this$props2.pagination;
      var _this$defaultPaginati = this.defaultPaginationProps,
          pageSize = _this$defaultPaginati.pageSize,
          otherProps = (0, _objectWithoutProperties2["default"])(_this$defaultPaginati, _excluded);
      var paginationProps = (0, _objectSpread2["default"])((0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, otherProps), pagination || {}), {}, {
        total: dataSet ? dataSet.totalCount : dataSource.length,
        page: dataSet && dataSet.paging ? dataSet.currentPage : this.paginationCurrent || 1,
        pageSize: dataSet && dataSet.paging ? dataSet.pageSize : pagination && pagination.pageSize || pageSize
      });
      return paginationProps;
    }
  }, {
    key: "componentWillMount",
    value: function componentWillMount() {
      var _this2 = this;

      this.handleDataSetLoad();
      this.processDataSetListener(true);
      (0, _mobx.runInAction)(function () {
        _this2.stateCheckedKeys = [];
      });
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      this.processDataSetListener(false);
    }
  }, {
    key: "handleDataSetLoad",
    value: function handleDataSetLoad() {
      this.initDefaultCheckRows();
    }
  }, {
    key: "processDataSetListener",
    value: function processDataSetListener(flag) {
      var dataSet = this.props.dataSet;

      if (dataSet) {
        var handler = flag ? dataSet.addEventListener : dataSet.removeEventListener;
        handler.call(dataSet, _enum.DataSetEvents.load, this.handleDataSetLoad);
      }
    }
  }, {
    key: "initDefaultCheckRows",
    value: function initDefaultCheckRows() {
      var dataSet = this.props.dataSet;

      if (dataSet && dataSet.selection) {
        var checkField = dataSet.props.checkField;

        if (checkField) {
          var field = dataSet.getField(checkField);
          dataSet.forEach(function (record) {
            if (record.get(checkField) === (field ? field.get(_enum.BooleanValue.trueValue, record) : true)) {
              record.isSelected = true;
            }
          });
        }
      }
    }
  }, {
    key: "getContextValue",
    value: function getContextValue() {
      var grid = this.props.grid;
      var getPrefixCls = this.context.getPrefixCls;
      return {
        grid: grid,
        getPrefixCls: getPrefixCls
      };
    }
  }, {
    key: "isSomethingAfterLastItem",
    value: function isSomethingAfterLastItem() {
      var _this$props3 = this.props,
          loadMore = _this$props3.loadMore,
          pagination = _this$props3.pagination,
          footer = _this$props3.footer;
      return !!(loadMore || pagination || footer);
    }
  }, {
    key: "getPrefixCls",
    value: function getPrefixCls() {
      var prefixCls = this.props.prefixCls;
      var getPrefixCls = this.context.getPrefixCls;
      return getPrefixCls('list', prefixCls);
    }
  }, {
    key: "updateStateKey",
    value: function updateStateKey(value, key) {
      if (value && !this.stateCheckedKeys.includes(key)) {
        this.stateCheckedKeys = [].concat((0, _toConsumableArray2["default"])(this.stateCheckedKeys), [key]);
      } else if (!value) {
        this.stateCheckedKeys = this.stateCheckedKeys.filter(function (x) {
          return x !== key;
        });
      }

      return this.stateCheckedKeys;
    }
  }, {
    key: "handleChange",
    value: function handleChange(value, key) {
      var _this$props4 = this.props,
          rowSelection = _this$props4.rowSelection,
          dataSet = _this$props4.dataSet;

      if (dataSet && dataSet.selection) {
        var primaryKey = dataSet.props.primaryKey;
        dataSet.forEach(function (record) {
          if ((0, _util.getKey)(record, primaryKey) === key) {
            if (!record.isSelected) {
              dataSet.select(record);
            } else {
              dataSet.unSelect(record);
            }
          }
        });
        return;
      }

      if (rowSelection) {
        if ((0, _typeof2["default"])(rowSelection) === 'object') {
          var selectedRowKeys = rowSelection.selectedRowKeys,
              _rowSelection$onChang = rowSelection.onChange,
              onChange = _rowSelection$onChang === void 0 ? _noop["default"] : _rowSelection$onChang;
          var resultKeys = [];

          if (selectedRowKeys) {
            if (value && !selectedRowKeys.includes(key)) {
              resultKeys = [].concat((0, _toConsumableArray2["default"])(selectedRowKeys), [key]);
            } else if (!value) {
              resultKeys = selectedRowKeys.filter(function (x) {
                return x !== key;
              });
            }

            onChange(resultKeys);
            return;
          }

          var newKeys = this.updateStateKey(value, key);
          onChange(newKeys);
        } else if (typeof rowSelection === 'boolean') {
          this.updateStateKey(value, key);
        }
      }
    }
  }, {
    key: "renderCheckBox",
    value: function renderCheckBox(key) {
      var _this3 = this;

      var _this$props5 = this.props,
          rowSelection = _this$props5.rowSelection,
          dataSet = _this$props5.dataSet;

      var checkboxWrapper = function checkboxWrapper() {
        var isChecked = _this3.checkedKeys.includes(key);

        return {
          element: function element() {
            return /*#__PURE__*/_react["default"].createElement("div", {
              className: "".concat(_this3.getPrefixCls(), "-selection-checkbox")
            }, /*#__PURE__*/_react["default"].createElement(_checkBox["default"], {
              name: "ckBox",
              value: key,
              onChange: function onChange(val) {
                return _this3.handleChange(val, key);
              },
              checked: isChecked
            }));
          },
          isChecked: isChecked
        };
      };

      if (dataSet) {
        if (dataSet.selection) {
          return checkboxWrapper();
        }

        return undefined;
      }

      if (rowSelection) {
        return checkboxWrapper();
      }

      return undefined;
    }
  }, {
    key: "render",
    value: function render() {
      var _classNames,
          _this4 = this;

      var _this$paginationProps = this.paginationProps,
          pageSize = _this$paginationProps.pageSize,
          page = _this$paginationProps.page,
          total = _this$paginationProps.total,
          position = _this$paginationProps.position,
          _this$paginationProps2 = _this$paginationProps.onChange,
          onChange = _this$paginationProps2 === void 0 ? _noop["default"] : _this$paginationProps2,
          _this$props6 = this.props,
          bordered = _this$props6.bordered,
          split = _this$props6.split,
          className = _this$props6.className,
          children = _this$props6.children,
          itemLayout = _this$props6.itemLayout,
          loadMore = _this$props6.loadMore,
          pagination = _this$props6.pagination,
          grid = _this$props6.grid,
          dataSource = _this$props6.dataSource,
          size = _this$props6.size,
          header = _this$props6.header,
          footer = _this$props6.footer,
          empty = _this$props6.empty,
          loading = _this$props6.loading,
          rowPrefixCls = _this$props6.rowPrefixCls,
          spinPrefixCls = _this$props6.spinPrefixCls,
          dataSet = _this$props6.dataSet,
          rest = (0, _objectWithoutProperties2["default"])(_this$props6, _excluded2);
      var prefixCls = this.getPrefixCls();
      var loadingProp = loading;

      if (typeof loadingProp === 'boolean') {
        loadingProp = {
          spinning: loadingProp
        };
      }

      var isLoading = loadingProp && loadingProp.spinning; // large => lg
      // small => sm

      var sizeCls = '';

      switch (size) {
        case _enum2.Size.large:
          sizeCls = 'lg';
          break;

        case _enum2.Size.small:
          sizeCls = 'sm';
          break;

        default:
      }

      var classString = (0, _classnames["default"])(prefixCls, className, (_classNames = {}, (0, _defineProperty2["default"])(_classNames, "".concat(prefixCls, "-vertical"), itemLayout === 'vertical'), (0, _defineProperty2["default"])(_classNames, "".concat(prefixCls, "-").concat(sizeCls), sizeCls), (0, _defineProperty2["default"])(_classNames, "".concat(prefixCls, "-split"), split), (0, _defineProperty2["default"])(_classNames, "".concat(prefixCls, "-bordered"), bordered), (0, _defineProperty2["default"])(_classNames, "".concat(prefixCls, "-loading"), isLoading), (0, _defineProperty2["default"])(_classNames, "".concat(prefixCls, "-grid"), grid), (0, _defineProperty2["default"])(_classNames, "".concat(prefixCls, "-something-after-last-item"), this.isSomethingAfterLastItem()), _classNames));
      var largestPage = Math.ceil(total / pageSize);

      if (page > largestPage) {
        this.paginationProps.page = largestPage;
      }

      var isDsPagination = dataSet && dataSet.paging;
      var paginationContent = pagination ? /*#__PURE__*/_react["default"].createElement("div", {
        className: "".concat(prefixCls, "-pagination")
      }, /*#__PURE__*/_react["default"].createElement(_pagination["default"], (0, _extends2["default"])({}, this.paginationProps, {
        onChange: onChange,
        dataSet: isDsPagination ? dataSet : undefined
      }))) : null;
      var splitDataSource = dataSet ? dataSet.records : (0, _toConsumableArray2["default"])(dataSource);

      if (pagination && pageSize) {
        if (!dataSet && dataSource.length > (page - 1) * pageSize) {
          splitDataSource = (0, _toConsumableArray2["default"])(dataSource).splice((page - 1) * pageSize, pageSize);
        } else if (dataSet && !dataSet.paging) {
          splitDataSource = dataSet.slice((page - 1) * pageSize, pageSize * page);
        }
      }

      var childrenContent;
      childrenContent = isLoading && /*#__PURE__*/_react["default"].createElement("div", {
        style: {
          minHeight: 53
        }
      });

      if (splitDataSource.length > 0) {
        var items = splitDataSource.map(function (item, index) {
          return _this4.renderItem(item, index);
        });

        var childrenList = _react.Children.map(items, function (child, index) {
          var recordKey = _this4.keys[index];
          return /*#__PURE__*/(0, _react.cloneElement)(child, {
            key: recordKey,
            renderCheckBox: _this4.renderCheckBox(recordKey)
          });
        });

        childrenContent = grid ? /*#__PURE__*/_react["default"].createElement(_grid.Row, {
          prefixCls: rowPrefixCls,
          gutter: grid.gutter
        }, childrenList) : childrenList;
      } else if (!children && !isLoading && !empty) {
        childrenContent = /*#__PURE__*/_react["default"].createElement(_LocaleReceiver["default"], {
          componentName: "Table",
          defaultLocale: _default2["default"].Table
        }, this.renderEmpty);
      } else {
        childrenContent = empty;
      }

      var paginationPosition = position || 'bottom';

      var content = /*#__PURE__*/_react["default"].createElement(_spin["default"], (0, _extends2["default"])({
        prefixCls: spinPrefixCls
      }, loadingProp), childrenContent, children);

      return /*#__PURE__*/_react["default"].createElement(_ListContext.ListContextProvider, (0, _extends2["default"])({}, this.getContextValue()), /*#__PURE__*/_react["default"].createElement("div", (0, _extends2["default"])({
        className: classString
      }, (0, _omit["default"])(rest, ['prefixCls', 'rowKey', 'renderItem', 'selectable', 'renderItem', 'locale', 'rowSelection'])), (paginationPosition === 'top' || paginationPosition === 'both') && paginationContent, header && /*#__PURE__*/_react["default"].createElement("div", {
        className: "".concat(prefixCls, "-header")
      }, header), content, footer && /*#__PURE__*/_react["default"].createElement("div", {
        className: "".concat(prefixCls, "-footer")
      }, footer), loadMore || (paginationPosition === 'bottom' || paginationPosition === 'both') && paginationContent));
    }
  }], [{
    key: "contextType",
    get: function get() {
      return _ConfigContext["default"];
    }
  }]);
  return List;
}(_react.Component);

List.displayName = 'List';
List.Item = _Item["default"];
List.defaultProps = {
  dataSource: [],
  bordered: false,
  split: true,
  loading: false,
  pagination: false
};
(0, _tslib.__decorate)([_mobx.observable], List.prototype, "stateCheckedKeys", void 0);
(0, _tslib.__decorate)([_mobx.observable], List.prototype, "paginationCurrent", void 0);
(0, _tslib.__decorate)([_autobind["default"]], List.prototype, "handleDataSetLoad", null);
(0, _tslib.__decorate)([_mobx.action], List.prototype, "initDefaultCheckRows", null);
(0, _tslib.__decorate)([_mobx.action], List.prototype, "updateStateKey", null);
List = (0, _tslib.__decorate)([_mobxReact.observer], List);
var _default = List;
exports["default"] = _default;
//# sourceMappingURL=index.js.map
