import "choerodon-ui/pro/lib/tree/style";
import _Tree from "choerodon-ui/pro/lib/tree";
import "choerodon-ui/pro/lib/text-field/style";
import _TextField from "choerodon-ui/pro/lib/text-field";
import "choerodon-ui/pro/lib/icon/style";
import _Icon from "choerodon-ui/pro/lib/icon";
import "choerodon-ui/lib/collapse/style";
import _Collapse from "choerodon-ui/lib/collapse";

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

/* eslint-disable no-param-reassign */
import React, { useMemo, useCallback, useEffect } from 'react';
import { observer } from 'mobx-react-lite';
import { runInAction } from 'mobx';
import toUpper from 'lodash/toUpper';
import debounce from 'lodash/debounce';
import ScrollContext from 'react-infinite-scroll-component';
import { usePipelineManageStore } from "../../stores";
import TreeItem from "./TreeItem";
import "./index.less";
var Panel = _Collapse.Panel;
var TreeMenu = observer(function () {
  var _usePipelineManageSto = usePipelineManageStore(),
      formatMessage = _usePipelineManageSto.intl.formatMessage,
      mainStore = _usePipelineManageSto.mainStore,
      prefixCls = _usePipelineManageSto.prefixCls,
      treeDs = _usePipelineManageSto.treeDs,
      projectId = _usePipelineManageSto.projectId;

  var bounds = useMemo(function () {
    return mainStore.getNavBounds;
  }, [mainStore.getNavBounds]);

  function nodeRenderer(_ref) {
    var record = _ref.record;
    return /*#__PURE__*/React.createElement(TreeItem, {
      record: record,
      search: mainStore.getSearchValue
    });
  }
  /**
   * 展开节点的所有父节点
   * 通过Record内置的方法展开目标节点
   * 将展开节点缓存进传入的数组
   * @param record
   * @param expendedKeys
   */


  function expandParents(record, expendedKeys) {
    if (!record.isExpanded) {
      var children = record.children,
          parent = record.parent;

      if (children && children.length || record.get('hasRecords')) {
        var key = record.get('key');
        expendedKeys.push(key);
        record.isExpanded = true;
      }

      if (parent && !parent.isExpanded) {
        expandParents(parent, expendedKeys);
      }
    }
  }

  var handleSearch = useCallback( /*#__PURE__*/function () {
    var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(value) {
      var realValue, expandedKeys, uniqKeys;
      return regeneratorRuntime.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              realValue = value || '';
              expandedKeys = []; // NOTE: 让多个 action 只执行一次

              runInAction( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
                return regeneratorRuntime.wrap(function _callee$(_context) {
                  while (1) {
                    switch (_context.prev = _context.next) {
                      case 0:
                        mainStore.setTreeDataPage(1);
                        mainStore.setSearchValue(realValue);
                        mainStore.setLoadedKeys([]);
                        handleExpanded([]);
                        /**
                         *
                         * 如果在 DataSet 的 load 方法中对原始数据进行了修改
                         * 那么就不能使用 ds.reset(); 进行重置，因为该方法是基于 originalData 的
                         * 应该手动将各记录重置
                         *
                         * */

                        treeDs.forEach(function (record) {
                          record.reset();
                          /**
                           * 未清除搜索值就刷新，Record会记录expand状态，导致上一步record.reset()失效
                           * */

                          record.isExpanded = false;
                        });
                        _context.next = 7;
                        return treeDs.query();

                      case 7:
                        treeDs.forEach(function (treeRecord) {
                          var pipelineName = treeRecord.get('name');
                          var appServiceName = treeRecord.get('appServiceName');
                          var parentId = treeRecord.get('parentId');
                          var id = parentId && treeRecord.get('viewId') ? treeRecord.get('viewId').toString() : null;

                          if (value) {
                            var _toUpper, _toUpper2, _toUpper3;

                            if (!parentId && (((_toUpper = toUpper(pipelineName)) === null || _toUpper === void 0 ? void 0 : _toUpper.indexOf(toUpper(value))) > -1 || ((_toUpper2 = toUpper(appServiceName)) === null || _toUpper2 === void 0 ? void 0 : _toUpper2.indexOf(toUpper(value))) > -1)) {
                              expandParents(treeRecord, expandedKeys);
                            } else if (parentId && ((_toUpper3 = toUpper(id)) === null || _toUpper3 === void 0 ? void 0 : _toUpper3.indexOf(toUpper(value))) > -1) {
                              expandParents(treeRecord, expandedKeys);
                            }
                          }
                        });

                      case 8:
                      case "end":
                        return _context.stop();
                    }
                  }
                }, _callee);
              })));
              uniqKeys = new Set(expandedKeys);
              handleExpanded(_toConsumableArray(uniqKeys));

            case 5:
            case "end":
              return _context2.stop();
          }
        }
      }, _callee2);
    }));

    return function (_x) {
      return _ref2.apply(this, arguments);
    };
  }(), []);

  function handleExpanded(keys) {
    mainStore.setExpandedKeys(keys);
  }

  var loadMoreTreeData = /*#__PURE__*/function () {
    var _ref4 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3() {
      var page;
      return regeneratorRuntime.wrap(function _callee3$(_context3) {
        while (1) {
          switch (_context3.prev = _context3.next) {
            case 0:
              page = mainStore.getTreeDataPage;
              mainStore.setTreeDataPage(page + 1);
              treeDs.query();

            case 3:
            case "end":
              return _context3.stop();
          }
        }
      }, _callee3);
    }));

    return function loadMoreTreeData() {
      return _ref4.apply(this, arguments);
    };
  }();

  var onLoadData = /*#__PURE__*/function () {
    var _ref6 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee4(_ref5) {
      var key, children;
      return regeneratorRuntime.wrap(function _callee4$(_context4) {
        while (1) {
          switch (_context4.prev = _context4.next) {
            case 0:
              key = _ref5.key, children = _ref5.children;

              if (children) {
                _context4.next = 4;
                break;
              }

              _context4.next = 4;
              return mainStore.loadRecordData({
                projectId: projectId,
                key: key,
                treeDs: treeDs
              });

            case 4:
            case "end":
              return _context4.stop();
          }
        }
      }, _callee4);
    }));

    return function onLoadData(_x2) {
      return _ref6.apply(this, arguments);
    };
  }();

  function nodeCover(_ref7) {
    var record = _ref7.record;
    var nodeProps = {
      title: /*#__PURE__*/React.createElement(TreeItem, {
        record: record,
        search: mainStore.getSearchValue
      })
    };

    if (!record.get('hasRecords')) {
      nodeProps.isLeaf = true;
    }

    return nodeProps;
  }

  return /*#__PURE__*/React.createElement("nav", {
    style: bounds,
    className: "".concat(prefixCls, "-sidebar")
  }, /*#__PURE__*/React.createElement(_TextField, {
    className: "".concat(prefixCls, "-sidebar-search"),
    placeholder: formatMessage({
      id: 'search.placeholder'
    }),
    clearButton: true,
    name: "search",
    prefix: /*#__PURE__*/React.createElement(_Icon, {
      type: "search"
    }),
    value: mainStore.getSearchValue,
    onChange: handleSearch
  }), !treeDs.length && treeDs.status === 'ready' ? /*#__PURE__*/React.createElement("span", {
    className: "".concat(prefixCls, "-sidebar-empty")
  }, formatMessage({
    id: 'nodata'
  })) : /*#__PURE__*/React.createElement(ScrollContext, {
    className: "".concat(prefixCls, "-sidebar-scroll"),
    dataLength: treeDs.length,
    next: loadMoreTreeData,
    hasMore: mainStore.getTreeDataHasMore,
    loader: null,
    height: "100%"
  }, /*#__PURE__*/React.createElement(_Tree, {
    dataSet: treeDs // renderer={nodeRenderer}
    ,
    onExpand: handleExpanded,
    className: "".concat(prefixCls, "-sidebar-tree"),
    loadData: onLoadData,
    treeNodeRenderer: nodeCover,
    loadedKeys: mainStore.getLoadedKeys
  })));
});
export default TreeMenu;