function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
var _excluded = ["request", "onSelect", "permissionCode", "searchProps", "showSearch", "selfNameMap"],
  _excluded2 = ["data"];
function _extends() { _extends = Object.assign ? Object.assign.bind() : 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 _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 _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 ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
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(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
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; }
import React, { useState, useEffect, useCallback, useMemo, useRef, useContext } from 'react';
import { Spin, Input, Tree } from 'antd';
import { debounce } from 'lodash';
import net from "../services";
import { ComposeTreeContext } from "./hooks/use-compose-tree";
//   import UserTree from './user-tree';
import useTreeData from "./hooks/use-tree-data";
import { TreeProps as PropTypes } from "./interface";
import { getUid } from "./utils";
import "./index.less";
var Search = Input.Search;
function CFTree(_ref) {
  var _treeWrapper$current, _treeData$, _treeData$2, _treeData$3;
  var searchTreeNodes = _ref.request.searchTreeNodes,
    onSelect = _ref.onSelect,
    permissionCode = _ref.permissionCode,
    searchProps = _ref.searchProps,
    _ref$showSearch = _ref.showSearch,
    showSearch = _ref$showSearch === void 0 ? true : _ref$showSearch,
    selfNameMap = _ref.selfNameMap,
    others = _objectWithoutProperties(_ref, _excluded);
  var _useContext = useContext(ComposeTreeContext),
    expandedKeys = _useContext.expandedKeys,
    dataSource = _useContext.dataSource,
    treePaths = _useContext.treePaths,
    setIsSearch = _useContext.setIsSearch,
    setExpandedKeys = _useContext.setExpandedKeys,
    loadData = _useContext.loadData;
  var _useState = useState([]),
    _useState2 = _slicedToArray(_useState, 2),
    selectedKeys = _useState2[0],
    setSelectedKeys = _useState2[1];
  // 渲染树的数据
  var _useState3 = useState([]),
    _useState4 = _slicedToArray(_useState3, 2),
    searchResult = _useState4[0],
    setSearchResult = _useState4[1];
  var _useState5 = useState(false),
    _useState6 = _slicedToArray(_useState5, 2),
    loading = _useState6[0],
    setLoading = _useState6[1];
  // const [userList, setUserList] = useState([]);
  var _useState7 = useState(''),
    _useState8 = _slicedToArray(_useState7, 2),
    searchText = _useState8[0],
    setSearchText = _useState8[1];
  var requestIds = useRef({
    search: 0
  });
  var partialDataSource = useMemo(function () {
    return searchText ? searchResult : dataSource;
  }, [searchText, searchResult, dataSource]);
  var treeWrapper = useRef();
  var _useTreeData = useTreeData(partialDataSource, searchText),
    _useTreeData2 = _slicedToArray(_useTreeData, 1),
    treeData = _useTreeData2[0];
  // const [height, setHeight] = useState(0);
  var _useState9 = useState(0),
    _useState10 = _slicedToArray(_useState9, 2),
    minWidth = _useState10[0],
    setMinWidth = _useState10[1];
  useEffect(function () {
    if (searchText) {
      setIsSearch(true);
    } else {
      setIsSearch(false);
    }
  }, [searchText]);
  // useEffect(() => {
  //   updateHeight();
  // }, [treeWrapper.current?.offsetHeight]);
  // const updateHeight = useCallback(() => {
  //   if (treeWrapper.current?.offsetHeight !== height) {
  //     setHeight(treeWrapper.current?.offsetHeight);
  //   }
  // }, [height, treeWrapper, setHeight]);

  useEffect(function () {
    updateMinWidth();
  }, [(_treeWrapper$current = treeWrapper.current) === null || _treeWrapper$current === void 0 ? void 0 : _treeWrapper$current.scrollWidth, searchText,
  //   userList.length,
  treeData.length]);
  var updateMinWidth = useCallback(function () {
    var _treeWrapper$current2;
    if (searchText && treeData.length === 0) {
      setMinWidth(259);
    } else if (((_treeWrapper$current2 = treeWrapper.current) === null || _treeWrapper$current2 === void 0 ? void 0 : _treeWrapper$current2.scrollWidth) !== minWidth) {
      var _treeWrapper$current3;
      setMinWidth((_treeWrapper$current3 = treeWrapper.current) === null || _treeWrapper$current3 === void 0 ? void 0 : _treeWrapper$current3.scrollWidth);
    }
  }, [minWidth, treeWrapper, setMinWidth, searchText, treeData.length]);

  // useEffect(() => {
  //   window.addEventListener('resize', updateHeight);
  //   return () => {
  //     window.removeEventListener('resize', updateHeight);
  //   };
  // }, [updateHeight, window]);

  // 搜索
  var search = useCallback(function (value, requestId) {
    // 丢掉旧的请求
    // 如果输入的内容为纯空格，则不发送请求
    if (requestIds.current.search !== requestId || !value.trim()) {
      return;
    }
    var url = searchTreeNodes.url,
      method = searchTreeNodes.method,
      _searchTreeNodes$para = searchTreeNodes.params,
      params = _searchTreeNodes$para === void 0 ? {} : _searchTreeNodes$para;
    setLoading(true);
    // 增量获取子树
    // tslint:disable-next-line: no-floating-promises
    net.request(url, {
      method: method,
      data: _objectSpread(_objectSpread({}, params), {}, {
        keyword: value
      }),
      showError: true
    }).then(function (_ref2) {
      var data = _ref2.data,
        others = _objectWithoutProperties(_ref2, _excluded2);
      // 丢掉旧请求
      var code = others.code;
      // localStorage.setItem('request-code', code);
      if (requestIds.current.search !== requestId) {
        return;
      }
      setSearchResult(((data === null || data === void 0 ? void 0 : data.dataSource) || []).map(function (item) {
        return _objectSpread(_objectSpread({}, item), {}, {
          key: getUid(),
          id: item.key,
          label: item.labelPath || item.label,
          isLeaf: true
        });
      }));
      setSearchText(value);
      setLoading(false);
    }).catch(function () {
      setLoading(false);
    });
  }, [searchTreeNodes]);
  var debounced = useRef(debounce(search, 300, {
    leading: false
  }));
  var handleSearch = function handleSearch(e) {
    // e.persist();
    var value = e.target.value;
    var requestId = requestIds.current.search + 1;
    requestIds.current.search = requestId;

    // 如果是清空搜索框，则恢复原来的树
    if (!value) {
      setSearchText(value);
      setSearchResult([]);
      setLoading(false);
      // setUseList([]);
      return;
    }
    debounced.current(value, requestId);
  };
  var handleSelect = function handleSelect(nextSelectedKeys, event) {
    // debugger;
    // 点击展开收起
    var key = event.node.key;
    var matchedExpandIndex = expandedKeys.indexOf(key);
    // 禁止反选
    // if (event.selected) {
    //   setSelectedKeys(nextSelectedKeys);
    // }
    // setTimeout(() => {
    // 点击同一个项目
    if (nextSelectedKeys[0] === selectedKeys[0] && matchedExpandIndex >= 0) {
      setExpandedKeys([].concat(_toConsumableArray(expandedKeys.slice(0, matchedExpandIndex)), _toConsumableArray(expandedKeys.slice(matchedExpandIndex + 1))));
    } else {
      setExpandedKeys(Array.from(new Set([].concat(_toConsumableArray(expandedKeys), [key]))));
    }
    // 禁止反选
    if (!event.selected) {
      return;
    }
    // console.log(partialDataSource, 'partialDataSource');
    onSelect(nextSelectedKeys, event, partialDataSource);
    // }, 0);
  };
  var handleExpand = function handleExpand(nextExpandedKeys, event) {
    if (event.expanded) {
      loadData(event.node);
    } else {
      setExpandedKeys(nextExpandedKeys);
    }
  };

  // 根据 selectedKeys 寻找选中的节点 key
  useEffect(function () {
    // 如果有搜索内容，则不更新高亮项
    if (searchText) return;
    if (!dataSource) {
      setSelectedKeys([]);
      return;
    }
    var traverser = dataSource;
    var activeKey;
    var max = treePaths.length;
    treePaths.every(function (id, index) {
      if (!traverser) return false;
      var matchedItem = traverser.find(function (item) {
        return item.id === id;
      });
      // 没有找到目标节点，跳过
      if (!matchedItem) {
        return false;
      }
      if (index === max - 1) {
        activeKey = matchedItem.key;
      }
      traverser = matchedItem.children;
      return true;
    });
    setSelectedKeys(activeKey ? [activeKey] : []);
  }, [treePaths, dataSource, searchText]);

  // console.log(permissionCode, 'permissionCode1');
  // console.log(treeData, 'treeData');
  return /*#__PURE__*/React.createElement("div", {
    className: "ss-biz-tree"
  }, /*#__PURE__*/React.createElement("div", {
    className: "biz-search-main"
  }, showSearch ? /*#__PURE__*/React.createElement(Search
  // className="biz-tree-search"
  // shape="simple"
  , _extends({
    allowClear: true
  }, searchProps, {
    onChange: handleSearch
  })) : null), /*#__PURE__*/React.createElement("div", {
    className: "biz-tree-main",
    ref: treeWrapper
  }, /*#__PURE__*/React.createElement("div", {
    style: {
      width: minWidth
    }
  }, /*#__PURE__*/React.createElement(Spin, {
    delay: 500
    // wrapperClassName="biz-tree-main"
    ,
    spinning: loading
  }, permissionCode === 30512 && /*#__PURE__*/React.createElement("p", {
    className: "emptyText"
  }, "\u6743\u9650\u4E0D\u8DB3"), permissionCode === 9000 && /*#__PURE__*/React.createElement("p", {
    className: "emptyText"
  }, "\u6682\u65E0\u6570\u636E"),
  // 如果没有搜索结果，则提示文案
  permissionCode !== 30512 && searchText && treeData.length === 0 ? /*#__PURE__*/React.createElement("p", {
    className: "emptyText"
  }, "\u641C\u7D22\u7ED3\u679C\u4E3A\u7A7A\uFF0C\u8BF7\u8C03\u6574\u641C\u7D22\u5185\u5BB9") : null, permissionCode !== 30512 && searchText && treeData.length > 0 && (selfNameMap && selfNameMap[(_treeData$ = treeData[0]) === null || _treeData$ === void 0 ? void 0 : _treeData$.iconType] || nameMap[(_treeData$2 = treeData[0]) === null || _treeData$2 === void 0 ? void 0 : _treeData$2.iconType]) ? /*#__PURE__*/React.createElement("div", {
    className: "treeTitle"
  }, selfNameMap && selfNameMap[(_treeData$3 = treeData[0]) === null || _treeData$3 === void 0 ? void 0 : _treeData$3.iconType] || nameMap[treeData[0].iconType]) : null, permissionCode !== 30512 && /*#__PURE__*/React.createElement(Tree, _extends({
    className: searchText ? 'removeIndent000' : '',
    onExpand: handleExpand,
    expandedKeys: expandedKeys,
    onSelect: handleSelect,
    blockNode: true
    // height={height}
    // loadData={loadData}
    ,
    treeData: treeData,
    selectedKeys: selectedKeys
  }, others, {
    checkable: false
  })), searchText && treeData.length > 19 ? /*#__PURE__*/React.createElement("div", {
    className: "treeFooter"
  }, "\u4EC5\u5C55\u793A\u524D20\u4E2A\u641C\u7D22\u7ED3\u679C\uFF0C\u8BF7\u8F93\u5165\u66F4\u7CBE\u786E\u7684\u641C\u7D22\u5185\u5BB9\u83B7\u53D6") : null, !searchText && treeData.length > 19 ? /*#__PURE__*/React.createElement("div", {
    className: "treeFooter"
  }, "\u4EC5\u5C55\u793A\u524D20\u6761\u6570\u636E\uFF0C\u8BF7\u8F93\u5165\u66F4\u7CBE\u786E\u7684\u641C\u7D22\u5185\u5BB9\u83B7\u53D6") : null))));
}
export default CFTree;
export { PropTypes, ComposeTreeContext };