import _extends from "@babel/runtime/helpers/extends";
import _defineProperty from "@babel/runtime/helpers/defineProperty";
import _toConsumableArray from "@babel/runtime/helpers/toConsumableArray";
import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties";
import _typeof from "@babel/runtime/helpers/typeof";
import _objectSpread from "@babel/runtime/helpers/objectSpread2";
import _classCallCheck from "@babel/runtime/helpers/classCallCheck";
import _createClass from "@babel/runtime/helpers/createClass";
import _assertThisInitialized from "@babel/runtime/helpers/assertThisInitialized";
import _inherits from "@babel/runtime/helpers/inherits";
import _createSuper from "@babel/runtime/helpers/createSuper";
var _excluded = ["pageSize"],
    _excluded2 = ["bordered", "split", "className", "children", "itemLayout", "loadMore", "pagination", "grid", "dataSource", "size", "header", "footer", "empty", "loading", "rowPrefixCls", "spinPrefixCls", "dataSet"];
import { __decorate } from "tslib"; // @ts-nocheck

import React, { Children, cloneElement, Component } from 'react';
import classNames from 'classnames';
import { action, observable, runInAction } from 'mobx';
import { observer } from 'mobx-react';
import omit from 'lodash/omit';
import noop from 'lodash/noop';
import Pagination from '../../pro/es/pagination';
import ObserverCheckBox from '../../pro/es/check-box';
import autobind from '../../pro/es/_util/autobind';
import { BooleanValue, DataSetEvents } from '../../pro/es/data-set/enum';
import { getKey } from '../../pro/es/tree/util';
import Spin from '../spin';
import LocaleReceiver from '../locale-provider/LocaleReceiver';
import defaultLocale from '../locale-provider/default';
import { Size } from '../_util/enum';
import { Row } from '../grid';
import Item from './Item';
import { ListContextProvider } from './ListContext';
import ConfigContext from '../config-provider/ConfigContext';

var List = /*#__PURE__*/function (_Component) {
  _inherits(List, _Component);

  var _super = _createSuper(List);

  function List() {
    var _this;

    _classCallCheck(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 = _assertThisInitialized(_this),
          props = _assertThisInitialize.props;

      var locale = _objectSpread(_objectSpread({}, contextLocale), props.locale);

      return /*#__PURE__*/React.createElement("div", {
        className: "".concat(_this.getPrefixCls(), "-empty-text")
      }, locale.emptyText);
    };

    return _this;
  }

  _createClass(List, [{
    key: "rowSelectionKeys",
    get: function get() {
      var rowSelection = this.props.rowSelection;

      if (rowSelection && _typeof(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 = getKey(record, primaryKey);

            if (record.get(checkField) === (field ? field.get(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 = _objectWithoutProperties(_this$defaultPaginati, _excluded);

      var paginationProps = _objectSpread(_objectSpread(_objectSpread({}, 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);
      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, 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(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(_toConsumableArray(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 (getKey(record, primaryKey) === key) {
            if (!record.isSelected) {
              dataSet.select(record);
            } else {
              dataSet.unSelect(record);
            }
          }
        });
        return;
      }

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

          if (selectedRowKeys) {
            if (value && !selectedRowKeys.includes(key)) {
              resultKeys = [].concat(_toConsumableArray(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.createElement("div", {
              className: "".concat(_this3.getPrefixCls(), "-selection-checkbox")
            }, /*#__PURE__*/React.createElement(ObserverCheckBox, {
              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 : _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 = _objectWithoutProperties(_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 Size.large:
          sizeCls = 'lg';
          break;

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

        default:
      }

      var classString = classNames(prefixCls, className, (_classNames = {}, _defineProperty(_classNames, "".concat(prefixCls, "-vertical"), itemLayout === 'vertical'), _defineProperty(_classNames, "".concat(prefixCls, "-").concat(sizeCls), sizeCls), _defineProperty(_classNames, "".concat(prefixCls, "-split"), split), _defineProperty(_classNames, "".concat(prefixCls, "-bordered"), bordered), _defineProperty(_classNames, "".concat(prefixCls, "-loading"), isLoading), _defineProperty(_classNames, "".concat(prefixCls, "-grid"), grid), _defineProperty(_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.createElement("div", {
        className: "".concat(prefixCls, "-pagination")
      }, /*#__PURE__*/React.createElement(Pagination, _extends({}, this.paginationProps, {
        onChange: onChange,
        dataSet: isDsPagination ? dataSet : undefined
      }))) : null;
      var splitDataSource = dataSet ? dataSet.records : _toConsumableArray(dataSource);

      if (pagination && pageSize) {
        if (!dataSet && dataSource.length > (page - 1) * pageSize) {
          splitDataSource = _toConsumableArray(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.createElement("div", {
        style: {
          minHeight: 53
        }
      });

      if (splitDataSource.length > 0) {
        var items = splitDataSource.map(function (item, index) {
          return _this4.renderItem(item, index);
        });
        var childrenList = Children.map(items, function (child, index) {
          var recordKey = _this4.keys[index];
          return /*#__PURE__*/cloneElement(child, {
            key: recordKey,
            renderCheckBox: _this4.renderCheckBox(recordKey)
          });
        });
        childrenContent = grid ? /*#__PURE__*/React.createElement(Row, {
          prefixCls: rowPrefixCls,
          gutter: grid.gutter
        }, childrenList) : childrenList;
      } else if (!children && !isLoading && !empty) {
        childrenContent = /*#__PURE__*/React.createElement(LocaleReceiver, {
          componentName: "Table",
          defaultLocale: defaultLocale.Table
        }, this.renderEmpty);
      } else {
        childrenContent = empty;
      }

      var paginationPosition = position || 'bottom';
      var content = /*#__PURE__*/React.createElement(Spin, _extends({
        prefixCls: spinPrefixCls
      }, loadingProp), childrenContent, children);
      return /*#__PURE__*/React.createElement(ListContextProvider, _extends({}, this.getContextValue()), /*#__PURE__*/React.createElement("div", _extends({
        className: classString
      }, omit(rest, ['prefixCls', 'rowKey', 'renderItem', 'selectable', 'renderItem', 'locale', 'rowSelection'])), (paginationPosition === 'top' || paginationPosition === 'both') && paginationContent, header && /*#__PURE__*/React.createElement("div", {
        className: "".concat(prefixCls, "-header")
      }, header), content, footer && /*#__PURE__*/React.createElement("div", {
        className: "".concat(prefixCls, "-footer")
      }, footer), loadMore || (paginationPosition === 'bottom' || paginationPosition === 'both') && paginationContent));
    }
  }], [{
    key: "contextType",
    get: function get() {
      return ConfigContext;
    }
  }]);

  return List;
}(Component);

List.displayName = 'List';
List.Item = Item;
List.defaultProps = {
  dataSource: [],
  bordered: false,
  split: true,
  loading: false,
  pagination: false
};

__decorate([observable], List.prototype, "stateCheckedKeys", void 0);

__decorate([observable], List.prototype, "paginationCurrent", void 0);

__decorate([autobind], List.prototype, "handleDataSetLoad", null);

__decorate([action], List.prototype, "initDefaultCheckRows", null);

__decorate([action], List.prototype, "updateStateKey", null);

List = __decorate([observer], List);
export default List;
//# sourceMappingURL=index.js.map
