"use strict";

var _typeof = require("@babel/runtime-corejs3/helpers/typeof");
var _WeakMap = require("@babel/runtime-corejs3/core-js-stable/weak-map");
var _Object$getOwnPropertyDescriptor = require("@babel/runtime-corejs3/core-js-stable/object/get-own-property-descriptor");
var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.RESIZED_COLUMN_KEY = exports.LAST_RESIZED_COLUMN_KEY = exports.COLUMN_SIZE_KEY = void 0;
exports.columnResize = columnResize;
var _set = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/set"));
var _keys = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/object/keys"));
var _map = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/map"));
var _extends2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/extends"));
var _taggedTemplateLiteral2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/taggedTemplateLiteral"));
var _react = _interopRequireDefault(require("react"));
var _styledComponents = _interopRequireDefault(require("styled-components"));
var _rxjs = require("rxjs");
var op = _interopRequireWildcard(require("rxjs/operators"));
var _utils = require("../../utils");
var _internals = require("../../internals");
var _styles = require("../../base/styles");
var _utils2 = require("../../base/utils");
var _touchEventUtils = require("./utils/touchEventUtils");
var _templateObject, _templateObject2;
function _interopRequireWildcard(e, t) { if ("function" == typeof _WeakMap) var r = new _WeakMap(), n = new _WeakMap(); return (_interopRequireWildcard = function _interopRequireWildcard(e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != _typeof(e) && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (var _t in e) "default" !== _t && {}.hasOwnProperty.call(e, _t) && ((i = (o = Object.defineProperty) && _Object$getOwnPropertyDescriptor(e, _t)) && (i.get || i.set) ? o(f, _t, i) : f[_t] = e[_t]); return f; })(e, t); }
var TableHeaderCellResize = _styledComponents.default.div(_templateObject || (_templateObject = (0, _taggedTemplateLiteral2.default)(["\n  position: absolute;\n  top: 0;\n  ", ": -5px;\n  height: 100%;\n  width: 10px;\n  cursor: ew-resize;\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n  z-index:1;\n\n  &:after {\n    content: \"\";\n    position: absolute;\n    display: block;\n    ", ": calc(50% - 1px);\n    width: 1px;\n    height: calc(100% - 14px);\n    top: 7px;\n  }\n"])), function (props) {
  return (0, _utils2.swapRTLDirection)(props.direction, 'right');
}, function (props) {
  return (0, _utils2.swapRTLDirection)(props.direction, 'left');
});
var TableHeaderGroupCellResize = (0, _styledComponents.default)(function (props) {
  return /*#__PURE__*/_react.default.createElement(TableHeaderCellResize, (0, _extends2.default)({}, props));
})(_templateObject2 || (_templateObject2 = (0, _taggedTemplateLiteral2.default)(["\n  &:after {\n    height: 100%;\n    top: 0;\n  }\n"])));
function clamp(min, x, max) {
  return Math.max(min, Math.min(max, x));
}
function disableSelect(event) {
  event.preventDefault();
}
var stateKey = 'columnResize';
var COLUMN_SIZE_KEY = exports.COLUMN_SIZE_KEY = 'columnResize';
var RESIZED_COLUMN_KEY = exports.RESIZED_COLUMN_KEY = 'resizedColumn';
var LAST_RESIZED_COLUMN_KEY = exports.LAST_RESIZED_COLUMN_KEY = 'lastResizedColumn';
function columnResize() {
  var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var _a, _b, _c;
  var minSize = (_a = opts.minSize) !== null && _a !== void 0 ? _a : 60;
  var fallbackSize = (_b = opts.fallbackSize) !== null && _b !== void 0 ? _b : 150;
  var maxSize = (_c = opts.maxSize) !== null && _c !== void 0 ? _c : 1000;
  return function columnResizeFeature(pipeline) {
    var _a, _b;
    var columnSize = (_b = (_a = opts.columnSize) !== null && _a !== void 0 ? _a : pipeline.getStateAtKey(stateKey)) !== null && _b !== void 0 ? _b : {};
    var leafColumns = (0, _utils.collectNodes)(pipeline.getColumns(), 'leaf-only');
    leafColumns.forEach(function (_ref) {
      var code = _ref.code,
        width = _ref.width;
      if (columnSize[code] === undefined) {
        if (typeof width === 'number') {
          columnSize[code] = width;
        } else {
          columnSize[code] = fallbackSize;
        }
      }
    });
    // 实时存储一份最新的columnSize，与autoFill共用一份数据
    // 存在state里可能存到取不到最新的
    pipeline.setFeatureOptions(COLUMN_SIZE_KEY, columnSize);
    var onChangeSize = function onChangeSize(nextColumnSize) {
      window.requestAnimationFrame(function () {
        var _a;
        pipeline.setStateAtKey(stateKey, nextColumnSize);
        (_a = opts === null || opts === void 0 ? void 0 : opts.onChangeSize) === null || _a === void 0 ? void 0 : _a.call(opts, nextColumnSize);
      });
    };
    var handleDoubleClick = function handleDoubleClick(e, col) {
      var _a;
      (_a = opts.doubleClickCallback) === null || _a === void 0 ? void 0 : _a.call(opts, e, col);
    };
    // 通用的拖拽处理逻辑
    var handleResize = function handleResize(startEvent, col, eventType) {
      window.addEventListener('selectstart', disableSelect);
      var changedColumnSize = {};
      var startCoordinates = (0, _touchEventUtils.getEventCoordinates)(startEvent);
      var startX = startCoordinates.clientX;
      var children = col.children,
        code = col.code,
        _col$features = col.features,
        features = _col$features === void 0 ? {} : _col$features;
      var minWidth = features.minWidth,
        maxWidth = features.maxWidth;
      var realMinSize = typeof minWidth === 'number' ? minWidth : minSize;
      var realMaxSize = typeof maxWidth === 'number' ? maxWidth : maxSize;
      var columnSize = pipeline.getFeatureOptions(COLUMN_SIZE_KEY);
      var recordColumnSize = columnSize;
      // 根据事件类型选择不同的事件监听器
      var moveEventName = eventType === 'mouse' ? 'mousemove' : 'touchmove';
      var endEventName = eventType === 'mouse' ? 'mouseup' : 'touchend';
      var moveEventOptions = eventType === 'touch' ? {
        passive: false
      } : undefined;
      var endEventOptions = eventType === 'touch' ? {
        passive: false
      } : undefined;
      var nextSize$ = (0, _rxjs.fromEvent)(window, moveEventName, moveEventOptions).pipe(op.takeUntil((0, _rxjs.fromEvent)(window, endEventName, endEventOptions)), op.map(function (e) {
        // 触摸事件需要阻止默认行为，防止页面滚动
        if (eventType === 'touch' && e.cancelable) {
          e.preventDefault();
        }
        var coordinates = (0, _touchEventUtils.getEventCoordinates)(e);
        var movingX = coordinates.clientX;
        var nextColumnSize = (0, _extends2.default)({}, columnSize);
        var deltaSum = pipeline.ctx.direction === 'rtl' ? startX - movingX : movingX - startX;
        var deltaRemaining = deltaSum;
        if ((children === null || children === void 0 ? void 0 : children.length) > 0) {
          var leafChildColumns = (0, _utils.collectNodes)(children, 'leaf-only');
          var childrenWidthSum = leafChildColumns.reduce(function (sum, _ref2) {
            var code = _ref2.code;
            return sum + columnSize[code];
          }, 0);
          leafChildColumns.forEach(function (_ref3, index) {
            var code = _ref3.code;
            var startSize = columnSize[code];
            var currentDeltaWidth = Math.round(deltaSum * startSize / childrenWidthSum);
            if (index < leafChildColumns.length - 1) {
              nextColumnSize[code] = clamp(realMinSize, startSize + currentDeltaWidth, realMaxSize);
              changedColumnSize[code] = nextColumnSize[code];
              deltaRemaining -= currentDeltaWidth;
            } else {
              nextColumnSize[code] = clamp(realMinSize, startSize + deltaRemaining, realMaxSize);
              changedColumnSize[code] = nextColumnSize[code];
            }
          });
        } else {
          var startSize = columnSize[code];
          nextColumnSize[code] = clamp(realMinSize, startSize + deltaSum, realMaxSize);
          changedColumnSize[code] = nextColumnSize[code];
        }
        recordColumnSize = nextColumnSize;
        return nextColumnSize;
      }));
      nextSize$.subscribe({
        next: function next(nextColumnSize) {
          onChangeSize(nextColumnSize);
          // 由于COLUMN_RESIZE_KEY记录的是全量的列宽，此处记录被改变过的列宽
          var resizedColumnSet = pipeline.getFeatureOptions(RESIZED_COLUMN_KEY) || new _set.default();
          (0, _keys.default)(changedColumnSize).forEach(function (code) {
            resizedColumnSet.add(code, changedColumnSize[code]);
          });
          pipeline.setFeatureOptions(RESIZED_COLUMN_KEY, resizedColumnSet);
          pipeline.setFeatureOptions(LAST_RESIZED_COLUMN_KEY, code);
        },
        complete: function complete() {
          var _context;
          var changedColumnSizes = (0, _map.default)(_context = (0, _keys.default)(changedColumnSize)).call(_context, function (code) {
            return {
              code: code,
              width: changedColumnSize[code]
            };
          });
          window.requestAnimationFrame(function () {
            var _a;
            (_a = opts === null || opts === void 0 ? void 0 : opts.afterChangeSize) === null || _a === void 0 ? void 0 : _a.call(opts, recordColumnSize, changedColumnSizes);
          });
          window.removeEventListener('selectstart', disableSelect);
        }
      });
    };
    var handleMouseDown = function handleMouseDown(e, col) {
      e.stopPropagation();
      handleResize(e.nativeEvent, col, 'mouse');
    };
    // 触摸事件处理函数
    var handleTouchStart = function handleTouchStart(e, col) {
      // 阻止触摸事件的默认行为
      if (e.cancelable) {
        e.preventDefault();
      }
      e.stopPropagation();
      handleResize(e.nativeEvent, col, 'touch');
    };
    var isGroup = (0, _utils.isGroupColumn)(pipeline.getColumns());
    return pipeline.mapColumns((0, _utils.makeRecursiveMapper)(function (col) {
      var _a;
      var prevTitle = _internals.internals.safeRenderHeader(col);
      var code = col.code,
        features = col.features,
        width = col.width;
      return (0, _extends2.default)((0, _extends2.default)({}, col), {
        width: (_a = columnSize[code]) !== null && _a !== void 0 ? _a : width,
        title: (/*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, prevTitle, (features === null || features === void 0 ? void 0 : features.resizeable) !== false && (isGroup ? /*#__PURE__*/_react.default.createElement(TableHeaderGroupCellResize, {
          direction: pipeline.ctx.direction,
          className: _styles.Classes.tableHeaderCellResize,
          onDoubleClick: function onDoubleClick(e) {
            return handleDoubleClick(e, col);
          },
          onMouseDown: function onMouseDown(e) {
            return handleMouseDown(e, col);
          },
          onTouchStart: function onTouchStart(e) {
            return handleTouchStart(e, col);
          }
        }) : /*#__PURE__*/_react.default.createElement(TableHeaderCellResize, {
          direction: pipeline.ctx.direction,
          className: _styles.Classes.tableHeaderCellResize,
          onDoubleClick: function onDoubleClick(e) {
            return handleDoubleClick(e, col);
          },
          onMouseDown: function onMouseDown(e) {
            return handleMouseDown(e, col);
          },
          onTouchStart: function onTouchStart(e) {
            return handleTouchStart(e, col);
          }
        })))),
        headerCellProps: (0, _utils.mergeCellProps)(col.headerCellProps, {
          className: 'resizeable'
        })
      });
    }));
  };
}