"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.defaultRenderer = defaultRenderer;
exports.fromRangeValue = fromRangeValue;
exports.getCurrencyFormatOptions = getCurrencyFormatOptions;
exports.getCurrencyFormatter = getCurrencyFormatter;
exports.getDateFormatByFieldType = exports.getDateFormatByField = void 0;
exports.getNumberFormatOptions = getNumberFormatOptions;
exports.getNumberFormatter = getNumberFormatter;
exports.getValueKey = getValueKey;
exports.isFieldValueEmpty = isFieldValueEmpty;
exports.processFieldValue = processFieldValue;
exports.processValue = processValue;
exports.renderMultiLine = renderMultiLine;
exports.renderMultipleValues = renderMultipleValues;
exports.renderRangeValue = renderRangeValue;
exports.renderValidationMessage = renderValidationMessage;
exports.showValidationMessage = showValidationMessage;
exports.toMultipleValue = toMultipleValue;
exports.toRangeValue = void 0;
exports.transformHighlightProps = transformHighlightProps;

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

var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));

var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));

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

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

var _isObject = _interopRequireDefault(require("lodash/isObject"));

var _isNil = _interopRequireDefault(require("lodash/isNil"));

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

var _isNumber = _interopRequireDefault(require("lodash/isNumber"));

var _defaultTo = _interopRequireDefault(require("lodash/defaultTo"));

var _isPlainObject = _interopRequireDefault(require("lodash/isPlainObject"));

var _noop = _interopRequireDefault(require("lodash/noop"));

var _mobx = require("mobx");

var _classnames = _interopRequireDefault(require("classnames"));

var _moment = require("moment");

var _dataset = require("choerodon-ui/dataset");

var _utils = require("../../../lib/configure/utils");

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

var _EventManager = require("../_util/EventManager");

var _formatCurrency = _interopRequireDefault(require("../formatter/formatCurrency"));

var _formatNumber = _interopRequireDefault(require("../formatter/formatNumber"));

var _isEmpty = _interopRequireDefault(require("../_util/isEmpty"));

var _CloseButton = _interopRequireDefault(require("./CloseButton"));

var _singleton = require("../tooltip/singleton");

var _icon = _interopRequireDefault(require("../icon"));

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

var _isReactChildren = _interopRequireDefault(require("../_util/isReactChildren"));

var _utils2 = require("../data-set/utils");

var _ObjectChainValue = _interopRequireDefault(require("../_util/ObjectChainValue"));

var _MultiLine = _interopRequireDefault(require("../output/MultiLine"));

var toRangeValue = _dataset.Utils.toRangeValue;
exports.toRangeValue = toRangeValue;
var getDateFormatByFieldType = _dataset.Utils.getDateFormatByFieldType;
exports.getDateFormatByFieldType = getDateFormatByFieldType;
var getDateFormatByField = _dataset.Utils.getDateFormatByField;
exports.getDateFormatByField = getDateFormatByField;

function fromRangeValue(value, range) {
  if ((0, _mobx.isArrayLike)(range)) {
    var _ref;

    var _range = (0, _slicedToArray2["default"])(range, 2),
        start = _range[0],
        end = _range[1];

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

  return value;
}

function toMultipleValue(value, range) {
  if (!(0, _isNil["default"])(value)) {
    var multipleValue = (0, _mobx.isArrayLike)(value) ? value.slice() : [value];

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

    return multipleValue;
  }

  return [];
}

function transformHighlightProps(highlight, props) {
  if ( /*#__PURE__*/(0, _react.isValidElement)(highlight) || (0, _isString["default"])(highlight)) {
    return (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, props), {}, {
      content: highlight
    });
  }

  if ((0, _isObject["default"])(highlight)) {
    return (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, props), highlight);
  }

  return props;
}

function getCurrencyFormatter() {
  var getConfig = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _utils.getConfig;
  var currencyFormatter = getConfig('currencyFormatter');

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

  return _formatCurrency["default"];
}

