"use strict";

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard")["default"];

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault")["default"];

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.findCell = findCell;
exports.findIndexedSibling = findIndexedSibling;
exports.findRow = findRow;
exports.getCachedRecords = getCachedRecords;
exports.getCachedSelectableCounts = getCachedSelectableCounts;
exports.getCachedSelectableRecords = getCachedSelectableRecords;
exports.getCellVerticalSize = getCellVerticalSize;
exports.getColumnKey = getColumnKey;
exports.getColumnLock = getColumnLock;
exports.getCount = getCount;
exports.getCurrentSelectableCounts = getCurrentSelectableCounts;
exports.getEditorByColumnAndRecord = getEditorByColumnAndRecord;
exports.getEditorByField = getEditorByField;
exports.getHeader = getHeader;
exports.getHeight = getHeight;
exports.getMaxClientWidth = getMaxClientWidth;
exports.getPaginationPosition = getPaginationPosition;
exports.getPlaceholderByField = getPlaceholderByField;
exports.getTableHeaderRows = getTableHeaderRows;
exports.isCanEdictingRow = isCanEdictingRow;
exports.isDisabledRow = isDisabledRow;
exports.isDraggingStyle = isDraggingStyle;
exports.isDropresult = isDropresult;
exports.isInCellEditor = isInCellEditor;
exports.isSelectedRow = isSelectedRow;
Object.defineProperty(exports, "isStickySupport", {
  enumerable: true,
  get: function get() {
    return _isStickySupport["default"];
  }
});
exports.onlyCustomizedColumn = onlyCustomizedColumn;

var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));

var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof"));

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

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

var _isString = _interopRequireDefault(require("lodash/isString"));

var _warning = _interopRequireDefault(require("../../../lib/_util/warning"));

var _UnitConvertor = require("../../../lib/_util/UnitConvertor");

var _isStickySupport = _interopRequireDefault(require("../../../lib/_util/isStickySupport"));

var _CheckBox = _interopRequireDefault(require("../check-box/CheckBox"));

var _enum = require("../data-set/enum");

var _Select = _interopRequireDefault(require("../select/Select"));

var _TreeSelect = _interopRequireDefault(require("../tree-select/TreeSelect"));

var _Option = _interopRequireDefault(require("../option/Option"));

var _Lov = _interopRequireDefault(require("../lov/Lov"));

var _NumberField = _interopRequireDefault(require("../number-field/NumberField"));

var _Currency = _interopRequireDefault(require("../currency/Currency"));

var _DatePicker = _interopRequireDefault(require("../date-picker/DatePicker"));

var _DateTimePicker = _interopRequireDefault(require("../date-time-picker/DateTimePicker"));

var _TimePicker = _interopRequireDefault(require("../time-picker/TimePicker"));

var _WeekPicker = _interopRequireDefault(require("../week-picker/WeekPicker"));

var _MonthPicker = _interopRequireDefault(require("../month-picker/MonthPicker"));

var _YearPicker = _interopRequireDefault(require("../year-picker/YearPicker"));

var _TextField = _interopRequireDefault(require("../text-field/TextField"));

var _enum2 = require("./enum");

var _IntlField = _interopRequireDefault(require("../intl-field/IntlField"));

var _UrlField = _interopRequireDefault(require("../url-field/UrlField"));

var _EmailField = _interopRequireDefault(require("../email-field/EmailField"));

var _ColorPicker = _interopRequireDefault(require("../color-picker/ColorPicker"));

var _Output = _interopRequireDefault(require("../output/Output"));

var _Attachment = _interopRequireDefault(require("../attachment/Attachment"));

var _SecretField = _interopRequireDefault(require("../secret-field/SecretField"));

var _TableStore = require("./TableStore");

var _localeContext = require("../locale-context");

var _measureTextWidth = _interopRequireDefault(require("../_util/measureTextWidth"));

