"use strict";

var _sliceInstanceProperty = 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.default = TableHeader;

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

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

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

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

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

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

var _classnames = _interopRequireDefault(require("classnames"));

var _react = _interopRequireDefault(require("react"));

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

var _styles = require("./styles");

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 _context6; if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = _sliceInstanceProperty(_context6 = Object.prototype.toString.call(o)).call(_context6, 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 range(n) {
  var array = [];

  for (var i = 0; i < n; i++) {
    array.push(i);
  }

  return array;
}
/** 根据当前横向虚拟滚动 对 nested.center 进行过滤，结果只保留当前视野内可见的那些列配置 */


function filterNestedCenter(centerNested, hoz, leftFlatCount) {
  return dfs(centerNested, leftFlatCount).filtered;

  function dfs(cols, startColIndex) {
    var leafCount = 0;
    var filtered = [];

    var _iterator = _createForOfIteratorHelper(cols),
        _step;

    try {
      for (_iterator.s(); !(_step = _iterator.n()).done;) {
        var col = _step.value;
        var colIndex = startColIndex + leafCount;

        if ((0, _utils.isLeafNode)(col)) {
          leafCount += 1;

          if (leftFlatCount + hoz.leftIndex <= colIndex && colIndex < leftFlatCount + hoz.rightIndex) {
            filtered.push({
              colIndex: colIndex,
              col: col
            });
          }
        } else {
          var dfsRes = dfs(col.children, colIndex);
          leafCount += dfsRes.leafCount;

          if (dfsRes.filtered.length > 0) {
            filtered.push({
              colIndex: colIndex,
              col: col,
              children: dfsRes.filtered
            });
          }
        }
      }
    } catch (err) {
      _iterator.e(err);
    } finally {
      _iterator.f();
    }

    return {
      filtered: filtered,
      leafCount: leafCount
    };
  }
}
/** 根据输入的 nested 列配置，算出相应的 leveled & flat 配置方便渲染 */


function calculateLeveledAndFlat(inputNested, rowCount) {
  var leveled = [];

  for (var depth = 0; depth < rowCount; depth++) {
    leveled.push([]);
  }

  var flat = [];
  dfs(inputNested, 0);
  return {
    flat: flat,
    leveled: leveled
  };

  function dfs(input, depth) {
    var leafCount = 0;

    for (var i = 0; i < input.length; i++) {
      var indexedCol = input[i];

      if ((0, _utils.isLeafNode)(indexedCol)) {
        leafCount += 1;
        var wrapped = {
          type: 'normal',
          width: indexedCol.col.width,
          col: indexedCol.col,
          colIndex: indexedCol.colIndex,
          colSpan: 1,
          isLeaf: true
        };
        leveled[depth].push(wrapped);
        flat.push(wrapped);
      } else {
        var dfsRes = dfs(indexedCol.children, depth + 1);
        leafCount += dfsRes.leafCount;

        if (dfsRes.leafCount > 0) {
          leveled[depth].push({
            type: 'normal',
            width: indexedCol.col.width,
            col: indexedCol.col,
            colIndex: indexedCol.colIndex,
            colSpan: dfsRes.leafCount,
            isLeaf: false
          });
        }
      }
    }

    return {
      leafCount: leafCount
    };
  }
}
/** 包装列配置，附加上 colIndex 属性 */


function attachColIndex(inputNested, colIndexOffset) {
  return dfs(inputNested, colIndexOffset).result;

  function dfs(input, startColIndex) {
    var result = [];
    var leafCount = 0;

    for (var i = 0; i < input.length; i++) {
      var col = input[i];
      var colIndex = startColIndex + leafCount;

      if ((0, _utils.isLeafNode)(col)) {
        leafCount += 1;
        result.push({
          colIndex: colIndex,
          col: col
        });
      } else {
        var sub = dfs(col.children, colIndex);
        leafCount += sub.leafCount;

        if (sub.leafCount > 0) {
          result.push({
            col: col,
            colIndex: colIndex,
            children: sub.result
          });
        }
      }
    }

    return {
      result: result,
      leafCount: leafCount
    };
  }
}
/** 计算用于渲染表头的数据结构 */


function calculateHeaderRenderInfo(_ref, rowCount) {
  var flat = (0, _flat.default)(_ref),
      nested = _ref.nested,
      hoz = _ref.horizontalRenderRange,
      useVirtual = _ref.useVirtual;

  if (useVirtual.header) {
    var _context, _context2;

    var leftPart = calculateLeveledAndFlat(attachColIndex(nested.left, 0), rowCount);
    var filtered = filterNestedCenter(nested.center, hoz, flat.left.length);
    var centerPart = calculateLeveledAndFlat(filtered, rowCount);
    var rightPart = calculateLeveledAndFlat(attachColIndex(nested.right, flat.left.length + flat.center.length), rowCount);
    return {
      flat: (0, _concat.default)(_context = []).call(_context, (0, _toConsumableArray2.default)((0, _flat.default)(leftPart)), [{
        type: 'blank',
        width: hoz.leftBlank,
        blankSide: 'left'
      }], (0, _toConsumableArray2.default)((0, _flat.default)(centerPart)), [{
        type: 'blank',
        width: hoz.rightBlank,
        blankSide: 'right'
      }], (0, _toConsumableArray2.default)((0, _flat.default)(rightPart))),
      leveled: (0, _map.default)(_context2 = range(rowCount)).call(_context2, function (depth) {
        var _context3;

        return (0, _concat.default)(_context3 = []).call(_context3, (0, _toConsumableArray2.default)(leftPart.leveled[depth]), [{
          type: 'blank',
          width: hoz.leftBlank,
          blankSide: 'left'
        }], (0, _toConsumableArray2.default)(centerPart.leveled[depth]), [{
          type: 'blank',
          width: hoz.rightBlank,
          blankSide: 'right'
        }], (0, _toConsumableArray2.default)(rightPart.leveled[depth]));
      })
    };
  }

  return calculateLeveledAndFlat(attachColIndex(nested.full, 0), rowCount);
}

function TableHeader(_ref2) {
  var _context4, _context5;

  var info = _ref2.info,
      theaderPosition = _ref2.theaderPosition,
      _rowCount = _ref2.rowCount;
  var nested = info.nested,
      flat = (0, _flat.default)(info),
      stickyLeftMap = info.stickyLeftMap,
      stickyRightMap = info.stickyRightMap;
  var rowCount = _rowCount !== null && _rowCount !== void 0 ? _rowCount : (0, _utils.getTreeDepth)(nested.full) + 1;
  var headerRenderInfo = calculateHeaderRenderInfo(info, rowCount);
  var fullFlatCount = flat.full.length;
  var leftFlatCount = flat.left.length;
  var rightFlatCount = flat.right.length;
  var thead = (0, _map.default)(_context4 = headerRenderInfo.leveled).call(_context4, function (wrappedCols, level) {
    var _cx2;

    var _wrappedCols = (0, _concat.default)(wrappedCols).call(wrappedCols); // 左中右区域渲染，分组列可能单独位于一个区域，此时其他区域也需要适配分组的高度
    // rowspan 需要空白的列头去占位, 需要补充额外的空白列头


    if (rowCount > 1 && ['left', 'right'].indexOf(theaderPosition) > -1) {
      _wrappedCols.push({
        type: 'blank',
        blankSide: 'left',
        width: 1,
        isPlacehoder: true
      });
    }

    var headerCells = (0, _map.default)(_wrappedCols).call(_wrappedCols, function (wrapped, index) {
      var _a, _b, _c;

      if (wrapped.type === 'normal') {
        var _cx;

        var colIndex = wrapped.colIndex,
            colSpan = wrapped.colSpan,
            isLeaf = wrapped.isLeaf,
            col = wrapped.col;
        var headerCellProps = (_a = col.headerCellProps) !== null && _a !== void 0 ? _a : {};
        var positionStyle = {};

        if (colIndex < leftFlatCount) {
          positionStyle.position = 'sticky';
          positionStyle.left = stickyLeftMap.get(colIndex);
        } else if (colIndex >= fullFlatCount - rightFlatCount) {
          positionStyle.position = 'sticky';
          positionStyle.right = stickyRightMap.get(colIndex);
        }

        var justifyContent = col.align === 'right' ? 'flex-end' : col.align === 'center' ? 'center' : 'flex-start';

        var cell = /*#__PURE__*/_react.default.createElement("th", (0, _extends2.default)({
          key: colIndex
        }, headerCellProps, {
          className: (0, _classnames.default)(_styles.Classes.tableHeaderCell, headerCellProps.className, (_cx = {}, (0, _defineProperty2.default)(_cx, _styles.Classes.first, colIndex === 0), (0, _defineProperty2.default)(_cx, _styles.Classes.last, colIndex + colSpan === fullFlatCount), (0, _defineProperty2.default)(_cx, _styles.Classes.lockLeft, colIndex < leftFlatCount || theaderPosition === 'left'), (0, _defineProperty2.default)(_cx, _styles.Classes.lockRight, colIndex >= fullFlatCount - rightFlatCount || theaderPosition === 'right'), (0, _defineProperty2.default)(_cx, _styles.Classes.leaf, wrapped.isLeaf), _cx)),
          colSpan: colSpan,
          rowSpan: isLeaf ? rowCount - level : undefined,
          style: (0, _extends2.default)((0, _extends2.default)({
            textAlign: col.align,
            verticalAlign: (_b = col.verticalAlign) !== null && _b !== void 0 ? _b : 'middle'
          }, headerCellProps.style), positionStyle),
          "data-code": col.code
        }), theaderPosition === 'center' && positionStyle.position === 'sticky' ? null : /*#__PURE__*/_react.default.createElement("div", {
          className: _styles.Classes.tableHeaderCellContent,
          style: {
            justifyContent: justifyContent
          }
        }, (_c = col.title) !== null && _c !== void 0 ? _c : col.name));

        return cell;
      } else {
        if (wrapped.width > 0) {
          return /*#__PURE__*/_react.default.createElement("th", {
            key: wrapped.blankSide,
            style: {
              visibility: wrapped.isPlacehoder ? 'hidden' : undefined
            }
          });
        } else {
          return null;
        }
      }
    });
    return /*#__PURE__*/_react.default.createElement("tr", {
      key: level,
      className: (0, _classnames.default)(_styles.Classes.tableHeaderRow, (_cx2 = {}, (0, _defineProperty2.default)(_cx2, _styles.Classes.first, level === 0), (0, _defineProperty2.default)(_cx2, _styles.Classes.last, level === rowCount - 1), _cx2))
    }, headerCells);
  });
  var colgroup = (0, _map.default)(_context5 = (0, _flat.default)(headerRenderInfo)).call(_context5, function (wrapped) {
    if (wrapped.type === 'blank') {
      if (wrapped.width > 0) {
        return /*#__PURE__*/_react.default.createElement("col", {
          key: wrapped.blankSide,
          style: {
            width: wrapped.width
          }
        });
      } else {
        return null;
      }
    } else {
      return /*#__PURE__*/_react.default.createElement("col", {
        key: wrapped.colIndex,
        style: {
          width: wrapped.width
        }
      });
    }
  });
  return /*#__PURE__*/_react.default.createElement("table", null, /*#__PURE__*/_react.default.createElement("colgroup", null, colgroup), /*#__PURE__*/_react.default.createElement("thead", null, thead));
}