"use strict";

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

var _components = require("@alicloudfe/components");

var _utils = require("@teamix/utils");

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

var _treeNode = require("../tree-node");

require("./index.scss");

require("../tree-node/index.scss");

var _utils2 = require("../../utils");

var _hooks = require("@teamix/hooks");

var _actionRef = require("../../utils/action-ref");

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

var _excluded = ["dataSource", "selectedKeys", "checkedKeys", "defaultExpandedKeys", "defaultExpandAll", "expandedKeys", "onSelect", "onCheck", "isNodeBlock", "searchKey", "actionRef", "onBeforeRenderNodeEvent", "beforeRenderNode", "className", "expandAll", "onDataSourceChange", "expandLevel"];

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

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && 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 ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); 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 = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(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 _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }

function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }

function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

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

var cls = (0, _utils.usePrefixCls)('teamix-pro-sidebar-tree');

var ProSidebarTree = function ProSidebarTree(props) {
  var _ref;

  var dataSourceProp = props.dataSource,
      selectedKeysProp = props.selectedKeys,
      checkedKeysProp = props.checkedKeys,
      defaultExpandedKeys = props.defaultExpandedKeys,
      defaultExpandAll = props.defaultExpandAll,
      expandedKeysProp = props.expandedKeys,
      onSelect = props.onSelect,
      onCheck = props.onCheck,
      isNodeBlock = props.isNodeBlock,
      searchKey = props.searchKey,
      actionRef = props.actionRef,
      onBeforeRenderNodeEvent = props.onBeforeRenderNodeEvent,
      beforeRenderNode = props.beforeRenderNode,
      _props$className = props.className,
      className = _props$className === void 0 ? '' : _props$className,
      expandAll = props.expandAll,
      onDataSourceChange = props.onDataSourceChange,
      _props$expandLevel = props.expandLevel,
      expandLevel = _props$expandLevel === void 0 ? 1 : _props$expandLevel,
      others = _objectWithoutProperties(props, _excluded); // 使用 beforeRenderNode 处理 dataSource


  var processDataSource = function processDataSource(dataSource) {
    var newDataSource = (0, _lodash.default)(dataSource);

    if (beforeRenderNode) {
      (0, _utils2.loop)(newDataSource, function (item, level) {
        var _beforeRenderNode;

        var newItem = (_beforeRenderNode = beforeRenderNode === null || beforeRenderNode === void 0 ? void 0 : beforeRenderNode(item, level, dataSource)) !== null && _beforeRenderNode !== void 0 ? _beforeRenderNode : {};
        var allItemKeys = Array.from(new Set([].concat(_toConsumableArray(Object.keys(item)), _toConsumableArray(Object.keys(newItem)))));
        allItemKeys.forEach(function (key) {
          item[key] = newItem[key];
        });
      });
    }

    return newDataSource;
  }; // 自动展开父节点。过滤时用


  var _useState = (0, _react.useState)(false),
      _useState2 = _slicedToArray(_useState, 2),
      autoExpandParent = _useState2[0],
      setAutoExpandParent = _useState2[1];

  var _useState3 = (0, _react.useState)(),
      _useState4 = _slicedToArray(_useState3, 2),
      matchedKeys = _useState4[0],
      setMatchedKeys = _useState4[1];

  var _useState5 = (0, _react.useState)((_ref = expandedKeysProp !== null && expandedKeysProp !== void 0 ? expandedKeysProp : defaultExpandedKeys) !== null && _ref !== void 0 ? _ref : []),
      _useState6 = _slicedToArray(_useState5, 2),
      expandedKeys = _useState6[0],
      setExpandedKeys = _useState6[1];

  var _useState7 = (0, _react.useState)(processDataSource(dataSourceProp !== null && dataSourceProp !== void 0 ? dataSourceProp : [])),
      _useState8 = _slicedToArray(_useState7, 2),
      dataSource = _useState8[0],
      setDataSource = _useState8[1];

  var _useState9 = (0, _react.useState)(selectedKeysProp),
      _useState10 = _slicedToArray(_useState9, 2),
      selectedKeys = _useState10[0],
      setSelectedKeys = _useState10[1];

  var _useState11 = (0, _react.useState)(checkedKeysProp),
      _useState12 = _slicedToArray(_useState11, 2),
      checkedKeys = _useState12[0],
      setCheckedKeys = _useState12[1];

  (0, _react.useEffect)(function () {
    setDefaultExpandedKeys();
  }, []); // 监听 selectedKeys，用于受控

  (0, _react.useEffect)(function () {
    setSelectedKeys(selectedKeysProp);
  }, [selectedKeysProp]); // 更新外部传入的 dataSource

  (0, _hooks.useUpdateEffect)(function () {
    setDataSource(processDataSource(dataSourceProp !== null && dataSourceProp !== void 0 ? dataSourceProp : []));
  }, [dataSourceProp]); // 监听展开全部事件

  (0, _hooks.useUpdateEffect)(function () {
    onChangeExpandAll();
  }, [expandAll]); // 监听展开层级事件

  (0, _hooks.useUpdateEffect)(function () {
    onChangeExpandLevel();
  }, [expandLevel]); // 监听 DataSource 变化事件

  (0, _react.useEffect)(function () {
    onDataSourceChange === null || onDataSourceChange === void 0 ? void 0 : onDataSourceChange(dataSource); // 更新层级状态

    if (expandAll) {
      onChangeExpandAll();
    }

    if (expandLevel > 1) {
      onChangeExpandLevel();
    }
  }, [dataSource]); // 展开全部事件

  var onChangeExpandAll = function onChangeExpandAll() {
    if (expandAll) {
      setExpandedKeys((0, _utils2.getAllNodeKey)(dataSource));
    } else {
      setExpandedKeys([]);
    }
  }; // 展开层级事件


  var onChangeExpandLevel = function onChangeExpandLevel() {
    var keys = (0, _utils2.getTreeLevelKey)(dataSource, expandLevel - 1);
    setExpandedKeys(keys);
  }; // 绑定actionRef


  (0, _actionRef.useActionType)(actionRef, {
    setTreeNode: function setTreeNode(treeNode) {
      var newDataSource = (0, _lodash.default)(dataSource); // TODO 此处可做性能优化

      (0, _utils2.loop)(newDataSource, function (item) {
        if (item.value === treeNode.value) {
          Object.entries(treeNode).forEach(function (_ref2) {
            var _ref3 = _slicedToArray(_ref2, 2),
                key = _ref3[0],
                value = _ref3[1];

            item[key] = value;
          });
        }
      });
      setDataSource(newDataSource);
    }
  }); // dataSource 是否为一层结构

  var hasChildren = (0, _react.useMemo)(function () {
    var flag = false; // TODO 此处可做性能优化

    dataSource.forEach(function (item) {
      if (item.children && item.children.length > 0) {
        flag = true;
      }
    });
    return flag;
  }, [dataSource]); // 组件第一次加载时不执行过滤

  (0, _hooks.useUpdateEffect)(function () {
    filterDataSource(searchKey !== null && searchKey !== void 0 ? searchKey : '');
  }, [searchKey]); // expandedKeys 更新

  (0, _hooks.useUpdateEffect)(function () {
    var _ref4;

    setExpandedKeys((_ref4 = expandedKeysProp !== null && expandedKeysProp !== void 0 ? expandedKeysProp : defaultExpandedKeys) !== null && _ref4 !== void 0 ? _ref4 : []);
  }, [expandedKeysProp, defaultExpandedKeys]); // 设置默认节点展开

  var setDefaultExpandedKeys = function setDefaultExpandedKeys() {
    if (defaultExpandAll) {
      setExpandedKeys((0, _utils2.getAllNodeKey)(dataSource));
    } else {
      var _ref5;

      setExpandedKeys((_ref5 = expandedKeysProp !== null && expandedKeysProp !== void 0 ? expandedKeysProp : defaultExpandedKeys) !== null && _ref5 !== void 0 ? _ref5 : []);
    }
  }; // 是否占满节点


  var getIsNodeBlock = function getIsNodeBlock() {
    if (isNodeBlock && typeof isNodeBlock === 'boolean') {
      return {
        defaultPaddingLeft: 8,
        indent: 16
      };
    }

    if (isNodeBlock && _typeof(isNodeBlock) === 'object') {
      return isNodeBlock;
    }

    return false;
  }; // 过滤


  var filterDataSource = function filterDataSource(value) {
    var searchDataSource = processDataSource(dataSourceProp !== null && dataSourceProp !== void 0 ? dataSourceProp : []);
    var expandedKeys = [];

    if (!value) {
      // TODO 过滤清空数据之后状态会丢失
      setDataSource(searchDataSource); // 数据过滤清空时展开状态继承用户传入的默认状态

      setDefaultExpandedKeys();
      return;
    }

    var _filterTreeData = (0, _utils2.filterTreeData)(searchDataSource, function (node) {
      var _node$label;

      return ((_node$label = node === null || node === void 0 ? void 0 : node.label) !== null && _node$label !== void 0 ? _node$label : '').includes(value);
    }),
        filterTreeValue = _filterTreeData.filterTreeValue;

    (0, _utils2.loop)(filterTreeValue, function (item) {
      hasSearchValue(value, item) && expandedKeys.push(String(item['value']));
    }, {
      children: 'children'
    });
    setMatchedKeys(matchedKeys);
    handleExpand(expandedKeys);
    setDataSource(filterTreeValue);
  };

  var filterTreeNode = function filterTreeNode(node) {
    return matchedKeys && matchedKeys.indexOf(node.props.eventKey) > -1;
  };
  /** 节点是否包含搜索项 */


  var hasSearchValue = function hasSearchValue(key, item) {
    var _item$label;

    if (((_item$label = item === null || item === void 0 ? void 0 : item.label) !== null && _item$label !== void 0 ? _item$label : '').includes(key)) {
      return true;
    } else if (Array.isArray(item['children'])) {
      return item['children'].some(function (child) {
        return hasSearchValue(key, child);
      });
    }

    return false;
  }; // 树节点点击回调


  var onSelectChange = function onSelectChange(value, extra) {
    var _extra$event, _extra$event$target, _extra$event$target$c;

    if (extra === null || extra === void 0 ? void 0 : (_extra$event = extra.event) === null || _extra$event === void 0 ? void 0 : (_extra$event$target = _extra$event.target) === null || _extra$event$target === void 0 ? void 0 : (_extra$event$target$c = _extra$event$target.closest) === null || _extra$event$target$c === void 0 ? void 0 : _extra$event$target$c.call(_extra$event$target, '.teamix-pro-sidebar-delete-overlay')) {
      return;
    }

    setSelectedKeys(value);
    onSelect === null || onSelect === void 0 ? void 0 : onSelect(value, extra);
  }; // 树节点选中回调


  var onCheckChange = function onCheckChange(value, extra) {
    setCheckedKeys(value);
    onCheck === null || onCheck === void 0 ? void 0 : onCheck(value, extra);
  }; // 节点展开回调


  var handleExpand = function handleExpand(key) {
    setExpandedKeys(key);
    setAutoExpandParent(false);
  };

  return /*#__PURE__*/_react.default.createElement("div", {
    className: cls({
      '': true,
      'is-list': !hasChildren
    })
  }, /*#__PURE__*/_react.default.createElement(_components.Tree, _objectSpread({
    isLabelBlock: true,
    checkedKeys: checkedKeys,
    selectedKeys: selectedKeys,
    isNodeBlock: getIsNodeBlock(),
    filterTreeNode: filterTreeNode,
    expandedKeys: expandedKeys,
    onExpand: handleExpand,
    autoExpandParent: autoExpandParent,
    onSelect: onSelectChange,
    onCheck: onCheckChange,
    className: "".concat(cls({
      checkable: others.checkable
    }), " ").concat(className)
  }, others), !onBeforeRenderNodeEvent && (0, _treeNode.renderTreeNode)(dataSource), onBeforeRenderNodeEvent && (0, _treeNode.renderTreeNodeDependenceValue)(dataSource, onBeforeRenderNodeEvent, checkedKeys, selectedKeys)));
};

var _default = ProSidebarTree;
exports.default = _default;