var _enum3 = require("../button/enum");

function getEditorByField(field, record, isQueryField, isFlat) {
  var type = field.get('type', record);
  var name = field.name;
  var flatProps = isFlat ? {
    isFlat: isFlat,
    maxTagCount: 3
  } : {};

  if (field.get('lookupCode', record) || (0, _isString["default"])(field.get('lookupUrl', record)) || type !== _enum.FieldType.object && (field.get('lovCode', record) || field.getLookup(record) || field.get('options', record))) {
    if (field.get('parentField', record)) {
      return /*#__PURE__*/_react["default"].createElement(_TreeSelect["default"], (0, _extends2["default"])({}, flatProps));
    }

    return /*#__PURE__*/_react["default"].createElement(_Select["default"], (0, _extends2["default"])({}, flatProps));
  }

  if (field.get('lovCode', record)) {
    return /*#__PURE__*/_react["default"].createElement(_Lov["default"], (0, _extends2["default"])({}, flatProps));
  }

  if (field.get('multiLine', record)) {
    return /*#__PURE__*/_react["default"].createElement(_Output["default"], null);
  }

  if (type === _enum.FieldType.bigNumber) {
    if (field.get('currency', record)) {
      return /*#__PURE__*/_react["default"].createElement(_Currency["default"], {
        isFlat: isFlat
      });
    }

    return /*#__PURE__*/_react["default"].createElement(_NumberField["default"], (0, _extends2["default"])({}, flatProps));
  }

  switch (type) {
    case _enum.FieldType["boolean"]:
      return isQueryField ? /*#__PURE__*/_react["default"].createElement(_Select["default"], (0, _extends2["default"])({
        clearButton: true
      }, flatProps), /*#__PURE__*/_react["default"].createElement(_Option["default"], {
        value: field.get('trueValue', record)
      }, (0, _localeContext.$l)('Table', 'query_option_yes')), /*#__PURE__*/_react["default"].createElement(_Option["default"], {
        value: field.get('falseValue', record)
      }, (0, _localeContext.$l)('Table', 'query_option_no'))) : /*#__PURE__*/_react["default"].createElement(_CheckBox["default"], null);

    case _enum.FieldType.number:
      return /*#__PURE__*/_react["default"].createElement(_NumberField["default"], (0, _extends2["default"])({}, flatProps));

    case _enum.FieldType.currency:
      return /*#__PURE__*/_react["default"].createElement(_Currency["default"], {
        isFlat: isFlat
      });

    case _enum.FieldType.date:
      return /*#__PURE__*/_react["default"].createElement(_DatePicker["default"], {
        isFlat: isFlat
      });

    case _enum.FieldType.dateTime:
      return /*#__PURE__*/_react["default"].createElement(_DateTimePicker["default"], {
        isFlat: isFlat
      });

    case _enum.FieldType.time:
      return /*#__PURE__*/_react["default"].createElement(_TimePicker["default"], {
        isFlat: isFlat
      });

    case _enum.FieldType.week:
      return /*#__PURE__*/_react["default"].createElement(_WeekPicker["default"], {
        isFlat: isFlat
      });

    case _enum.FieldType.month:
      return /*#__PURE__*/_react["default"].createElement(_MonthPicker["default"], {
        isFlat: isFlat
      });

    case _enum.FieldType.year:
      return /*#__PURE__*/_react["default"].createElement(_YearPicker["default"], {
        isFlat: isFlat
      });

    case _enum.FieldType.intl:
      return /*#__PURE__*/_react["default"].createElement(_IntlField["default"], {
        isFlat: isFlat
      });

    case _enum.FieldType.email:
      return /*#__PURE__*/_react["default"].createElement(_EmailField["default"], {
        isFlat: isFlat
      });

    case _enum.FieldType.url:
      return /*#__PURE__*/_react["default"].createElement(_UrlField["default"], {
        isFlat: isFlat
      });

    case _enum.FieldType.color:
      return /*#__PURE__*/_react["default"].createElement(_ColorPicker["default"], {
        isFlat: isFlat
      });

    case _enum.FieldType.attachment:
      return /*#__PURE__*/_react["default"].createElement(_Attachment["default"], {
        viewMode: "popup",
        funcType: _enum3.FuncType.link
      });

    case _enum.FieldType.secret:
      return /*#__PURE__*/_react["default"].createElement(_SecretField["default"], {
        isFlat: isFlat
      });

    case _enum.FieldType.string:
      return /*#__PURE__*/_react["default"].createElement(_TextField["default"], {
        isFlat: isFlat
      });

    default:
      (0, _warning["default"])(false, "Table auto editor: No editor exists on the field<".concat(name, ">'s type<").concat(type, ">, so use the TextField as default editor"));
      return /*#__PURE__*/_react["default"].createElement(_TextField["default"], {
        isFlat: isFlat
      });
  }
}

