import _defineProperty from "@babel/runtime-corejs3/helpers/defineProperty";
import _concatInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/concat";
import _findInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/find";
import _sliceInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/slice";
import _findIndexInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/find-index";
import React from 'react';
import { fromEvent } from 'rxjs';
import { map, takeUntil, filter } from 'rxjs/operators';
import cx from 'classnames';
import { Classes } from '../../base/styles';
import { FeatureName } from '../const';
import { internals } from '../../internals';
export var ROW_DRAG_COLUMN_CODE = '$_row_drag_column_&';
export var rowDragKey = 'rowDragKey';
export var rowDragOptionsKey = 'rowDragOptions';
var SCROLL_OFFSET = 30;
var SCROLL_START_OFFSET = 20;
var defaultRowDragColumn = {
  name: '拖拽列',
  code: ROW_DRAG_COLUMN_CODE,
  lock: true,
  title: '',
  width: 40,
  align: 'center',
  getCellProps: function getCellProps(value, row, rowIndex) {
    return {
      className: cx(Classes.rowDragCell)
    };
  },
  render: function render(value, row, rowIndex) {
    return /*#__PURE__*/React.createElement("svg", {
      viewBox: '0 0 1024 1024',
      version: '1.1',
      xmlns: 'http://www.w3.org/1999/xlink',
      "data-icon": 'drag',
      width: '16',
      height: '16'
    }, /*#__PURE__*/React.createElement("path", {
      d: 'M298.688 192a64 64 0 1 0 128 0 64 64 0 0 0-128 0z m298.624 0a64 64 0 1 0 128 0 64 64 0 0 0-128 0zM298.688 512a64 64 0 1 0 128 0 64 64 0 0 0-128 0z m298.624 0a64 64 0 1 0 128 0 64 64 0 0 0-128 0z m-298.624 320a64 64 0 1 0 128 0 64 64 0 0 0-128 0z m298.624 0a64 64 0 1 0 128 0 64 64 0 0 0-128 0z',
      "p-id": '4278'
    }));
  }
};
export function rowDrag(opt) {
  return function rowDragStep(pipeline) {
    var _context;
    var tableBody = pipeline.ref.current.domHelper && pipeline.ref.current.domHelper.tableBody;
    var artTable = pipeline.ref.current.domHelper && pipeline.ref.current.domHelper.artTable;
    var rowDragApi = pipeline.addFeatureApi(FeatureName.rowDrag);
    pipeline.setFeatureOptions(rowDragOptionsKey, opt);
    if (!tableBody) return pipeline;
    var dataSource = pipeline.getDataSource();
    var getRowDragEvent = function getRowDragEvent(dropTargetEvent, isFinished) {
      var dragItem = dropTargetEvent.dragItem,
        x = dropTargetEvent.x,
        y = dropTargetEvent.y,
        dropZoneTarget = dropTargetEvent.dropZoneTarget,
        startDropZoneTagret = dropTargetEvent.startDropZoneTagret,
        commonParams = dropTargetEvent.commonParams,
        startCommonParams = dropTargetEvent.startCommonParams,
        event = dropTargetEvent.event,
        dropZoneTableParams = dropTargetEvent.dropZoneTableParams;
      var getDataSource = dropZoneTableParams.getDataSource,
        getTreeModeOptions = dropZoneTableParams.getTreeModeOptions,
        getRowDragOptions = dropZoneTableParams.getRowDragOptions;
      var dataSource = getDataSource();
      var treeModeOptions = getTreeModeOptions();
      var rowDragOptions = getRowDragOptions();
      var allowDragIntoRow = !!treeModeOptions && (rowDragOptions === null || rowDragOptions === void 0 ? void 0 : rowDragOptions.allowDragIntoRow);
      var isLeave = !isMouseOnDropTarget(event, dropZoneTarget);
      var overIndex = -1;
      var direction = 'bottom';
      if (!isLeave) {
        var overDragItem = getDragRowItem(event.target, dropZoneTarget, dataSource);
        if (overDragItem) {
          var rowIndex = overDragItem.rowIndex,
            cell = overDragItem.cell;
          overIndex = rowIndex;
          direction = getDirection(cell, event.clientY, allowDragIntoRow);
        }
      }
      var overRow = overIndex >= 0 ? dataSource[overIndex] : null;
      return {
        startRowIndex: dragItem.rowIndex,
        startRow: dragItem.row,
        endRowIndex: overIndex,
        endRow: overRow,
        startDropZoneTagret: startDropZoneTagret,
        startCommonParams: startCommonParams,
        commonParams: commonParams,
        dropZoneTarget: dropZoneTarget,
        event: event,
        dragPosition: direction,
        isFinished: isFinished,
        x: x,
        y: y
      };
    };
    var onDragging = function onDragging(event) {
      var _a;
      var rowDragEvent = getRowDragEvent(event, false);
      (_a = opt === null || opt === void 0 ? void 0 : opt.onDragMove) === null || _a === void 0 ? void 0 : _a.call(opt, rowDragEvent);
      pipeline.setStateAtKey(rowDragKey, rowDragEvent);
    };
    var onDragStop = function onDragStop(event) {
      var _a;
      var rowDragEvent = getRowDragEvent(event, true);
      pipeline.setStateAtKey(rowDragKey, rowDragEvent);
      (_a = opt === null || opt === void 0 ? void 0 : opt.onDragEnd) === null || _a === void 0 ? void 0 : _a.call(opt, rowDragEvent);
    };
    var onDragStart = function onDragStart(event) {
      var _a;
      var rowDragEvent = getRowDragEvent(event, false);
      (_a = opt === null || opt === void 0 ? void 0 : opt.onDragStart) === null || _a === void 0 ? void 0 : _a.call(opt, rowDragEvent);
    };
    var onDragLeave = function onDragLeave(event) {
      var _a;
      var rowDragEvent = getRowDragEvent(event, false);
      pipeline.setStateAtKey(rowDragKey, rowDragEvent);
      (_a = opt === null || opt === void 0 ? void 0 : opt.onDragLeave) === null || _a === void 0 ? void 0 : _a.call(opt, rowDragEvent);
    };
    var onDragEnter = function onDragEnter(event) {
      var _a;
      var rowDragEvent = getRowDragEvent(event, false);
      pipeline.setStateAtKey(rowDragKey, rowDragEvent);
      (_a = opt === null || opt === void 0 ? void 0 : opt.onDragEnter) === null || _a === void 0 ? void 0 : _a.call(opt, rowDragEvent);
    };
    var currentDropZone = {
      getContainer: function getContainer() {
        var lastPipeline = pipeline.getLastPipeline();
        return lastPipeline.ref.current.domHelper.tableBody;
      },
      onDragEnter: onDragEnter,
      onDragLeave: onDragLeave,
      onDragging: onDragging,
      onDragStop: onDragStop,
      isTable: true,
      tableParams: {
        getDataSource: function getDataSource() {
          var lastPipeline = pipeline.getLastPipeline();
          return lastPipeline.getDataSource();
        },
        getTreeModeOptions: function getTreeModeOptions() {
          var lastPipeline = pipeline.getLastPipeline();
          return lastPipeline.getFeatureOptions('treeModeOptions');
        },
        getRowDragOptions: function getRowDragOptions() {
          var lastPipeline = pipeline.getLastPipeline();
          return lastPipeline.getFeatureOptions('rowDragOptions');
        }
      }
    };
    var onMouseDown = function onMouseDown(event) {
      var _a;
      var mouseDownEvent = event.nativeEvent;
      var startDataItem = getDragRowItem(mouseDownEvent.target, tableBody, dataSource);
      if (!startDataItem || startDataItem.code !== rowDragColumn.code) return;
      if ((_a = opt === null || opt === void 0 ? void 0 : opt.isDisabled) === null || _a === void 0 ? void 0 : _a.call(opt, startDataItem.row, startDataItem.rowIndex)) return;
      var isValidDrag = false;
      var isDragging = false;
      var dragElement = null;
      var dragLine = null;
      var lastDropTarget = null;
      var timeoutId = null;
      var intervalId = null;
      var expandRowTimeoutId = null;
      var expandRowCallBackList = [];
      var updateScrollPosition = function updateScrollPosition(tableBody, mouseMoveEvent) {
        if (opt === null || opt === void 0 ? void 0 : opt.suppressScrollMove) return;
        if (timeoutId) {
          clearTimeout(timeoutId);
        }
        if (intervalId) {
          clearInterval(intervalId);
        }
        var moveOffset = getScrollMoveOffset(tableBody, mouseMoveEvent);
        if (moveOffset === 0) {
          return;
        }
        timeoutId = setTimeout(function () {
          intervalId = setInterval(function () {
            tableBody.scrollTop += moveOffset;
          }, 100);
        }, 500);
      };
      var handleDragStart = function handleDragStart(mouseDownEvent) {
        var _a;
        dragElement = createDragElement(mouseDownEvent, tableBody); // 创建拖拽悬浮框
        var isTreeTable = !!pipeline.getFeatureOptions('treeModeOptions');
        dragLine = createDragLine(isTreeTable); // 创建拖拽插入指示线
        var dragText = (opt === null || opt === void 0 ? void 0 : opt.rowDragText) ? (_a = opt === null || opt === void 0 ? void 0 : opt.rowDragText) === null || _a === void 0 ? void 0 : _a.call(opt, startDataItem.row, startDataItem.rowIndex) : "\u7B2C".concat(startDataItem.rowIndex, "\u884C\u5185\u5BB9");
        setDragText(dragElement, dragText); // 设置悬浮框显示文本
        artTable.classList.add(cx(Classes.rowDragging));
        rowDragApi.setDragStatus('start');
        var dragEvent = createDropTargetEvent(currentDropZone, mouseDownEvent, startDataItem, currentDropZone);
        onDragStart(dragEvent);
      };
      var handleDragMove = function handleDragMove(mouseMoveEvent) {
        var _a;
        positionDragElemment(dragElement, mouseMoveEvent); // 更新拖拽悬浮框位置
        rowDragApi.setDragStatus('dragging');
        setDragElementIcon(dragElement, 'move');
        var rowDropZones = rowDragApi.getRowDropZone();
        var validDropZones = _concatInstanceProperty(rowDropZones).call(rowDropZones, currentDropZone); // 可放置区域加上自身
        var dropTarget = _findInstanceProperty(validDropZones).call(validDropZones, function (zone) {
          return isMouseOnDropTarget(mouseMoveEvent, zone.getContainer());
        }) || null;
        if (dropTarget !== lastDropTarget) {
          // 拖拽离开表格
          if (lastDropTarget !== null && dropTarget === null) {
            if (lastDropTarget.onDragLeave) {
              setDragElementIcon(dragElement, 'notAllowed');
              hiddenDragLine(dragLine);
              var dragEvent = createDropTargetEvent(lastDropTarget, mouseMoveEvent, startDataItem, currentDropZone);
              lastDropTarget.onDragLeave(dragEvent);
            }
          }
          // 拖拽进入表格
          if (lastDropTarget === null && dropTarget !== null) {
            if (dropTarget.onDragEnter) {
              setDragElementIcon(dragElement, 'move');
              if (dropTarget.isTable) {
                showDragLine(dragLine);
              }
              var _dragEvent = createDropTargetEvent(dropTarget, mouseMoveEvent, startDataItem, currentDropZone);
              dropTarget.onDragEnter(_dragEvent);
            }
          }
          lastDropTarget = dropTarget;
        }
        if (dropTarget) {
          // 拖拽区域在表格中，更新拖拽插入指示线位置
          if (dropTarget.isTable) {
            positionDragLine({
              lineElement: dragLine,
              dragZone: dropTarget,
              event: mouseMoveEvent
            });
            updateScrollPosition(dropTarget.getContainer(), mouseMoveEvent); // 拖拽到底时让滚动条可以滚动
          }
          // 树形表格悬停1s展开对应行节点
          if ((_a = dropTarget === null || dropTarget === void 0 ? void 0 : dropTarget.tableParams) === null || _a === void 0 ? void 0 : _a.getTreeModeOptions()) {
            if (expandRowTimeoutId) {
              clearTimeout(expandRowTimeoutId);
            }
            expandRowTimeoutId = setTimeout(function () {
              var treeModeOptions = dropTarget.tableParams.getTreeModeOptions();
              var treeMetaKey = treeModeOptions.treeMetaKey,
                onExpand = treeModeOptions.onExpand,
                isExpanded = treeModeOptions.isExpanded,
                onCollapse = treeModeOptions.onCollapse;
              // 鼠标悬停所在的拖拽行信息
              var dataSource = dropTarget.tableParams.getDataSource();
              var dragItem = getDragRowItem(mouseMoveEvent.target, dropTarget.getContainer(), dataSource);
              if (!dragItem) return;
              var row = dragItem.row;
              var rowKey = row[treeMetaKey].rowKey;
              if (!isExpanded(rowKey)) {
                onExpand(rowKey);
                expandRowCallBackList.push(function () {
                  return onCollapse(rowKey);
                });
              }
            }, 1000);
          }
          if (dropTarget.onDragging) {
            var _dragEvent2 = createDropTargetEvent(dropTarget, mouseMoveEvent, startDataItem, currentDropZone);
            dropTarget.onDragging(_dragEvent2);
          }
        }
      };
      var handleDragStop = function handleDragStop(mouseUpEvent) {
        removeElement(dragElement);
        removeElement(dragLine);
        artTable.classList.remove(cx(Classes.rowDragging));
        rowDragApi.setDragStatus('finished');
        clearTimeout(timeoutId);
        clearInterval(intervalId);
        clearTimeout(expandRowTimeoutId);
        while (expandRowCallBackList.length > 0) {
          var callback = expandRowCallBackList.pop();
          callback();
        }
        var rowDropZones = rowDragApi.getRowDropZone();
        var validDropZones = _concatInstanceProperty(rowDropZones).call(rowDropZones, currentDropZone);
        var dropTarget = _findInstanceProperty(validDropZones).call(validDropZones, function (zone) {
          return isMouseOnDropTarget(mouseUpEvent, zone.getContainer());
        });
        if (dropTarget && dropTarget.onDragStop) {
          var dragEvent = createDropTargetEvent(dropTarget, mouseUpEvent, startDataItem, currentDropZone);
          dropTarget.onDragStop(dragEvent);
        }
      };
      var mousemove$ = fromEvent(window, 'mousemove');
      var mouseup$ = fromEvent(window, 'mouseup');
      var rowDragMove$ = mousemove$.pipe(filter(function (mouseMoveEvent) {
        var mouseMoveClientY = mouseMoveEvent.clientY;
        var mouseDownClientY = mouseDownEvent.clientY;
        // 上下移动偏移量大于5才是有效的拖拽
        if (Math.abs(mouseMoveClientY - mouseDownClientY) > 5) {
          isValidDrag = true;
        }
        return isValidDrag;
      }), map(function (mouseMoveEvent) {
        if (!isDragging) {
          isDragging = true;
          handleDragStart(mouseDownEvent);
          handleDragMove(mouseDownEvent);
        }
        handleDragMove(mouseMoveEvent);
      }), takeUntil(mouseup$));
      rowDragMove$.subscribe();
      var rowDragEnd$ = mouseup$.pipe(map(function (mouseUpEvent) {
        handleDragStop(mouseUpEvent);
      })).subscribe({
        next: function next() {
          rowDragEnd$.unsubscribe();
        }
      });
    };
    var rowDragColumn = (opt === null || opt === void 0 ? void 0 : opt.rowDragColumn) || defaultRowDragColumn;
    pipeline.setFeatureOptions('rowDragColumnKey', rowDragColumn.code);
    rowDragApi.setRowDropZoneParams(currentDropZone);
    var nextColumns = _sliceInstanceProperty(_context = pipeline.getColumns()).call(_context);
    nextColumns.unshift(rowDragColumn);
    pipeline.columns(nextColumns);
    pipeline.addTableProps({
      onMouseDown: onMouseDown
    });
    pipeline.appendRowPropsGetter(function (row, rowIndex) {
      var rowDragEvent = pipeline.getStateAtKey(rowDragKey) || {};
      var dragStatus = rowDragApi.getDragStatus();
      var startRowIndex = rowDragEvent.startRowIndex,
        endRowIndex = rowDragEvent.endRowIndex,
        endRow = rowDragEvent.endRow,
        isFinished = rowDragEvent.isFinished,
        dragPosition = rowDragEvent.dragPosition;
      var isFooterCell = row[pipeline.getFeatureOptions('footerRowMetaKey')];
      var treeModeOptions = pipeline.getFeatureOptions('treeModeOptions');
      var isTreeTable = !!treeModeOptions;
      if (isFooterCell || isFinished || !isTreeTable && rowIndex !== startRowIndex && rowIndex !== endRowIndex) return;
      var parentRowKeyIndex = -1;
      if (isTreeTable && endRow) {
        var _context2;
        var treeMetaKey = treeModeOptions.treeMetaKey;
        var parentRowKey = endRow[treeMetaKey].parentRowKey;
        var primaryKey = pipeline.ensurePrimaryKey('rowDrag');
        parentRowKeyIndex = _findIndexInstanceProperty(_context2 = pipeline.getDataSource()).call(_context2, function (row) {
          return internals.safeGetRowKey(primaryKey, row, -1) === parentRowKey;
        });
      }
      var className = cx(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({}, Classes.rowDragStart, rowIndex === startRowIndex && dragStatus !== 'finished'), Classes.rowDragEnd, rowIndex === endRowIndex), Classes.rowDragEndParent, isTreeTable && rowIndex === parentRowKeyIndex && dragPosition !== 'into'), Classes.rowDragEndInto, rowIndex === endRowIndex && dragPosition === 'into'), Classes.rowDragEndToTop, rowIndex === endRowIndex && dragPosition === 'top'), Classes.rowDragEndToBottom, rowIndex === endRowIndex && dragPosition === 'bottom'));
      return {
        className: className
      };
    });
    return pipeline;
  };
}
function getDragRowItem(target, tableBody, record) {
  while (target && tableBody.contains(target)) {
    if (target.getAttribute('data-role') === 'table-cell') {
      var code = target.getAttribute('data-code');
      var rowIndex = parseInt(target.getAttribute('data-rowindex'));
      var row = record[rowIndex];
      var isFooterCell = isEleInFooter(target);
      if (!row || isFooterCell) return null;
      return {
        rowIndex: rowIndex,
        row: row,
        code: code,
        cell: target
      };
    }
    target = target.parentElement;
  }
  return null;
}
function findTargetRow(target, tableBody) {
  while (target && tableBody.contains(target)) {
    if (target.getAttribute('data-role') === 'table-row') {
      return target;
    }
    target = target.parentElement;
  }
  return null;
}
function isEleInFooter(target) {
  while (target && !target.classList.contains(Classes.artTable)) {
    if (target.classList.contains(Classes.tableFooter)) {
      return true;
    }
    target = target.parentElement;
  }
  return false;
}
function createDragElement(mouseDownEvent, tableBody) {
  var _context3, _context4;
  var ELEMENT_TEMPLATE = _concatInstanceProperty(_context3 = _concatInstanceProperty(_context4 = "<div class='".concat(Classes.rowDragElement, "'>\n      <span class='")).call(_context4, Classes.rowDragElementIcon, "'></span>\n      <div class='")).call(_context3, Classes.rowDragElementLabel, "'></div>\n    </div>");
  var element = document.createElement('div');
  element.innerHTML = ELEMENT_TEMPLATE;
  var dragElement = element.firstChild;
  var targetRow = findTargetRow(mouseDownEvent.target, tableBody);
  if (targetRow) {
    var rect = targetRow.getBoundingClientRect();
    dragElement.style.height = rect.height + 'px';
  }
  var bodyRect = tableBody.getBoundingClientRect();
  dragElement.style.maxWidth = bodyRect.width + 'px';
  document.body.appendChild(dragElement);
  return dragElement;
}
function createDragLine(isTreeTable) {
  var dragLine = document.createElement('div');
  dragLine.classList.add(Classes.rowDragLine);
  if (isTreeTable) {
    dragLine.classList.add(Classes.treeTableRowDragLine);
  }
  document.body.appendChild(dragLine);
  return dragLine;
}
function positionDragLine(_ref) {
  var lineElement = _ref.lineElement,
    dragZone = _ref.dragZone,
    event = _ref.event;
  var tableContainer = dragZone.getContainer();
  var _dragZone$tableParams = dragZone.tableParams,
    getDataSource = _dragZone$tableParams.getDataSource,
    getTreeModeOptions = _dragZone$tableParams.getTreeModeOptions,
    getRowDragOptions = _dragZone$tableParams.getRowDragOptions;
  var dataSource = getDataSource();
  var treeModeOptions = getTreeModeOptions();
  var rowDragOptions = getRowDragOptions() || {};
  var allowDragIntoRow = rowDragOptions.allowDragIntoRow;
  // 鼠标悬停所在的拖拽行信息
  var dragItem = getDragRowItem(event.target, tableContainer, dataSource);
  if (!dragItem) return;
  var cell = dragItem.cell,
    rowIndex = dragItem.rowIndex,
    row = dragItem.row;
  var bodyRect = tableContainer.getBoundingClientRect();
  var offsetParentSize = getElementRectWithOffset(document.body);
  var isTreeTable = !!treeModeOptions;
  var allowDragInto = isTreeTable && allowDragIntoRow;
  var direction = getDirection(cell, event.clientY, allowDragInto);
  if (isTreeTable) {
    var _context5;
    var iconWidth = treeModeOptions.iconWidth,
      iconIndent = treeModeOptions.iconIndent,
      iconGap = treeModeOptions.iconGap,
      indentSize = treeModeOptions.indentSize,
      treeMetaKey = treeModeOptions.treeMetaKey;
    var expandCell = tableContainer.querySelector(_concatInstanceProperty(_context5 = "tr[data-rowindex=\"".concat(rowIndex, "\"] .")).call(_context5, Classes.tableExtendCell));
    if (expandCell) {
      var _getElementSize2 = _getElementSize(expandCell),
        paddingLeft = _getElementSize2.paddingLeft;
      var expandCellRect = expandCell.getBoundingClientRect();
      var _row$treeMetaKey = row[treeMetaKey],
        rowKey = _row$treeMetaKey.rowKey,
        depth = _row$treeMetaKey.depth,
        isLeaf = _row$treeMetaKey.isLeaf,
        expanded = _row$treeMetaKey.expanded;
      var addWidth = isLeaf ? iconWidth + iconGap : 0;
      var indent = iconIndent + depth * indentSize + addWidth;
      var x = expandCellRect.x,
        _y = expandCellRect.y,
        _height = expandCellRect.height;
      var _top = direction === 'bottom' ? _y + _height - offsetParentSize.top : _y - offsetParentSize.top;
      var offsetX = Math.max(x + paddingLeft + indent - bodyRect.x, 0);
      var _left = bodyRect.x + offsetX - offsetParentSize.left;
      lineElement.style.left = "".concat(_left, "px");
      lineElement.style.top = "".concat(_top, "px");
      lineElement.style.width = "".concat(bodyRect.width - offsetX, "px");
      if (direction === 'into') {
        lineElement.style.display = 'none';
      } else {
        lineElement.style.display = 'block';
      }
      return;
    }
  }
  // 根据鼠标悬停位置所在单元格和显示位置计算拖拽线的位置
  var rect = cell.getBoundingClientRect();
  var y = rect.y,
    height = rect.height;
  var top = direction === 'bottom' ? y + height - offsetParentSize.top : y - offsetParentSize.top;
  var left = bodyRect.x - offsetParentSize.left;
  lineElement.style.left = "".concat(left, "px");
  lineElement.style.top = "".concat(top, "px");
  lineElement.style.width = "".concat(bodyRect.width, "px");
}
function showDragLine(lineElement) {
  lineElement.style.display = 'block';
}
function hiddenDragLine(lineElement) {
  lineElement.style.display = 'none';
}
function positionDragElemment(element, event) {
  var _a, _b, _c, _d, _e, _f;
  if (!element) return;
  var elementRect = element.getBoundingClientRect();
  var eleHeight = elementRect.height;
  var browserWidth = (_b = (_a = document.body) === null || _a === void 0 ? void 0 : _a.clientWidth) !== null && _b !== void 0 ? _b : window.innerHeight || ((_c = document.documentElement) === null || _c === void 0 ? void 0 : _c.clientWidth) || 0;
  var browserHeight = (_e = (_d = document.body) === null || _d === void 0 ? void 0 : _d.clientHeight) !== null && _e !== void 0 ? _e : window.innerHeight || ((_f = document.documentElement) === null || _f === void 0 ? void 0 : _f.clientHeight) || 0;
  var offsetParentSize = getElementRectWithOffset(element.offsetParent);
  var clientX = event.clientX,
    clientY = event.clientY;
  var top = clientY - offsetParentSize.top - eleHeight / 2;
  var left = clientX - offsetParentSize.left;
  var windowScrollX = window.pageXOffset;
  var windowScrollY = window.pageYOffset;
  if (browserWidth > 0 && left + element.clientWidth > browserWidth + windowScrollX) {
    left = Math.max(browserWidth + windowScrollX - element.clientWidth, 0);
  }
  if (browserHeight > 0 && top + element.clientHeight > browserHeight + windowScrollY) {
    top = Math.max(browserHeight + windowScrollY - element.clientHeight, 0);
  }
  element.style.left = "".concat(left, "px");
  element.style.top = "".concat(top, "px");
}
function getElementRectWithOffset(el) {
  var offsetElementRect = el.getBoundingClientRect();
  var _getElementSize3 = _getElementSize(el),
    borderTopWidth = _getElementSize3.borderTopWidth,
    borderLeftWidth = _getElementSize3.borderLeftWidth,
    borderRightWidth = _getElementSize3.borderRightWidth,
    borderBottomWidth = _getElementSize3.borderBottomWidth;
  return {
    top: offsetElementRect.top + (borderTopWidth || 0),
    left: offsetElementRect.left + (borderLeftWidth || 0),
    right: offsetElementRect.right + (borderRightWidth || 0),
    bottom: offsetElementRect.bottom + (borderBottomWidth || 0)
  };
}
function _getElementSize(el) {
  var _window$getComputedSt = window.getComputedStyle(el),
    height = _window$getComputedSt.height,
    width = _window$getComputedSt.width,
    borderTopWidth = _window$getComputedSt.borderTopWidth,
    borderRightWidth = _window$getComputedSt.borderRightWidth,
    borderBottomWidth = _window$getComputedSt.borderBottomWidth,
    borderLeftWidth = _window$getComputedSt.borderLeftWidth,
    paddingTop = _window$getComputedSt.paddingTop,
    paddingRight = _window$getComputedSt.paddingRight,
    paddingBottom = _window$getComputedSt.paddingBottom,
    paddingLeft = _window$getComputedSt.paddingLeft,
    marginTop = _window$getComputedSt.marginTop,
    marginRight = _window$getComputedSt.marginRight,
    marginBottom = _window$getComputedSt.marginBottom,
    marginLeft = _window$getComputedSt.marginLeft,
    boxSizing = _window$getComputedSt.boxSizing;
  return {
    height: parseFloat(height || '0'),
    width: parseFloat(width || '0'),
    borderTopWidth: parseFloat(borderTopWidth || '0'),
    borderRightWidth: parseFloat(borderRightWidth || '0'),
    borderBottomWidth: parseFloat(borderBottomWidth || '0'),
    borderLeftWidth: parseFloat(borderLeftWidth || '0'),
    paddingTop: parseFloat(paddingTop || '0'),
    paddingRight: parseFloat(paddingRight || '0'),
    paddingBottom: parseFloat(paddingBottom || '0'),
    paddingLeft: parseFloat(paddingLeft || '0'),
    marginTop: parseFloat(marginTop || '0'),
    marginRight: parseFloat(marginRight || '0'),
    marginBottom: parseFloat(marginBottom || '0'),
    marginLeft: parseFloat(marginLeft || '0'),
    boxSizing: boxSizing
  };
}
function removeElement(element) {
  document.body.removeChild(element);
}
function setDragElementIcon(element, iconName) {
  var elementIcon = element.querySelector(".".concat(Classes.rowDragElementIcon));
  clearElementChildren(elementIcon);
  iconName = iconName || 'notAllowed';
  var iconElement = document.createElement('span');
  if (iconName === 'move') {
    iconElement.classList.add(Classes.iconMove);
  } else if (iconName === 'notAllowed') {
    iconElement.classList.add(Classes.iconNotAllowed);
  }
  elementIcon.appendChild(iconElement);
}
function clearElementChildren(element) {
  while (element && element.firstChild) {
    element.removeChild(element.firstChild);
  }
}
function getScrollMoveOffset(tableBody, mouseMoveEvent) {
  var clientY = mouseMoveEvent.clientY;
  var tableBodyClientRect = tableBody.getBoundingClientRect();
  var top = tableBodyClientRect.top,
    height = tableBodyClientRect.height;
  if (clientY >= top + height - SCROLL_START_OFFSET && clientY <= top + height) {
    return SCROLL_OFFSET;
  }
  if (clientY >= top && clientY <= top + SCROLL_START_OFFSET) {
    return -SCROLL_OFFSET;
  }
  return 0;
}
function setDragText(element, dragText) {
  var dragTextString = dragText.toString();
  var elementIcon = element.querySelector(".".concat(Classes.rowDragElementLabel));
  var stringNode = document.createTextNode(dragTextString);
  elementIcon.appendChild(stringNode);
}
function isMouseOnDropTarget(mouseEvent, target) {
  return target.contains(mouseEvent.target);
}
function createDropTargetEvent(dropZone, event, dragItem, startDropZone) {
  var dropZoneTarget = dropZone.getContainer();
  var startDropZoneTagret = startDropZone.getContainer();
  var rect = dropZoneTarget.getBoundingClientRect();
  var x = event.clientX - rect.left;
  var y = event.clientY - rect.top;
  var startDropZoneOptions = startDropZone.tableParams.getRowDragOptions();
  var startCommonParams = startDropZoneOptions === null || startDropZoneOptions === void 0 ? void 0 : startDropZoneOptions.commonParams;
  var targetEvent = {
    dragItem: dragItem,
    startDropZoneTagret: startDropZoneTagret,
    startCommonParams: startCommonParams,
    dropZoneTarget: dropZoneTarget,
    event: event,
    x: x,
    y: y
  };
  if (dropZone.isTable) {
    var dropZoneOptions = dropZone.tableParams.getRowDragOptions();
    var commonParams = dropZoneOptions === null || dropZoneOptions === void 0 ? void 0 : dropZoneOptions.commonParams;
    targetEvent.dropZoneTableParams = dropZone.tableParams;
    targetEvent.commonParams = commonParams;
  }
  return targetEvent;
}
function getDirection(cell, clientY) {
  var isTreeTable = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  var _cell$getBoundingClie = cell.getBoundingClientRect(),
    height = _cell$getBoundingClie.height,
    y = _cell$getBoundingClie.y;
  var direction = 'bottom';
  if (isTreeTable) {
    if (y + height / 4 > clientY) {
      direction = 'top';
    } else if (y + height * 3 / 4 > clientY) {
      direction = 'into';
    }
  } else if (y + height / 2 > clientY) {
    direction = 'top';
  }
  return direction;
}