import _extends from "@babel/runtime/helpers/extends";
import _objectSpread from "@babel/runtime/helpers/objectSpread2";
import _defineProperty from "@babel/runtime/helpers/defineProperty";
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import React, { cloneElement, isValidElement } from 'react';
import isObject from 'lodash/isObject';
import isNil from 'lodash/isNil';
import isString from 'lodash/isString';
import isNumber from 'lodash/isNumber';
import defaultTo from 'lodash/defaultTo';
import isPlainObject from 'lodash/isPlainObject';
import noop from 'lodash/noop';
import { get, isArrayLike, isObservableObject } from 'mobx';
import classNames from 'classnames';
import { isMoment } from 'moment';
import { math, Utils } from 'choerodon-ui/dataset';
import { getConfig as getConfigDefault, getProPrefixCls as getProPrefixClsDefault } from '../../../es/configure/utils';
import { FieldType, RecordStatus } from '../data-set/enum';
import { stopEvent } from '../_util/EventManager';
import formatCurrency from '../formatter/formatCurrency';
import formatNumber from '../formatter/formatNumber';
import isEmpty from '../_util/isEmpty';
import CloseButton from './CloseButton';
import { hide, show } from '../tooltip/singleton';
import Icon from '../icon';
import { $l } from '../locale-context';
import isReactChildren from '../_util/isReactChildren';
import { defaultTextField, findBindFields } from '../data-set/utils';
import ObjectChainValue from '../_util/ObjectChainValue';
import MultiLine from '../output/MultiLine';
var toRangeValue = Utils.toRangeValue;
var getDateFormatByFieldType = Utils.getDateFormatByFieldType;
var getDateFormatByField = Utils.getDateFormatByField;
export { toRangeValue, getDateFormatByFieldType, getDateFormatByField };
export function fromRangeValue(value, range) {
  if (isArrayLike(range)) {
    var _ref;

    var _range = _slicedToArray(range, 2),
        start = _range[0],
        end = _range[1];

    return _ref = {}, _defineProperty(_ref, start, value[0]), _defineProperty(_ref, end, value[1]), _ref;
  }

  return value;
}
export function toMultipleValue(value, range) {
  if (!isNil(value)) {
    var multipleValue = isArrayLike(value) ? value.slice() : [value];

    if (range) {
      return multipleValue.map(function (item) {
        return toRangeValue(item, range);
      });
    }

    return multipleValue;
  }

  return [];
}
export function transformHighlightProps(highlight, props) {
  if ( /*#__PURE__*/isValidElement(highlight) || isString(highlight)) {
    return _objectSpread(_objectSpread({}, props), {}, {
      content: highlight
    });
  }

  if (isObject(highlight)) {
    return _objectSpread(_objectSpread({}, props), highlight);
  }

  return props;
}
export function getCurrencyFormatter() {
  var getConfig = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getConfigDefault;
  var currencyFormatter = getConfig('currencyFormatter');

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

  return formatCurrency;
}
export function getNumberFormatter() {
  var getConfig = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getConfigDefault;
  var numberFieldFormatter = getConfig('numberFieldFormatter');

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

  return formatNumber;
}
export function getCurrencyFormatOptions(getProp, getDisplayProp, controlLang) {
  var getConfig = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : getConfigDefault;
  var precision = getProp('precision');
  var formatterOptions = getDisplayProp('formatterOptions') || {};
  var currencyFormatterOptions = getConfig('currencyFormatterOptions') || {
    options: {}
  };
  var lang = formatterOptions.lang || currencyFormatterOptions.lang || controlLang;
  var options = {};

  if (isNumber(precision)) {
    options.minimumFractionDigits = precision;
    options.maximumFractionDigits = precision;
  }

  _extends(options, currencyFormatterOptions.options, formatterOptions.options);

  var numberGrouping = getDisplayProp('numberGrouping');
  var currency = getProp('currency');

  if (currency) {
    options.currency = currency;
  }

  if (numberGrouping === false) {
    options.useGrouping = false;
  }

  return {
    lang: lang,
    options: options
  };
}
export function getNumberFormatOptions(getProp, getDisplayProp, getValue, value, controlLang) {
  var getConfig = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : getConfigDefault;
  var precision = getProp('precision');
  var useZeroFilledDecimal = precision > 0 && getConfig('useZeroFilledDecimal');
  var v = isNil(value) ? getValue && getValue() : value;
  var precisionInValue = isNumber(precision) ? precision : math.dp(v || 0);
  var formatterOptions = getDisplayProp('formatterOptions') || {};
  var numberFieldFormatterOptions = getConfig('numberFieldFormatterOptions') || {
    options: {}
  };
  var lang = formatterOptions.lang || numberFieldFormatterOptions.lang || controlLang;

  var options = _objectSpread(_objectSpread({
    maximumFractionDigits: precisionInValue,
    minimumFractionDigits: useZeroFilledDecimal ? precisionInValue : undefined
  }, numberFieldFormatterOptions.options), formatterOptions.options);

  var numberGrouping = getDisplayProp('numberGrouping');

  if (!isNil(numberGrouping)) {
    options.useGrouping = numberGrouping;
  }

  return {
    lang: lang,
    options: options
  };
}
export function processFieldValue(value, field, options, showValueIfNotFound, record) {
  var getConfig = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : getConfigDefault;
  var getProp = options.getProp,
      getValue = options.getValue,
      lang = options.lang,
      _options$getDisplayPr = options.getDisplayProp,
      getDisplayProp = _options$getDisplayPr === void 0 ? getProp : _options$getDisplayPr;
  var type = getProp('type');
  var currency = getProp('currency');

  if (currency || type === FieldType.currency) {
    var formatOptions = getCurrencyFormatOptions(getProp, getDisplayProp, lang, getConfig);
    var formatter = getProp('formatter');
    return (formatter || getCurrencyFormatter(getConfig))(value, formatOptions.lang, formatOptions.options);
  }

  if (type === FieldType.number || type === FieldType.bigNumber) {
    var _formatOptions = getNumberFormatOptions(getProp, getDisplayProp, getValue, value, lang, getConfig);

    var _formatter = getProp('formatter');

    return (_formatter || getNumberFormatter(getConfig))(value, _formatOptions.lang, _formatOptions.options);
  }

  if (field) {
    return field.getText(value, showValueIfNotFound, record);
  }

  return value;
}
export function processValue(value) {
  var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

  if (!isNil(value)) {
    if (isMoment(value)) {
      if (value.isValid()) {
        return value.format(options.dateFormat);
      }

      if (options.showInvalidDate) {
        return $l('DatePicker', 'invalid_date');
      }

      return '';
    }

    if (isReactChildren(value)) {
      // For Select's Option and TreeSelect's TreeNode which type may be ReactElement
      return value;
    }

    if (options.isNumber && math.isValidNumber(value)) {
      return options.precision && options.useZeroFilledDecimal ? math.toFixed(value, options.precision) : math.toString(value);
    }

    return value.toString();
  }

  return '';
}
export function isFieldValueEmpty(value, range, multiple, valueField, textField) {
  if (isEmpty(value)) {
    return true;
  }

  if (multiple) {
    return !isArrayLike(value) || value.length === 0;
  }

  if (range === true) {
    return isArrayLike(value) && value.every(function (v) {
      return isEmpty(v);
    });
  }

  if (isArrayLike(range)) {
    return value && Object.values(value).every(function (v) {
      return isEmpty(v);
    });
  }

  var isObjectEmpty = function isObjectEmpty(v) {
    if (valueField && textField) {
      if (isObservableObject(v)) {
        return isEmpty(get(v, valueField)) && isEmpty(get(v, textField));
      }

      if (isObject(v)) {
        return isEmpty(v[valueField]) && isEmpty(v[textField]);
      }
    }

    return false;
  };

  if (isArrayLike(value)) {
    return value.length ? value.every(function (v) {
      if (isEmpty(v)) {
        return true;
      }

      return isObjectEmpty(v);
    }) : true;
  }

  return isObjectEmpty(value);
}
export function renderRangeValue(value, option) {
  var repeat = option.repeat,
      processRenderer = option.processRenderer;
  var rangeValue = (value || []).map(function (item) {
    return processRenderer(item, repeat);
  }, []);

  if (rangeValue.some(function (v) {
    return !isEmpty(v);
  })) {
    return /*#__PURE__*/React.createElement(React.Fragment, null, rangeValue[0], "~", rangeValue[1]);
  }
}
export function getValueKey(v) {
  if (isArrayLike(v)) {
    return v.join(',');
  }

  return v;
}
export function renderMultipleValues(value, option) {
  var range = option.range,
      maxTagPlaceholder = option.maxTagPlaceholder,
      prefixCls = option.prefixCls,
      validationResults = option.validationResults,
      disabled = option.disabled,
      readOnly = option.readOnly,
      tagRenderer = option.tagRenderer,
      isMultipleBlockDisabled = option.isMultipleBlockDisabled,
      processRenderer = option.processRenderer,
      renderValidationResult = option.renderValidationResult,
      _option$handleMultipl = option.handleMultipleValueRemove,
      handleMultipleValueRemove = _option$handleMultipl === void 0 ? noop : _option$handleMultipl,
      _option$getKey = option.getKey,
      getKey = _option$getKey === void 0 ? getValueKey : _option$getKey,
      isValidationMessageHidden = option.isValidationMessageHidden,
      selfShowValidationMessage = option.showValidationMessage,
      tooltipTheme = option.tooltipTheme;
  var values = toMultipleValue(value, range);
  var valueLength = values.length;
  var _option$maxTagCount = option.maxTagCount,
      maxTagCount = _option$maxTagCount === void 0 ? getConfigDefault('fieldMaxTagCount') : _option$maxTagCount;
  var repeats = new Map();
  var multipleValidateMessageLength = 0;
  var tags = values.slice(0, maxTagCount).map(function (v, index) {
    var key = getKey(v);
    var repeat = repeats.get(key) || 0;
    var text = range ? renderRangeValue(v, {
      repeat: repeat,
      processRenderer: processRenderer
    }) : processRenderer(v, repeat);
    repeats.set(key, repeat + 1);

    if (!isEmpty(text)) {
      var _classNames;

      var validationResult = validationResults && validationResults.find(function (error) {
        return error.value === v;
      });
      var blockDisabled = isMultipleBlockDisabled ? isMultipleBlockDisabled(v) : disabled;
      var className = classNames((_classNames = {}, _defineProperty(_classNames, "".concat(prefixCls, "-multiple-block-invalid"), validationResult), _defineProperty(_classNames, "".concat(prefixCls, "-multiple-block-disabled"), blockDisabled), _classNames), "".concat(prefixCls, "-multiple-block"));
      var validationMessage = validationResult && renderValidationResult(validationResult);

      if (validationMessage) {
        multipleValidateMessageLength++;
      }

      var closeBtn = !blockDisabled && !readOnly && /*#__PURE__*/React.createElement(CloseButton, {
        onClose: handleMultipleValueRemove,
        value: v,
        index: repeat
      });
      var inner;

      if (typeof tagRenderer === 'function') {
        var onClose = function onClose(e) {
          stopEvent(e);
          handleMultipleValueRemove(e, v, repeat);
        };

        inner = tagRenderer({
          value: v,
          text: text,
          key: String(index),
          invalid: !!validationResult,
          disabled: blockDisabled,
          readOnly: readOnly,
          className: className,
          onClose: onClose
        });
      } else {
        inner = readOnly ? /*#__PURE__*/React.createElement("span", {
          key: String(index),
          className: className
        }, text) : /*#__PURE__*/React.createElement("li", {
          key: String(index),
          className: className
        }, /*#__PURE__*/React.createElement("div", null, text), closeBtn);
      }

      if (!isValidationMessageHidden(validationMessage)) {
        return /*#__PURE__*/cloneElement(inner, {
          onMouseEnter: function onMouseEnter(e) {
            return selfShowValidationMessage(e, validationMessage, tooltipTheme);
          },
          onMouseLeave: function onMouseLeave() {
            return hide();
          }
        });
      }

      return inner;
    }

    return undefined;
  });
  var isOverflowMaxTagCount = !!maxTagCount && valueLength > maxTagCount;

  if (maxTagCount && isOverflowMaxTagCount) {
    var blockClassName = classNames(_defineProperty({}, "".concat(prefixCls, "-multiple-block-disabled"), disabled), "".concat(prefixCls, "-multiple-block"), "".concat(prefixCls, "-multiple-block-more"));
    var content = "+ ".concat(valueLength - maxTagCount, " ...");

    if (maxTagPlaceholder) {
      var omittedValues = values.slice(maxTagCount, valueLength);
      content = typeof maxTagPlaceholder === 'function' ? maxTagPlaceholder(omittedValues) : maxTagPlaceholder;
    }

    var moreBlock;

    if (typeof tagRenderer === 'function') {
      moreBlock = tagRenderer({
        value: "maxTagPlaceholder",
        text: content,
        key: "maxTagPlaceholder",
        disabled: disabled,
        readOnly: readOnly,
        className: blockClassName
      });
    } else {
      moreBlock = /*#__PURE__*/React.createElement("li", {
        key: "maxTagPlaceholder",
        className: blockClassName
      }, /*#__PURE__*/React.createElement("div", null, content));
    }

    tags.push(moreBlock);
  }

  return {
    tags: tags,
    multipleValidateMessageLength: multipleValidateMessageLength,
    isOverflowMaxTagCount: isOverflowMaxTagCount
  };
}
export function renderMultiLine(options) {
  var field = options.field,
      record = options.record,
      dataSet = options.dataSet,
      name = options.name,
      prefixCls = options.prefixCls,
      renderer = options.renderer,
      renderValidationResult = options.renderValidationResult,
      isValidationMessageHidden = options.isValidationMessageHidden,
      selfProcessValue = options.processValue,
      labelTooltip = options.labelTooltip,
      tooltip = options.tooltip;
  var multipleValidateMessageLength = 0;

  if (record) {
    var multiLineFields = findBindFields(field, record.dataSet.fields, false, record);

    if (renderer) {
      return {
        lines: renderer({
          multiLineFields: multiLineFields,
          record: record,
          dataSet: dataSet,
          name: name
        }),
        multipleValidateMessageLength: multipleValidateMessageLength
      };
    }

    if (multiLineFields.length) {
      var lines = multiLineFields.map(function (fieldItem) {
        if (fieldItem) {
          var required = defaultTo(fieldItem.get('required', record), field.get('required', record));
          var fieldName = fieldItem.name;
          var value = record.get(fieldName);
          var validationResults = record.getValidationError(fieldName);
          var validationResult = validationResults && validationResults.find(function (error) {
            return error.value === value;
          });
          var validationMessage = validationResult && renderValidationResult(validationResult);
          var validationHidden = isValidationMessageHidden(validationMessage);
          var processedValue = '';

          if (fieldItem.get('lovCode', record)) {
            var fieldValue = fieldItem.getValue(record);

            if (isPlainObject(fieldValue)) {
              processedValue = ObjectChainValue.get(fieldValue, fieldItem.get('textField', record) || defaultTextField);
            }
          }

          var notEmpty = !isEmpty(value); // 值集中不存在 再去取直接返回的值

          var text = processedValue || selfProcessValue(value);
          multipleValidateMessageLength++;
          var validationInner = notEmpty ? text : validationHidden ? record.status === RecordStatus.add ? '' : /*#__PURE__*/React.createElement("span", {
            className: "".concat(prefixCls, "-multi-value-invalid")
          }, text) : validationMessage;
          var label = fieldItem.get('label', record);
          return /*#__PURE__*/React.createElement(MultiLine, {
            key: "".concat(record.index, "-multi-").concat(fieldName),
            prefixCls: prefixCls,
            label: label,
            required: required,
            validationMessage: validationMessage,
            validationHidden: validationHidden,
            tooltip: tooltip,
            labelTooltip: labelTooltip
          }, validationInner);
        }

        return null;
      });
      return {
        lines: lines,
        multipleValidateMessageLength: multipleValidateMessageLength
      };
    }
  }

  return {
    multipleValidateMessageLength: multipleValidateMessageLength
  };
}
export function renderValidationMessage(validationMessage, showIcon) {
  var getProPrefixCls = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : getProPrefixClsDefault;

  if (validationMessage) {
    return /*#__PURE__*/React.createElement("div", {
      className: getProPrefixCls('validation-message')
    }, showIcon && /*#__PURE__*/React.createElement(Icon, {
      type: "error"
    }), /*#__PURE__*/React.createElement("span", null, validationMessage));
  }
}
export function defaultRenderer(renderOption) {
  var text = renderOption.text,
      repeat = renderOption.repeat,
      maxTagTextLength = renderOption.maxTagTextLength;
  return repeat !== undefined && maxTagTextLength && isString(text) && text.length > maxTagTextLength ? "".concat(text.slice(0, maxTagTextLength), "...") : text;
}
export function showValidationMessage(e, message, tooltipTheme, tooltipPlacement) {
  var getConfig = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : getConfigDefault;
  show(e.currentTarget, {
    suffixCls: "form-tooltip ".concat(getConfig('proPrefixCls'), "-tooltip"),
    title: message,
    theme: tooltipTheme,
    placement: tooltipPlacement || 'bottomLeft'
  });
}
//# sourceMappingURL=utils.js.map
