import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import _typeof from "@babel/runtime/helpers/typeof";
import _extends from "@babel/runtime/helpers/extends";
import React, { isValidElement } from 'react';
import isString from 'lodash/isString';
import warning from '../../../es/_util/warning';
import { toPx } from '../../../es/_util/UnitConvertor';
import isStickySupport from '../../../es/_util/isStickySupport';
import ObserverCheckBox from '../check-box/CheckBox';
import { FieldType, RecordCachedType, RecordStatus } from '../data-set/enum';
import ObserverSelect from '../select/Select';
import TreeSelect from '../tree-select/TreeSelect';
import Option from '../option/Option';
import Lov from '../lov/Lov';
import ObserverNumberField from '../number-field/NumberField';
import Currency from '../currency/Currency';
import DatePicker from '../date-picker/DatePicker';
import DateTimePicker from '../date-time-picker/DateTimePicker';
import TimePicker from '../time-picker/TimePicker';
import WeekPicker from '../week-picker/WeekPicker';
import MonthPicker from '../month-picker/MonthPicker';
import YearPicker from '../year-picker/YearPicker';
import ObserverTextField from '../text-field/TextField';
import { ColumnLock, TablePaginationPosition } from './enum';
import IntlField from '../intl-field/IntlField';
import UrlField from '../url-field/UrlField';
import EmailField from '../email-field/EmailField';
import ColorPicker from '../color-picker/ColorPicker';
import Output from '../output/Output';
import Attachment from '../attachment/Attachment';
import SecretField from '../secret-field/SecretField';
import { CUSTOMIZED_KEY } from './TableStore';
import { $l } from '../locale-context';
import measureTextWidth from '../_util/measureTextWidth';
import { FuncType } from '../button/enum';
export { isStickySupport };
export 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) || isString(field.get('lookupUrl', record)) || type !== FieldType.object && (field.get('lovCode', record) || field.getLookup(record) || field.get('options', record))) {
    if (field.get('parentField', record)) {
      return /*#__PURE__*/React.createElement(TreeSelect, _extends({}, flatProps));
    }

    return /*#__PURE__*/React.createElement(ObserverSelect, _extends({}, flatProps));
  }

  if (field.get('lovCode', record)) {
    return /*#__PURE__*/React.createElement(Lov, _extends({}, flatProps));
  }

  if (field.get('multiLine', record)) {
    return /*#__PURE__*/React.createElement(Output, null);
  }

  if (type === FieldType.bigNumber) {
    if (field.get('currency', record)) {
      return /*#__PURE__*/React.createElement(Currency, {
        isFlat: isFlat
      });
    }

    return /*#__PURE__*/React.createElement(ObserverNumberField, _extends({}, flatProps));
  }

  switch (type) {
    case FieldType["boolean"]:
      return isQueryField ? /*#__PURE__*/React.createElement(ObserverSelect, _extends({
        clearButton: true
      }, flatProps), /*#__PURE__*/React.createElement(Option, {
        value: field.get('trueValue', record)
      }, $l('Table', 'query_option_yes')), /*#__PURE__*/React.createElement(Option, {
        value: field.get('falseValue', record)
      }, $l('Table', 'query_option_no'))) : /*#__PURE__*/React.createElement(ObserverCheckBox, null);

    case FieldType.number:
      return /*#__PURE__*/React.createElement(ObserverNumberField, _extends({}, flatProps));

    case FieldType.currency:
      return /*#__PURE__*/React.createElement(Currency, {
        isFlat: isFlat
      });

    case FieldType.date:
      return /*#__PURE__*/React.createElement(DatePicker, {
        isFlat: isFlat
      });

    case FieldType.dateTime:
      return /*#__PURE__*/React.createElement(DateTimePicker, {
        isFlat: isFlat
      });

    case FieldType.time:
      return /*#__PURE__*/React.createElement(TimePicker, {
        isFlat: isFlat
      });

    case FieldType.week:
      return /*#__PURE__*/React.createElement(WeekPicker, {
        isFlat: isFlat
      });

    case FieldType.month:
      return /*#__PURE__*/React.createElement(MonthPicker, {
        isFlat: isFlat
      });

    case FieldType.year:
      return /*#__PURE__*/React.createElement(YearPicker, {
        isFlat: isFlat
      });

    case FieldType.intl:
      return /*#__PURE__*/React.createElement(IntlField, {
        isFlat: isFlat
      });

    case FieldType.email:
      return /*#__PURE__*/React.createElement(EmailField, {
        isFlat: isFlat
      });

    case FieldType.url:
      return /*#__PURE__*/React.createElement(UrlField, {
        isFlat: isFlat
      });

    case FieldType.color:
      return /*#__PURE__*/React.createElement(ColorPicker, {
        isFlat: isFlat
      });

    case FieldType.attachment:
      return /*#__PURE__*/React.createElement(Attachment, {
        viewMode: "popup",
        funcType: FuncType.link
      });

    case FieldType.secret:
      return /*#__PURE__*/React.createElement(SecretField, {
        isFlat: isFlat
      });

    case FieldType.string:
      return /*#__PURE__*/React.createElement(ObserverTextField, {
        isFlat: isFlat
      });

    default:
      warning(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.createElement(ObserverTextField, {
        isFlat: isFlat
      });
  }
}
export function getPlaceholderByField(field, record) {
  if (field) {
    var type = field.get('type', record);

    if (field.get('lookupCode', record) || isString(field.get('lookupUrl', record)) || type !== FieldType.object && (field.get('lovCode', record) || field.getLookup(record) || field.get('options', record))) {
      return undefined;
    }

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

      default:
    }
  }
}
export 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 === RecordStatus.add) {
          return getEditorByField(field, record);
        }
      } else {
        return /*#__PURE__*/React.createElement(ObserverTextField, null);
      }
    }

    if ( /*#__PURE__*/isValidElement(cellEditor)) {
      return cellEditor;
    }
  }

  if ( /*#__PURE__*/isValidElement(editor)) {
    return editor;
  }
}
export function isInCellEditor(element) {
  if (element) {
    return !!element.type.__IS_IN_CELL_EDITOR;
  }

  return false;
}
export function findRow(tableStore, record) {
  var node = tableStore.node;
  var selector = "tr[data-index=\"".concat(record.id, "\"]");
  return node.element.querySelector(selector);
}
export 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 = !isStickySupport() && overflowX && lock ? ".".concat(prefixCls, "-fixed-").concat(lock === true ? 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;
  }
}
export 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;
}
export function findIndexedSibling(element, direction) {
  var sibling = direction > 0 ? element.nextElementSibling : element.previousElementSibling;

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

  return findIndexedSibling(sibling, direction);
}
export function isDisabledRow(record) {
  return record.status === RecordStatus["delete"] || record.disabled;
}
export function isSelectedRow(record) {
  return record.isSelected;
}

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

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

