"use strict";

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

require("maycur-antd/lib/alert/style/css");

var _alert = _interopRequireDefault(require("maycur-antd/lib/alert"));

require("maycur-antd/lib/popconfirm/style/css");

var _popconfirm = _interopRequireDefault(require("maycur-antd/lib/popconfirm"));

require("maycur-antd/lib/icon/style/css");

var _icon = _interopRequireDefault(require("maycur-antd/lib/icon"));

require("maycur-antd/lib/tooltip/style/css");

var _tooltip = _interopRequireDefault(require("maycur-antd/lib/tooltip"));

require("maycur-antd/lib/popover/style/css");

var _popover = _interopRequireDefault(require("maycur-antd/lib/popover"));

require("maycur-antd/lib/input/style/css");

var _input = _interopRequireDefault(require("maycur-antd/lib/input"));

require("maycur-antd/lib/tree/style/css");

var _tree2 = _interopRequireDefault(require("maycur-antd/lib/tree"));

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

var _Loader = _interopRequireDefault(require("../Loader"));

var _Empty = _interopRequireDefault(require("../Empty"));

var _lodash = _interopRequireDefault(require("lodash"));

var _i18next = _interopRequireDefault(require("i18next"));

var _debounce = _interopRequireDefault(require("lodash/debounce"));

var _utils = _interopRequireDefault(require("../utils/utils"));

var _mkTranslate = _interopRequireDefault(require("../utils/mkTranslate"));

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

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

var prefix = _utils["default"].prefixCls;
var TreeNode = _tree2["default"].TreeNode;
var Search = _input["default"].Search;

var NodeIcon = function NodeIcon(props) {
  var node = props.node;
  var icon = null;

  if (node.customIcon) {
    icon = node.customIcon;
  } else {
    if (node.isRoot) {
      icon = _react["default"].createElement("span", {
        className: "fm fm-ordered-list"
      });
    } else if (node.isLeaf) {
      icon = _react["default"].createElement("span", {
        className: "fm fm-".concat(props.leafIcon)
      });
    } else {
      icon = _react["default"].createElement("span", {
        className: "fm fm-".concat(props.folderIcon)
      });
    }
  }

  return icon;
};

