"use strict";

var _typeof = require("@babel/runtime-corejs3/helpers/typeof");
var _sliceInstanceProperty2 = require("@babel/runtime-corejs3/core-js-stable/instance/slice");
var _Array$from = require("@babel/runtime-corejs3/core-js-stable/array/from");
var _Symbol = require("@babel/runtime-corejs3/core-js-stable/symbol");
var _getIteratorMethod = require("@babel/runtime-corejs3/core-js/get-iterator-method");
var _WeakMap = require("@babel/runtime-corejs3/core-js-stable/weak-map");
var _Object$getOwnPropertyDescriptor = require("@babel/runtime-corejs3/core-js-stable/object/get-own-property-descriptor");
var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.makeTreeModeTransform = makeTreeModeTransform;
exports.useTreeModeTransform = useTreeModeTransform;
var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/slicedToArray"));
var _toArray2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/toArray"));
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/defineProperty"));
var _extends3 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/extends"));
var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/toConsumableArray"));
var _getOwnPropertySymbols = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/object/get-own-property-symbols"));
var _set = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/set"));
var _filter = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/filter"));
var _concat = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/concat"));
var _slice = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/slice"));
var _classnames = _interopRequireDefault(require("classnames"));
var _react = _interopRequireWildcard(require("react"));
var _commonViews = require("../common-views");
var _internals = require("../internals");
var _features = require("../pipeline/features");
var _utils = require("../utils");
var _warnTransformsDeprecated = require("./warnTransformsDeprecated");
function _interopRequireWildcard(e, t) { if ("function" == typeof _WeakMap) var r = new _WeakMap(), n = new _WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != _typeof(e) && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t in e) "default" !== _t && {}.hasOwnProperty.call(e, _t) && ((i = (o = Object.defineProperty) && _Object$getOwnPropertyDescriptor(e, _t)) && (i.get || i.set) ? o(f, _t, i) : f[_t] = e[_t]); return f; })(e, t); }
function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof _Symbol && _getIteratorMethod(r) || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t.return || t.return(); } finally { if (u) throw o; } } }; }
function _unsupportedIterableToArray(r, a) { if (r) { var _context4; if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = _sliceInstanceProperty2(_context4 = {}.toString.call(r)).call(_context4, 8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? _Array$from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
var __rest = void 0 && (void 0).__rest || function (s, e) {
  var t = {};
  for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
  if (s != null && typeof _getOwnPropertySymbols.default === "function") for (var i = 0, p = (0, _getOwnPropertySymbols.default)(s); i < p.length; i++) {
    if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
  }
  return t;
};
var ICON_WIDTH = 16;
/** @deprecated transform 用法已经过时，请使用 pipeline 来对表格进行拓展 */
function makeTreeModeTransform(_ref) {
  var onChangeOpenKeys = _ref.onChangeOpenKeys,
    openKeys = _ref.openKeys,
    primaryKey = _ref.primaryKey,
    _ref$iconIndent = _ref.iconIndent,
    iconIndent = _ref$iconIndent === void 0 ? -6 : _ref$iconIndent,
    _ref$iconGap = _ref.iconGap,
    iconGap = _ref$iconGap === void 0 ? 0 : _ref$iconGap,
    _ref$indentSize = _ref.indentSize,
    indentSize = _ref$indentSize === void 0 ? 16 : _ref$indentSize,
    _ref$isLeafNode = _ref.isLeafNode,
    isLeafNode = _ref$isLeafNode === void 0 ? _utils.isLeafNode : _ref$isLeafNode,
    _ref$clickArea = _ref.clickArea,
    clickArea = _ref$clickArea === void 0 ? 'cell' : _ref$clickArea,
    _ref$treeMetaKey = _ref.treeMetaKey,
    treeMetaKey = _ref$treeMetaKey === void 0 ? _features.treeMetaSymbol : _ref$treeMetaKey,
    stopClickEventPropagation = _ref.stopClickEventPropagation;
  (0, _warnTransformsDeprecated.warnTransformsDeprecated)('makeTreeModeTransform');
  var openKeySet = new _set.default(openKeys);
  var toggle = function toggle(rowKey) {
    var expanded = openKeySet.has(rowKey);
    if (expanded) {
      onChangeOpenKeys((0, _filter.default)(openKeys).call(openKeys, function (key) {
        return key !== rowKey;
      }), rowKey, 'collapse');
    } else {
      var _context;
      onChangeOpenKeys((0, _concat.default)(_context = []).call(_context, (0, _toConsumableArray2.default)(openKeys), [rowKey]), rowKey, 'expand');
    }
  };
  return function (_ref2) {
    var columns = _ref2.columns,
      dataSource = _ref2.dataSource;
    return {
      columns: processColumns(columns),
      dataSource: processDataSource(dataSource)
    };
    function processDataSource(input) {
      var result = [];
      dfs(input, 0);
      function dfs(nodes, depth) {
        if (nodes == null) {
          return;
        }
        var _iterator = _createForOfIteratorHelper(nodes),
          _step;
        try {
          for (_iterator.s(); !(_step = _iterator.n()).done;) {
            var node = _step.value;
            var rowKey = node[primaryKey];
            var expanded = openKeySet.has(rowKey);
            var isLeaf = isLeafNode(node, {
              depth: depth,
              expanded: expanded,
              rowKey: rowKey
            });
            var treeMeta = {
              depth: depth,
              isLeaf: isLeaf,
              expanded: expanded,
              rowKey: rowKey
            };
            result.push((0, _extends3.default)((0, _defineProperty2.default)({}, treeMetaKey, treeMeta), node));
            if (!isLeaf && expanded) {
              dfs(node.children, depth + 1);
            }
          }
        } catch (err) {
          _iterator.e(err);
        } finally {
          _iterator.f();
        }
      }
      return result;
    }
    function processColumns(columns) {
      var _context2, _context3;
      if (columns.length === 0) {
        return columns;
      }
      var _columns = (0, _toArray2.default)(columns),
        firstCol = _columns[0],
        others = (0, _slice.default)(_context2 = _arrayLikeToArray(_columns)).call(_context2, 1);
      var render = function render(value, record, recordIndex) {
        var content = _internals.internals.safeRender(firstCol, record, recordIndex);
        if (record[treeMetaKey] == null) {
          // 没有 treeMeta 信息的话，就返回原先的渲染结果
          return content;
        }
        var _record$treeMetaKey = record[treeMetaKey],
          rowKey = _record$treeMetaKey.rowKey,
          depth = _record$treeMetaKey.depth,
          isLeaf = _record$treeMetaKey.isLeaf,
          expanded = _record$treeMetaKey.expanded;
        var indent = iconIndent + depth * indentSize;
        if (isLeaf) {
          return /*#__PURE__*/_react.default.createElement(_commonViews.InlineFlexCell, {
            className: "expansion-cell leaf"
          }, /*#__PURE__*/_react.default.createElement("span", {
            style: {
              marginLeft: indent + ICON_WIDTH + iconGap
            }
          }, content));
        }
        var onClick = function onClick(e) {
          if (stopClickEventPropagation) {
            e.stopPropagation();
          }
          toggle(rowKey);
        };
        var expandCls = expanded ? 'expanded' : 'collapsed';
        return /*#__PURE__*/_react.default.createElement(_commonViews.ExpansionCell, {
          className: (0, _classnames.default)('expansion-cell', expandCls),
          style: {
            cursor: clickArea === 'content' ? 'pointer' : undefined
          },
          onClick: clickArea === 'content' ? onClick : undefined
        }, /*#__PURE__*/_react.default.createElement(_commonViews.icons.CaretRight, {
          className: (0, _classnames.default)('expansion-icon', expandCls),
          style: {
            cursor: clickArea === 'icon' ? 'pointer' : undefined,
            marginLeft: indent,
            marginRight: iconGap
          },
          onClick: clickArea === 'icon' ? onClick : undefined
        }), content);
      };
      var getCellProps = function getCellProps(value, record, rowIndex) {
        var prevProps = _internals.internals.safeGetCellProps(firstCol, record, rowIndex);
        if (record[treeMetaKey] == null) {
          // 没有 treeMeta 信息的话，就返回原先的 cellProps
          return prevProps;
        }
        var _record$treeMetaKey2 = record[treeMetaKey],
          isLeaf = _record$treeMetaKey2.isLeaf,
          rowKey = _record$treeMetaKey2.rowKey;
        if (isLeaf) {
          return prevProps;
        }
        return (0, _utils.mergeCellProps)(prevProps, {
          onClick: function onClick(e) {
            if (stopClickEventPropagation) {
              e.stopPropagation();
            }
            toggle(rowKey);
          },
          style: {
            cursor: 'pointer'
          }
        });
      };
      return (0, _concat.default)(_context3 = [(0, _extends3.default)((0, _extends3.default)({}, firstCol), {
        title: (/*#__PURE__*/_react.default.createElement("span", {
          style: {
            marginLeft: iconIndent + ICON_WIDTH + iconGap
          }
        }, _internals.internals.safeRenderHeader(firstCol))),
        render: render,
        getCellProps: clickArea === 'cell' ? getCellProps : firstCol.getCellProps
      })]).call(_context3, (0, _toConsumableArray2.default)(others));
    }
  };
}
/** @deprecated transform 用法已经过时，请使用 pipeline 来对表格进行拓展 */
function useTreeModeTransform(_a) {
  var _a$defaultOpenKeys = _a.defaultOpenKeys,
    defaultOpenKeys = _a$defaultOpenKeys === void 0 ? [] : _a$defaultOpenKeys,
    others = __rest(_a, ["defaultOpenKeys"]);
  var _useState = (0, _react.useState)(defaultOpenKeys),
    _useState2 = (0, _slicedToArray2.default)(_useState, 2),
    openKeys = _useState2[0],
    onChangeOpenKeys = _useState2[1];
  return makeTreeModeTransform((0, _extends3.default)({
    openKeys: openKeys,
    onChangeOpenKeys: onChangeOpenKeys
  }, others));
}