"use strict";

var _filterInstanceProperty = require("@babel/runtime-corejs3/core-js-stable/instance/filter");
var _mapInstanceProperty = require("@babel/runtime-corejs3/core-js-stable/instance/map");
var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ROW_DRAG_COLUMN_CODE = void 0;
exports.rowDrag = rowDrag;
exports.rowDragOptionsKey = exports.rowDragKey = void 0;
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/defineProperty"));
var _concat = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/concat"));
var _find = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/find"));
var _slice = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/slice"));
var _findIndex = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/find-index"));
var _react = _interopRequireDefault(require("react"));
var _rxjs = require("rxjs");
var _operators = require("rxjs/operators");
var _classnames = _interopRequireDefault(require("classnames"));
var _styles = require("../../base/styles");
var _const = require("../const");
var _internals = require("../../internals");
var _touchEventUtils = require("./utils/touchEventUtils");
var ROW_DRAG_COLUMN_CODE = exports.ROW_DRAG_COLUMN_CODE = '$_row_drag_column_&';
var rowDragKey = exports.rowDragKey = 'rowDragKey';
var rowDragOptionsKey = exports.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: (0, _classnames.default)(_styles.Classes.rowDragCell)
    };
  },
  render: function render(value, row, rowIndex) {
    return /*#__PURE__*/_react.default.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.default.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"
    }));
  }
};
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(_const.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 = !isPointerOnDropTarget(event, dropZoneTarget);
      var overIndex = -1;
      var direction = 'bottom';
      if (!isLeave && dataSource.length > 0) {
        var overDragItem = getDragRowItem((0, _touchEventUtils.getEventTarget)(event), dropZoneTarget, dataSource);
        if (overDragItem) {
          var rowIndex = overDragItem.rowIndex,
            cell = overDragItem.cell;
          overIndex = rowIndex;
          direction = getDirection(cell, (0, _touchEventUtils.getEventCoordinates)(event).clientY, allowDragIntoRow);
        }
      }
      if (overIndex === -1 && dataSource.length > 0 && dropZoneTarget.contains((0, _touchEventUtils.getEventTarget)(event))) {
        overIndex = dataSource.length - 1;
        direction = 'bottom';
      }
      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) {
      handlePointerDown(event.nativeEvent);
    };
    // PC 单据移动端显示，兼容移动端的拖拽事件
    var onTouchStart = function onTouchStart(event) {
      // 尝试阻止触摸事件的默认行为，防止页面滚动
      try {
        if (event.cancelable) {
          event.preventDefault();
        }
      } catch (error) {
        // 忽略passive event listener错误
        console.warn('preventDefault failed in passive touch event listener');
      }
      handlePointerDown(event.nativeEvent);
    };
    // 统一的拖拽处理函数
    var handlePointerDown = function handlePointerDown(startEvent) {
      var _a;
      var startDataItem = getDragRowItem((0, _touchEventUtils.getEventTarget)(startEvent), 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, moveEvent) {
        if (opt === null || opt === void 0 ? void 0 : opt.suppressScrollMove) return;
        if (timeoutId) {
          clearTimeout(timeoutId);
        }
        if (intervalId) {
          clearInterval(intervalId);
        }
        if (!tableBody) return;
        var moveOffset = getScrollMoveOffset(tableBody, moveEvent);
        if (moveOffset === 0) {
          return;
        }
        timeoutId = setTimeout(function () {
          intervalId = setInterval(function () {
            tableBody.scrollTop += moveOffset;
          }, 50);
        }, 500);
      };
      var handleDragStart = function handleDragStart(event) {
        var _a;
        // 屏蔽默认事件，防止文本选择、框选等
        try {
          if (event.cancelable) {
            event.preventDefault();
          }
        } catch (error) {
          // 忽略passive event listener错误
          console.warn('preventDefault failed in passive event listener');
        }
        // 禁用页面的文本选择
        document.body.style.userSelect = 'none';
        document.body.style.webkitUserSelect = 'none';
        // 添加拖拽状态的CSS类，可以在样式中进一步控制
        document.body.classList.add('row-dragging');
        dragElement = createDragElement(event, 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((0, _classnames.default)(_styles.Classes.rowDragging));
        rowDragApi.setDragStatus('start');
        var dragEvent = createDropTargetEvent(currentDropZone, event, startDataItem, currentDropZone);
        onDragStart(dragEvent);
      };
      var handleDragMove = function handleDragMove(moveEvent) {
        var _a;
        // 尝试屏蔽默认事件，在passive监听器中可能会失败
        try {
          if (moveEvent.cancelable) {
            moveEvent.preventDefault();
          }
        } catch (error) {
          // 忽略passive event listener错误
          console.warn('preventDefault failed in passive event listener');
        }
        var isRTL = pipeline.ctx.direction === 'rtl';
        positionDragElemment(dragElement, moveEvent, isRTL); // 更新拖拽悬浮框位置
        rowDragApi.setDragStatus('dragging');
        setDragElementIcon(dragElement, 'move');
        var rowDropZones = rowDragApi.getRowDropZone();
        var validDropZones = (0, _concat.default)(rowDropZones).call(rowDropZones, currentDropZone); // 可放置区域加上自身
        var dropTarget = (0, _find.default)(validDropZones).call(validDropZones, function (zone) {
          return isPointerOnDropTarget(moveEvent, zone.getContainer());
        }) || null;
        updateScrollPosition(dropTarget === null || dropTarget === void 0 ? void 0 : dropTarget.getContainer(), moveEvent); // 拖拽到底时让滚动条可以滚动
        if (dropTarget !== lastDropTarget) {
          // 拖拽离开表格
          if (lastDropTarget !== null && dropTarget === null) {
            if (lastDropTarget.onDragLeave) {
              setDragElementIcon(dragElement, 'notAllowed');
              hiddenDragLine(dragLine);
              lastDropTarget.getContainer().classList.remove(_styles.Classes.rowDragNoData);
              var dragEvent = createDropTargetEvent(lastDropTarget, moveEvent, startDataItem, currentDropZone);
              lastDropTarget.onDragLeave(dragEvent);
            }
          }
          // 拖拽进入表格
          if (lastDropTarget === null && dropTarget !== null) {
            if (dropTarget.onDragEnter) {
              setDragElementIcon(dragElement, 'move');
              if (dropTarget.isTable) {
                showDragLine(dragLine);
                var getTreeModeOptions = dropTarget.tableParams.getTreeModeOptions;
                var treeModeOptions = getTreeModeOptions();
                var isTreeTable = !!treeModeOptions;
                // 判断拖拽进入的表格是否是树形表格，控制指示线样式
                if (isTreeTable) {
                  dragLine.classList.add(_styles.Classes.treeTableRowDragLine);
                } else {
                  dragLine.classList.remove(_styles.Classes.treeTableRowDragLine);
                }
              }
              var _dragEvent = createDropTargetEvent(dropTarget, moveEvent, startDataItem, currentDropZone);
              dropTarget.onDragEnter(_dragEvent);
            }
          }
          lastDropTarget = dropTarget;
        }
        if (dropTarget) {
          // 拖拽区域在表格中，更新拖拽插入指示线位置
          if (dropTarget.isTable) {
            positionDragLine({
              lineElement: dragLine,
              dragZone: dropTarget,
              event: moveEvent,
              isRTL: isRTL
            });
          }
          // 树形表格悬停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((0, _touchEventUtils.getEventTarget)(moveEvent), dropTarget.getContainer(), dataSource);
              if (!dragItem) return;
              var row = dragItem.row;
              var _row$treeMetaKey = row[treeMetaKey],
                rowKey = _row$treeMetaKey.rowKey,
                isLeaf = _row$treeMetaKey.isLeaf;
              if (!isLeaf && !isExpanded(rowKey)) {
                onExpand(rowKey);
                expandRowCallBackList.push(function () {
                  return onCollapse(rowKey);
                });
              }
            }, 1000);
          }
          if (dropTarget.onDragging) {
            var _dragEvent2 = createDropTargetEvent(dropTarget, moveEvent, startDataItem, currentDropZone);
            dropTarget.onDragging(_dragEvent2);
          }
        }
      };
      var handleDragStop = function handleDragStop(endEvent) {
        if (!isValidDrag) {
          return;
        }
        // 恢复默认的文本选择功能
        document.body.style.userSelect = '';
        document.body.style.webkitUserSelect = '';
        // 移除拖拽状态的CSS类
        document.body.classList.remove('row-dragging');
        removeElement(dragElement);
        removeElement(dragLine);
        artTable.classList.remove((0, _classnames.default)(_styles.Classes.rowDragging));
        rowDragApi.setDragStatus('finished');
        clearTimeout(timeoutId);
        clearInterval(intervalId);
        clearTimeout(expandRowTimeoutId);
        var rowDropZones = rowDragApi.getRowDropZone();
        rowDropZones.forEach(function (dropzone) {
          var container = dropzone.getContainer();
          container && container.classList.remove(_styles.Classes.rowDragNoData);
        });
        var validDropZones = (0, _concat.default)(rowDropZones).call(rowDropZones, currentDropZone);
        var dropTarget = (0, _find.default)(validDropZones).call(validDropZones, function (zone) {
          return isPointerOnDropTarget(endEvent, zone.getContainer());
        });
        if (dropTarget && dropTarget.onDragStop) {
          var dragEvent = createDropTargetEvent(dropTarget, endEvent, startDataItem, currentDropZone);
          dropTarget.onDragStop(dragEvent);
        }
        while (expandRowCallBackList.length > 0) {
          var callback = expandRowCallBackList.pop();
          callback();
        }
      };
      // 判断是鼠标事件还是触摸事件，分别监听对应的移动和结束事件
      var isTouchEvent = 'touches' in startEvent;
      if (isTouchEvent) {
        // 触摸事件处理
        var touchmove$ = (0, _rxjs.fromEvent)(window, 'touchmove', {
          passive: false
        });
        var touchend$ = (0, _rxjs.fromEvent)(window, 'touchend', {
          passive: false
        });
        var touchDragMove$ = touchmove$.pipe((0, _filterInstanceProperty(_operators))(function (moveEvent) {
          var coordinates = (0, _touchEventUtils.getEventCoordinates)(moveEvent);
          var startCoordinates = (0, _touchEventUtils.getEventCoordinates)(startEvent);
          var moveClientY = coordinates.clientY;
          var startClientY = startCoordinates.clientY;
          // 上下移动偏移量大于5才是有效的拖拽
          if (Math.abs(moveClientY - startClientY) > 5) {
            isValidDrag = true;
          }
          return isValidDrag;
        }), (0, _mapInstanceProperty(_operators))(function (moveEvent) {
          if (!isDragging) {
            isDragging = true;
            handleDragStart(startEvent);
            handleDragMove(startEvent);
          }
          handleDragMove(moveEvent);
        }), (0, _operators.takeUntil)(touchend$));
        touchDragMove$.subscribe();
        var touchDragEnd$ = touchend$.pipe((0, _mapInstanceProperty(_operators))(function (endEvent) {
          handleDragStop(endEvent);
        })).subscribe({
          next: function next() {
            touchDragEnd$.unsubscribe();
          }
        });
      } else {
        // 鼠标事件处理
        var mousemove$ = (0, _rxjs.fromEvent)(window, 'mousemove');
        var mouseup$ = (0, _rxjs.fromEvent)(window, 'mouseup');
        var rowDragMove$ = mousemove$.pipe((0, _filterInstanceProperty(_operators))(function (moveEvent) {
          var coordinates = (0, _touchEventUtils.getEventCoordinates)(moveEvent);
          var startCoordinates = (0, _touchEventUtils.getEventCoordinates)(startEvent);
          var moveClientY = coordinates.clientY;
          var startClientY = startCoordinates.clientY;
          // 上下移动偏移量大于5才是有效的拖拽
          if (Math.abs(moveClientY - startClientY) > 5) {
            isValidDrag = true;
          }
          return isValidDrag;
        }), (0, _mapInstanceProperty(_operators))(function (moveEvent) {
          if (!isDragging) {
            isDragging = true;
            handleDragStart(startEvent);
            handleDragMove(startEvent);
          }
          handleDragMove(moveEvent);
        }), (0, _operators.takeUntil)(mouseup$));
        rowDragMove$.subscribe();
        var rowDragEnd$ = mouseup$.pipe((0, _mapInstanceProperty(_operators))(function (endEvent) {
          handleDragStop(endEvent);
        })).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 = (0, _slice.default)(_context = pipeline.getColumns()).call(_context);
    nextColumns.unshift(rowDragColumn);
    pipeline.columns(nextColumns);
    pipeline.addTableProps({
      onMouseDown: onMouseDown,
      onTouchStart: onTouchStart
    });
    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 = (0, _findIndex.default)(_context2 = pipeline.getDataSource()).call(_context2, function (row) {
          return _internals.internals.safeGetRowKey(primaryKey, row, -1) === parentRowKey;
        });
      }
      var className = (0, _classnames.default)((0, _defineProperty2.default)((0, _defineProperty2.default)((0, _defineProperty2.default)((0, _defineProperty2.default)((0, _defineProperty2.default)((0, _defineProperty2.default)({}, _styles.Classes.rowDragStart, rowIndex === startRowIndex && dragStatus !== 'finished'), _styles.Classes.rowDragEnd, rowIndex === endRowIndex), _styles.Classes.rowDragEndParent, isTreeTable && rowIndex === parentRowKeyIndex && dragPosition !== 'into'), _styles.Classes.rowDragEndInto, rowIndex === endRowIndex && dragPosition === 'into'), _styles.Classes.rowDragEndToTop, rowIndex === endRowIndex && dragPosition === 'top'), _styles.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(_styles.Classes.artTable)) {
    if (target.classList.contains(_styles.Classes.tableFooter)) {
      return true;
    }
    target = target.parentElement;
  }
  return false;
}
function createDragElement(event, tableBody) {
  var _context3, _context4;
  var ELEMENT_TEMPLATE = (0, _concat.default)(_context3 = (0, _concat.default)(_context4 = "<div class='".concat(_styles.Classes.rowDragElement, "'>\n      <span class='")).call(_context4, _styles.Classes.rowDragElementIcon, "'></span>\n      <div class='")).call(_context3, _styles.Classes.rowDragElementLabel, "'></div>\n    </div>");
  var element = document.createElement('div');
  element.innerHTML = ELEMENT_TEMPLATE;
  var dragElement = element.firstChild;
  var targetRow = findTargetRow((0, _touchEventUtils.getEventTarget)(event), 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(_styles.Classes.rowDragLine);
  if (isTreeTable) {
    dragLine.classList.add(_styles.Classes.treeTableRowDragLine);
  }
  document.body.appendChild(dragLine);
  return dragLine;
}
function positionDragLine(_ref) {
  var _context7;
  var lineElement = _ref.lineElement,
    dragZone = _ref.dragZone,
    event = _ref.event,
    isRTL = _ref.isRTL;
  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 isTreeTable = !!treeModeOptions;
  var bodyRect = tableContainer.getBoundingClientRect();
  var offsetParentSize = getElementRectWithOffset(document.body);
  if (dataSource.length === 0) {
    tableContainer.classList.add(_styles.Classes.rowDragNoData);
    lineElement.style.display = 'none';
  } else {
    tableContainer.classList.remove(_styles.Classes.rowDragNoData);
    lineElement.style.display = 'block';
  }
  // 鼠标悬停所在的拖拽行信息
  var dragItem = getDragRowItem((0, _touchEventUtils.getEventTarget)(event), tableContainer, dataSource);
  if (!dragItem) {
    if (dataSource.length > 0 && tableContainer.contains((0, _touchEventUtils.getEventTarget)(event))) {
      var _context5, _context6;
      var _rowIndex = dataSource.length - 1;
      var _row = dataSource[_rowIndex];
      var _direction = 'bottom';
      var _targetCell = isTreeTable ? tableContainer.querySelector((0, _concat.default)(_context5 = "tr[data-rowindex=\"".concat(_rowIndex, "\"] .")).call(_context5, _styles.Classes.tableExtendCell)) : tableContainer.querySelector((0, _concat.default)(_context6 = "tr[data-rowindex=\"".concat(_rowIndex, "\"] .")).call(_context6, _styles.Classes.rowDragCell));
      if (!_targetCell) return;
      var _getLinePosition = getLinePosition({
          treeModeOptions: treeModeOptions,
          cell: _targetCell,
          row: _row,
          direction: _direction,
          offsetParentSize: offsetParentSize,
          bodyRect: bodyRect,
          isRTL: isRTL
        }),
        _top = _getLinePosition.top,
        _left2 = _getLinePosition.left,
        _width2 = _getLinePosition.width;
      lineElement.style.left = "".concat(_left2, "px");
      lineElement.style.top = "".concat(_top, "px");
      lineElement.style.width = "".concat(_width2, "px");
    }
    return;
  }
  var cell = dragItem.cell,
    rowIndex = dragItem.rowIndex,
    row = dragItem.row;
  var allowDragInto = isTreeTable && allowDragIntoRow;
  var direction = getDirection(cell, (0, _touchEventUtils.getEventCoordinates)(event).clientY, allowDragInto);
  var targetCell = isTreeTable ? tableContainer.querySelector((0, _concat.default)(_context7 = "tr[data-rowindex=\"".concat(rowIndex, "\"] .")).call(_context7, _styles.Classes.tableExtendCell)) : cell;
  if (!targetCell) return;
  var _getLinePosition2 = getLinePosition({
      treeModeOptions: treeModeOptions,
      cell: targetCell,
      row: row,
      direction: direction,
      offsetParentSize: offsetParentSize,
      bodyRect: bodyRect,
      isRTL: isRTL
    }),
    top = _getLinePosition2.top,
    left = _getLinePosition2.left,
    width = _getLinePosition2.width;
  lineElement.style.left = "".concat(left, "px");
  lineElement.style.top = "".concat(top, "px");
  lineElement.style.width = "".concat(width, "px");
  if (direction === 'into') {
    lineElement.style.display = 'none';
  } else {
    lineElement.style.display = 'block';
  }
}
function showDragLine(lineElement) {
  lineElement.style.display = 'block';
}
function hiddenDragLine(lineElement) {
  lineElement.style.display = 'none';
}
function positionDragElemment(element, event, isRTL) {
  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 _getEventCoordinates = (0, _touchEventUtils.getEventCoordinates)(event),
    clientX = _getEventCoordinates.clientX,
    clientY = _getEventCoordinates.clientY;
  var top = clientY - offsetParentSize.top - eleHeight / 2;
  var left = clientX - offsetParentSize.left;
  var right = Math.max(browserWidth - clientX, 0);
  var windowScrollX = window.pageXOffset || window.scrollX;
  var windowScrollY = window.pageYOffset || window.scrollY;
  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);
  }
  if (browserWidth > 0 && right + element.clientWidth > browserWidth + windowScrollX) {
    right = Math.max(browserWidth + windowScrollX - element.clientWidth, 0);
  }
  if (isRTL) {
    element.style.right = right + 'px';
  } else {
    element.style.left = left + 'px';
  }
  element.style.top = top + 'px';
}
function getElementRectWithOffset(el) {
  var offsetElementRect = el.getBoundingClientRect();
  var _getElementSize2 = _getElementSize(el),
    borderTopWidth = _getElementSize2.borderTopWidth,
    borderLeftWidth = _getElementSize2.borderLeftWidth,
    borderRightWidth = _getElementSize2.borderRightWidth,
    borderBottomWidth = _getElementSize2.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(_styles.Classes.rowDragElementIcon));
  clearElementChildren(elementIcon);
  iconName = iconName || 'notAllowed';
  var iconElement = document.createElement('span');
  if (iconName === 'move') {
    iconElement.classList.add(_styles.Classes.iconMove);
  } else if (iconName === 'notAllowed') {
    iconElement.classList.add(_styles.Classes.iconNotAllowed);
  }
  elementIcon.appendChild(iconElement);
}
function clearElementChildren(element) {
  while (element === null || element === void 0 ? void 0 : element.firstChild) {
    element.removeChild(element.firstChild);
  }
}
function getScrollMoveOffset(tableBody, moveEvent) {
  var _getEventCoordinates2 = (0, _touchEventUtils.getEventCoordinates)(moveEvent),
    clientY = _getEventCoordinates2.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(_styles.Classes.rowDragElementLabel));
  var stringNode = document.createTextNode(dragTextString);
  elementIcon.appendChild(stringNode);
}
function isPointerOnDropTarget(pointerEvent, target) {
  var eventTarget = (0, _touchEventUtils.getEventTarget)(pointerEvent);
  return target.contains(eventTarget);
}
function createDropTargetEvent(dropZone, event, dragItem, startDropZone) {
  var dropZoneTarget = dropZone.getContainer();
  var startDropZoneTagret = startDropZone.getContainer();
  var rect = dropZoneTarget.getBoundingClientRect();
  var _getEventCoordinates3 = (0, _touchEventUtils.getEventCoordinates)(event),
    clientX = _getEventCoordinates3.clientX,
    clientY = _getEventCoordinates3.clientY;
  var x = clientX - rect.left;
  var y = 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;
}
var getLinePosition = function getLinePosition(_ref2) {
  var treeModeOptions = _ref2.treeModeOptions,
    cell = _ref2.cell,
    row = _ref2.row,
    direction = _ref2.direction,
    offsetParentSize = _ref2.offsetParentSize,
    bodyRect = _ref2.bodyRect,
    isRTL = _ref2.isRTL;
  var isTreeTable = !!treeModeOptions;
  if (isTreeTable) {
    var iconWidth = treeModeOptions.iconWidth,
      iconIndent = treeModeOptions.iconIndent,
      iconGap = treeModeOptions.iconGap,
      indentSize = treeModeOptions.indentSize,
      treeMetaKey = treeModeOptions.treeMetaKey;
    var _getElementSize3 = _getElementSize(cell),
      paddingLeft = _getElementSize3.paddingLeft,
      paddingRight = _getElementSize3.paddingRight;
    var expandCellRect = cell.getBoundingClientRect();
    var _row$treeMetaKey2 = row[treeMetaKey],
      depth = _row$treeMetaKey2.depth,
      isLeaf = _row$treeMetaKey2.isLeaf;
    var addWidth = isLeaf ? iconWidth + iconGap : 0;
    var indent = iconIndent + depth * indentSize + addWidth;
    var x = expandCellRect.x,
      _y = expandCellRect.y,
      _height = expandCellRect.height;
    var _top2 = direction === 'bottom' ? _y + _height - offsetParentSize.top : _y - offsetParentSize.top;
    var offsetX = Math.max(x + paddingLeft + indent - bodyRect.x, 0);
    var _left3 = bodyRect.x + offsetX - offsetParentSize.left;
    var _width3 = bodyRect.width - offsetX;
    if (isRTL) {
      var expandCellOffsetRight = bodyRect.right - expandCellRect.right; // 展示收起单元格相较于表格右边的距离
      var _left = bodyRect.x - offsetParentSize.left;
      // 表格的宽度 - expandCellOffsetRight - 表格的paddingRight - 计算得出的缩进
      var _width = bodyRect.width - expandCellOffsetRight - paddingRight - indent;
      return {
        top: _top2,
        left: _left,
        width: _width
      };
    }
    return {
      top: _top2,
      left: _left3,
      width: _width3
    };
  }
  // 根据鼠标悬停位置所在单元格和显示位置计算拖拽线的位置
  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;
  var width = bodyRect.width;
  return {
    top: top,
    left: left,
    width: width
  };
};