"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["default"] = exports.NumberField = void 0;

var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));

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

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

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

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

var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));

var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));

var _get2 = _interopRequireDefault(require("@babel/runtime/helpers/get"));

var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));

var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));

var _createSuper2 = _interopRequireDefault(require("@babel/runtime/helpers/createSuper"));

var _tslib = require("tslib");

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

var _mobx = require("mobx");

var _mobxReact = require("mobx-react");

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

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

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

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

var _bignumber = require("bignumber.js");

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

var _KeyCode = _interopRequireDefault(require("../../../lib/_util/KeyCode"));

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

var _autobind = _interopRequireDefault(require("../_util/autobind"));

var _keepRunning = _interopRequireDefault(require("../_util/keepRunning"));

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

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

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

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

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

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

var _LocaleContext = _interopRequireDefault(require("../locale-context/LocaleContext"));

var _utils2 = require("../field/utils");

function getCurrentValidValue(value, options) {
  var valueBig = new _bignumber.BigNumber(value.replace(/\.$/, ''));
  return _dataset.math.isValidBigNumber(valueBig) ? options.strict ? valueBig : _dataset.math.fix(valueBig) : 0;
}

function getStepUpGenerator() {
  return this.stepGenerator(true);
}

function getStepDownGenerator() {
  return this.stepGenerator(false);
}

function run(value) {
  var element = this.element;

  if (element) {
    element.value = String(value);
  }
}

function enabled() {
  return Boolean(this.getProp('step'));
}

var stepUpKeyboardProps = {
  getStepGenerator: getStepUpGenerator,
  run: run,
  validator: function validator(target) {
    return target === this.element;
  },
  enabled: enabled
};
var stepDownKeyboardProps = {
  getStepGenerator: getStepDownGenerator,
  run: run,
  validator: function validator(target) {
    return target === this.element;
  },
  enabled: enabled
};
var stepUpMouseProps = {
  getStepGenerator: getStepUpGenerator,
  run: run,
  validator: function validator(target) {
    return target === this.plusElement;
  }
};
var stepDownMouseProps = {
  getStepGenerator: getStepDownGenerator,
  run: run,
  validator: function validator(target) {
    return target === this.minusElement;
  }
};