function getPlaceholderByField(field, record) {
  if (field) {
    var type = field.get('type', record);

    if (field.get('lookupCode', record) || (0, _isString["default"])(field.get('lookupUrl', record)) || type !== _enum.FieldType.object && (field.get('lovCode', record) || field.getLookup(record) || field.get('options', record))) {
      return undefined;
    }

    switch (type) {
      case _enum.FieldType.number:
      case _enum.FieldType.bigNumber:
      case _enum.FieldType.currency:
      case _enum.FieldType.string:
      case _enum.FieldType.intl:
      case _enum.FieldType.email:
      case _enum.FieldType.url:
        return (0, _localeContext.$l)('Table', 'please_enter');

      default:
    }
  }
}

function getEditorByColumnAndRecord(column, record) {
  var name = column.name,
      editor = column.editor;

  if (record) {
    var cellEditor = editor;

    if (typeof editor === 'function') {
      cellEditor = editor(record, name);
    }

    if (cellEditor === true) {
      var field = record.dataSet.getField(name);

      if (field) {
        if (!field.get('unique', record) || field.get('multiple', record) || field.get('range', record) || record.status === _enum.RecordStatus.add) {
          return getEditorByField(field, record);
        }
      } else {
        return /*#__PURE__*/_react["default"].createElement(_TextField["default"], null);
      }
    }

    if ( /*#__PURE__*/(0, _react.isValidElement)(cellEditor)) {
      return cellEditor;
    }
  }

  if ( /*#__PURE__*/(0, _react.isValidElement)(editor)) {
    return editor;
  }
}

function isInCellEditor(element) {
  if (element) {
    return !!element.type.__IS_IN_CELL_EDITOR;
  }

  return false;
}

function findRow(tableStore, record) {
  var node = tableStore.node;
  var selector = "tr[data-index=\"".concat(record.id, "\"]");
  return node.element.querySelector(selector);
}

function findCell(tableStore, name, lock, record, extra) {
  var node = tableStore.node,
      dataSet = tableStore.dataSet,
      overflowX = tableStore.overflowX,
      currentEditRecord = tableStore.currentEditRecord,
      prefixCls = tableStore.prefixCls;
  var current = record || currentEditRecord || dataSet.current;

  if (name !== undefined && current && node.element) {
    var wrapperSelector = !(0, _isStickySupport["default"])() && overflowX && lock ? ".".concat(prefixCls, "-fixed-").concat(lock === true ? _enum2.ColumnLock.left : lock, " ") : '';
    var selector = "".concat(wrapperSelector, "tr[data-index=\"").concat(current.id, "\"] td[data-index=\"").concat(name, "\"]");
    var td = node.element.querySelector(selector);

    if (td) {
      var cell = td.querySelector("span.".concat(prefixCls, "-cell-inner"));

      if (cell) {
        return cell;
      }

      if (!extra && tableStore.virtualCell && !td.childElementCount) {
        return td;
      }
    }

    return undefined;
  }
}

