"use strict";

var _sliceInstanceProperty2 = require("@babel/runtime-corejs3/core-js-stable/instance/slice");

var _Array$from = require("@babel/runtime-corejs3/core-js-stable/array/from");

var _Symbol = require("@babel/runtime-corejs3/core-js-stable/symbol");

var _getIteratorMethod = require("@babel/runtime-corejs3/core-js/get-iterator-method");

var _interopRequireDefault = require("@babel/runtime-corejs3/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.calculateRenderInfo = calculateRenderInfo;
exports.getLeftNestedLockCount = getLeftNestedLockCount;

var _flat = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/flat"));

var _map = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/map"));

var _slice = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/slice"));

var _concat = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/concat"));

var _filter = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/filter"));

var _map2 = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/map"));

var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/toConsumableArray"));

var _typeof2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/typeof"));

var _extends2 = _interopRequireDefault(require("@babel/runtime-corejs3/helpers/extends"));

var _utils = require("../utils");

var _utils2 = require("./utils");

function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof _Symbol !== "undefined" && _getIteratorMethod(o) || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }

function _unsupportedIterableToArray(o, minLen) { var _context10; if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = _sliceInstanceProperty2(_context10 = Object.prototype.toString.call(o)).call(_context10, 8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return _Array$from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function resolveVirtualEnabled(virtualEnum, defaultValue) {
  if (virtualEnum == null || virtualEnum === 'auto') {
    return defaultValue;
  }

  return virtualEnum;
}

var lockColumnNeedSpecifiedWidthWarned = false;

function warnLockColumnNeedSpecifiedWidth(column) {
  if (!lockColumnNeedSpecifiedWidthWarned) {
    lockColumnNeedSpecifiedWidthWarned = true;

    _utils.console.warn('lock=true 的列需要指定宽度', column);
  }
}

var columnHiddenDeprecatedWarned = false;

function warnColumnHiddenDeprecated(column) {
  if (!columnHiddenDeprecatedWarned) {
    columnHiddenDeprecatedWarned = true;

    _utils.console.warn('column.hidden 已经过时，如果需要隐藏该列，请将其从 columns 数组中移除', column);
  }
}
/** 检查列配置 & 设置默认宽度 & 剔除隐藏的列 */


function processColumns(columns, defaultColumnWidth) {
  if (columns == null || !Array.isArray(columns)) {
    _utils.console.warn('<BaseTable /> props.columns 需要传入一个数组', columns);

    columns = [];
  }

  function dfs(columns) {
    var result = [];

    var _iterator = _createForOfIteratorHelper(columns),
        _step;

    try {
      for (_iterator.s(); !(_step = _iterator.n()).done;) {
        var column = _step.value;

        if (column.width == null) {
          if (defaultColumnWidth != null) {
            column = (0, _extends2.default)((0, _extends2.default)({}, column), {
              width: defaultColumnWidth
            });
          } else if (process.env.NODE_ENV !== 'production' && (0, _utils.isLeafNode)(column) && column.lock) {
            warnLockColumnNeedSpecifiedWidth(column);
          }
        }

        if ((0, _utils.isLeafNode)(column)) {
          if (column.hidden) {
            // 被隐藏的列 会在这里被剔除
            warnColumnHiddenDeprecated(column);
          } else {
            result.push(column);
          }
        } else {
          var nextChildren = dfs(column.children); // 如果 nextChildren 为空，说明所有的子节点均被隐藏了，在这里隐藏父节点

          if (nextChildren.length > 0) {
            result.push((0, _extends2.default)((0, _extends2.default)({}, column), {
              children: nextChildren
            }));
          }
        }
      }
    } catch (err) {
      _iterator.e(err);
    } finally {
      _iterator.f();
    }

    return result;
  }

  return dfs(columns);
}

function getLeftNestedLockCount(columns) {
  var nestedCount = 0;

  var _iterator2 = _createForOfIteratorHelper(columns),
      _step2;

  try {
    for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
      var col = _step2.value;

      if (isLock(col)) {
        nestedCount += 1;
      } else {
        break;
      }
    }
  } catch (err) {
    _iterator2.e(err);
  } finally {
    _iterator2.f();
  }

  return nestedCount;

  function isLock(col) {
    if ((0, _utils.isLeafNode)(col)) {
      return col.lock;
    } else {
      return col.lock || col.children.some(isLock);
    }
  }
}

function getHorizontalRenderRange(_ref) {
  var _context, _context2;

  var offsetX = _ref.offsetX,
      maxRenderWidth = _ref.maxRenderWidth,
      flat = (0, _flat.default)(_ref),
      useVirtual = _ref.useVirtual;

  if (!useVirtual.horizontal) {
    return {
      leftIndex: 0,
      leftBlank: 0,
      rightIndex: flat.full.length,
      rightBlank: 0
    };
  }

  var leftIndex = 0;
  var centerCount = 0;
  var leftBlank = 0;
  var centerRenderWidth = 0;
  var overscannedOffsetX = Math.max(0, offsetX - _utils2.OVERSCAN_SIZE);

  while (leftIndex < flat.center.length) {
    var col = flat.center[leftIndex];

    if (col.width + leftBlank < overscannedOffsetX) {
      leftIndex += 1;
      leftBlank += col.width;
    } else {
      break;
    }
  } // 考虑 over scan 之后，中间部分的列至少需要渲染的宽度


  var minCenterRenderWidth = maxRenderWidth + (overscannedOffsetX - leftBlank) + 2 * _utils2.OVERSCAN_SIZE;

  while (leftIndex + centerCount < flat.center.length) {
    var _col = flat.center[leftIndex + centerCount];

    if (centerRenderWidth < minCenterRenderWidth) {
      centerRenderWidth += _col.width;
      centerCount += 1;
    } else {
      break;
    }
  }

  var rightBlankCount = flat.center.length - leftIndex - centerCount;
  var rightBlank = (0, _utils2.sum)((0, _map.default)(_context = (0, _slice.default)(_context2 = flat.center).call(_context2, flat.center.length - rightBlankCount)).call(_context, function (col) {
    return col.width;
  }));
  return {
    leftIndex: leftIndex,
    leftBlank: leftBlank,
    rightIndex: leftIndex + centerCount,
    rightBlank: rightBlank
  };
} // 一顿计算，将表格本次渲染所需要的数据都给算出来（代码写得有点乱，有较大优化空间）
// todo 可以考虑下将 header 部分的计算逻辑也放到这个文件中，目前应该有一些重复的计算逻辑


function calculateRenderInfo(table) {
  var _context3, _context4, _context5, _context6, _context7, _context8, _context9;

  var _table$state = table.state,
      offsetX = _table$state.offsetX,
      maxRenderWidth = _table$state.maxRenderWidth;
  var _table$props = table.props,
      useVirtualProp = _table$props.useVirtual,
      columnsProp = _table$props.columns,
      dataSourceProp = _table$props.dataSource,
      defaultColumnWidth = _table$props.defaultColumnWidth;
  var columns = processColumns(columnsProp, defaultColumnWidth);
  var leftNestedLockCount = getLeftNestedLockCount(columns);
  var fullFlat = (0, _utils.collectNodes)(columns, 'leaf-only');
  var flat;
  var nested;
  var useVirtual;

  if (leftNestedLockCount === columns.length) {
    flat = {
      left: [],
      right: [],
      full: fullFlat,
      center: fullFlat
    };
    nested = {
      left: [],
      right: [],
      full: columns,
      center: columns
    };
    useVirtual = {
      horizontal: false,
      vertical: false,
      header: false
    };
  } else {
    var leftNested = (0, _slice.default)(columns).call(columns, 0, leftNestedLockCount);
    var rightNestedLockCount = getLeftNestedLockCount((0, _slice.default)(columns).call(columns).reverse());
    var centerNested = (0, _slice.default)(columns).call(columns, leftNestedLockCount, columns.length - rightNestedLockCount);
    var rightNested = (0, _slice.default)(columns).call(columns, columns.length - rightNestedLockCount);
    var shouldEnableHozVirtual = fullFlat.length >= _utils2.AUTO_VIRTUAL_THRESHOLD && fullFlat.every(function (col) {
      return col.width != null;
    });
    var shouldEnableVerVirtual = dataSourceProp.length >= _utils2.AUTO_VIRTUAL_THRESHOLD;
    useVirtual = {
      horizontal: resolveVirtualEnabled((0, _typeof2.default)(useVirtualProp) === 'object' ? useVirtualProp.horizontal : useVirtualProp, shouldEnableHozVirtual),
      vertical: resolveVirtualEnabled((0, _typeof2.default)(useVirtualProp) === 'object' ? useVirtualProp.vertical : useVirtualProp, shouldEnableVerVirtual),
      header: resolveVirtualEnabled((0, _typeof2.default)(useVirtualProp) === 'object' ? useVirtualProp.header : useVirtualProp, false)
    };
    flat = {
      left: (0, _utils.collectNodes)(leftNested, 'leaf-only'),
      full: fullFlat,
      right: (0, _utils.collectNodes)(rightNested, 'leaf-only'),
      center: (0, _utils.collectNodes)(centerNested, 'leaf-only')
    };
    nested = {
      left: leftNested,
      full: columns,
      right: rightNested,
      center: centerNested
    };
  }

  var horizontalRenderRange = getHorizontalRenderRange({
    maxRenderWidth: maxRenderWidth,
    offsetX: offsetX,
    useVirtual: useVirtual,
    flat: flat
  });
  var verticalRenderRange = table.getVerticalRenderRange(useVirtual);
  var leftBlank = horizontalRenderRange.leftBlank,
      leftIndex = horizontalRenderRange.leftIndex,
      rightBlank = horizontalRenderRange.rightBlank,
      rightIndex = horizontalRenderRange.rightIndex;
  var unfilteredVisibleColumnDescriptors = (0, _concat.default)(_context3 = []).call(_context3, (0, _toConsumableArray2.default)((0, _map.default)(_context4 = flat.left).call(_context4, function (col, i) {
    return {
      type: 'normal',
      col: col,
      colIndex: i
    };
  })), [leftBlank > 0 && {
    type: 'blank',
    blankSide: 'left',
    width: leftBlank
  }], (0, _toConsumableArray2.default)((0, _map.default)(_context5 = (0, _slice.default)(_context6 = flat.center).call(_context6, leftIndex, rightIndex)).call(_context5, function (col, i) {
    return {
      type: 'normal',
      col: col,
      colIndex: flat.left.length + leftIndex + i
    };
  })), [rightBlank > 0 && {
    type: 'blank',
    blankSide: 'right',
    width: rightBlank
  }], (0, _toConsumableArray2.default)((0, _map.default)(_context7 = flat.right).call(_context7, function (col, i) {
    return {
      type: 'normal',
      col: col,
      colIndex: flat.full.length - flat.right.length + i
    };
  })));
  var visibleColumnDescriptors = (0, _filter.default)(unfilteredVisibleColumnDescriptors).call(unfilteredVisibleColumnDescriptors, Boolean); // const totalWidth = visibleColumnDescriptors.reduce((pre, cur) => {
  //   if (cur.type === 'blank') {
  //     return cur.width + pre
  //   } else {
  //     return cur.col.width + pre
  //   }
  // }, 0)
  // if (totalWidth < maxRenderWidth) {
  //   visibleColumnDescriptors.push({
  //     type: 'blank',
  //     blankSide: 'left',
  //     width: `width: calc(100% - ${totalWidth}px)`
  //   } as VisibleColumnDescriptor)
  // }

  var fullFlatCount = flat.full.length;
  var leftFlatCount = flat.left.length;
  var rightFlatCount = flat.right.length;
  var stickyLeftMap = new _map2.default();
  var stickyLeft = 0;

  for (var i = 0; i < leftFlatCount; i++) {
    stickyLeftMap.set(i, stickyLeft);
    stickyLeft += flat.full[i].width;
  }

  var stickyRightMap = new _map2.default();
  var stickyRight = 0;

  for (var _i = 0; _i < rightFlatCount; _i++) {
    stickyRightMap.set(fullFlatCount - 1 - _i, stickyRight);
    stickyRight += flat.full[fullFlatCount - 1 - _i].width;
  }

  var leftLockTotalWidth = (0, _utils2.sum)((0, _map.default)(_context8 = flat.left).call(_context8, function (col) {
    return col.width;
  }));
  var rightLockTotalWidth = (0, _utils2.sum)((0, _map.default)(_context9 = flat.right).call(_context9, function (col) {
    return col.width;
  }));
  return {
    horizontalRenderRange: horizontalRenderRange,
    verticalRenderRange: verticalRenderRange,
    visible: visibleColumnDescriptors,
    flat: flat,
    nested: nested,
    useVirtual: useVirtual,
    stickyLeftMap: stickyLeftMap,
    stickyRightMap: stickyRightMap,
    leftLockTotalWidth: leftLockTotalWidth,
    rightLockTotalWidth: rightLockTotalWidth,
    hasLockColumn: nested.left.length > 0 || nested.right.length > 0
  };
}