"use strict";

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

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

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

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

var _cell = _interopRequireDefault(require("./tree/cell"));

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

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

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 _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 _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 noop = function noop() {};

function tree(BaseComponent) {
  var TreeTable =
  /*#__PURE__*/
  function (_React$Component) {
    _inherits(TreeTable, _React$Component);

    function TreeTable(props, context) {
      var _this;

      _classCallCheck(this, TreeTable);

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

      _defineProperty(_assertThisInitialized(_this), "onTreeNodeClick", function (record) {
        var primaryKey = _this.props.primaryKey;
        var id = record[primaryKey];
        var dataSource = _this.ds;

        var openRowKeys = _toConsumableArray(_this.state.openRowKeys);

        var index = openRowKeys.indexOf(id);

        var getChildrenKeyById = function getChildrenKeyById(id) {
          var ret = [id];

          var loop = function loop(data) {
            data.forEach(function (item) {
              ret.push(item[primaryKey]);

              if (item.children) {
                loop(item.children);
              }
            });
          };

          dataSource.forEach(function (item) {
            if (item[primaryKey] === id) {
              if (item.children) {
                loop(item.children);
              }
            }
          });
          return ret;
        };

        if (index > -1) {
          // 不仅要删除当前的openRowKey，还需要删除关联子节点的openRowKey
          var ids = getChildrenKeyById(id);
          ids.forEach(function (id) {
            var i = openRowKeys.indexOf(id);

            if (i > -1) {
              openRowKeys.splice(i, 1);
            }
          });
        } else {
          openRowKeys.push(id);
        }

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

        _this.props.onRowOpen(openRowKeys, id, index === -1, record);
      });

      _this.state = {
        openRowKeys: props.openRowKeys || []
      };
      return _this;
    }

    _createClass(TreeTable, [{
      key: "getChildContext",
      value: function getChildContext() {
        return {
          openTreeRowKeys: this.state.openRowKeys,
          indent: this.props.indent,
          treeStatus: this.getTreeNodeStatus(this.ds),
          onTreeNodeClick: this.onTreeNodeClick,
          isTree: this.props.isTree
        };
      }
    }, {
      key: "UNSAFE_componentWillReceiveProps",
      value: function UNSAFE_componentWillReceiveProps(nextProps) {
        if ('openRowKeys' in nextProps) {
          var openRowKeys = nextProps.openRowKeys;
          this.setState({
            openRowKeys: openRowKeys
          });
        }
      }
    }, {
      key: "normalizeDataSource",
      value: function normalizeDataSource(dataSource) {
        var ret = [];

        var loop = function loop(dataSource, level) {
          dataSource.forEach(function (item) {
            item.__level = level;
            ret.push(item);

            if (item.children) {
              loop(item.children, level + 1);
            }
          });
        };

        loop(dataSource, 0);
        this.ds = ret;
        return ret;
      }
    }, {
      key: "getTreeNodeStatus",
      value: function getTreeNodeStatus() {
        var dataSource = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
        var openRowKeys = this.state.openRowKeys;
        var primaryKey = this.props.primaryKey;
        var ret = [];
        openRowKeys.forEach(function (openKey) {
          dataSource.forEach(function (item) {
            if (item[primaryKey] === openKey) {
              if (item.children) {
                item.children.forEach(function (child) {
                  ret.push(child[primaryKey]);
                });
              }
            }
          });
        });
        return ret;
      }
    }, {
      key: "render",
      value: function render() {
        /* eslint-disable no-unused-vars, prefer-const */
        var _this$props = this.props,
            components = _this$props.components,
            isTree = _this$props.isTree,
            dataSource = _this$props.dataSource,
            indent = _this$props.indent,
            others = _objectWithoutProperties(_this$props, ["components", "isTree", "dataSource", "indent"]);

        if (isTree) {
          components = _objectSpread({}, components);

          if (!components.Row) {
            components.Row = _row["default"];
          }

          if (!components.Cell) {
            components.Cell = _cell["default"];
          }

          dataSource = this.normalizeDataSource(dataSource);
        }

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

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

  _defineProperty(TreeTable, "TreeRow", _row["default"]);

  _defineProperty(TreeTable, "TreeCell", _cell["default"]);

  _defineProperty(TreeTable, "propTypes", _objectSpread({
    /**
     * 默认情况下展开的树形表格，传入了此属性代表tree的展开为受控操作
     */
    openRowKeys: _propTypes["default"].array,

    /**
     * 点击tree展开或者关闭的时候触发的事件
     * @param {Array} openRowKeys tree模式下展开的key
     * @param {String} currentRowKey 当前点击行的key
     * @param {Boolean} opened 当前点击是展开还是收起
     * @param {Object} currentRecord 当前点击行的记录
     */
    onRowOpen: _propTypes["default"].func,

    /**
     * dataSource当中数据的主键，如果给定的数据源中的属性不包含该主键，会造成选择状态全部选中
     */
    primaryKey: _propTypes["default"].string,

    /**
     * 在tree模式下的缩进尺寸， 仅在isTree为true时候有效
     */
    indent: _propTypes["default"].number,

    /**
     * 开启Table的tree模式, 接收的数据格式中包含children则渲染成tree table
     */
    isTree: _propTypes["default"].bool,
    locale: _propTypes["default"].object
  }, BaseComponent.propTypes));

  _defineProperty(TreeTable, "defaultProps", _objectSpread({}, BaseComponent.defaultProps, {
    primaryKey: 'id',
    onRowOpen: noop,
    components: {},
    indent: 12
  }));

  _defineProperty(TreeTable, "childContextTypes", {
    openTreeRowKeys: _propTypes["default"].array,
    indent: _propTypes["default"].number,
    treeStatus: _propTypes["default"].array,
    onTreeNodeClick: _propTypes["default"].func,
    isTree: _propTypes["default"].bool
  });

  (0, _util.statics)(TreeTable, BaseComponent);
  return TreeTable;
}