"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 _templateObject, _templateObject2;
function _getRequireWildcardCache(e) { if ("function" != typeof _WeakMap) return null; var r = new _WeakMap(), t = new _WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && _Object$getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? _Object$getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
var TableHeaderCellResize = _styledComponents.default.div(_templateObject || (_templateObject = (0, _taggedTemplateLiteral2.default)(["\n  position: absolute;\n  top: 0;\n  right: -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    left: calc(50% - 1px);\n    width: 1px;\n    height: calc(100% - 14px);\n    top: 7px;\n  }\n"])));
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 handleMouseDown = function handleMouseDown(e, col) {
      window.addEventListener('selectstart', disableSelect);
      var changedColumnSize = {};
      var startX = e.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;
      e.stopPropagation();
      var nextSize$ = (0, _rxjs.fromEvent)(window, 'mousemove').pipe(op.takeUntil((0, _rxjs.fromEvent)(window, 'mouseup')), op.map(function (e) {
        var movingX = e.clientX;
        var nextColumnSize = (0, _extends2.default)({}, columnSize);
        var deltaSum = 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 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, {
          className: _styles.Classes.tableHeaderCellResize,
          onDoubleClick: function onDoubleClick(e) {
            return handleDoubleClick(e, col);
          },
          onMouseDown: function onMouseDown(e) {
            return handleMouseDown(e, col);
          }
        }) : /*#__PURE__*/_react.default.createElement(TableHeaderCellResize, {
          className: _styles.Classes.tableHeaderCellResize,
          onDoubleClick: function onDoubleClick(e) {
            return handleDoubleClick(e, col);
          },
          onMouseDown: function onMouseDown(e) {
            return handleMouseDown(e, col);
          }
        })))),
        headerCellProps: (0, _utils.mergeCellProps)(col.headerCellProps, {
          className: 'resizeable'
        })
      });
    }));
  };
}