function getNumberFormatter() {
  var getConfig = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _utils.getConfig;
  var numberFieldFormatter = getConfig('numberFieldFormatter');

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

  return _formatNumber["default"];
}

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

  if ((0, _isNumber["default"])(precision)) {
    options.minimumFractionDigits = precision;
    options.maximumFractionDigits = precision;
  }

  (0, _extends2["default"])(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
  };
}

function getNumberFormatOptions(getProp, getDisplayProp, getValue, value, controlLang) {
  var getConfig = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : _utils.getConfig;
  var precision = getProp('precision');
  var useZeroFilledDecimal = precision > 0 && getConfig('useZeroFilledDecimal');
  var v = (0, _isNil["default"])(value) ? getValue && getValue() : value;
  var precisionInValue = (0, _isNumber["default"])(precision) ? precision : _dataset.math.dp(v || 0);
  var formatterOptions = getDisplayProp('formatterOptions') || {};
  var numberFieldFormatterOptions = getConfig('numberFieldFormatterOptions') || {
    options: {}
  };
  var lang = formatterOptions.lang || numberFieldFormatterOptions.lang || controlLang;
  var options = (0, _objectSpread2["default"])((0, _objectSpread2["default"])({
    maximumFractionDigits: precisionInValue,
    minimumFractionDigits: useZeroFilledDecimal ? precisionInValue : undefined
  }, numberFieldFormatterOptions.options), formatterOptions.options);
  var numberGrouping = getDisplayProp('numberGrouping');

  if (!(0, _isNil["default"])(numberGrouping)) {
    options.useGrouping = numberGrouping;
  }

  return {
    lang: lang,
    options: options
  };
}

function processFieldValue(value, field, options, showValueIfNotFound, record) {
  var getConfig = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : _utils.getConfig;
  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 === _enum.FieldType.currency) {
    var formatOptions = getCurrencyFormatOptions(getProp, getDisplayProp, lang, getConfig);
    var formatter = getProp('formatter');
    return (formatter || getCurrencyFormatter(getConfig))(value, formatOptions.lang, formatOptions.options);
  }

  if (type === _enum.FieldType.number || type === _enum.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;
}

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

  if (!(0, _isNil["default"])(value)) {
    if ((0, _moment.isMoment)(value)) {
      if (value.isValid()) {
        return value.format(options.dateFormat);
      }

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

      return '';
    }

    if ((0, _isReactChildren["default"])(value)) {
      // For Select's Option and TreeSelect's TreeNode which type may be ReactElement
      return value;
    }

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

    return value.toString();
  }

  return '';
}

function isFieldValueEmpty(value, range, multiple, valueField, textField) {
  if ((0, _isEmpty["default"])(value)) {
    return true;
  }

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

  if (range === true) {
    return (0, _mobx.isArrayLike)(value) && value.every(function (v) {
      return (0, _isEmpty["default"])(v);
    });
  }

  if ((0, _mobx.isArrayLike)(range)) {
    return value && Object.values(value).every(function (v) {
      return (0, _isEmpty["default"])(v);
    });
  }

  var isObjectEmpty = function isObjectEmpty(v) {
    if (valueField && textField) {
      if ((0, _mobx.isObservableObject)(v)) {
        return (0, _isEmpty["default"])((0, _mobx.get)(v, valueField)) && (0, _isEmpty["default"])((0, _mobx.get)(v, textField));
      }

      if ((0, _isObject["default"])(v)) {
        return (0, _isEmpty["default"])(v[valueField]) && (0, _isEmpty["default"])(v[textField]);
      }
    }

    return false;
  };

  if ((0, _mobx.isArrayLike)(value)) {
    return value.length ? value.every(function (v) {
      if ((0, _isEmpty["default"])(v)) {
        return true;
      }

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

  return isObjectEmpty(value);
}

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 !(0, _isEmpty["default"])(v);
  })) {
    return /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, rangeValue[0], "~", rangeValue[1]);
  }
}

