"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"] = void 0;

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

var _cloneDeep = _interopRequireDefault(require("clone-deep"));

var _classnames = _interopRequireDefault(require("classnames"));

var _okrMap = _interopRequireDefault(require("../../okr-map"));

var _requestApis = require("../../request-apis");

var _helper = require("../../utils/helper");

var _treeHandler = require("../../utils/tree-handler");

var _toast = _interopRequireDefault(require("../../../toast"));

var _exportModal = _interopRequireDefault(require("../../export-modal"));

var _config = require("../../utils/config");

require("./index.css");

var _precls = _interopRequireDefault(require("../../precls"));

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 _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 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 _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 OkrSearchPanel(props, ref) {
  var searchType = props.searchType,
      _props$rootId = props.rootId,
      rootId = _props$rootId === void 0 ? 0 : _props$rootId,
      _props$rootName = props.rootName,
      rootName = _props$rootName === void 0 ? '' : _props$rootName,
      _props$avatar = props.avatar,
      avatar = _props$avatar === void 0 ? {} : _props$avatar,
      direction = props.direction,
      cycleType = props.cycleType,
      yqmNum = props.yqmNum,
      annualNum = props.annualNum,
      _props$okrType = props.okrType,
      okrType = _props$okrType === void 0 ? '' : _props$okrType,
      _props$openLevel = props.openLevel,
      openLevel = _props$openLevel === void 0 ? 2 : _props$openLevel,
      _props$showkr = props.showkr,
      showkr = _props$showkr === void 0 ? true : _props$showkr,
      _props$darkTheme = props.darkTheme,
      darkTheme = _props$darkTheme === void 0 ? false : _props$darkTheme,
      _props$showCardKr = props.showCardKr,
      showCardKr = _props$showCardKr === void 0 ? false : _props$showCardKr,
      onNodeClick = props.onNodeClick;

  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),
      dataSource = _useState4[0],
      setDataSource = _useState4[1];

  var _useState5 = (0, _react.useState)(false),
      _useState6 = _slicedToArray(_useState5, 2),
      exportVisible = _useState6[0],
      setExportVisible = _useState6[1];

  var _useState7 = (0, _react.useState)(null),
      _useState8 = _slicedToArray(_useState7, 2),
      treeNodes = _useState8[0],
      setTreeNodes = _useState8[1]; // 当前树


  var getSearchData = (0, _react.useRef)((0, _helper.debounce)( /*#__PURE__*/function () {
    var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(searchType, rootId, rootName, avatar, cycleType, yqmNum, annualNum, okrType, openLevel, showkr, showCardKr) {
      var _yield$searchOkrs, works, okrIds, nodes, allNodes, subTreeNodes;

      return regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              setLoading(true);
              setTreeNodes(null);
              _context.next = 4;
              return (0, _requestApis.searchOkrs)({
                cycleType: cycleType,
                yqmNum: yqmNum,
                annualNum: annualNum,
                userIds: searchType == 'user' ? rootId : '',
                departmentIds: searchType == 'depart' ? rootId : '',
                haveSubDept: false,
                onlyThisDept: true,
                // 地图中不显示子部门
                groupIds: searchType == 'group' ? rootId : '',
                orderType: 2,
                // 排序
                okrType: _config.OkrTypeSetting ? searchType == 'user' ? '' : okrType : '',
                status: 0
              });

            case 4:
              _yield$searchOkrs = _context.sent;
              works = _yield$searchOkrs.works;
              okrIds = (works || []).reduce(function (ids, cur) {
                return [].concat(_toConsumableArray(ids), [cur.workId]);
              }, []);

              if (okrIds.length) {
                _context.next = 11;
                break;
              }

              setDataSource([]);
              setLoading(false);
              return _context.abrupt("return");

            case 11:
              _context.next = 13;
              return (0, _requestApis.expandNodesByLevel)({
                okrIds: okrIds,
                level: openLevel - 1,
                showKr: showkr ? 1 : 0,
                showCardKr: showCardKr ? 1 : 0
              });

            case 13:
              nodes = _context.sent;
              allNodes = (0, _treeHandler.formatNodes)(nodes, showkr, okrIds); // 初始情况

              subTreeNodes = (0, _treeHandler.buildTreeNodes)(allNodes, openLevel, showkr);
              setTreeNodes({
                id: 0,
                modelType: 'root',
                data: _defineProperty({
                  searchType: searchType,
                  rootName: rootName,
                  rootId: rootId,
                  avatar: {
                    hasAvatar: avatar.HasAvatar || avatar.hasAvatar,
                    color: avatar.Color || avatar.color,
                    small: avatar.Small || avatar.small,
                    big: avatar.Original || avatar.original || avatar.large || avatar.big || avatar.Large
                  }
                }, "searchType", searchType),
                children: subTreeNodes
              });
              setLoading(false);

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

    return function (_x, _x2, _x3, _x4, _x5, _x6, _x7, _x8, _x9, _x10, _x11) {
      return _ref.apply(this, arguments);
    };
  }(), 500)).current;
  var okrFlow = (0, _react.useRef)();
  (0, _react.useEffect)(function () {
    if (!annualNum) return;
    getSearchData(searchType, rootId, rootName, avatar, cycleType, yqmNum, annualNum, okrType, openLevel, showkr, showCardKr);
  }, [searchType, rootId, rootName, cycleType, yqmNum, annualNum, okrType, openLevel, showkr, showCardKr]);
  (0, _react.useEffect)(function () {
    var data = (0, _treeHandler.transToMapData)(treeNodes, showkr);
    setDataSource(data.length > 1 ? data : []);
  }, [treeNodes, showkr, showCardKr]);

  var handleParentExpand = /*#__PURE__*/function () {
    var _ref2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(node) {
      var id, modelType, data, res, _toTree, _toTree2, parentTree, prevIndex, prevNode, i;

      return regeneratorRuntime.wrap(function _callee2$(_context2) {
        while (1) {
          switch (_context2.prev = _context2.next) {
            case 0:
              id = node.id, modelType = node.modelType, data = node.data;
              _context2.next = 3;
              return (0, _requestApis.expandNode)({
                krId: modelType == 'kr' ? id : 0,
                okrId: modelType == 'kr' ? data.workId : id,
                okrIdParent: modelType == 'work' ? data.parentId : data.workId,
                childRoot: false,
                showCardKr: showCardKr ? 1 : 0
              });

            case 3:
              res = _context2.sent;
              _toTree = (0, _treeHandler.toTree)((0, _treeHandler.formatNodes)(res, showkr), showkr), _toTree2 = _slicedToArray(_toTree, 1), parentTree = _toTree2[0];
              treeNodes.children.forEach(function (item, index) {
                if (!item) return false;

                if (item.id == id) {
                  prevNode = item;
                  prevIndex = index;
                }
              });

              for (i = 0; i < parentTree.children.length; i++) {
                if (parentTree.children[i].id == id) {
                  parentTree.children[i] = prevNode;
                }
              }

              (0, _treeHandler.diffAndUpdate)([parentTree], treeNodes.children || []);
              treeNodes.children.splice(prevIndex, 1, parentTree);
              setTreeNodes((0, _cloneDeep["default"])(treeNodes));

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

    return function handleParentExpand(_x12) {
      return _ref2.apply(this, arguments);
    };
  }();

  var handleChildExpand = /*#__PURE__*/function () {
    var _ref3 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3(node) {
      var id, modelType, data, res, children, subNodes, i, currentExpandNode;
      return regeneratorRuntime.wrap(function _callee3$(_context3) {
        while (1) {
          switch (_context3.prev = _context3.next) {
            case 0:
              id = node.id, modelType = node.modelType, data = node.data;
              _context3.next = 3;
              return (0, _requestApis.expandNode)({
                krId: modelType == 'kr' ? id : 0,
                okrId: modelType == 'work' ? id : data.workId,
                okrIdParent: 0,
                childRoot: true,
                showCardKr: showCardKr ? 1 : 0,
                currentOkrRole: modelType == 'kr' ? data.mapkrVisible : data.MapOkrVisible
              });

            case 3:
              res = _context3.sent;
              children = (0, _treeHandler.formatNodes)(res, showkr);
              subNodes = (0, _treeHandler.toTree)(children, showkr);

              for (i = 0; i < subNodes.length; i++) {
                (0, _treeHandler.checkChildrenLevel)(subNodes[i], 1, 1);
              } // const { children: firstLevelNodes = [] } = treeNodes;
              // diffAndUpdate(subNodes, firstLevelNodes); //children merge firstLevelNodes


              currentExpandNode = (0, _treeHandler.findNode)(treeNodes, id);
              currentExpandNode.children = subNodes;
              setTreeNodes((0, _cloneDeep["default"])(treeNodes));

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

    return function handleChildExpand(_x13) {
      return _ref3.apply(this, arguments);
    };
  }();

  var handleChildClose = function handleChildClose(id) {
    (0, _treeHandler.deleteChildrenById)(treeNodes, id);
    setTreeNodes((0, _cloneDeep["default"])(treeNodes));
  };

  var handleNodeClick = function handleNodeClick(node) {
    onNodeClick && onNodeClick(node);
  };

  var exportCurrentFlow = /*#__PURE__*/function () {
    var _ref4 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee4() {
      return regeneratorRuntime.wrap(function _callee4$(_context4) {
        while (1) {
          switch (_context4.prev = _context4.next) {
            case 0:
              if (dataSource.length) {
                _context4.next = 3;
                break;
              }

              _toast["default"].Warning('暂无OKR');

              return _context4.abrupt("return");

            case 3:
              setExportVisible(true);

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

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

  (0, _react.useImperativeHandle)(ref, function () {
    return {
      updateNodeData: function updateNodeData(_ref5) {
        var id = _ref5.id,
            data = _ref5.data;
        if (!id) return;
        var updateNode = (0, _treeHandler.findNode)(treeNodes, id);
        if (!updateNode) return;
        updateNode.data = _objectSpread(_objectSpread({}, updateNode.data), data);
        setTreeNodes((0, _cloneDeep["default"])(treeNodes));
      },
      deleteNode: function deleteNode(_ref6) {
        var id = _ref6.id;
        if (!id) return; // 删除当前kr ，将kr 的children 添加到parent.children 中

        (0, _treeHandler.deleteKrById)(id, treeNodes);
        setTreeNodes((0, _cloneDeep["default"])(treeNodes));
      },
      exportCurrentFlow: exportCurrentFlow
    };
  });

  var cancelHandler = function cancelHandler() {
    return setExportVisible(false);
  };

  return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, loading ? /*#__PURE__*/_react["default"].createElement("div", {
    className: (0, _classnames["default"])("".concat(_precls["default"], "--loading"))
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: (0, _classnames["default"])("".concat(_precls["default"], "--loading-img"), _defineProperty({}, "".concat(_precls["default"], "--loading-img__dark"), darkTheme))
  })) : /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement(_okrMap["default"], {
    ref: okrFlow,
    dataSource: dataSource,
    direction: direction,
    darkTheme: darkTheme,
    showkr: showkr,
    onNodeClick: handleNodeClick,
    onChildExpand: handleChildExpand,
    onChildClose: handleChildClose,
    onParentExpand: handleParentExpand
  }), /*#__PURE__*/_react["default"].createElement(_exportModal["default"], {
    visible: exportVisible,
    onCloseHandler: cancelHandler,
    direction: direction,
    darkTheme: darkTheme,
    showkr: showkr,
    dataSource: dataSource
  })));
}

var _default = /*#__PURE__*/(0, _react.forwardRef)(OkrSearchPanel);

exports["default"] = _default;