function isCanEdictingRow(element) {
  var sibling = element;

  if (!sibling || 'index' in sibling.dataset && !sibling.getAttributeNodeNS('', 'disabled') && (!document.defaultView || document.defaultView.getComputedStyle(sibling).display !== 'none')) {
    return true;
  }

  return false;
}

function findIndexedSibling(element, direction) {
  var sibling = direction > 0 ? element.nextElementSibling : element.previousElementSibling;

  if (isCanEdictingRow(element)) {
    return sibling;
  }

  return findIndexedSibling(sibling, direction);
}

function isDisabledRow(record) {
  return record.status === _enum.RecordStatus["delete"] || record.disabled;
}

function isSelectedRow(record) {
  return record.isSelected;
}

function getLabel(dataSet, name) {
  var field = dataSet.getField(name);

  if (field) {
    return field.get('label');
  }
}

function getHeader(column) {
  var header = column.header,
      name = column.name,
      title = column.title,
      dataSet = column.dataSet,
      aggregation = column.aggregation,
      group = column.group,
      groups = column.groups,
      aggregationTree = column.aggregationTree;

  if (typeof header === 'function') {
    var $title = title === undefined ? getLabel(dataSet, name) : title;
    var options = {
      dataSet: dataSet,
      name: name,
      title: $title,
      aggregation: aggregation,
      group: group,
      groups: groups,
      aggregationTree: aggregationTree
    };

    try {
      return header(options, name, $title, aggregation);
    } catch (e) {
      return header(dataSet, name, $title, aggregation);
    }
  }

  if (title !== undefined) {
    return title;
  }

  if (header !== undefined) {
    return header;
  }

  return getLabel(dataSet, name);
}

function getColumnKey(_ref) {
  var name = _ref.name,
      key = _ref.key;
  return key || name;
}

function getColumnLock(lock) {
  if (lock === true) {
    return _enum2.ColumnLock.left;
  }

  if (lock) {
    return lock;
  }

  return false;
}

function getPaginationPosition(pagination) {
  if (pagination) {
    var position = pagination.position;

    if (position) {
      return position;
    }
  }

  return _enum2.TablePaginationPosition.bottom;
}

function getHeight(el) {
  return Math.round(el.getBoundingClientRect().height);
}

function getTableHeaderRows(columns) {
  var currentRow = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  var rows = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
  rows[currentRow] = rows[currentRow] || [];
  columns.forEach(function (column) {
    var hidden = column.hidden,
        rowSpan = column.rowSpan,
        colSpan = column.colSpan,
        children = column.children;

    if (!hidden) {
      if (rowSpan && rows.length < rowSpan) {
        while (rows.length < rowSpan) {
          rows.push([]);
        }
      }

      if (children) {
        getTableHeaderRows(children.columns, currentRow + rowSpan, rows);
      }

      if (colSpan !== 0) {
        rows[currentRow].push(column);
      }
    }
  });
  return rows;
}

function isDropresult(dropResult) {
  if (dropResult && dropResult.destination) {
    return typeof dropResult.source.index === 'number' && (0, _typeof2["default"])(dropResult.destination) === 'object' && typeof dropResult.destination.index === 'number';
  }

  return false;
}

function isDraggingStyle(style) {
  return style ? 'left' in style : false;
}

function getMaxClientWidth(element) {
  var textContent = element.textContent,
      ownerDocument = element.ownerDocument,
      clientWidth = element.clientWidth;

  if (textContent && ownerDocument) {
    var scrollWidth = element.scrollWidth;

    if (scrollWidth > clientWidth) {
      return scrollWidth;
    }

    var defaultView = ownerDocument.defaultView;

    if (defaultView) {
      var computedStyle = defaultView.getComputedStyle(element);
      var paddingLeft = computedStyle.paddingLeft,
          paddingRight = computedStyle.paddingRight;
      var pl = paddingLeft ? parseFloat(paddingLeft) : 0;
      var pr = paddingRight ? parseFloat(paddingRight) : 0;

      if (pl || pr) {
        var textWidth = (0, _measureTextWidth["default"])(textContent, computedStyle) + pl + pr;

        if (textWidth > clientWidth) {
          return textWidth;
        }
      }
    }
  }

  return clientWidth;
}

