import _extends from "@babel/runtime/helpers/extends";
import _defineProperty from "@babel/runtime/helpers/defineProperty";
import _objectSpread from "@babel/runtime/helpers/objectSpread2";
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import React, { useCallback, useContext } from 'react';
import { action } from 'mobx';
import { observer } from 'mobx-react-lite';
import classNames from 'classnames';
import omit from 'lodash/omit';
import isFunction from 'lodash/isFunction';
import { IteratorHelper } from 'choerodon-ui/dataset';
import { pxToRem } from '../../../es/_util/UnitConvertor';
import { defaultAggregationRenderer } from './Column';
import TableContext from './TableContext';
import { getColumnLock, getEditorByColumnAndRecord, isDisabledRow, isStickySupport } from './utils';
import { ColumnLock } from './enum';
import TableCellInner from './TableCellInner';
import { treeSome } from '../_util/treeUtils';
import TableGroupCellInner from './TableGroupCellInner';
import { DRAG_KEY, SELECTION_KEY } from './TableStore';
import { groupedAggregationTree } from './AggregationTree';
import AggregationTreeGroups from './AggregationTreeGroups';

function getRowSpan(group, tableStore) {
  if (tableStore.headerTableGroups.length) {
    var subGroups = group.subGroups,
        subHGroups = group.subHGroups;

    if (subHGroups) {
      return IteratorHelper.iteratorReduce(subHGroups.values(), function (rowSpan, group) {
        return Math.max(rowSpan, group.records.length);
      }, 0);
    }

    return subGroups.reduce(function (rowSpan, subGroup) {
      return rowSpan + (subGroup.subGroups.length ? getRowSpan(subGroup, tableStore) : 0) + subGroup.records.length;
    }, 0);
  }

  return group.expandedRecords.length;
}