var NumberField = /*#__PURE__*/function (_TextField) {
  (0, _inherits2["default"])(NumberField, _TextField);

  var _super = (0, _createSuper2["default"])(NumberField);

  function NumberField() {
    (0, _classCallCheck2["default"])(this, NumberField);
    return _super.apply(this, arguments);
  }

  (0, _createClass2["default"])(NumberField, [{
    key: "lang",
    get: function get() {
      var lang = this.observableProps.lang;

      if (lang) {
        return lang;
      }

      var dataSet = this.dataSet;

      if (dataSet && dataSet.lang) {
        return dataSet.lang;
      }

      var numberFormatLanguage = _LocaleContext["default"].numberFormatLanguage,
          locale = _LocaleContext["default"].locale;

      if (numberFormatLanguage) {
        return numberFormatLanguage;
      }

      return locale.lang;
    }
  }, {
    key: "defaultValidationMessages",
    get: function get() {
      var label = this.getProp('label');
      return {
        valueMissing: (0, _localeContext.$l)('NumberField', label ? 'value_missing' : 'value_missing_no_label', {
          label: label
        })
      };
    }
  }, {
    key: "strict",
    get: function get() {
      var field = this.field;
      return field ? field.get('type', this.record) === _enum.FieldType.bigNumber : false;
    }
  }, {
    key: "allowDecimal",
    get: function get() {
      var min = this.min,
          nonStrictStep = this.nonStrictStep;
      var precision = this.getProp('precision');

      if (precision === 0) {
        return false;
      } // 非严格步距下允许输入小数


      if (nonStrictStep) {
        return true;
      }

      var step = this.getProp('step');
      return !step || !_dataset.math.eq(_dataset.math.mod(step, 1), 0) || !!min && !_dataset.math.eq(_dataset.math.mod(min, 1), 0);
    }
  }, {
    key: "nonStrictStep",
    get: function get() {
      var nonStrictStep = this.getProp('nonStrictStep');

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

      var numberFieldNonStrictStep = this.getContextConfig('numberFieldNonStrictStep');

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

      return false;
    }
  }, {
    key: "allowNegative",
    get: function get() {
      var min = this.min;
      return (0, _isNil["default"])(min) || min < 0;
    }
  }, {
    key: "min",
    get: function get() {
      return this.getLimit('min');
    }
  }, {
    key: "max",
    get: function get() {
      return this.getLimit('max');
    }
  }, {
    key: "value",
    get: function get() {
      var value = this.observableProps.value;

      if ((0, _mobx.isArrayLike)(value)) {
        return value;
      }

      var range = this.range;

      if ((0, _mobx.isArrayLike)(range)) {
        if ((0, _isPlainObject["default"])(value)) {
          var _ref;

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

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

      return value;
    },
    set: function set(value) {
      var _this = this;

      (0, _mobx.runInAction)(function () {
        _this.observableProps.value = value;
      });
    }
  }, {
    key: "clearButton",
    get: function get() {
      var step = this.getProp('step');

      if (step) {
        return false;
      }

      return (0, _get2["default"])((0, _getPrototypeOf2["default"])(NumberField.prototype), "clearButton", this);
    }
  }, {
    key: "keyboard",
    get: function get() {
      if ('keyboard' in this.props) {
        return this.props.keyboard;
      }

      return this.getContextConfig('numberFieldKeyboard') !== false;
    }
  }, {
    key: "savePlusRef",
    value: function savePlusRef(ref) {
      this.plusElement = ref;
    }
  }, {
    key: "saveMinusRef",
    value: function saveMinusRef(ref) {
      this.minusElement = ref;
    }
  }, {
    key: "isLowerRange",
    value: function isLowerRange(value1, value2) {
      return _dataset.math.lt(value1, value2);
    }
  }, {
    key: "getFieldType",
    value: function getFieldType() {
      return _enum.FieldType.number;
    }
  }, {
    key: "getLimit",
    value: function getLimit(type) {
      var record = this.record;
      var limit = this.getProp(type);

      if (record && (0, _isString["default"])(limit)) {
        var num = record.get(limit);

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

      return limit;
    }
  }, {
    key: "getValidatorProp",
    value: function getValidatorProp(key) {
      if (['maxLength', 'minLength'].includes(key)) {
        return;
      }

      switch (key) {
        case 'min':
          return this.min;

        case 'max':
          return this.max;

        case 'nonStrictStep':
          return this.nonStrictStep;

        default:
          return (0, _get2["default"])((0, _getPrototypeOf2["default"])(NumberField.prototype), "getValidatorProp", this).call(this, key);
      }
    }
  }, {
    key: "getInnerSpanButton",
    value: function getInnerSpanButton() {
      var prefixCls = this.prefixCls,
          range = this.range,
          clearButton = this.clearButton;
      var longPressPlus = this.props.longPressPlus;
      var step = this.getProp('step');

      if (step && !range && !this.readOnly && !this.disabled) {
        var plusIconProps = {
          ref: this.savePlusRef,
          key: 'plus',
          className: "".concat(prefixCls, "-plus"),
          onMouseDown: longPressPlus ? this.handlePlus : this.handleOncePlus,
          onTouchStart: this.handleOncePlus
        };
        var minIconProps = {
          ref: this.saveMinusRef,
          key: 'minus',
          className: "".concat(prefixCls, "-minus"),
          onMouseDown: longPressPlus ? this.handleMinus : this.handleOnceMinus,
          onTouchStart: this.handleOnceMinus
        };
        return this.wrapperInnerSpanButton( /*#__PURE__*/_react["default"].createElement("div", null, /*#__PURE__*/_react["default"].createElement("div", (0, _extends2["default"])({}, plusIconProps), /*#__PURE__*/_react["default"].createElement(_icon["default"], {
          type: "keyboard_arrow_up"
        })), /*#__PURE__*/_react["default"].createElement("div", (0, _extends2["default"])({}, minIconProps), /*#__PURE__*/_react["default"].createElement(_icon["default"], {
          type: "keyboard_arrow_down"
        }))));
      }

      if (clearButton) {
        var right;

        if (this.suffixWidth && this.isSuffixClick) {
          right = (0, _defaultTo["default"])(this.suffixWidth, 0);
        }

        return this.wrapperInnerSpanButton( /*#__PURE__*/_react["default"].createElement(_icon["default"], {
          type: "close",
          onClick: this.handleClearButtonClick,
          onMouseDown: this.handleInnerButtonMouseDown
        }), {
          className: "".concat(prefixCls, "-clear-button"),
          style: {
            right: right
          }
        });
      }
    }
  }, {
    key: "getWrapperClassNames",
    value: function getWrapperClassNames() {
      var prefixCls = this.prefixCls;
      var step = this.getProp('step');
      var suffix = this.getSuffix();
      var button = this.getInnerSpanButton();

      for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
        args[_key] = arguments[_key];
      }

      return (0, _get2["default"])((0, _getPrototypeOf2["default"])(NumberField.prototype), "getWrapperClassNames", this).call(this, (0, _objectSpread3["default"])((0, _defineProperty2["default"])({}, "".concat(prefixCls, "-step-suffix"), button && /*#__PURE__*/(0, _react.isValidElement)(suffix) && step), args));
    }
  }, {
    key: "handleEnterDown",
    value: function handleEnterDown(e) {
      if (this.multiple && this.range && this.text) {
        this.prepareSetValue(this.text);
      }

      (0, _get2["default"])((0, _getPrototypeOf2["default"])(NumberField.prototype), "handleEnterDown", this).call(this, e);

      if (this.multiple && this.range) {
        this.setRangeTarget(0);
        this.beginRange();
      }
    }
  }, {
    key: "handleKeyDown",
    value: function handleKeyDown(e) {
      if (!this.disabled && !this.readOnly && this.keyboard) {
        switch (e.keyCode) {
          case _KeyCode["default"].UP:
            this.handleKeyDownUp(e);
            break;

          case _KeyCode["default"].DOWN:
            this.handleKeyDownDown(e);
            break;

          default:
        }
      }

      (0, _get2["default"])((0, _getPrototypeOf2["default"])(NumberField.prototype), "handleKeyDown", this).call(this, e);
    }
  }, {
    key: "handleKeyDownUp",
    value: function handleKeyDownUp(value) {
      this.afterStep(value);
    }
  }, {
    key: "handleKeyDownDown",
    value: function handleKeyDownDown(value) {
      this.afterStep(value);
    }
  }, {
    key: "handlePlus",
    value: function handlePlus(value) {
      this.afterStep(value);
    }
  }, {
    key: "handleMinus",
    value: function handleMinus(value) {
      this.afterStep(value);
    }
  }, {
    key: "handleOncePlus",
    value: function handleOncePlus() {
      this.step(true);
    }
  }, {
    key: "handleOnceMinus",
    value: function handleOnceMinus() {
      this.step(false);
    }
  }, {
    key: "getOmitPropsKeys",
    value: function getOmitPropsKeys() {
      return (0, _get2["default"])((0, _getPrototypeOf2["default"])(NumberField.prototype), "getOmitPropsKeys", this).call(this).concat(['nonStrictStep', 'formatter', 'formatterOptions', 'longPressPlus', 'precision', 'numberGrouping', 'maxLength', 'minLength', 'keyboard', 'stringMode']);
    }
  }, {
    key: "getOtherProps",
    value: function getOtherProps() {
      var _this2 = this;

      var otherProps = (0, _get2["default"])((0, _getPrototypeOf2["default"])(NumberField.prototype), "getOtherProps", this).call(this);
      delete otherProps.maxLength;
      otherProps.max = this.max;
      otherProps.min = this.min;

      otherProps.onCompositionEnd = function (e) {
        _this2.lock = false;

        _this2.handleChange(e);
      };

      return otherProps;
    }
  }, {
    key: "getObservableProps",
    value: function getObservableProps(props, context) {
      return (0, _objectSpread3["default"])((0, _objectSpread3["default"])({}, (0, _get2["default"])((0, _getPrototypeOf2["default"])(NumberField.prototype), "getObservableProps", this).call(this, props, context)), {}, {
        max: props.max,
        min: props.min,
        precision: props.precision,
        nonStrictStep: props.nonStrictStep
      });
    }
  }, {
    key: "stepGenerator",
    value: function stepGenerator(isPlus) {
      var min = this.min,
          max = this.max,
          nonStrictStep = this.nonStrictStep,
          strict = this.strict;
      var options = {
        strict: strict
      };
      var step = (0, _defaultTo["default"])(this.getProp('step'), 1);
      var value = this.getCurrentInputValue();
      var currentValue = getCurrentValidValue(String(value), options);
      return /*#__PURE__*/_regenerator["default"].mark(function _callee(newValue) {
        var nearStep, nextValue, nearMaxStep;
        return _regenerator["default"].wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                if (!true) {
                  _context.next = 18;
                  break;
                }

                nearStep = nonStrictStep === false ? (0, _utils.getNearStepValues)(newValue, step, min, max, options) : undefined;

                if (!(nonStrictStep === false && nearStep)) {
                  _context.next = 12;
                  break;
                }

                _context.t0 = nearStep.length;
                _context.next = _context.t0 === 1 ? 6 : _context.t0 === 2 ? 8 : 10;
                break;

              case 6:
                newValue = nearStep[0];
                return _context.abrupt("break", 10);

              case 8:
                newValue = nearStep[isPlus ? 1 : 0];
                return _context.abrupt("break", 10);

              case 10:
                _context.next = 14;
                break;

              case 12:
                nextValue = isPlus ? _dataset.math.plus(newValue, step, options) : _dataset.math.minus(newValue, step, options);

                if (!(0, _isEmpty["default"])(min) && _dataset.math.lt(nextValue, min)) {
                  newValue = min;
                } else if (!(0, _isEmpty["default"])(max) && _dataset.math.gt(nextValue, max)) {
                  nearMaxStep = nonStrictStep === false ? (0, _utils.getNearStepValues)(max, step, min, max, options) : undefined;

                  if (nonStrictStep === false && nearMaxStep) {
                    newValue = nearMaxStep[0];
                  } else {
                    newValue = max;
                  }
                } else {
                  newValue = nextValue;
                }

              case 14:
                _context.next = 16;
                return newValue;

              case 16:
                _context.next = 0;
                break;

              case 18:
              case "end":
                return _context.stop();
            }
          }
        }, _callee);
      })(currentValue);
    }
  }, {
    key: "getCurrentInputValue",
    value: function getCurrentInputValue() {
      var value;

      if (!(0, _isEmpty["default"])(this.text)) {
        value = this.text;
      } else if (this.range && !(0, _isNil["default"])(this.rangeTarget) && this.rangeValue) {
        value = this.rangeValue[this.rangeTarget];
      } else {
        value = this.getValue();
      }

      return value;
    }
  }, {
    key: "step",
    value: function step(isPlus) {
      this.afterStep(this.stepGenerator(isPlus).next().value);
    }
  }, {
    key: "afterStep",
    value: function afterStep(newValue) {
      if (this.multiple) {
        this.setText(String(newValue));
      } else {
        this.prepareSetValue(newValue);
      }
    }
  }, {
    key: "prepareSetValue",
    value: function prepareSetValue(value) {
      if (isNaN(value) || (0, _isEmpty["default"])(value)) {
        (0, _get2["default"])((0, _getPrototypeOf2["default"])(NumberField.prototype), "prepareSetValue", this).call(this, null);
      } else {
        (0, _get2["default"])((0, _getPrototypeOf2["default"])(NumberField.prototype), "prepareSetValue", this).call(this, (0, _utils.parseNumber)(value, this.getProp('precision'), this.strict));
      }
    }
  }, {
    key: "getProcessValueOptions",
    value: function getProcessValueOptions() {
      var options = (0, _get2["default"])((0, _getPrototypeOf2["default"])(NumberField.prototype), "getProcessValueOptions", this).call(this);
      options.isNumber = true;
      options.precision = this.getProp('precision');
      options.useZeroFilledDecimal = this.getContextConfig('useZeroFilledDecimal');
      return options;
    }
  }, {
    key: "restrictInput",
    value: function restrictInput(value) {
      if (this.lock) return value;

      if (value) {
        value = value.replace('。', '.');
        var restrict = '0-9';

        if (this.allowDecimal) {
          restrict += '.';
        } else if (value.indexOf('.') !== -1) {
          var boforeValue = this.getCurrentInputValue();
          boforeValue = !(0, _isNil["default"])(boforeValue) ? String(boforeValue) : '';

          if (boforeValue.indexOf('.') === -1) {
            return boforeValue;
          }

          value = String(this.stepGenerator(false).next().value);
        }

        var isNegative = this.allowNegative && /^-/.test(value);
        value = (0, _get2["default"])((0, _getPrototypeOf2["default"])(NumberField.prototype), "restrictInput", this).call(this, value.replace(new RegExp("[^".concat(restrict, "]+"), 'g'), ''));
        var values = value.split('.');

        if (values.length > 2) {
          value = "".concat(values.shift(), ".").concat(values.join(''));
        }

        if (isNegative) {
          value = "-".concat(value);
        }
      }

      return value;
    }
  }, {
    key: "getFormatOptions",
    value: function getFormatOptions(value) {
      var _this3 = this;

      return (0, _utils2.getNumberFormatOptions)(function (name) {
        return _this3.getProp(name);
      }, function (name) {
        return _this3.getDisplayProp(name);
      }, function () {
        return _this3.getValue();
      }, value, this.lang, this.getContextConfig);
    }
  }, {
    key: "getFormatter",
    value: function getFormatter() {
      return this.getProp('formatter') || (0, _utils2.getNumberFormatter)(this.getContextConfig);
    }
  }, {
    key: "processText",
    value: function processText(value) {
      var fixedValue = _dataset.math.fix(new _bignumber.BigNumber(String(value)));

      var formatOptions = this.getFormatOptions(fixedValue);
      return this.getFormatter()(value, formatOptions.lang, formatOptions.options);
    }
  }, {
    key: "renderLengthInfo",
    value: function renderLengthInfo() {
      return undefined;
    }
  }, {
    key: "compare",
    value: function compare(oldValue, newValue) {
      return _dataset.math.eq(oldValue, newValue);
    }
  }, {
    key: "isValidInput",
    value: function isValidInput(input) {
      return !input.endsWith('.');
    }
  }]);
  return NumberField;
}(_TextField2.TextField);