export 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);
}
export function getColumnKey(_ref) {
  var name = _ref.name,
      key = _ref.key;
  return key || name;
}
export function getColumnLock(lock) {
  if (lock === true) {
    return ColumnLock.left;
  }

  if (lock) {
    return lock;
  }

  return false;
}
export function getPaginationPosition(pagination) {
  if (pagination) {
    var position = pagination.position;

    if (position) {
      return position;
    }
  }

  return TablePaginationPosition.bottom;
}
export function getHeight(el) {
  return Math.round(el.getBoundingClientRect().height);
}
export 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;
}
export function isDropresult(dropResult) {
  if (dropResult && dropResult.destination) {
    return typeof dropResult.source.index === 'number' && _typeof(dropResult.destination) === 'object' && typeof dropResult.destination.index === 'number';
  }

  return false;
}
export function isDraggingStyle(style) {
  return style ? 'left' in style : false;
}
export 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 = measureTextWidth(textContent, computedStyle) + pl + pr;

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

  return clientWidth;
}
export function onlyCustomizedColumn(tableStore) {
  var rightLeafs = tableStore.columnGroups.rightLeafs;
  return rightLeafs.length === 0 || rightLeafs[0].key === CUSTOMIZED_KEY;
}
export 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 (toPx(style.paddingTop) || 0) + (toPx(style.paddingBottom) || 0) + (toPx(style.borderTopWidth) || 0) + (toPx(style.borderBottomWidth) || 0);
      }
    }
  }
}
export function getCachedRecords(dataSet, type, showCachedTips) {
  if (showCachedTips) {
    switch (type) {
      case RecordCachedType.selected:
        return dataSet.cachedSelected;

      case RecordCachedType.add:
        return dataSet.cachedCreated;

      case RecordCachedType.update:
        return dataSet.cachedUpdated;

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

      default:
        return [];
    }
  }

  return dataSet.cachedRecords;
}

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

export function getCachedSelectableRecords(dataSet, type, showCachedTips, filter) {
  return getCachedRecords(dataSet, type, showCachedTips).filter(function (r) {
    return isRecordSelectable(r, filter);
  });
}
export function getCurrentSelectableCounts(dataSet, filter) {
  return dataSet.records.reduce(function (_ref2, r) {
    var _ref3 = _slicedToArray(_ref2, 2),
        selectedLength = _ref3[0],
        recordLength = _ref3[1];

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

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

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

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

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

    return [selectedLength, recordLength];
  }, [0, 0]);
}
export function getCount(dataSet, type) {
  switch (type) {
    case RecordCachedType.selected:
      return dataSet.isAllPageSelection ? dataSet.totalCount - dataSet.unSelected.length : dataSet.selected.length;

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

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

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

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