"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(r, e) { var t = "undefined" != typeof _Symbol && _getIteratorMethod(r) || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, 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 o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t.return || t.return(); } finally { if (u) throw o; } } }; }
function _unsupportedIterableToArray(r, a) { if (r) { var _context6; if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = _sliceInstanceProperty(_context6 = {}.toString.call(r)).call(_context6, 8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? _Array$from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
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, false);
  return {
    flat: flat,
    leveled: leveled
  };
  function dfs(input, depth, suppressLeveled) {
    var _a;
    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
        };
        if (!suppressLeveled) {
          leveled[depth].push(wrapped);
        }
        flat.push(wrapped);
      } else {
        var mergeHeader = Boolean((_a = indexedCol.col) === null || _a === void 0 ? void 0 : _a.isHeaderMerge);
        var dfsRes = dfs(indexedCol.children, depth + 1, suppressLeveled || mergeHeader);
        leafCount += dfsRes.leafCount;
        if (dfsRes.leafCount > 0 && !suppressLeveled) {
          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,
    stickyRightOffset = _ref2.stickyRightOffset;
  var nested = info.nested,
    flat = (0, _flat.default)(info),
    stickyLeftMap = info.stickyLeftMap,
    stickyRightMap = info.stickyRightMap,
    direction = info.direction;
  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 _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 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';
          if (direction === 'rtl') {
            positionStyle.right = stickyLeftMap.get(colIndex);
          } else {
            positionStyle.left = stickyLeftMap.get(colIndex);
          }
        } else if (colIndex >= fullFlatCount - rightFlatCount) {
          positionStyle.position = 'sticky';
          var stickyRightIndex = colSpan > 1 ? colIndex + colSpan - 1 : colIndex;
          if (direction === 'rtl') {
            positionStyle.left = stickyRightMap.get(stickyRightIndex) + (typeof stickyRightOffset === 'number' ? stickyRightOffset : 0);
          } else {
            positionStyle.right = stickyRightMap.get(stickyRightIndex) + (typeof stickyRightOffset === 'number' ? stickyRightOffset : 0);
          }
        }
        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, (0, _defineProperty2.default)((0, _defineProperty2.default)((0, _defineProperty2.default)((0, _defineProperty2.default)((0, _defineProperty2.default)({}, _styles.Classes.first, colIndex === 0), _styles.Classes.last, colIndex + colSpan === fullFlatCount), _styles.Classes.lockLeft, colIndex < leftFlatCount || theaderPosition === 'left'), _styles.Classes.lockRight, colIndex >= fullFlatCount - rightFlatCount || theaderPosition === 'right'), _styles.Classes.leaf, wrapped.isLeaf || col.isHeaderMerge)),
          colSpan: colSpan,
          rowSpan: isLeaf || col.isHeaderMerge ? 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, (0, _defineProperty2.default)((0, _defineProperty2.default)({}, _styles.Classes.first, level === 0), _styles.Classes.last, level === rowCount - 1))
    }, 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));
}