import _Array$from from "@babel/runtime-corejs3/core-js-stable/array/from";
import _Symbol from "@babel/runtime-corejs3/core-js-stable/symbol";
import _getIteratorMethod from "@babel/runtime-corejs3/core-js/get-iterator-method";
import _slicedToArray from "@babel/runtime-corejs3/helpers/slicedToArray";
import _toArray from "@babel/runtime-corejs3/helpers/toArray";
import _defineProperty from "@babel/runtime-corejs3/helpers/defineProperty";
import _extends from "@babel/runtime-corejs3/helpers/extends";
import _toConsumableArray from "@babel/runtime-corejs3/helpers/toConsumableArray";
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 _context3; if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = _sliceInstanceProperty(_context3 = {}.toString.call(r)).call(_context3, 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; }
import _Object$getOwnPropertySymbols from "@babel/runtime-corejs3/core-js-stable/object/get-own-property-symbols";
import _Set from "@babel/runtime-corejs3/core-js-stable/set";
import _filterInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/filter";
import _concatInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/concat";
import _sliceInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/slice";
var __rest = this && this.__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 _Object$getOwnPropertySymbols === "function") for (var i = 0, p = _Object$getOwnPropertySymbols(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;
};
import cx from 'classnames';
import React, { useState } from 'react';
import { ExpansionCell, icons, InlineFlexCell } from '../common-views';
import { internals } from '../internals';
import { treeMetaSymbol } from '../pipeline/features';
import { isLeafNode as standardIsLeafNode, mergeCellProps } from '../utils';
import { warnTransformsDeprecated } from './warnTransformsDeprecated';
var ICON_WIDTH = 16;
/** @deprecated transform 用法已经过时，请使用 pipeline 来对表格进行拓展 */
export 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 ? standardIsLeafNode : _ref$isLeafNode,
    _ref$clickArea = _ref.clickArea,
    clickArea = _ref$clickArea === void 0 ? 'cell' : _ref$clickArea,
    _ref$treeMetaKey = _ref.treeMetaKey,
    treeMetaKey = _ref$treeMetaKey === void 0 ? treeMetaSymbol : _ref$treeMetaKey,
    stopClickEventPropagation = _ref.stopClickEventPropagation;
  warnTransformsDeprecated('makeTreeModeTransform');
  var openKeySet = new _Set(openKeys);
  var toggle = function toggle(rowKey) {
    var expanded = openKeySet.has(rowKey);
    if (expanded) {
      onChangeOpenKeys(_filterInstanceProperty(openKeys).call(openKeys, function (key) {
        return key !== rowKey;
      }), rowKey, 'collapse');
    } else {
      var _context;
      onChangeOpenKeys(_concatInstanceProperty(_context = []).call(_context, _toConsumableArray(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(_extends(_defineProperty({}, 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;
      if (columns.length === 0) {
        return columns;
      }
      var _columns = _toArray(columns),
        firstCol = _columns[0],
        others = _sliceInstanceProperty(_columns).call(_columns, 1);
      var render = function render(value, record, recordIndex) {
        var content = 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.createElement(InlineFlexCell, {
            className: "expansion-cell leaf"
          }, /*#__PURE__*/React.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.createElement(ExpansionCell, {
          className: cx('expansion-cell', expandCls),
          style: {
            cursor: clickArea === 'content' ? 'pointer' : undefined
          },
          onClick: clickArea === 'content' ? onClick : undefined
        }, /*#__PURE__*/React.createElement(icons.CaretRight, {
          className: cx('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.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 mergeCellProps(prevProps, {
          onClick: function onClick(e) {
            if (stopClickEventPropagation) {
              e.stopPropagation();
            }
            toggle(rowKey);
          },
          style: {
            cursor: 'pointer'
          }
        });
      };
      return _concatInstanceProperty(_context2 = [_extends(_extends({}, firstCol), {
        title: (/*#__PURE__*/React.createElement("span", {
          style: {
            marginLeft: iconIndent + ICON_WIDTH + iconGap
          }
        }, internals.safeRenderHeader(firstCol))),
        render: render,
        getCellProps: clickArea === 'cell' ? getCellProps : firstCol.getCellProps
      })]).call(_context2, _toConsumableArray(others));
    }
  };
}
/** @deprecated transform 用法已经过时，请使用 pipeline 来对表格进行拓展 */
export function useTreeModeTransform(_a) {
  var _a$defaultOpenKeys = _a.defaultOpenKeys,
    defaultOpenKeys = _a$defaultOpenKeys === void 0 ? [] : _a$defaultOpenKeys,
    others = __rest(_a, ["defaultOpenKeys"]);
  var _useState = useState(defaultOpenKeys),
    _useState2 = _slicedToArray(_useState, 2),
    openKeys = _useState2[0],
    onChangeOpenKeys = _useState2[1];
  return makeTreeModeTransform(_extends({
    openKeys: openKeys,
    onChangeOpenKeys: onChangeOpenKeys
  }, others));
}