import _defineProperty from "@babel/runtime-corejs3/helpers/defineProperty";
import _extends from "@babel/runtime-corejs3/helpers/extends";
import _toConsumableArray from "@babel/runtime-corejs3/helpers/toConsumableArray";
import _flatInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/flat";
import _concatInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/concat";
import _mapInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/map";
import _sliceInstanceProperty from "@babel/runtime-corejs3/core-js-stable/instance/slice";
import _Array$from from "@babel/runtime-corejs3/core-js-stable/array/from";
import _Symbol from "@babel/runtime-corejs3/core-js-stable/symbol";
import _getIteratorMethod from "@babel/runtime-corejs3/core-js/get-iterator-method";
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; }
import cx from 'classnames';
import React from 'react';
import { getTreeDepth, isLeafNode } from '../utils';
import { Classes } from './styles';
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 (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 (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 (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 = _flatInstanceProperty(_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: _concatInstanceProperty(_context = []).call(_context, _toConsumableArray(_flatInstanceProperty(leftPart)), [{
        type: 'blank',
        width: hoz.leftBlank,
        blankSide: 'left'
      }], _toConsumableArray(_flatInstanceProperty(centerPart)), [{
        type: 'blank',
        width: hoz.rightBlank,
        blankSide: 'right'
      }], _toConsumableArray(_flatInstanceProperty(rightPart))),
      leveled: _mapInstanceProperty(_context2 = range(rowCount)).call(_context2, function (depth) {
        var _context3;
        return _concatInstanceProperty(_context3 = []).call(_context3, _toConsumableArray(leftPart.leveled[depth]), [{
          type: 'blank',
          width: hoz.leftBlank,
          blankSide: 'left'
        }], _toConsumableArray(centerPart.leveled[depth]), [{
          type: 'blank',
          width: hoz.rightBlank,
          blankSide: 'right'
        }], _toConsumableArray(rightPart.leveled[depth]));
      })
    };
  }
  return calculateLeveledAndFlat(attachColIndex(nested.full, 0), rowCount);
}
export default function TableHeader(_ref2) {
  var _context4, _context5;
  var info = _ref2.info,
    theaderPosition = _ref2.theaderPosition,
    _rowCount = _ref2.rowCount,
    stickyRightOffset = _ref2.stickyRightOffset;
  var nested = info.nested,
    flat = _flatInstanceProperty(info),
    stickyLeftMap = info.stickyLeftMap,
    stickyRightMap = info.stickyRightMap,
    direction = info.direction;
  var rowCount = _rowCount !== null && _rowCount !== void 0 ? _rowCount : 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 = _mapInstanceProperty(_context4 = headerRenderInfo.leveled).call(_context4, function (wrappedCols, level) {
    var _cx2;
    var _wrappedCols = _concatInstanceProperty(wrappedCols).call(wrappedCols);
    // 左中右区域渲染，分组列可能单独位于一个区域，此时其他区域也需要适配分组的高度
    // rowspan 需要空白的列头去占位, 需要补充额外的空白列头
    if (rowCount > 1 && ['left', 'right'].indexOf(theaderPosition) > -1) {
      _wrappedCols.push({
        type: 'blank',
        blankSide: 'left',
        width: 1,
        isPlacehoder: true
      });
    }
    var headerCells = _mapInstanceProperty(_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';
          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.createElement("th", _extends({
          key: colIndex
        }, headerCellProps, {
          className: cx(Classes.tableHeaderCell, headerCellProps.className, (_cx = {}, _defineProperty(_cx, Classes.first, colIndex === 0), _defineProperty(_cx, Classes.last, colIndex + colSpan === fullFlatCount), _defineProperty(_cx, Classes.lockLeft, colIndex < leftFlatCount || theaderPosition === 'left'), _defineProperty(_cx, Classes.lockRight, colIndex >= fullFlatCount - rightFlatCount || theaderPosition === 'right'), _defineProperty(_cx, Classes.leaf, wrapped.isLeaf), _cx)),
          colSpan: colSpan,
          rowSpan: isLeaf ? rowCount - level : undefined,
          style: _extends(_extends({
            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.createElement("div", {
          className: 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.createElement("th", {
            key: wrapped.blankSide,
            style: {
              visibility: wrapped.isPlacehoder ? 'hidden' : undefined
            }
          });
        } else {
          return null;
        }
      }
    });
    return /*#__PURE__*/React.createElement("tr", {
      key: level,
      className: cx(Classes.tableHeaderRow, (_cx2 = {}, _defineProperty(_cx2, Classes.first, level === 0), _defineProperty(_cx2, Classes.last, level === rowCount - 1), _cx2))
    }, headerCells);
  });
  var colgroup = _mapInstanceProperty(_context5 = _flatInstanceProperty(headerRenderInfo)).call(_context5, function (wrapped) {
    if (wrapped.type === 'blank') {
      if (wrapped.width > 0) {
        return /*#__PURE__*/React.createElement("col", {
          key: wrapped.blankSide,
          style: {
            width: wrapped.width
          }
        });
      } else {
        return null;
      }
    } else {
      return /*#__PURE__*/React.createElement("col", {
        key: wrapped.colIndex,
        style: {
          width: wrapped.width
        }
      });
    }
  });
  return /*#__PURE__*/React.createElement("table", null, /*#__PURE__*/React.createElement("colgroup", null, colgroup), /*#__PURE__*/React.createElement("thead", null, thead));
}