"use strict";

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

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

var _propTypes = _interopRequireDefault(require("prop-types"));

var _checkbox = _interopRequireDefault(require("../checkbox"));

var _radio = _interopRequireDefault(require("../radio"));

var _util = require("../util");

var _zhCn = _interopRequireDefault(require("../locale/zh-cn"));

var _row = _interopRequireDefault(require("./selection/row"));

var _column = _interopRequireDefault(require("./column"));

var _util2 = require("./util");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { "default": obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj["default"] = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

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 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 _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); }

function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); }

function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); }

function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } }

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

var makeChain = _util.func.makeChain;

var unique = function unique(arr) {
  var key = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'this';
  var temp = {};
  var ret = [];
  arr.forEach(function (item) {
    var value;

    if (key === 'this') {
      value = item;
    } else {
      value = item[key];
    }

    if (!temp[value]) {
      ret.push(item);
      temp[value] = true;
    }
  });
  return ret;
};

function selection(BaseComponent) {
  /** Table */
  var SelectionTable =
  /*#__PURE__*/
  function (_React$Component) {
    _inherits(SelectionTable, _React$Component);

    function SelectionTable(props, context) {
      var _this;

      _classCallCheck(this, SelectionTable);

      _this = _possibleConstructorReturn(this, _getPrototypeOf(SelectionTable).call(this, props, context));

      _defineProperty(_assertThisInitialized(_this), "normalizeChildren", function (children) {
        var _this$props = _this.props,
            prefix = _this$props.prefix,
            rowSelection = _this$props.rowSelection;

        if (rowSelection) {
          children = _react.Children.map(children, function (child, index) {
            return _react["default"].cloneElement(child, {
              key: index
            });
          });
          var attrs = rowSelection.columnProps && rowSelection.columnProps() || {};
          children.unshift(_react["default"].createElement(_column["default"], _extends({
            key: "selection",
            title: _this.renderSelectionHeader,
            cell: _this.renderSelectionBody,
            width: 44,
            className: "".concat(prefix, "table-selection"),
            __normalized: true
          }, attrs)));
          return children;
        }

        return children;
      });

      _defineProperty(_assertThisInitialized(_this), "renderSelectionHeader", function () {
        var onChange = _this.selectAllRow;
        var attrs = {};
        var _this$props2 = _this.props,
            rowSelection = _this$props2.rowSelection,
            primaryKey = _this$props2.primaryKey,
            dataSource = _this$props2.dataSource,
            entireDataSource = _this$props2.entireDataSource,
            locale = _this$props2.locale;
        var selectedRowKeys = _this.state.selectedRowKeys;
        var mode = rowSelection.mode ? rowSelection.mode : 'multiple';
        var checked = !!selectedRowKeys.length;
        var indeterminate = false;
        var source = entireDataSource || dataSource;

        _this.flatDataSource(source).filter(function (record, index) {
          if (!rowSelection.getProps) {
            return true;
          } else {
            return !(rowSelection.getProps(record, index) || {}).disabled;
          }
        }).map(function (record) {
          return record[primaryKey];
        }).forEach(function (id) {
          if (selectedRowKeys.indexOf(id) === -1) {
            checked = false;
          } else {
            indeterminate = true;
          }
        });

        attrs.onClick = makeChain(function (e) {
          e.stopPropagation();
        }, attrs.onClick);
        var userAttrs = rowSelection.titleProps && rowSelection.titleProps() || {};

        if (checked) {
          indeterminate = false;
        }

        return [mode === 'multiple' ? _react["default"].createElement(_checkbox["default"], _extends({
          key: "_total",
          indeterminate: indeterminate,
          "aria-label": locale.selectAll,
          checked: checked,
          onChange: onChange
        }, attrs, userAttrs)) : null, rowSelection.titleAddons && rowSelection.titleAddons()];
      });

      _defineProperty(_assertThisInitialized(_this), "renderSelectionBody", function (value, index, record) {
        var _this$props3 = _this.props,
            rowSelection = _this$props3.rowSelection,
            primaryKey = _this$props3.primaryKey;
        var selectedRowKeys = _this.state.selectedRowKeys;
        var mode = rowSelection.mode ? rowSelection.mode : 'multiple';
        var checked = selectedRowKeys.indexOf(record[primaryKey]) > -1;

        var onChange = _this.selectOneRow.bind(_assertThisInitialized(_this), index, record);

        var attrs = rowSelection.getProps ? rowSelection.getProps(record, index) || {} : {};
        attrs.onClick = makeChain(function (e) {
          e.stopPropagation();
        }, attrs.onClick);
        return mode === 'multiple' ? _react["default"].createElement(_checkbox["default"], _extends({
          checked: checked,
          onChange: onChange
        }, attrs)) : _react["default"].createElement(_radio["default"], _extends({
          checked: checked,
          onChange: onChange
        }, attrs));
      });

      _defineProperty(_assertThisInitialized(_this), "selectAllRow", function (checked, e) {
        var ret = _toConsumableArray(_this.state.selectedRowKeys);

        var _this$props4 = _this.props,
            rowSelection = _this$props4.rowSelection,
            primaryKey = _this$props4.primaryKey,
            dataSource = _this$props4.dataSource,
            entireDataSource = _this$props4.entireDataSource;
        var selectedRowKeys = _this.state.selectedRowKeys;
        var getProps = rowSelection.getProps;
        var attrs = {};
        var records = [];
        var source = entireDataSource || dataSource;

        _this.flatDataSource(source).forEach(function (record, index) {
          var id = record[primaryKey];

          if (getProps) {
            attrs = getProps(record, index) || {};
          } // 反选和全选的时候不要丢弃禁用项的选中状态


          if (checked && (!attrs.disabled || selectedRowKeys.indexOf(id) > -1)) {
            ret.push(id);
            records.push(record);
          } else if (attrs.disabled && selectedRowKeys.indexOf(id) > -1) {
            ret.push(id);
            records.push(record);
          } else {
            var i = ret.indexOf(id);
            i > -1 && ret.splice(i, 1);
          }
        });

        records = unique(records, primaryKey);

        if (typeof rowSelection.onSelectAll === 'function') {
          rowSelection.onSelectAll(checked, records);
        }

        _this.triggerSelection(rowSelection, unique(ret), records);

        e.stopPropagation();
      });

      _defineProperty(_assertThisInitialized(_this), "selectOneRow", function (index, record, checked, e) {
        var selectedRowKeys = _toConsumableArray(_this.state.selectedRowKeys);

        var i;
        var _this$props5 = _this.props,
            primaryKey = _this$props5.primaryKey,
            rowSelection = _this$props5.rowSelection,
            dataSource = _this$props5.dataSource;
        var mode = rowSelection.mode ? rowSelection.mode : 'multiple';
        var id = record[primaryKey];

        if (!id) {
          _util.log.warning("Can't get value from record using given ".concat(primaryKey, " as primaryKey."));
        }

        if (mode === 'multiple') {
          if (checked) {
            selectedRowKeys.push(id);
          } else {
            i = selectedRowKeys.indexOf(id);
            selectedRowKeys.splice(i, 1);
          }
        } else if (checked) {
          selectedRowKeys = [id];
        }

        var records = unique(dataSource.filter(function (item) {
          return selectedRowKeys.indexOf(item[primaryKey]) > -1;
        }), primaryKey);

        if (typeof rowSelection.onSelect === 'function') {
          rowSelection.onSelect(checked, record, records);
        }

        _this.triggerSelection(rowSelection, selectedRowKeys, records);

        e.stopPropagation();
      });

      _defineProperty(_assertThisInitialized(_this), "triggerSelection", function (rowSelection, selectedRowKeys, records) {
        if (!('selectedRowKeys' in rowSelection)) {
          _this.setState({
            selectedRowKeys: selectedRowKeys
          });
        }

        if (typeof rowSelection.onChange === 'function') {
          rowSelection.onChange(selectedRowKeys, records);
        }
      });

      _defineProperty(_assertThisInitialized(_this), "flatDataSource", function (dataSource) {
        var ret = dataSource;
        var listHeader = _this.context.listHeader;

        if (listHeader) {
          ret = [];
          var hasChildrenSelection = listHeader.hasChildrenSelection,
              hasSelection = listHeader.hasSelection;
          dataSource.forEach(function (item) {
            var children = item.children; // 如果需要渲染selection才将这条记录插入到dataSource
            // 或者没有孩子节点

            if (hasSelection) {
              ret.push(item);
            }

            if (children && hasChildrenSelection) {
              ret = ret.concat(children);
            }
          });
        }

        return ret;
      });

      _this.state = {
        selectedRowKeys: props.rowSelection && 'selectedRowKeys' in props.rowSelection ? props.rowSelection.selectedRowKeys || [] : []
      };
      return _this;
    }

    _createClass(SelectionTable, [{
      key: "getChildContext",
      value: function getChildContext() {
        return {
          rowSelection: this.props.rowSelection,
          selectedRowKeys: this.state.selectedRowKeys
        };
      }
    }, {
      key: "UNSAFE_componentWillReceiveProps",
      value: function UNSAFE_componentWillReceiveProps(nextProps) {
        if (nextProps.rowSelection && 'selectedRowKeys' in nextProps.rowSelection) {
          var selectedRowKeys = nextProps.rowSelection.selectedRowKeys || [];
          this.setState({
            selectedRowKeys: selectedRowKeys
          });
        }
      }
    }, {
      key: "render",
      value: function render() {
        /* eslint-disable prefer-const */
        var _this$props6 = this.props,
            rowSelection = _this$props6.rowSelection,
            components = _this$props6.components,
            children = _this$props6.children,
            others = _objectWithoutProperties(_this$props6, ["rowSelection", "components", "children"]);

        if (rowSelection) {
          children = this.normalizeChildren(children);
          components = _objectSpread({}, components);
          components.Row = components.Row || _row["default"];
        }

        return _react["default"].createElement(BaseComponent, _extends({}, others, {
          components: components
        }), children);
      }
    }]);

    return SelectionTable;
  }(_react["default"].Component);

  _defineProperty(SelectionTable, "SelectionRow", _row["default"]);

  _defineProperty(SelectionTable, "propTypes", _objectSpread({
    /**
     * 是否启用选择模式
     * @property {Function} getProps `Function(record, index)=>Object` 获取selection的默认属性
     * @property {Function} onChange `Function(selectedRowKeys:Array, records:Array)` 选择改变的时候触发的事件，**注意:** 其中records只会包含当前dataSource的数据，很可能会小于selectedRowKeys的长度。
     * @property {Function} onSelect `Function(selected:Boolean, record:Object, records:Array)` 用户手动选择/取消选择某行的回调
     * @property {Function} onSelectAll `Function(selected:Boolean, records:Array)` 用户手动选择/取消选择所有行的回调
     * @property {Array} selectedRowKeys 设置了此属性,将rowSelection变为受控状态,接收值为该行数据的primaryKey的值
     * @property {String} mode 选择selection的模式, 可选值为`single`, `multiple`，默认为`multiple`
     * @property {Function} columnProps `Function()=>Object` 选择列 的props，例如锁列、对齐等，可使用`Table.Column` 的所有参数
     * @property {Function} titleProps `Function()=>Object` 选择列 表头的props，仅在 `multiple` 模式下生效
     * @property {Function} titleAddons `Function()=>Node` 选择列 表头添加的元素，在`single` `multiple` 下都生效
     */
    rowSelection: _propTypes["default"].object,
    primaryKey: _propTypes["default"].string,
    dataSource: _propTypes["default"].array,
    entireDataSource: _propTypes["default"].array
  }, BaseComponent.propTypes));

  _defineProperty(SelectionTable, "defaultProps", _objectSpread({}, BaseComponent.defaultProps, {
    locale: _zhCn["default"].Table,
    primaryKey: 'id',
    prefix: 'next-'
  }));

  _defineProperty(SelectionTable, "contextTypes", {
    listHeader: _propTypes["default"].any
  });

  _defineProperty(SelectionTable, "childContextTypes", {
    rowSelection: _propTypes["default"].object,
    selectedRowKeys: _propTypes["default"].array
  });

  (0, _util2.statics)(SelectionTable, BaseComponent);
  return SelectionTable;
}