import { rpx2vw4style as __rpx2vw__ } from "babel-runtime-jsx-style-transform";

function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

import { __awaiter, __rest } from "tslib";
import classNames from 'classnames';
import React, { createElement, forwardRef, useEffect, useRef, useState } from "react";
import { TextInput } from "@alifd/meet-react-component-one";
import { isWeb } from '@uni/env';
import Button from '../button';
import Icon from '../icon';
import { getValueFromEvents, isFunction, isInvalidValue, isMiniappPlatform, isStrictMiniApp, isStrictWechatMiniProgram, isUndef, isNumber } from '../utils';
import { useDeprecated, useGuid } from '../utils/hooks';
import View from '../view';
import { clamp, getDefaultValue, toNumber } from './utils';
var MAX_NUMBER_PICKER_THRESHOLD = 9999999;
var isIOSH5 = isWeb && window.navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);

function getInitInputValue(props) {
  var initialValue;

  if ('value' in props) {
    initialValue = props.value;
  } else if (!isUndef(props.defaultValue)) {
    initialValue = props.defaultValue;
  }

  return !isInvalidValue(initialValue) ? toNumber(initialValue) : '';
}

function isDecreaseDisabled(value, min) {
  if (!isNumber(value)) {
    return false;
  }

  return min !== -Infinity && value <= min;
}

function isIncreaseDisabled(value, max) {
  if (!isNumber(value)) {
    return false;
  }

  return max !== Infinity && value >= max;
}

function getPrecision(precision, step) {
  if (typeof precision !== 'number' || precision < 0) {
    precision = 0;
  }

  var stepString = step.toString();
  var pcs = 0;

  if (stepString.indexOf('.') >= 0) {
    pcs = stepString.length - stepString.indexOf('.') - 1;
  }

  return Math.max(pcs, precision);
}

function getPrecisionFactor(precision) {
  return Math.pow(10, precision);
}

function hackChrome(value, precision) {
  if (precision > 0) {
    return Number(Number(value).toFixed(precision));
  }

  return value;
}