var TableCell = function TableCell(props) {
  var _classNames, _classNames3;

  var columnGroup = props.columnGroup,
      record = props.record,
      isDragging = props.isDragging,
      provided = props.provided,
      isDragDisabled = props.isDragDisabled,
      colSpan = props.colSpan,
      className = props.className,
      children = props.children,
      disabled = props.disabled,
      groupPath = props.groupPath,
      rowIndex = props.rowIndex,
      virtualHeight = props.virtualHeight,
      intersectionRef = props.intersectionRef,
      isFixedRowHeight = props.isFixedRowHeight,
      isRenderCell = props.isRenderCell;
  var dragDisabled = isFunction(isDragDisabled) ? isDragDisabled(record) : isDragDisabled;
  var column = columnGroup.column,
      key = columnGroup.key;

  var _useContext = useContext(TableContext),
      tableStore = _useContext.tableStore,
      prefixCls = _useContext.prefixCls,
      dataSet = _useContext.dataSet,
      expandIconAsCell = _useContext.expandIconAsCell,
      tableAggregation = _useContext.aggregation,
      rowHeight = _useContext.rowHeight;

  var cellPrefix = "".concat(prefixCls, "-cell");
  var tableColumnOnCell = tableStore.getConfig('tableColumnOnCell');
  var __tableGroup = column.__tableGroup,
      style = column.style,
      lock = column.lock,
      onCell = column.onCell,
      aggregation = column.aggregation;

  var _ref = __tableGroup && groupPath && groupPath.find(function (_ref3) {
    var _ref4 = _slicedToArray(_ref3, 1),
        path = _ref4[0];

    return path.name === __tableGroup.name;
  }) || [undefined, false],
      _ref2 = _slicedToArray(_ref, 2),
      group = _ref2[0],
      isLast = _ref2[1];

  var _ref5 = group || !groupPath || !groupPath.length ? [undefined, false] : groupPath[groupPath.length - 1],
      _ref6 = _slicedToArray(_ref5, 1),
      rowGroup = _ref6[0];

  var getInnerNode = useCallback(function (col, onCellStyle, inAggregation, headerGroup) {
    return record ? /*#__PURE__*/React.createElement(TableCellInner, {
      column: col,
      record: record,
      style: onCellStyle,
      disabled: disabled,
      inAggregation: inAggregation,
      prefixCls: cellPrefix,
      colSpan: colSpan,
      headerGroup: headerGroup,
      rowGroup: rowGroup
    }, children) : undefined;
  }, [record, disabled, children, cellPrefix, colSpan, rowGroup]);
  var isBuiltInColumn = tableStore.isBuiltInColumn(column);
  var columnOnCell = !isBuiltInColumn && (onCell || tableColumnOnCell);
  var cellExternalProps = typeof columnOnCell === 'function' && record ? columnOnCell({
    dataSet: dataSet,
    record: record,
    column: column
  }) : {};
  var handleClickCapture = useCallback(action(function (e) {
    if (tableStore.currentEditorName && key === DRAG_KEY) {
      tableStore.blurEditor();
    }

    if (record && !isDisabledRow(record) && e.target.dataset.selectionKey !== SELECTION_KEY) {
      dataSet.current = record;
    }

    var onClickCapture = cellExternalProps.onClickCapture;

    if (typeof onClickCapture === 'function') {
      onClickCapture(e);
    }
  }), [record, dataSet, cellExternalProps]);
  var aggregationTreeRenderer = useCallback(function (_ref7) {
    var colGroup = _ref7.colGroup,
        style = _ref7.style;
    return getInnerNode(colGroup.column, style, true, colGroup.headerGroup);
  }, [getInnerNode]);
  var columnLock = isStickySupport() && getColumnLock(lock);

  var baseStyle = function () {
    if (columnLock) {
      if (columnLock === ColumnLock.left) {
        return _objectSpread(_objectSpread({}, style), {}, {
          left: pxToRem(columnGroup.left, true)
        });
      }

      if (columnLock === ColumnLock.right) {
        return _objectSpread(_objectSpread({}, style), {}, {
          right: pxToRem(colSpan && colSpan > 1 ? 0 : columnGroup.right, true)
        });
      }
    }

    return style;
  }();

  var baseClassName = classNames(cellPrefix, (_classNames = {}, _defineProperty(_classNames, "".concat(cellPrefix, "-fix-").concat(columnLock), columnLock), _defineProperty(_classNames, "".concat(cellPrefix, "-no-transition"), !tableStore.tableColumnResizeTransition), _classNames));
  var intersectionProps = {};

  if (intersectionRef) {
    intersectionProps.ref = intersectionRef;

    if (virtualHeight !== undefined) {
      intersectionProps.style = _objectSpread(_objectSpread({}, baseStyle), {}, {
        height: virtualHeight
      });
    }
  }

  if (!record) {
    return /*#__PURE__*/React.createElement("td", _extends({
      className: baseClassName,
      style: baseStyle,
      "data-index": key,
      colSpan: colSpan
    }, intersectionProps));
  }

  var indexInGroup = group ? group.expandedRecords.indexOf(record) : -1;
  var groupCell = indexInGroup === 0 || tableStore.virtual && indexInGroup > -1 && tableStore.virtualStartIndex === rowIndex;

  if (group && !groupCell) {
    return null;
  }

  var getAggregationTreeGroups = function getAggregationTreeGroups($aggregation) {
    if ($aggregation) {
      var childrenInAggregation = columnGroup.childrenInAggregation;

      if (childrenInAggregation) {
        var groups = childrenInAggregation.columns;
        return groupedAggregationTree({
          rowGroup: __tableGroup ? group : rowGroup,
          headerGroup: columnGroup.headerGroup,
          record: record,
          groups: groups,
          column: column,
          renderer: aggregationTreeRenderer
        });
      }
    }
  };

  var groupRowSpan = groupCell && group ? getRowSpan(group, tableStore) - indexInGroup : undefined;
  var rowSpan = groupRowSpan === 1 ? undefined : groupRowSpan;

  var renderInnerNode = function renderInnerNode($aggregation, onCellStyle) {
    if (expandIconAsCell && children) {
      return /*#__PURE__*/React.createElement("span", {
        className: classNames("".concat(cellPrefix, "-inner"), _defineProperty({}, "".concat(cellPrefix, "-inner-row-height-fixed"), rowHeight !== 'auto')),
        style: _objectSpread({
          textAlign: 'center'
        }, onCellStyle)
      }, children);
    }

    var aggregationList = getAggregationTreeGroups($aggregation);

    if (groupCell && group && __tableGroup) {
      return /*#__PURE__*/React.createElement(TableGroupCellInner, {
        rowSpan: rowSpan,
        group: group,
        column: column,
        isFixedRowHeight: isFixedRowHeight
      }, aggregationList);
    }

    if (aggregationList) {
      var _column$renderer = column.renderer,
          renderer = _column$renderer === void 0 ? defaultAggregationRenderer : _column$renderer;
      var treeGroups = /*#__PURE__*/React.createElement(AggregationTreeGroups, {
        trees: aggregationList
      });
      return /*#__PURE__*/React.createElement("span", {
        className: "".concat(cellPrefix, "-inner")
      }, renderer({
        text: treeGroups,
        record: record,
        dataSet: dataSet,
        aggregation: tableAggregation,
        headerGroup: columnGroup.headerGroup,
        rowGroup: rowGroup,
        aggregationTree: aggregationList
      }));
    }

    return getInnerNode(column, onCellStyle, undefined, columnGroup.headerGroup);
  };

  var scope = groupCell ? 'row' : undefined;
  var TCell = scope ? 'th' : 'td';

  if (!isRenderCell) {
    var hasEditor = aggregation ? treeSome(column.children || [], function (node) {
      return !!getEditorByColumnAndRecord(node, record);
    }) : !!getEditorByColumnAndRecord(column, record);

    var emptyCellProps = _objectSpread(_objectSpread({
      colSpan: colSpan,
      rowSpan: rowSpan,
      'data-index': key
    }, cellExternalProps), {}, {
      className: classNames(baseClassName, cellExternalProps.className),
      scope: scope,
      onClickCapture: handleClickCapture
    });

    if (hasEditor) {
      emptyCellProps.onFocus = function (e) {
        tableStore.activeEmptyCell = e.target;
      };

      emptyCellProps.onBlur = function () {
        delete tableStore.activeEmptyCell;
      };

      emptyCellProps.tabIndex = 0;
    }

    return /*#__PURE__*/React.createElement(TCell, _extends({}, emptyCellProps, intersectionProps, {
      style: _objectSpread(_objectSpread(_objectSpread({}, baseStyle), cellExternalProps.style), intersectionProps.style)
    }));
  }

  var cellStyle = _objectSpread(_objectSpread(_objectSpread({}, baseStyle), cellExternalProps.style), provided && {
    cursor: dragDisabled ? 'not-allowed' : 'move'
  });

  var classString = classNames(baseClassName, (_classNames3 = {}, _defineProperty(_classNames3, "".concat(cellPrefix, "-aggregation"), aggregation), _defineProperty(_classNames3, "".concat(cellPrefix, "-last-group"), groupCell && isLast), _classNames3), column.className, className, cellExternalProps.className);

  var widthDraggingStyle = function widthDraggingStyle() {
    var draggingStyle = {};

    if (isDragging) {
      var dom = tableStore.node.element.querySelector(".".concat(prefixCls, "-tbody .").concat(prefixCls, "-cell[data-index=\"").concat(key, "\"]"));

      if (dom) {
        draggingStyle.width = dom.clientWidth;
        draggingStyle.whiteSpace = 'nowrap';
      }
    }

    return draggingStyle;
  }; // 只有全局属性时候的样式可以继承给下级满足对td的样式能够一致表现


  var onCellStyle = !isBuiltInColumn && tableColumnOnCell === columnOnCell && typeof tableColumnOnCell === 'function' ? omit(cellExternalProps.style, ['width', 'height']) : undefined;
  return /*#__PURE__*/React.createElement(TCell, _extends({
    colSpan: colSpan,
    rowSpan: rowSpan
  }, cellExternalProps, {
    className: classString,
    "data-index": key
  }, provided && provided.dragHandleProps, intersectionProps, {
    style: _objectSpread(_objectSpread(_objectSpread({}, omit(cellStyle, ['width', 'height'])), widthDraggingStyle()), intersectionProps.style),
    scope: scope,
    onClickCapture: handleClickCapture
  }), renderInnerNode(aggregation, onCellStyle));
};

TableCell.displayName = 'TableCell';
export default observer(TableCell);
//# sourceMappingURL=TableCell.js.map
