"use strict";

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

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

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

var _tree = _interopRequireDefault(require("../../../tree"));

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

var _empty = _interopRequireDefault(require("../../empty"));

var _treePersonNode = _interopRequireDefault(require("../tree-nodes/tree-person-node"));

var _treeDepartNode = _interopRequireDefault(require("../tree-nodes/tree-depart-node"));

var _treeGroupNode = _interopRequireDefault(require("../tree-nodes/tree-group-node"));

var _treeDutiesNode = _interopRequireDefault(require("../tree-nodes/tree-duties-node"));

var _context = require("../../context");

var _loading = _interopRequireDefault(require("../../loading"));

require("./index.css");

var _excluded = ["onSelect", "selected", "multiple", "getTreeData", "loadNodes", "expandedKeys", "asyncData", "itemHeight", "height", "virtual", "isGetRoot", "renderEmpty"];

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 _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 _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 _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 _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 _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 _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 _default(props) {
  var onSelect = props.onSelect,
      _props$selected = props.selected,
      selected = _props$selected === void 0 ? [] : _props$selected,
      multiple = props.multiple,
      getTreeData = props.getTreeData,
      loadNodes = props.loadNodes,
      expandedKeys = props.expandedKeys,
      asyncData = props.asyncData,
      itemHeight = props.itemHeight,
      height = props.height,
      virtual = props.virtual,
      isGetRoot = props.isGetRoot,
      _props$renderEmpty = props.renderEmpty,
      renderEmpty = _props$renderEmpty === void 0 ? function () {
    return /*#__PURE__*/_react["default"].createElement(_empty["default"], null);
  } : _props$renderEmpty,
      restProps = _objectWithoutProperties(props, _excluded);

  var loadedNode = (0, _react.useRef)([]);

  var _useState = (0, _react.useState)(true),
      _useState2 = _slicedToArray(_useState, 2),
      loading = _useState2[0],
      setLoading = _useState2[1];

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

  var _useState5 = (0, _react.useState)(),
      _useState6 = _slicedToArray(_useState5, 2),
      rawTreeData = _useState6[0],
      setRawTreeData = _useState6[1];

  var _useContext = (0, _react.useContext)(_context.CommonContext),
      disabledDepartSelect = _useContext.disabledDepartSelect,
      staffStatus = _useContext.staffStatus;

  (0, _react.useEffect)(function () {
    if (!asyncData) {
      setTreeData(props.treeData);
      setLoading(false);
      return;
    }

    getTreeData().then(function (rawTreeData) {
      setRawTreeData(rawTreeData);
      setTreeData((0, _utils.toTree)(rawTreeData));
      setLoading(false);
    });
  }, [staffStatus]);

  var onBeforeSelect = function onBeforeSelect(node) {
    if (disabledDepartSelect && node.nodeType == "depart") return false;
    return true;
  };

  var titleRenderHandler = function titleRenderHandler(node) {
    if (node.nodeType == "person") {
      return /*#__PURE__*/_react["default"].createElement(_treePersonNode["default"], node);
    }

    if (node.nodeType == "depart") {
      return /*#__PURE__*/_react["default"].createElement(_treeDepartNode["default"], node);
    }

    if (node.nodeType == "group") {
      return /*#__PURE__*/_react["default"].createElement(_treeGroupNode["default"], node);
    }

    if (node.nodeType == "duties") {
      return /*#__PURE__*/_react["default"].createElement(_treeDutiesNode["default"], node);
    }

    return undefined;
  }; // 动态加载子节点数据集


  var onLoadDataHandler = function onLoadDataHandler(treeNode) {
    if (!treeNode.async) return null; // @ts-ignore

    if (loadedNode.current.includes(treeNode.id)) return null;
    return new Promise(function (resolve) {
      var promise = loadNodes(treeNode.id);
      if (!promise) return resolve(true);
      promise.then(function (nodes) {
        if (!nodes.length) return null; // 添加新的节点

        nodes.forEach(function (it) {
          return rawTreeData.push(it);
        });
        setRawTreeData(rawTreeData);
        setTreeData((0, _utils.toTree)(rawTreeData));
      });
      resolve(true);
    });
  };

  var onSelectHandler = function onSelectHandler(selectedKeys, info) {
    onSelect && onSelect(selectedKeys, info);
  };

  var selectedKeys = selected.map(function (it) {
    return it.id;
  }); // tree 组件根据条件添加配置

  var externalOpts = {};
  if (expandedKeys) externalOpts.expandedKeys = expandedKeys;

  if (virtual) {
    externalOpts.virtual = virtual;
    externalOpts.height = height;
    externalOpts.itemHeight = itemHeight;
  }

  if (asyncData) {
    externalOpts.loadData = onLoadDataHandler;
  }

  if (loading) return /*#__PURE__*/_react["default"].createElement(_loading["default"], null);

  if (!treeData || !treeData.length) {
    return renderEmpty();
  }

  var getDefaultExpandedKeys = function getDefaultExpandedKeys() {
    if (!isGetRoot) return [];
    var rootNode = treeData.find(function (item) {
      return item.id == -1;
    });
    if (!rootNode) return [treeData[0].id];
    return [rootNode.id];
  };

  return /*#__PURE__*/_react["default"].createElement("div", {
    className: "perspm-tree"
  }, /*#__PURE__*/_react["default"].createElement(_tree["default"], _extends({}, restProps, {
    key: staffStatus,
    multiple: multiple,
    selectNodeHighlight: false,
    defaultExpandedKeys: getDefaultExpandedKeys(),
    selectedKeys: selectedKeys
  }, externalOpts, {
    treeData: treeData,
    titleRender: titleRenderHandler,
    onSelect: onSelectHandler,
    beforeSelect: onBeforeSelect
  })));
}