var NumberPicker = function NumberPicker(props, ref) {
  var _classNames;

  var className = props.className,
      _props$prefix = props.prefix,
      prefix = _props$prefix === void 0 ? 'mt-' : _props$prefix,
      _props$size = props.size,
      size = _props$size === void 0 ? 'medium' : _props$size,
      value = props.value,
      defaultValue = props.defaultValue,
      _props$max = props.max,
      max = _props$max === void 0 ? MAX_NUMBER_PICKER_THRESHOLD : _props$max,
      _props$min = props.min,
      min = _props$min === void 0 ? -MAX_NUMBER_PICKER_THRESHOLD : _props$min,
      _props$step = props.step,
      step = _props$step === void 0 ? 1 : _props$step,
      _k1 = props.keybordType,
      _k2 = props.keyboardType,
      _props$readOnly = props.readOnly,
      readOnly = _props$readOnly === void 0 ? false : _props$readOnly,
      _props$disabled = props.disabled,
      disabled = _props$disabled === void 0 ? false : _props$disabled,
      _props$precision = props.precision,
      precisionProp = _props$precision === void 0 ? 0 : _props$precision,
      _props$focused = props.focused,
      focusedProp = _props$focused === void 0 ? false : _props$focused,
      _props$controlled = props.controlled,
      controlled = _props$controlled === void 0 ? false : _props$controlled,
      _props$inputStyle = props.inputStyle,
      inputStyle = _props$inputStyle === void 0 ? {} : _props$inputStyle,
      _props$onBeforeChange = props.onBeforeChange,
      onBeforeChange = _props$onBeforeChange === void 0 ? function () {
    return Promise.resolve();
  } : _props$onBeforeChange,
      onDisableClickProp = props.onDisableClick,
      onDisabledClickProp = props.onDisabledClick,
      _props$onChange = props.onChange,
      onChange = _props$onChange === void 0 ? function () {} : _props$onChange,
      _props$style = props.style,
      style = _props$style === void 0 ? {} : _props$style,
      _props$onInput = props.onInput,
      onInput = _props$onInput === void 0 ? function () {} : _props$onInput,
      _props$onFocus = props.onFocus,
      onFocus = _props$onFocus === void 0 ? function () {} : _props$onFocus,
      _props$onBlur = props.onBlur,
      onBlur = _props$onBlur === void 0 ? function () {} : _props$onBlur,
      _props$onCorrect = props.onCorrect,
      onCorrect = _props$onCorrect === void 0 ? function () {} : _props$onCorrect,
      others = __rest(props, ["className", "prefix", "size", "value", "defaultValue", "max", "min", "step", "keybordType", "keyboardType", "readOnly", "disabled", "precision", "focused", "controlled", "inputStyle", "onBeforeChange", "onDisableClick", "onDisabledClick", "onChange", "style", "onInput", "onFocus", "onBlur", "onCorrect"]);

  var clsPrefix = "".concat(prefix, "numberpicker");
  var isControlled = ('value' in props);
  var onDisabledClick = onDisabledClickProp || onDisableClickProp;
  var precision = getPrecision(precisionProp, step);
  var factor = getPrecisionFactor(precision);
  var inputRef = useRef(null);
  var defaultValAtEmpty = getDefaultValue(min, max, MAX_NUMBER_PICKER_THRESHOLD);

  var _useState = useState(!!props.focused),
      _useState2 = _slicedToArray(_useState, 2),
      focused = _useState2[0],
      setFocused = _useState2[1];

  var _useState3 = useState(getInitInputValue(props)),
      _useState4 = _slicedToArray(_useState3, 2),
      inputValue = _useState4[0],
      setInputValue = _useState4[1];

  var inputId = useGuid('mt-np-input-');

  var _useState5 = useState(isDecreaseDisabled(inputValue, min)),
      _useState6 = _slicedToArray(_useState5, 2),
      decreaseDisabled = _useState6[0],
      setDecreaseDisabled = _useState6[1];

  var _useState7 = useState(isIncreaseDisabled(inputValue, max)),
      _useState8 = _slicedToArray(_useState7, 2),
      increaseDisabled = _useState8[0],
      setIncreaseDisabled = _useState8[1];

  var keyboardType = useDeprecated('NumberPicker', props, 'keybordType', 'keyboardType', 'number-pad');
  useEffect(function () {
    var fn = function fn() {
      if (isControlled) {
        if (isInvalidValue(value)) {
          setInputValue('');
          updateInputVal('');
        } else {
          setInputValue(toNumber(props.value));
          updateInputVal(props.value);
        }
      }
    };

    if (isMiniappPlatform) {
      setTimeout(fn, 100);
    } else {
      fn();
    }
  });
  useEffect(function () {
    setDecreaseDisabled(isDecreaseDisabled(inputValue, min));
    setIncreaseDisabled(isIncreaseDisabled(inputValue, max));
  }, [inputValue, max, min]);

  function handleChange(numValue, e) {
    return __awaiter(this, void 0, void 0, /*#__PURE__*/regeneratorRuntime.mark(function _callee() {
      return regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              if (!readOnly) {
                _context.next = 2;
                break;
              }

              return _context.abrupt("return");

            case 2:
              _context.prev = 2;
              _context.next = 5;
              return onBeforeChange(numValue);

            case 5:
              _context.next = 10;
              break;

            case 7:
              _context.prev = 7;
              _context.t0 = _context["catch"](2);
              throw _context.t0;

            case 10:
              doChange(numValue, e);

            case 11:
            case "end":
              return _context.stop();
          }
        }
      }, _callee, null, [[2, 7]]);
    }));
  }

  function doChange(val, e) {
    if (!isControlled) {
      setInputValue(val);
    }

    onChange(val, e);
  }

  function handleFocus(e) {
    setFocused(true);

    if (isFunction(onFocus)) {
      onFocus(e);
    }
  }

  function updateInputVal(newVal) {
    var cur = inputRef.current;

    if (isWeb && cur && cur._nativeNode) {
      cur._nativeNode.value = '';
      cur._nativeNode.value = newVal;
    } else if (isStrictWechatMiniProgram || isStrictMiniApp) {
      var input = document.querySelector("#".concat(inputId));
      input.value = '';
      input.value = toNumber(newVal);
    }
  }

  function handleBlur(e) {
    var val = toNumber(getValueFromEvents(e));

    if (isFunction(onBlur)) {
      onBlur(e);
    }

    if (isInvalidValue(val)) {
      setFocused(false);
      handleChange('', Object.assign(Object.assign({}, e), {
        originalValue: getValueFromEvents(e)
      }));
      return;
    }

    var limitedValue = clamp(val, min, max);

    if (!isControlled) {
      updateInputVal(limitedValue);
    }

    var result = factor * limitedValue / factor;
    result = hackChrome(result, precision);

    if (val !== result) {
      if (!isControlled) {
        updateInputVal(result);
      }

      onCorrect(result, val);
    }

    setFocused(false);
    handleChange(result, Object.assign(Object.assign({}, e), {
      originalValue: getValueFromEvents(e)
    }));
  }

  function handleInput(e) {
    if (isFunction(onInput)) {
      var val = toNumber(getValueFromEvents(e));
      onInput(val, e);
    }
  }

  function handleDecrease(e) {
    if (isInvalidValue(inputValue)) {
      handleChange(defaultValAtEmpty, e);
      return;
    }

    var newValue = clamp(inputValue - step, min, max);
    var result = factor * newValue / factor;
    result = hackChrome(result, precision);

    if (newValue !== result && isFunction(onCorrect)) {
      onCorrect(result, newValue);
    }

    handleChange(result, e);
  }

  function handleIncrease(e) {
    if (isInvalidValue(inputValue)) {
      handleChange(defaultValAtEmpty, e);
      return;
    }

    var newValue = clamp(inputValue + step, min, max);
    var result = factor * newValue / factor;
    result = hackChrome(result, precision);

    if (newValue !== result && isFunction(onCorrect)) {
      onCorrect(result, newValue);
    }

    handleChange(result, e);
  }

  var handleDisableClick = function handleDisableClick(actionType, e) {
    if (isFunction(onDisabledClick)) {
      onDisabledClick(actionType, e);
    }
  };

  var classNameObj = {
    numberPicker: classNames("".concat(clsPrefix), "".concat(clsPrefix, "--").concat(size)),
    textInput: classNames("".concat(clsPrefix, "-input"), "".concat(clsPrefix, "-input--").concat(size), (_classNames = {}, _defineProperty(_classNames, "".concat(clsPrefix, "-input--focused"), focused), _defineProperty(_classNames, "".concat(clsPrefix, "-input--disabled"), !isIOSH5 && disabled), _defineProperty(_classNames, "".concat(clsPrefix, "-input--readonly"), readOnly), _classNames)),
    decrease: classNames("".concat(clsPrefix, "-button"), "".concat(clsPrefix, "-button-decrease"), "".concat(clsPrefix, "-button--").concat(size), _defineProperty({}, "".concat(clsPrefix, "-button--disabled"), disabled || decreaseDisabled)),
    decreaseIcon: classNames("".concat(clsPrefix, "-button-icon"), "".concat(clsPrefix, "-button-icon--").concat(size), _defineProperty({}, "".concat(clsPrefix, "-button-icon--disabled"), disabled || decreaseDisabled)),
    increase: classNames("".concat(clsPrefix, "-button"), "".concat(clsPrefix, "-button-increase"), "".concat(clsPrefix, "-button--").concat(size), _defineProperty({}, "".concat(clsPrefix, "-button--disabled"), disabled || increaseDisabled)),
    increaseIcon: classNames("".concat(clsPrefix, "-button-icon"), "".concat(clsPrefix, "-button-icon--").concat(size), _defineProperty({}, "".concat(clsPrefix, "-button-icon--disabled"), disabled || increaseDisabled))
  };
  return /*#__PURE__*/React.createElement(View, _extends({
    style: __rpx2vw__(style),
    className: classNames(classNameObj.numberPicker, className),
    ref: ref
  }, others), /*#__PURE__*/React.createElement(Button, {
    disabled: disabled || decreaseDisabled,
    type: "normal",
    model: "outline",
    size: size,
    className: classNameObj.decrease,
    onClick: handleDecrease,
    onDisabledClick: function onDisabledClick(e) {
      handleDisableClick('decrease', e);
    }
  }, /*#__PURE__*/React.createElement(Icon, {
    name: "minus",
    className: classNameObj.decreaseIcon
  })), /*#__PURE__*/React.createElement(TextInput, {
    id: inputId,
    className: classNameObj.textInput,
    ref: inputRef,
    value: "".concat(inputValue),
    editable: !disabled && !readOnly,
    keyboardType: keyboardType,
    onFocus: handleFocus,
    onBlur: handleBlur,
    onInput: handleInput,
    style: __rpx2vw__(inputStyle),
    controlled: controlled
  }), /*#__PURE__*/React.createElement(Button, {
    disabled: disabled || increaseDisabled,
    type: "normal",
    model: "outline",
    size: size,
    className: classNameObj.increase,
    onClick: handleIncrease,
    onDisabledClick: function onDisabledClick(e) {
      handleDisableClick('increase', e);
    }
  }, /*#__PURE__*/React.createElement(Icon, {
    name: "add",
    className: classNameObj.increaseIcon
  })));
};

NumberPicker.displayName = 'NumberPicker';
export default /*#__PURE__*/forwardRef(NumberPicker);