"use strict";

exports.__esModule = true;
exports.default = void 0;

var Waterfall =
/*#__PURE__*/
function () {
  function Waterfall(_ref) {
    var width = _ref.width,
        margin = _ref.margin,
        _ref$grid = _ref.grid,
        grid = _ref$grid === void 0 ? 1 : _ref$grid;
    this.config({
      width,
      margin,
      grid
    });
  }

  var _proto = Waterfall.prototype;

  _proto.config = function config(_ref2) {
    var width = _ref2.width,
        margin = _ref2.margin,
        _ref2$grid = _ref2.grid,
        grid = _ref2$grid === void 0 ? 1 : _ref2$grid;
    this.width = width;
    this.margin = margin;
    this.grid = grid;
    this.rowsLength = Math.floor(this.width / this.grid);
    var rows = [{
      num: this.rowsLength,
      value: 0
    }];
    this.rows = rows;
  };

  _proto.getPostion = function getPostion(width, height) {
    var num = Math.ceil(width / this.grid);

    if (num > this.rowsLength) {
      throw new Error('超出最大宽度');
    }

    var min = Infinity;
    var idx = 0;
    var rowsLength = 0;
    var leftNum = 0;
    var total = this.rowsLength;

    for (var i = this.rows.length - 1; i > -1; i--) {
      rowsLength += this.rows[i].num;
      total -= this.rows[i].num;

      if (rowsLength >= num) {
        var top = this.rows[i].value;

        if (top <= min) {
          leftNum = total;
          min = this.rows[i].value;
          idx = i;
        }
      }

      if (this.rows[i - 1] && this.rows[i - 1].value < this.rows[i].value) {
        rowsLength = 0;
      }
    }

    var row = this.rows[idx];

    if (row.num > num) {
      var newRow = {
        num: row.num - num,
        value: row.value
      };
      this.rows.splice(idx + 1, 0, newRow);
      row.num = num;
    } else if (row.num < num) {
      var _total = row.num;

      for (var index = idx + 1; index < this.rows.length; index++) {
        _total += this.rows[index].num;

        if (_total <= num) {
          row.num += this.rows[index].num;
          this.rows.splice(index, 1);
          index -= 1;
        } else {
          row.num = num;
          this.rows[index].num = _total - num;
        }

        if (_total >= num) break;
      }
    }

    var value = row.value;
    row.value += height + this.margin;
    return {
      left: leftNum * this.grid + idx * this.margin,
      top: value
    };
  };

  return Waterfall;
}();

exports.default = Waterfall;