"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 _reactFlowRenderer = _interopRequireWildcard(require("@titaui/react-flow-renderer"));

var _isEqual = _interopRequireDefault(require("lodash/isEqual"));

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

var _html2canvas = _interopRequireDefault(require("html2canvas"));

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

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

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

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

var _drawerManager = _interopRequireDefault(require("../../drawer-manager"));

var _miniMap = _interopRequireDefault(require("../mini-map"));

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

var OkrMap = /*#__PURE__*/(0, _react.forwardRef)(function (props, ref) {
  var _props$direction = props.direction,
      direction = _props$direction === void 0 ? 'horizontal' : _props$direction,
      _props$darkTheme = props.darkTheme,
      darkTheme = _props$darkTheme === void 0 ? false : _props$darkTheme,
      _props$showkr = props.showkr,
      showkr = _props$showkr === void 0 ? false : _props$showkr,
      _props$onNodeClick = props.onNodeClick,
      onNodeClick = _props$onNodeClick === void 0 ? function () {} : _props$onNodeClick,
      _props$onChildExpand = props.onChildExpand,
      onChildExpand = _props$onChildExpand === void 0 ? function () {} : _props$onChildExpand,
      _props$onParentExpand = props.onParentExpand,
      onParentExpand = _props$onParentExpand === void 0 ? function () {} : _props$onParentExpand,
      _props$onChildClose = props.onChildClose,
      onChildClose = _props$onChildClose === void 0 ? function () {} : _props$onChildClose,
      _props$dataSource = props.dataSource,
      dataSource = _props$dataSource === void 0 ? [] : _props$dataSource;
  var virtualElements = (0, _react.useRef)([]);

  var _useState = (0, _react.useState)(),
      _useState2 = _slicedToArray(_useState, 2),
      flowInstance = _useState2[0],
      setFlowInstance = _useState2[1];

  var isMoving = (0, _react.useRef)(false);

  var handleEmementClick = function handleEmementClick(_e, element) {
    var _element$data = element.data,
        data = _element$data === void 0 ? {} : _element$data,
        type = element.type;
    if (type == 'default' || type == 'RootNode' || (data === null || data === void 0 ? void 0 : data.modelType) == 'work') return;
    onNodeClick & onNodeClick(data);
  };

  var getDefaultPos = function getDefaultPos() {
    var containerHeight = document.body.clientHeight - 200 - 96;
    var containerWidth = document.body.clientWidth - 180 - 320;
    var rootNode = virtualElements[0];

    if (direction == 'horizontal') {
      var targetY = containerHeight / 2;
      return [-160, targetY - rootNode.position.y];
    }

    var targetX = containerWidth / 2;
    return [targetX - rootNode.position.x, -48]; // debugger
    // return [0, 0]
  };

  var onLoad = function onLoad(reactFlowInstance) {
    setFlowInstance(reactFlowInstance);
  };

  var NodeDebug = function NodeDebug() {
    var elements = (0, _reactFlowRenderer.useStoreState)(function (state) {
      return [].concat(_toConsumableArray(state.nodes), _toConsumableArray(state.edges));
    }, _isEqual["default"]);
    var setElements = (0, _reactFlowRenderer.useStoreActions)(function (actions) {
      return actions.setElements;
    });
    var newElements = (0, _utils.getLayoutedElements)(elements, direction);
    virtualElements = newElements;
    setElements(newElements);
    return null;
  };

  (0, _react.useEffect)(function () {
    if (flowInstance) {
      var _getDefaultPos = getDefaultPos(),
          _getDefaultPos2 = _slicedToArray(_getDefaultPos, 2),
          x = _getDefaultPos2[0],
          y = _getDefaultPos2[1];

      flowInstance.setTransform({
        x: x,
        y: y,
        zoom: 1
      });
    }
  }, [direction, flowInstance]);

  var mapMovingHandler = function mapMovingHandler(e) {
    if (flowInstance) {
      var _flowInstance$toObjec = flowInstance.toObject(),
          _flowInstance$toObjec2 = _slicedToArray(_flowInstance$toObjec.position, 2),
          x = _flowInstance$toObjec2[0],
          y = _flowInstance$toObjec2[1],
          zoom = _flowInstance$toObjec.zoom,
          width = _flowInstance$toObjec.width,
          height = _flowInstance$toObjec.height;

      var spacePixel = 15;
      var moveX = x - e.movementX * spacePixel;
      var moveY = y - e.movementY * spacePixel;

      if (isMoving.current) {
        if (moveX > width * 2.5 || moveX < -1 * width * 2.5) return;
        if (moveY > height * 2.5 || moveY < -1 * height * 2.5) return;
        flowInstance.setTransform({
          x: moveX,
          y: moveY,
          zoom: zoom
        });
      }
    }
  };

  var panelMouseUpHandler = function panelMouseUpHandler() {
    isMoving.current = false; // drawerWrapper.close()
  };

  var closeOkrDrawer = function closeOkrDrawer() {
    var _window, _window$parent, _window$parent$docume, _window$parent$docume2;

    var mousedown = document.createEvent('MouseEvents');
    mousedown.initMouseEvent('mousedown', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
    (_window = window) === null || _window === void 0 ? void 0 : (_window$parent = _window.parent) === null || _window$parent === void 0 ? void 0 : (_window$parent$docume = _window$parent.document) === null || _window$parent$docume === void 0 ? void 0 : (_window$parent$docume2 = _window$parent$docume.body) === null || _window$parent$docume2 === void 0 ? void 0 : _window$parent$docume2.dispatchEvent(mousedown); // drawerWrapper.close()
  };

  return /*#__PURE__*/_react["default"].createElement(_context.CommonContext.Provider, {
    value: {
      direction: direction,
      showkr: showkr,
      onNodeClick: onNodeClick,
      onChildExpand: onChildExpand,
      onParentExpand: onParentExpand,
      onChildClose: onChildClose,
      darkTheme: darkTheme
    }
  }, /*#__PURE__*/_react["default"].createElement("div", {
    className: (0, _classnames["default"])("".concat(_precls["default"]), _defineProperty({}, "".concat(_precls["default"], "__dark"), darkTheme)),
    onMouseMove: mapMovingHandler,
    onMouseUp: panelMouseUpHandler,
    onClick: closeOkrDrawer
  }, /*#__PURE__*/_react["default"].createElement(_reactFlowRenderer.ReactFlowProvider, null, dataSource.length == 0 ? /*#__PURE__*/_react["default"].createElement(_empty["default"], null) : /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement(_reactFlowRenderer["default"], {
    onLoad: onLoad,
    elements: dataSource,
    nodesDraggable: false,
    nodesConnectable: false,
    nodeTypes: _utils.nodeTypes,
    onElementClick: handleEmementClick,
    minZoom: 0.25,
    maxZoom: 1.5,
    panOnScroll: true
  }, /*#__PURE__*/_react["default"].createElement(NodeDebug, null)), /*#__PURE__*/_react["default"].createElement(_miniMap["default"], {
    onMoveStart: function onMoveStart() {
      return isMoving.current = true;
    }
  })))));
});
var _default = OkrMap;
exports["default"] = _default;