function getValueKey(v) {
  if ((0, _mobx.isArrayLike)(v)) {
    return v.join(',');
  }

  return v;
}

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["default"] : _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 ? (0, _utils.getConfig)('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 (!(0, _isEmpty["default"])(text)) {
      var _classNames;

      var validationResult = validationResults && validationResults.find(function (error) {
        return error.value === v;
      });
      var blockDisabled = isMultipleBlockDisabled ? isMultipleBlockDisabled(v) : disabled;
      var className = (0, _classnames["default"])((_classNames = {}, (0, _defineProperty2["default"])(_classNames, "".concat(prefixCls, "-multiple-block-invalid"), validationResult), (0, _defineProperty2["default"])(_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["default"].createElement(_CloseButton["default"], {
        onClose: handleMultipleValueRemove,
        value: v,
        index: repeat
      });

      var inner;

      if (typeof tagRenderer === 'function') {
        var onClose = function onClose(e) {
          (0, _EventManager.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["default"].createElement("span", {
          key: String(index),
          className: className
        }, text) : /*#__PURE__*/_react["default"].createElement("li", {
          key: String(index),
          className: className
        }, /*#__PURE__*/_react["default"].createElement("div", null, text), closeBtn);
      }

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

      return inner;
    }

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

  if (maxTagCount && isOverflowMaxTagCount) {
    var blockClassName = (0, _classnames["default"])((0, _defineProperty2["default"])({}, "".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["default"].createElement("li", {
        key: "maxTagPlaceholder",
        className: blockClassName
      }, /*#__PURE__*/_react["default"].createElement("div", null, content));
    }

    tags.push(moreBlock);
  }

  return {
    tags: tags,
    multipleValidateMessageLength: multipleValidateMessageLength,
    isOverflowMaxTagCount: isOverflowMaxTagCount
  };
}

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 = (0, _utils2.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 = (0, _defaultTo["default"])(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 ((0, _isPlainObject["default"])(fieldValue)) {
              processedValue = _ObjectChainValue["default"].get(fieldValue, fieldItem.get('textField', record) || _utils2.defaultTextField);
            }
          }

          var notEmpty = !(0, _isEmpty["default"])(value); // 值集中不存在 再去取直接返回的值

          var text = processedValue || selfProcessValue(value);
          multipleValidateMessageLength++;
          var validationInner = notEmpty ? text : validationHidden ? record.status === _enum.RecordStatus.add ? '' : /*#__PURE__*/_react["default"].createElement("span", {
            className: "".concat(prefixCls, "-multi-value-invalid")
          }, text) : validationMessage;
          var label = fieldItem.get('label', record);
          return /*#__PURE__*/_react["default"].createElement(_MultiLine["default"], {
            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
  };
}

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

  if (validationMessage) {
    return /*#__PURE__*/_react["default"].createElement("div", {
      className: getProPrefixCls('validation-message')
    }, showIcon && /*#__PURE__*/_react["default"].createElement(_icon["default"], {
      type: "error"
    }), /*#__PURE__*/_react["default"].createElement("span", null, validationMessage));
  }
}

function defaultRenderer(renderOption) {
  var text = renderOption.text,
      repeat = renderOption.repeat,
      maxTagTextLength = renderOption.maxTagTextLength;
  return repeat !== undefined && maxTagTextLength && (0, _isString["default"])(text) && text.length > maxTagTextLength ? "".concat(text.slice(0, maxTagTextLength), "...") : text;
}

function showValidationMessage(e, message, tooltipTheme, tooltipPlacement) {
  var getConfig = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : _utils.getConfig;
  (0, _singleton.show)(e.currentTarget, {
    suffixCls: "form-tooltip ".concat(getConfig('proPrefixCls'), "-tooltip"),
    title: message,
    theme: tooltipTheme,
    placement: tooltipPlacement || 'bottomLeft'
  });
}
//# sourceMappingURL=utils.js.map