function onlyCustomizedColumn(tableStore) {
  var rightLeafs = tableStore.columnGroups.rightLeafs;
  return rightLeafs.length === 0 || rightLeafs[0].key === _TableStore.CUSTOMIZED_KEY;
}

function getCellVerticalSize(element, prefixCls) {
  var ownerDocument = element.ownerDocument;

  if (ownerDocument) {
    var defaultView = ownerDocument.defaultView;

    if (defaultView) {
      var cell = element.querySelector(".".concat(prefixCls, "-cell"));

      if (cell) {
        var style = defaultView.getComputedStyle(cell);
        return ((0, _UnitConvertor.toPx)(style.paddingTop) || 0) + ((0, _UnitConvertor.toPx)(style.paddingBottom) || 0) + ((0, _UnitConvertor.toPx)(style.borderTopWidth) || 0) + ((0, _UnitConvertor.toPx)(style.borderBottomWidth) || 0);
      }
    }
  }
}

function getCachedRecords(dataSet, type, showCachedTips) {
  if (showCachedTips) {
    switch (type) {
      case _enum.RecordCachedType.selected:
        return dataSet.cachedSelected;

      case _enum.RecordCachedType.add:
        return dataSet.cachedCreated;

      case _enum.RecordCachedType.update:
        return dataSet.cachedUpdated;

      case _enum.RecordCachedType["delete"]:
        return dataSet.cachedDestroyed;

      default:
        return [];
    }
  }

  return dataSet.cachedRecords;
}

function isRecordSelectable(record, filter) {
  return record.selectable && (!filter || filter(record));
}

function getCachedSelectableRecords(dataSet, type, showCachedTips, filter) {
  return getCachedRecords(dataSet, type, showCachedTips).filter(function (r) {
    return isRecordSelectable(r, filter);
  });
}

function getCurrentSelectableCounts(dataSet, filter) {
  return dataSet.records.reduce(function (_ref2, r) {
    var _ref3 = (0, _slicedToArray2["default"])(_ref2, 2),
        selectedLength = _ref3[0],
        recordLength = _ref3[1];

    if (isRecordSelectable(r, filter)) {
      recordLength += 1;

      if (r.isSelected) {
        selectedLength += 1;
      }
    }

    return [selectedLength, recordLength];
  }, [0, 0]);
}

function getCachedSelectableCounts(dataSet, type, showCachedTips, filter) {
  var cachedRecords = getCachedRecords(dataSet, type, showCachedTips);
  return cachedRecords.reduce(function (_ref4, r) {
    var _ref5 = (0, _slicedToArray2["default"])(_ref4, 2),
        selectedLength = _ref5[0],
        recordLength = _ref5[1];

    if (isRecordSelectable(r, filter)) {
      recordLength += 1;

      if (r.isSelected) {
        selectedLength += 1;
      }
    }

    return [selectedLength, recordLength];
  }, [0, 0]);
}

function getCount(dataSet, type) {
  switch (type) {
    case _enum.RecordCachedType.selected:
      return dataSet.isAllPageSelection ? dataSet.totalCount - dataSet.unSelected.length : dataSet.selected.length;

    case _enum.RecordCachedType.add:
      return dataSet.created.length;

    case _enum.RecordCachedType.update:
      return dataSet.updated.length;

    case _enum.RecordCachedType["delete"]:
      return dataSet.destroyed.length;

    default:
      return 0;
  }
}
//# sourceMappingURL=utils.js.map
