import _extends from "@babel/runtime-corejs3/helpers/extends";
import _taggedTemplateLiteral from "@babel/runtime-corejs3/helpers/taggedTemplateLiteral";

var _templateObject, _templateObject2;

import _mapInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/map";
import _Object$keys from "@babel/runtime-corejs3/core-js-stable/object/keys";
import React from 'react';
import styled from 'styled-components';
import { fromEvent } from 'rxjs';
import * as op from 'rxjs/operators';
import { mergeCellProps, collectNodes, makeRecursiveMapper, isGroupColumn } from '../../utils';
import { internals } from '../../internals';
import { Classes } from '../../base/styles';
var TableHeaderCellResize = styled.div(_templateObject || (_templateObject = _taggedTemplateLiteral(["\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 = styled(TableHeaderCellResize)(_templateObject2 || (_templateObject2 = _taggedTemplateLiteral(["\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();
}

export function columnResize() {
  var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

  var _a, _b, _c;

  var stateKey = 'columnResize';
  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, _c;

    var columnSize = (_b = (_a = opts.columnSize) !== null && _a !== void 0 ? _a : pipeline.getStateAtKey(stateKey)) !== null && _b !== void 0 ? _b : {};
    var leafColumns = 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;
        }
      }
    }); // 初始化 || opts.columnSize发生变化（为了autofill时能取到最新值）

    if (!pipeline.getStateAtKey(stateKey) || ((_c = pipeline.ref) === null || _c === void 0 ? void 0 : _c.current.lastOptColumnSize) !== opts.columnSize) {
      pipeline.setStateAtKey(stateKey, columnSize);
    }

    if (pipeline.ref) {
      pipeline.ref.current.lastOptColumnSize = opts.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);

        if (opts.columnSize) {
          if (pipeline.ref) {
            pipeline.ref.current.lastOptColumnSize = nextColumnSize; // 这里记录由列宽拖拽导致的opts.columnSize变化,避免重复渲染
          }
        }
      });
    };

    var handleDoubleClick = function handleDoubleClick(e, col) {
      opts === null || opts === void 0 ? void 0 : opts.doubleClickCallback(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;
      var recordColumnSize = columnSize;
      e.stopPropagation();
      var nextSize$ = fromEvent(window, 'mousemove').pipe(op.takeUntil(fromEvent(window, 'mouseup')), op.map(function (e) {
        var movingX = e.clientX;

        var nextColumnSize = _extends({}, columnSize);

        var deltaSum = movingX - startX;
        var deltaRemaining = deltaSum;

        if ((children === null || children === void 0 ? void 0 : children.length) > 0) {
          var leafChildColumns = 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(minSize, startSize + currentDeltaWidth, maxSize);
              changedColumnSize[code] = nextColumnSize[code];
              deltaRemaining -= currentDeltaWidth;
            } else {
              nextColumnSize[code] = clamp(minSize, startSize + deltaRemaining, maxSize);
              changedColumnSize[code] = nextColumnSize[code];
            }
          });
        } else {
          var startSize = columnSize[code];
          nextColumnSize[code] = clamp(minSize, startSize + deltaSum, maxSize);
          changedColumnSize[code] = nextColumnSize[code];
        }

        recordColumnSize = nextColumnSize;
        return nextColumnSize;
      }));
      nextSize$.subscribe({
        next: onChangeSize,
        complete: function complete() {
          var _context;

          var changedColumnSizes = _mapInstanceProperty(_context = _Object$keys(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 = isGroupColumn(pipeline.getColumns());
    return pipeline.mapColumns(makeRecursiveMapper(function (col) {
      var _a;

      var prevTitle = internals.safeRenderHeader(col);
      var code = col.code,
          features = col.features,
          width = col.width;
      return _extends(_extends({}, col), {
        width: (_a = columnSize[code]) !== null && _a !== void 0 ? _a : width,
        title: /*#__PURE__*/React.createElement(React.Fragment, null, prevTitle, (features === null || features === void 0 ? void 0 : features.resizeable) !== false && (isGroup ? /*#__PURE__*/React.createElement(TableHeaderGroupCellResize, {
          className: Classes.tableHeaderCellResize,
          onDoubleClick: function onDoubleClick(e) {
            return handleDoubleClick(e, col);
          },
          onMouseDown: function onMouseDown(e) {
            return handleMouseDown(e, col);
          }
        }) : /*#__PURE__*/React.createElement(TableHeaderCellResize, {
          className: Classes.tableHeaderCellResize,
          onDoubleClick: function onDoubleClick(e) {
            return handleDoubleClick(e, col);
          },
          onMouseDown: function onMouseDown(e) {
            return handleMouseDown(e, col);
          }
        }))),
        headerCellProps: mergeCellProps(col.headerCellProps, {
          className: 'resizeable'
        })
      });
    }));
  };
}