exports.NumberField = NumberField;
NumberField.displayName = 'NumberField';
NumberField.defaultProps = (0, _objectSpread3["default"])((0, _objectSpread3["default"])({}, _TextField2.TextField.defaultProps), {}, {
  suffixCls: 'input-number',
  longPressPlus: true,
  max: Infinity,
  min: -Infinity
});
NumberField.format = _formatNumber["default"];
/**
 * @deprecated
 */

NumberField.bigNumberFormat = _formatNumber["default"];
(0, _tslib.__decorate)([_mobx.computed], NumberField.prototype, "lang", null);
(0, _tslib.__decorate)([_mobx.computed], NumberField.prototype, "allowDecimal", null);
(0, _tslib.__decorate)([_mobx.computed], NumberField.prototype, "nonStrictStep", null);
(0, _tslib.__decorate)([_mobx.computed], NumberField.prototype, "allowNegative", null);
(0, _tslib.__decorate)([_mobx.computed], NumberField.prototype, "min", null);
(0, _tslib.__decorate)([_mobx.computed], NumberField.prototype, "max", null);
(0, _tslib.__decorate)([_mobx.computed], NumberField.prototype, "value", null);
(0, _tslib.__decorate)([_autobind["default"]], NumberField.prototype, "savePlusRef", null);
(0, _tslib.__decorate)([_autobind["default"]], NumberField.prototype, "saveMinusRef", null);
(0, _tslib.__decorate)([_mobx.action], NumberField.prototype, "handleEnterDown", null);
(0, _tslib.__decorate)([_autobind["default"]], NumberField.prototype, "handleKeyDown", null);
(0, _tslib.__decorate)([(0, _keepRunning["default"])(stepUpKeyboardProps)], NumberField.prototype, "handleKeyDownUp", null);
(0, _tslib.__decorate)([(0, _keepRunning["default"])(stepDownKeyboardProps)], NumberField.prototype, "handleKeyDownDown", null);
(0, _tslib.__decorate)([(0, _keepRunning["default"])(stepUpMouseProps)], NumberField.prototype, "handlePlus", null);
(0, _tslib.__decorate)([(0, _keepRunning["default"])(stepDownMouseProps)], NumberField.prototype, "handleMinus", null);
(0, _tslib.__decorate)([_autobind["default"]], NumberField.prototype, "handleOncePlus", null);
(0, _tslib.__decorate)([_autobind["default"]], NumberField.prototype, "handleOnceMinus", null);
(0, _tslib.__decorate)([_autobind["default"]], NumberField.prototype, "compare", null);

var ObserverNumberField = /*#__PURE__*/function (_NumberField) {
  (0, _inherits2["default"])(ObserverNumberField, _NumberField);

  var _super2 = (0, _createSuper2["default"])(ObserverNumberField);

  function ObserverNumberField() {
    (0, _classCallCheck2["default"])(this, ObserverNumberField);
    return _super2.apply(this, arguments);
  }

  return (0, _createClass2["default"])(ObserverNumberField);
}(NumberField);

ObserverNumberField.defaultProps = NumberField.defaultProps;
ObserverNumberField.format = _formatNumber["default"];
/**
 * @deprecated
 */

ObserverNumberField.bigNumberFormat = _formatNumber["default"];
ObserverNumberField = (0, _tslib.__decorate)([_mobxReact.observer], ObserverNumberField);
var _default = ObserverNumberField;
exports["default"] = _default;
//# sourceMappingURL=NumberField.js.map
