function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

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 ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (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 = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { 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; }

import React, { useMemo, useCallback, useEffect } from 'react';
import { observer } from 'mobx-react-lite';
import moment from 'moment';
import { runInAction } from 'mobx';
import { uniqBy, toUpper, forEach, isEmpty, get, some } from 'lodash';
import setEnvRecentItem from "../../../../utils/setEnvRecentItem";
import { itemTypeMappings, RES_TYPES } from "../../stores/mappings";
import SidebarHeading from "./header";
import setTreeMenuSelect from "../../../../utils/setTreeMenuSelect";
import TreeView from "../../../../components/tree-view";
import TreeItem from "./tree-item";
import { useResourceStore } from "../../stores";
import { useMainStore } from "../stores";
import "./index.less";
import "./theme4.less";
var ENV_ITEM = itemTypeMappings.ENV_ITEM;
var TreeMenu = observer(function () {
  var _useResourceStore = useResourceStore(),
      treeDs = _useResourceStore.treeDs,
      prefixCls = _useResourceStore.prefixCls,
      resourceStore = _useResourceStore.resourceStore,
      _useResourceStore$App = _useResourceStore.AppState.currentMenuType,
      projectId = _useResourceStore$App.projectId,
      organizationId = _useResourceStore$App.organizationId,
      projectName = _useResourceStore$App.name,
      formatMessage = _useResourceStore.intl.formatMessage,
      _useResourceStore$vie = _useResourceStore.viewTypeMappings,
      RES_VIEW_TYPE = _useResourceStore$vie.RES_VIEW_TYPE,
      IST_VIEW_TYPE = _useResourceStore$vie.IST_VIEW_TYPE;

  var _useMainStore = useMainStore(),
      mainStore = _useMainStore.mainStore;

  var bounds = useMemo(function () {
    return mainStore.getNavBounds;
  }, [mainStore.getNavBounds]);
  var loadedKeys = useMemo(function () {
    return resourceStore.getLoadedKeys;
  }, [resourceStore.getLoadedKeys]);
  var nodeRenderer = useCallback(function (record, search) {
    return /*#__PURE__*/React.createElement(TreeItem, {
      record: record,
      search: search
    });
  }, []);
  useEffect(function () {
    var _ref = resourceStore.getSelectedMenu || {},
        key = _ref.key;

    if (!key || !some(resourceStore.getAllTreeData, ['key', key]) || resourceStore.getSearchValue) {
      setTreeMenuSelect(treeDs, resourceStore, getEnvItem);
    }
  }, [treeDs.data]);

  function getEnvItem(record) {
    var item = getParentRecord(record);

    if (item && item.itemType === ENV_ITEM) {
      var recentEnv = _objectSpread(_objectSpread({}, item), {}, {
        active: true,
        projectId: projectId,
        organizationId: organizationId,
        projectName: projectName,
        clickTime: moment().format('YYYY-MM-DD HH:mm:ss')
      });

      setEnvRecentItem({
        value: recentEnv
      });
    }
  }

  function getParentRecord(record) {
    if (record.parent) {
      return getParentRecord(record.parent);
    }

    return record.toData();
  }

  var getAllParents = useCallback(function (key, parentRecords, expandedKeys) {
    var parentRecord = resourceStore.getParentDataMap.get(key);

    if (parentRecord) {
      var parent = _objectSpread({}, parentRecord);

      parent.expand = true;
      expandedKeys.push(parentRecord.key);
      parentRecords.push(parent);
      getAllParents(parentRecord.key, parentRecords, expandedKeys);
    }
  }, []);
  var getAllChildren = useCallback(function (key, childrenRecords) {
    var children = resourceStore.getChildrenDataMap.get(key);

    if (!isEmpty(children)) {
      childrenRecords.push.apply(childrenRecords, _toConsumableArray(children));
      forEach(children, function (item) {
        getAllChildren(item.key, childrenRecords);
      });
    }
  }, []);
  var handleExpanded = useCallback(function (keys) {
    resourceStore.setExpandedKeys(keys);
  }, []);

  function handleSearch(_x) {
    return _handleSearch.apply(this, arguments);
  }

  function _handleSearch() {
    _handleSearch = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(value) {
      var realValue, expandedKeys, searchRecords;
      return regeneratorRuntime.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              realValue = value || '';
              expandedKeys = [];
              searchRecords = [];
              resourceStore.setSearchValue(realValue);
              resourceStore.setLoadedKeys([]);
              resourceStore.setExpandedKeys([]);

              if (value) {
                _context2.next = 9;
                break;
              }

              treeDs.query();
              return _context2.abrupt("return");

            case 9:
              if (!(value && resourceStore.getSearchValue && value !== resourceStore.getSearchValue)) {
                _context2.next = 12;
                break;
              }

              _context2.next = 12;
              return treeDs.query();

            case 12:
              // NOTE: 让多个 action 只执行一次
              runInAction(function () {
                /**
                 *
                 * 如果在 DataSet 的 load 方法中对原始数据进行了修改
                 * 那么就不能使用 ds.reset(); 进行重置，因为该方法是基于 originalData 的
                 * 应该手动将各记录重置
                 *
                 * */
                treeDs.forEach(function (record) {
                  record.reset();
                  /**
                   * 未清除搜索值就刷新，Record会记录expand状态，导致上一步record.reset()失效
                   * */
                  // eslint-disable-next-line no-param-reassign

                  record.isExpanded = false;
                });
                forEach(resourceStore.getAllTreeData, function (node) {
                  var name = get(node, 'name');
                  var key = get(node, 'key');

                  if (value && toUpper(name).indexOf(toUpper(value)) > -1) {
                    var childrenRecords = [];
                    var parentRecords = [];

                    var newNode = _objectSpread({}, node);

                    getAllParents(key, parentRecords, expandedKeys);
                    getAllChildren(key, childrenRecords);

                    if (!isEmpty(childrenRecords)) {
                      newNode.expand = true;
                      expandedKeys.push(key);
                    }

                    searchRecords.push.apply(searchRecords, [newNode].concat(parentRecords, childrenRecords));
                  }
                });
                var uniqKeys = new Set(expandedKeys);
                var newSearchRecords = uniqBy(searchRecords, 'key');
                handleExpanded(_toConsumableArray(uniqKeys));
                resourceStore.setLoadedKeys(_toConsumableArray(uniqKeys));
                treeDs.loadData(newSearchRecords);
              });

            case 13:
            case "end":
              return _context2.stop();
          }
        }
      }, _callee2);
    }));
    return _handleSearch.apply(this, arguments);
  }

  var onLoadData = useCallback( /*#__PURE__*/function () {
    var _ref3 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(_ref2) {
      var record, key, children;
      return regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              record = _ref2.record, key = _ref2.key, children = _ref2.children;
              resourceStore.loadMoreRecordData({
                key: key,
                treeDs: treeDs,
                children: children
              });

            case 2:
            case "end":
              return _context.stop();
          }
        }
      }, _callee);
    }));

    return function (_x2) {
      return _ref3.apply(this, arguments);
    };
  }(), [projectId]);
  var nodeCover = useCallback(function (_ref4) {
    var record = _ref4.record;
    var nodeProps = {
      title: nodeRenderer(record, resourceStore.getSearchValue),
      isLeaf: record.get('isLeaf')
    };
    return nodeProps;
  }, [resourceStore.getSearchValue]);
  return /*#__PURE__*/React.createElement("nav", {
    style: bounds,
    className: "".concat(prefixCls, "-sidebar")
  }, /*#__PURE__*/React.createElement(SidebarHeading, null), /*#__PURE__*/React.createElement("div", {
    className: "".concat(prefixCls, "-sidebar-menu")
  }, /*#__PURE__*/React.createElement(TreeView, {
    ds: treeDs,
    store: resourceStore,
    nodesRender: nodeRenderer,
    isFilter: true,
    onSearch: handleSearch,
    otherTreeProps: {
      loadData: onLoadData,
      loadedKeys: loadedKeys,
      treeNodeRenderer: nodeCover
    }
  })));
});
export default TreeMenu;