var IconButton = function IconButton(props) {
  var node = _react["default"].createElement("div", {
    className: "".concat(prefix, "-icon-btn"),
    style: props.style,
    onClick: typeof props.onClick === 'function' ? props.onClick : null
  }, typeof props.icon === 'string' ? _react["default"].createElement("span", {
    className: "fm ".concat(props.icon)
  }) : props.icon);

  return props.showTips ? _react["default"].createElement(_popover["default"], {
    placement: "bottomRight",
    overlayClassName: "mktree-tips",
    content: _react["default"].createElement("div", {
      style: {
        cursor: 'pointer'
      },
      onClick: props.onCloseTips
    }, _react["default"].createElement("span", null, props.title, "\u5728\u8FD9\u91CC"), _react["default"].createElement("span", {
      style: {
        marginLeft: 16
      },
      className: "fm fm-cross"
    })),
    visible: true,
    trigger: "click"
  }, node) : _react["default"].createElement(_tooltip["default"], {
    title: props.title
  }, node);
};

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

  function MKTree(props) {
    var _this;

    _classCallCheck(this, MKTree);

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

    _this.localeProcess = function () {
      _mkTranslate["default"].getNameSpace('MkTree').then(function (t) {
        _this.setState({
          t: t
        });
      });
    };

    _this.onExpand = function (expandedKeys) {
      _this.setState({
        expandedKeys: expandedKeys
      });
    };

    _this.onClickItem = function (node, parent) {
      var onClickItem = _this.props.onClickItem;
      if (node && node.key === _this.state.currentKey) return;
      _this.isItemChange = true;

      _this.setState({
        currentKey: node && node.key
      });

      if (typeof onClickItem === 'function') {
        _this.currentNode = node;
        onClickItem(node.originalData, parent);
      }
    };

    _this.onLoadData = function (treeNode) {
      return new Promise(function (resolve) {
        var _this$props = _this.props,
            loadData = _this$props.loadData,
            defaultSelect = _this$props.defaultSelect,
            pageSize = _this$props.pageSize;

        if (typeof loadData === 'function') {
          var dataRef = treeNode.props.dataRef;
          _this.props.paging && (dataRef.loading = true); // 加载更多loading

          loadData(dataRef.originalData).then(function (res) {
            if (_this.props.paging) {
              var showMore = res && res.length >= pageSize;
              dataRef.showMore = showMore;
              dataRef.loading = false;
            }

            if (!_lodash["default"].isEmpty(res)) {
              dataRef.children = [].concat(_toConsumableArray(dataRef.children || []), _toConsumableArray(_this.getTree(res))); // 默认选择根目录下的第一个

              if (dataRef.originalData.isRoot && defaultSelect === 'child') {
                if (dataRef.children && dataRef.children.length > 0) {
                  _this.onClickItem(dataRef.children[0], dataRef);
                }
              } else if (dataRef.originalData.isRoot && defaultSelect === 'child-child') {
                // 默认选择根目录下的第一个节点的子节点的第一个
                if (dataRef.children && dataRef.children.length > 0 && dataRef.children[0].children && dataRef.children[0].children.length > 0) {
                  _this.onClickItem(dataRef.children[0].children[0], dataRef);
                }
              }

              _this.setState(function (_ref) {
                var loadedKeys = _ref.loadedKeys,
                    tree = _ref.tree;
                return {
                  tree: _toConsumableArray(tree),
                  loadedKeys: _lodash["default"].union(loadedKeys, [dataRef.key])
                };
              });
            } else {
              _this.setState(function (_ref2) {
                var loadedKeys = _ref2.loadedKeys;
                return {
                  loadedKeys: _lodash["default"].union(loadedKeys, [dataRef.key])
                };
              });
            }

            resolve();
          });
        } else {
          resolve();
        }
      });
    };

    _this.addNode = function (_ref3, e) {
      var clickedNode = _ref3.clickedNode,
          isLeaf = _ref3.isLeaf,
          extra = _ref3.extra;
      e && e.stopPropagation(); // 添加并行子节点时 parentNode 的取值

      var parentNode = extra.isParallel ? extra.parentNode : clickedNode;

      _this.expandNodes([parentNode.key], function () {
        var nodeTemplate = _this.props.nodeTemplate;

        if (typeof nodeTemplate === 'function') {
          var node = nodeTemplate(isLeaf, parentNode.originalData);
          if (!parentNode.children) parentNode.children = [];
          var newNode = {
            key: "key_".concat(_this.index++),
            unSaved: true,
            isLeaf: node.isLeaf,
            hasMore: false,
            originalData: node
          }; // 添加并行子节点时，将新节点插入到被点击子节点的后面
          // 添加分类下的子节点时，将子节点添加到分类下第一位

          var clickedNodeIndex = _lodash["default"].findIndex(parentNode.children, {
            key: clickedNode.key
          });

          extra.isParallel ? parentNode.children.splice(clickedNodeIndex + 1, 0, newNode) : parentNode.children = [newNode].concat(_toConsumableArray(parentNode.children));
          parentNode.hasChildren = true;

          _this.setState({
            value: _this.state.value
          });

          _this.onClickItem(newNode, parentNode);
        }
      });
    };

    _this.onSave = function () {
      _this.isSave = true; // NOTE 搜索后的树节点跟树中的节点不是同一个，需要在树中找出相应节点更新originalData，否则修改后，树中的数据无法更新

      var tree = _lodash["default"].clone(_this.state.tree);

      var selectedNode = _this.iterateTree(tree, _this.currentNode.key);

      selectedNode.originalData = _this.currentNode.originalData;

      _this.setState({
        tree: tree
      });
    };

    _this.search = function (query, loadMore) {
      var tree = _this.state.tree;
      _this.searchKeyWord = query;

      if (!loadMore) {
        _this.searchList = [];
      }

      if (!query) {
        // 重置当前选择
        if (tree && tree.length) {
          if (tree[0].originalData.isRoot && tree[0].children && tree[0].children.length) {
            _this.onClickItem(tree[0].children[0], tree[0]);
          } else _this.onClickItem(tree[0]);
        }

        _this.setState({
          isSearch: false
        });

        return;
      }

      var _this$props2 = _this.props,
          onSearch = _this$props2.onSearch,
          pageSize = _this$props2.pageSize,
          paging = _this$props2.paging;

      if (typeof onSearch === 'function') {
        _this.setState({
          loading: true
        });

        _this.lastSearchId++;
        var searchId = _this.lastSearchId;
        onSearch(query, tree, loadMore).then(function (res) {
          if (searchId !== _this.lastSearchId) return; // 保证每次处理的是最后一次返回结果
          // 重置当前选择

          _this.onClickItem({
            originalData: {}
          });

          _this.searchList = [].concat(_toConsumableArray(_this.searchList || []), _toConsumableArray(res || []));

          _this.initSearchList();

          _this.showMoreInSearchList = paging && res && res.length >= pageSize;

          _this.setState({
            loading: false,
            isSearch: true
          });
        }, function () {
          _this.setState({
            loading: false
          });
        });
      }
    };

    _this.removeNode = function (node, parent, e) {
      e.stopPropagation();
      var _this$props3 = _this.props,
          removeRemoteNode = _this$props3.removeRemoteNode,
          keyName = _this$props3.keyName;

      var _removeNode = function _removeNode() {
        var i = parent.children.indexOf(node);
        if (i > -1) parent.children.splice(i, 1);

        if (parent.children.length === 0) {
          parent.hasChildren = false;
        }

        _this.setState({
          tree: _toConsumableArray(_this.state.tree)
        });

        if (parent.originalData.isRoot) {
          _this.onClickItem(parent.children && parent.children[0], parent);
        } else {
          _this.onClickItem(parent);
        }
      };

      if (node.originalData[keyName]) {
        if (typeof removeRemoteNode === 'function') {
          _this.setState({
            loading: true
          });

          removeRemoteNode(node.originalData).then(function () {
            _removeNode();

            _this.setState({
              loading: false
            });
          });
        }
      } else {
        _removeNode();
      }
    };

    _this.removeSearchNode = function (node, e) {
      e.stopPropagation();
      var removeRemoteNode = _this.props.removeRemoteNode;

      if (typeof removeRemoteNode === 'function') {
        _this.setState({
          loading: true
        });

        removeRemoteNode(node.originalData).then(function () {
          var key = node.key; // 先删除 searchList 中的节点

          _this.setState({
            loading: false,
            searchList: _this.state.searchList.filter(function (item) {
              return item.key !== key;
            })
          }, function () {
            // 删除节点后，默认选中第一个节点
            _this.onClickItem(_this.state.searchList.length && _this.state.searchList[0]); // tree 里面如果能够找到 该节点也要删除


            _this.removeTreeNode(node);
          });
        });
      }
    };

    _this.iterateTree = function (nodes, code) {
      var target = null;

      var _iteratee = function _iteratee(_nodes) {
        for (var i = 0; i < _nodes.length; i++) {
          var node = _nodes[i];

          if (node.key === code) {
            target = node;
            break;
          } else {
            if (node.children) {
              _iteratee(node.children);
            }
          }
        }
      };

      _iteratee(nodes);

      return target;
    };

    _this.moveTreeNode = function (currentNode, currentParentCode, targetParentCode) {
      var tree = _lodash["default"].clone(_this.state.tree);

      var cNodes;
      var childrenName = _this.props.childrenName; // 在树中查找当前节点的原父节点和目标父节点

      var cParent = _this.iterateTree(tree, currentParentCode);

      var tParent = _this.iterateTree(tree, targetParentCode); // 将当前节点从原父节点中移除


      var index = _lodash["default"].findIndex(cParent.children, function (child) {
        return child.key === currentNode.code;
      }); // 因为树结构会将文件夹全部请求回来，树节点是按需请求，所以有可能在parent中找不到该树节点（搜索的情况下）


      if (index > -1) {
        cNodes = cParent.children.splice(index, 1); // root 的 originalData 没有 [childrenName]

        cParent.originalData[childrenName] && cParent.originalData[childrenName].splice(index, 1); // 将当前节点加入到新的父节点中
        // TODO（bug）：若新的父节点还未展开过，则不应该将节点 push 进 children，因为点击节点展开的时候会请求子节点。push 进去会导致子节点重复。

        tParent.children = tParent.children || [];
        tParent.children.push(cNodes[0]);
        tParent.originalData[childrenName] = tParent.originalData[childrenName] || [];
        tParent.originalData[childrenName].push(currentNode); // 新增加的文件夹，将子节点添加进去后，没有可展开的箭头icon，所以增加以下代码

        if (!_this.state.expandedKeys.includes(tParent.key)) {
          _this.expandNodes([tParent.key]);
        }

        _this.setState({
          tree: tree
        });
      }
    };

    _this.expandNodes = function (keys, callback) {
      var expandedKeys = _this.state.expandedKeys;

      var cb = function cb() {
        if (typeof callback === 'function') {
          callback();
        }
      };

      if (Array.isArray(keys) && keys.length) {
        var newKeys = _toConsumableArray(new Set([].concat(_toConsumableArray(expandedKeys), _toConsumableArray(keys))));

        _this.setState({
          expandedKeys: newKeys
        }, function () {
          cb();
        });
      } else {
        cb();
      }
    };

    _this.loop = function (nodes, parent, level) {
      return nodes ? nodes.map(function (node, index) {
        return _react["default"].createElement(TreeNode, {
          key: node.key || index,
          title: _this.renderTitle(node, parent, level, index),
          dataRef: node,
          isLeaf: node.isLeaf || !node.hasChildren,
          ref: function ref(_ref4) {
            return node.ref = _ref4;
          }
        }, !_lodash["default"].isEmpty(node.children) && _this.loop(node.children, node, level + 1), node.showMore && _react["default"].createElement(TreeNode, {
          key: node.key,
          title: _react["default"].createElement("div", {
            className: "node__item load-more",
            onClick: function onClick() {
              return _this.onLoadData(node.ref);
            }
          }, "\u52A0\u8F7D\u66F4\u591A", node.loading && _react["default"].createElement(_icon["default"], {
            type: "loading",
            style: {
              fontSize: 18
            },
            spin: true
          })),
          dataRef: node,
          isLeaf: true
        }));
      }) : null;
    };

    _this.onCloseTips = function () {
      var pageId = _this.props.pageId;

      _this.setState({
        hasReadTips: true
      });

      var pageIds = localStorage.getItem('hasReadPageIds');
      localStorage.setItem('hasReadPageIds', pageIds ? "".concat(pageIds, ",").concat(pageId) : pageId);
    };

    _this.renderTitle = function (node, parent, level, index) {
      var _this$state = _this.state,
          currentKey = _this$state.currentKey,
          hasReadTips = _this$state.hasReadTips,
          t = _this$state.t;
      var _this$props4 = _this.props,
          titleName = _this$props4.titleName,
          needAction = _this$props4.needAction,
          leafIcon = _this$props4.leafIcon,
          folderIcon = _this$props4.folderIcon,
          keyName = _this$props4.keyName,
          maxLevel = _this$props4.maxLevel,
          renderIcon = _this$props4.renderIcon,
          renderExtra = _this$props4.renderExtra,
          addLeafTitle = _this$props4.addLeafTitle,
          addFolderTitle = _this$props4.addFolderTitle,
          addParallelLeafTitle = _this$props4.addParallelLeafTitle,
          showAddParallelLeafIcon = _this$props4.showAddParallelLeafIcon,
          needPopoverType = _this$props4.needPopoverType,
          isHideDeleteBtn = _this$props4.isHideDeleteBtn,
          hideActionBy = _this$props4.hideActionBy;
      var showTips = !parent && !hasReadTips;
      var nodeDisabled = 'enabled' in node.originalData ? node.originalData.enabled ? '' : ' disabled' : '';
      var isHideAction = node.originalData && node.originalData[hideActionBy];
      return _react["default"].createElement("div", {
        className: "node__item" + (currentKey === node.key ? ' active' : '') + "".concat(nodeDisabled),
        onClick: function onClick() {
          _this.onClickItem(node, parent);
        }
      }, _react["default"].createElement("div", {
        className: 'node--title'
      }, typeof renderIcon === 'function' ? renderIcon(node ? node.originalData : {}) : _react["default"].createElement(NodeIcon, {
        className: 'node--title__icon',
        node: node ? node.originalData : {},
        leafIcon: leafIcon,
        folderIcon: folderIcon
      }), _react["default"].createElement("div", {
        className: 'node--title__label'
      }, _react["default"].createElement("div", {
        className: 'title--label__text'
      }, node.originalData[titleName], node.originalData.totalCount ? _react["default"].createElement("span", {
        className: "title--label__count"
      }, "(", node.originalData.totalCount, ")") : null, typeof renderExtra === 'function' && renderExtra(node ? node.originalData : {})), node.unSaved && _react["default"].createElement("div", {
        className: 'title--label__unsaved'
      }, " [", t('unSaved'), "]"))), !isHideAction && !node.originalData.customConfig && needAction && _react["default"].createElement("span", {
        className: "node--operator".concat(!hasReadTips && showTips ? ' show-tips' : '')
      }, !node.isLeaf && node.originalData[keyName] && (!maxLevel || maxLevel && level < maxLevel) ? _react["default"].createElement(IconButton, {
        title: addFolderTitle,
        icon: "fm-".concat(folderIcon),
        showTips: needPopoverType === 'folder' ? showTips : false,
        onCloseTips: _this.onCloseTips,
        onClick: _this.addNode.bind(_assertThisInitialized(_this), {
          clickedNode: node,
          isLeaf: false,
          extra: {}
        })
      }) : null, (!node.isLeaf || showAddParallelLeafIcon) && node.originalData[keyName] ? _react["default"].createElement(IconButton, {
        title: !node.isLeaf ? addLeafTitle : addParallelLeafTitle || addLeafTitle,
        icon: "fm-".concat(leafIcon),
        showTips: needPopoverType === 'file' ? showTips : false,
        onCloseTips: _this.onCloseTips,
        onClick: _this.addNode.bind(_assertThisInitialized(_this), {
          clickedNode: node,
          isLeaf: true,
          extra: {
            isParallel: node.isLeaf,
            index: index,
            parentNode: parent
          }
        })
      }) : null, !node.originalData.isRoot && !isHideDeleteBtn && _react["default"].createElement(_popconfirm["default"], {
        overlayStyle: {
          width: '290px'
        },
        title: node.isLeaf ? t('confirm') : _react["default"].createElement(_react["default"].Fragment, null, _react["default"].createElement("div", null, t('delConfirm')), _react["default"].createElement("br", null), _react["default"].createElement("div", null, t('confirm'))),
        placement: "leftTop",
        onConfirm: function onConfirm(e) {
          return _this.removeNode(node, parent, e);
        },
        onCancel: function onCancel(e) {
          return e.stopPropagation();
        },
        icon: _react["default"].createElement("span", {
          className: "fm fm-info-o",
          style: {
            color: 'red',
            position: 'absolute',
            top: '5px'
          }
        }),
        okType: "default",
        cancelButtonProps: {
          type: 'primary'
        }
      }, _react["default"].createElement(IconButton, {
        icon: "fm-trash",
        onClick: function onClick(e) {
          return e.stopPropagation();
        }
      }))), !isHideAction && node.originalData.customConfig && _react["default"].createElement("span", {
        className: "node--operator".concat(!hasReadTips && showTips ? ' show-tips' : '')
      }, Array.isArray(node.originalData.customConfig.customIcons) && node.originalData.customConfig.customIcons.map(function (item, i) {
        return _react["default"].createElement(IconButton, {
          onCloseTips: _this.onCloseTips,
          key: i,
          title: item.title,
          icon: item.icon,
          onClick: function onClick() {
            return item.action(node.originalData);
          }
        });
      }), node.originalData.customConfig.isNeedAddFolder && node.originalData[keyName] && (!maxLevel || maxLevel && level < maxLevel) ? _react["default"].createElement(IconButton, {
        title: addFolderTitle,
        showTips: needPopoverType === 'folder' ? showTips : false,
        onCloseTips: _this.onCloseTips,
        icon: "fm-".concat(folderIcon),
        onClick: _this.addNode.bind(_assertThisInitialized(_this), {
          clickedNode: node,
          isLeaf: false,
          extra: {
            isParallel: node.isLeaf,
            index: index,
            parentNode: parent
          }
        })
      }) : null, node.originalData.customConfig.isNeedAddFile && node.originalData[keyName] ? _react["default"].createElement(IconButton, {
        title: addLeafTitle,
        icon: "fm-".concat(leafIcon),
        showTips: needPopoverType === 'file' ? showTips : false,
        onCloseTips: _this.onCloseTips,
        onClick: _this.addNode.bind(_assertThisInitialized(_this), {
          clickedNode: node,
          isLeaf: true,
          extra: {
            isParallel: node.isLeaf,
            index: index,
            parentNode: parent
          }
        })
      }) : null, node.originalData.customConfig.isNeedDelete && !isHideDeleteBtn && _react["default"].createElement(_popconfirm["default"], {
        title: t('confirm'),
        placement: "leftTop",
        onConfirm: function onConfirm(e) {
          return _this.removeNode(node, parent, e);
        },
        onCancel: function onCancel(e) {
          return e.stopPropagation();
        }
      }, _react["default"].createElement(IconButton, {
        icon: "fm-trash",
        onClick: function onClick(e) {
          return e.stopPropagation();
        }
      }))));
    };

    _this.renderSearchList = function (list) {
      var _this$props5 = _this.props,
          titleName = _this$props5.titleName,
          needAction = _this$props5.needAction,
          leafIcon = _this$props5.leafIcon,
          folderIcon = _this$props5.folderIcon,
          renderIcon = _this$props5.renderIcon,
          renderExtra = _this$props5.renderExtra,
          isHideDeleteBtn = _this$props5.isHideDeleteBtn,
          hideActionBy = _this$props5.hideActionBy;
      var _this$state2 = _this.state,
          currentKey = _this$state2.currentKey,
          loading = _this$state2.loading,
          t = _this$state2.t;
      return list instanceof Array && list.length > 0 ? _react["default"].createElement(_react["default"].Fragment, null, list.map(function (node) {
        var isHideAction = node.originalData && node.originalData[hideActionBy];
        return _react["default"].createElement("div", {
          key: node.key,
          className: "node__item search-list__item" + (currentKey === node.key ? ' active' : ''),
          onClick: function onClick() {
            _this.onClickItem(node);
          }
        }, _react["default"].createElement("span", {
          className: 'node--title'
        }, typeof renderIcon === 'function' ? renderIcon(node ? node.originalData : {}) : _react["default"].createElement(NodeIcon, {
          className: 'node--title__icon',
          node: node ? node.originalData : {},
          leafIcon: leafIcon,
          folderIcon: folderIcon
        }), _react["default"].createElement("span", {
          className: 'node--title__label'
        }, _react["default"].createElement("span", {
          className: 'title--label__text'
        }, node.originalData[titleName], typeof renderExtra === 'function' && renderExtra(node ? node.originalData : {})), node.unSaved && _react["default"].createElement("span", {
          className: 'title--label__unsaved'
        }, " [", t('unSaved'), "]"))), !isHideAction && needAction && !node.originalData.isRoot && !node.originalData.customConfig && !isHideDeleteBtn && _react["default"].createElement("span", {
          className: "node--operator"
        }, _react["default"].createElement(_popconfirm["default"], {
          title: t('confirm'),
          placement: "leftTop",
          onConfirm: function onConfirm(e) {
            return _this.removeSearchNode(node, e);
          },
          onCancel: function onCancel(e) {
            return e.stopPropagation();
          }
        }, _react["default"].createElement(IconButton, {
          icon: "fm-trash",
          onClick: function onClick(e) {
            return e.stopPropagation();
          }
        }))), !isHideAction && needAction && !node.originalData.isRoot && node.originalData.customConfig && node.originalData.customConfig.isNeedDelete && !isHideDeleteBtn && _react["default"].createElement("span", {
          className: "node--operator"
        }, _react["default"].createElement(_popconfirm["default"], {
          title: t('confirm'),
          placement: "leftTop",
          onConfirm: function onConfirm(e) {
            return _this.removeSearchNode(node, e);
          },
          onCancel: function onCancel(e) {
            return e.stopPropagation();
          }
        }, _react["default"].createElement(IconButton, {
          icon: "fm-trash",
          onClick: function onClick(e) {
            return e.stopPropagation();
          }
        }))));
      }), _this.showMoreInSearchList && _react["default"].createElement("div", {
        className: "node__item search-list__item load-more",
        onClick: function onClick() {
          return _this.search(_this.searchKeyWord, true);
        }
      }, t('loadMore'), loading && _react["default"].createElement(_icon["default"], {
        type: "loading",
        style: {
          fontSize: 18
        },
        spin: true
      }))) : _react["default"].createElement(_Empty["default"], {
        text: t('empty')
      });
    };

    _this.initSearchList = function () {
      _this.setState({
        searchList: _this.getTree(_this.searchList) || []
      }, function () {
        if (!_lodash["default"].isEmpty(_this.searchList)) {
          _this.onClickItem(_this.state.searchList[0]);
        }
      });
    };

    var hasReadPageIds = (localStorage.getItem('hasReadPageIds') || '').split(',');
    _this.state = {
      expandedKeys: [],
      tree: [],
      currentKey: '',
      loading: false,
      isSearch: false,
      loadedKeys: [],
      needFirstTips: true,
      hasReadTips: !props.pageId || hasReadPageIds.includes(props.pageId),
      t: _mkTranslate["default"].noop()
    };
    _this.index = 0;
    _this.isItemChange = false;
    _this.isSave = false;
    _this.currentNode = props.currentNode;
    _this.isInit = false;
    _this.lastSearchId = 0;
    _this.onSearchQueryChange = (0, _debounce["default"])(_this.search, 800);
    _this.onSearch = (0, _debounce["default"])(_this.search, 800, {
      leading: true,
      trailing: false
    });

    _this.localeProcess();

    return _this;
  }

  _createClass(MKTree, [{
    key: "removeTreeNode",
    value: function removeTreeNode(node) {
      var key = node.key;

      var _removeNode = function _removeNode(tree) {
        for (var i = 0; i < tree.length; i++) {
          var _node = tree[i];

          if (_node.key === key) {
            tree.splice(i, 1);
            return true;
          }

          if (!_lodash["default"].isEmpty(_node.children)) {
            if (_removeNode(_node.children)) return true;
          }
        }
      };

      var tree = this.state.tree;

      _removeNode(tree);

      this.setState({
        tree: _toConsumableArray(tree)
      });
    } // 在树中找出指定code的节点

  }, {
    key: "getTree",

    /* 将数据转化为内部格式 */
    value: function getTree(value) {
      var _this2 = this;

      if (!value) return;
      var _this$props6 = this.props,
          keyName = _this$props6.keyName,
          childrenName = _this$props6.childrenName,
          isSync = _this$props6.isSync;

      var _getTree = function _getTree(tree) {
        var _tree = [];
        tree.forEach(function (item) {
          var key = item[keyName] || "key_".concat(_this2.index++);
          var children = item[childrenName];
          var _hasChildren = true; // 有些后端接口还没有返回hasChildren

          if (!item.isRoot) {
            if (isSync) {
              _hasChildren = children && children.length > 0;
            } else {
              if ('hasChildren' in item) {
                _hasChildren = item.hasChildren;
              }
            }
          }

          var node = {
            key: key,
            isLeaf: !!item.isLeaf,
            hasChildren: _hasChildren,
            originalData: item
          };

          if (!_lodash["default"].isEmpty(children)) {
            node.children = _getTree(children);
          }

          _tree.push(node);
        });
        return _tree;
      };

      return _getTree(value);
    }
  }, {
    key: "initTree",

    /* 初始化tree(包含清空下拉操作记录,可用于树结构初始化) */
    value: function initTree(value) {
      var _this3 = this;

      var defaultExpandedKeys = this.props.defaultExpandedKeys;
      this.setState({
        tree: this.getTree(value)
      }, function () {
        if (defaultExpandedKeys) {
          _this3.setState({
            expandedKeys: defaultExpandedKeys,
            loadedKeys: []
          });
        } else {
          var tree = _this3.state.tree;

          if (tree && tree.length && tree[0].originalData.isRoot) {
            // 默认展开根节点
            _this3.setState({
              expandedKeys: [tree[0].key],
              loadedKeys: []
            });

            _this3.onClickItem(tree[0]);
          }
        }
      });
    }
  }, {
    key: "UNSAFE_componentWillReceiveProps",
    value: function UNSAFE_componentWillReceiveProps(props) {
      var outerNode = props.currentNode,
          preValue = props.value;

      if (!this.isInit && !_lodash["default"].isEmpty(preValue)) {
        this.initTree(_toConsumableArray(preValue));
        this.isInit = true;
      } else if (outerNode !== this.props.currentNode) {
        if (!this.isItemChange) {
          var currentNode = this.currentNode,
              isSave = this.isSave;
          currentNode.unSaved = !isSave;
          currentNode.originalData = outerNode;
          currentNode.key = outerNode.code;

          if (isSave) {
            this.isSave = false; // 如果是save 且 是文件夹节点 则需更新 loadedKeys

            if (!currentNode.isLeaf) {
              this.setState(function (_ref5) {
                var loadedKeys = _ref5.loadedKeys;
                return {
                  loadedKeys: [].concat(_toConsumableArray(loadedKeys), [currentNode.key])
                };
              });
            }
          }

          var isSearch = this.state.isSearch;
          var originData = isSearch ? 'searchList' : 'tree';
          this.setState(_defineProperty({}, originData, _toConsumableArray(this.state[originData])));
        } else {
          this.isItemChange = false;
        }
      }
    }
  }, {
    key: "componentDidMount",
    value: function componentDidMount() {
      if (!this.isInit && !_lodash["default"].isEmpty(this.props.value)) {
        this.initTree(_toConsumableArray(this.props.value));
        this.isInit = true;
      }
    }
  }, {
    key: "render",
    value: function render() {
      var _this4 = this;

      var _this$props7 = this.props,
          showSearch = _this$props7.showSearch,
          onSearch = _this$props7.onSearch,
          placeholder = _this$props7.placeholder,
          loadData = _this$props7.loadData,
          loading = _this$props7.loading,
          alertInfo = _this$props7.alertInfo,
          defaultExpandAll = _this$props7.defaultExpandAll,
          restProps = _objectWithoutProperties(_this$props7, ["showSearch", "onSearch", "placeholder", "loadData", "loading", "alertInfo", "defaultExpandAll"]);

      var _this$state3 = this.state,
          tree = _this$state3.tree,
          isSearch = _this$state3.isSearch,
          searchList = _this$state3.searchList,
          loadedKeys = _this$state3.loadedKeys;
      return _react["default"].createElement("div", {
        className: "".concat(prefix, "-mktree-container")
      }, showSearch ? _react["default"].createElement("div", {
        className: "search-box"
      }, _react["default"].createElement(Search, {
        onSearch: function onSearch(value) {
          return _this4.onSearch(value);
        },
        onChange: function onChange(e) {
          _this4.onSearchQueryChange(e.target.value);
        },
        placeholder: placeholder
      })) : null, !_lodash["default"].isEmpty(alertInfo) ? _react["default"].createElement("div", {
        className: 'alert-box'
      }, _react["default"].createElement(_alert["default"], alertInfo)) : null, _react["default"].createElement("div", {
        className: "directory-wrapper"
      }, isSearch ? _react["default"].createElement(_react["default"].Fragment, null, this.renderSearchList(searchList)) : _react["default"].createElement(_tree2["default"], _extends({}, restProps, {
        defaultExpandAll: defaultExpandAll,
        expandedKeys: this.state.expandedKeys,
        onExpand: this.onExpand,
        loadData: this.onLoadData,
        loadedKeys: loadedKeys
      }), this.loop(tree, null, 1))), loading ? _react["default"].createElement("div", {
        className: "loading-wrapper"
      }, _react["default"].createElement(_Loader["default"], {
        active: true,
        mask: true
      })) : null);
    }
  }]);

  return MKTree;
}(_react.Component);

MKTree.defaultProps = {
  keyName: 'code',
  childrenName: 'children',
  titleName: 'title',
  needAction: true,
  leafIcon: 'paper',
  folderIcon: 'folder-o',
  alertInfo: {},
  addLeafTitle: _i18next["default"].t('MkTree:add'),
  //操作按钮中添加子节点的tooltip文字
  addFolderTitle: _i18next["default"].t('MkTree:add'),
  //操作按钮中添加分类的tooltip文字
  needPopoverType: 'folder',
  paging: false //是否分页

};
var _default = MKTree;
exports["default"] = _default;