/**
 * amis-ui v6.14.0-beta.1
 * Copyright 2018-2025 fex
 */

'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var tslib = require('tslib');
var React = require('react');
var isInteger = require('lodash/isInteger');
var InputNumber = require('rc-input-number');
var getMiniDecimal = require('@rc-component/mini-decimal');
var icons = require('./icons.js');
var amisCore = require('amis-core');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var React__default = /*#__PURE__*/_interopDefaultLegacy(React);
var isInteger__default = /*#__PURE__*/_interopDefaultLegacy(isInteger);
var InputNumber__default = /*#__PURE__*/_interopDefaultLegacy(InputNumber);
var getMiniDecimal__default = /*#__PURE__*/_interopDefaultLegacy(getMiniDecimal);

var __react_jsx__ = require('react');
var _J$X_ = (__react_jsx__["default"] || __react_jsx__).createElement;
(__react_jsx__["default"] || __react_jsx__).Fragment;
var NumberInput = /** @class */ (function (_super) {
    tslib.__extends(NumberInput, _super);
    function NumberInput(props) {
        var _this = _super.call(this, props) || this;
        /**
         * 是否是 bigNumber，如果输入的内容是字符串就自动开启
         */
        _this.isBig = false;
        // 严格判断大数模式，因为初始化value为empty string时，修改value值格式仍然为string
        _this.isBig = !!props.big;
        _this.state = {
            focused: false
        };
        return _this;
    }
    NumberInput.prototype.componentDidUpdate = function (prevProps) {
        var isBig = !!this.props.big;
        if (!!(prevProps === null || prevProps === void 0 ? void 0 : prevProps.big) !== isBig) {
            this.isBig = isBig;
        }
    };
    NumberInput.prototype.handleChange = function (value) {
        var _a = this.props, min = _a.min, max = _a.max, step = _a.step, resetValue = _a.resetValue, clearValueOnEmpty = _a.clearValueOnEmpty, onChange = _a.onChange;
        var _b = this.props, suffix = _b.suffix, precision = _b.precision, showAsPercent = _b.showAsPercent;
        //在显示百分号情况下，需先将数值恢复到实际value值
        if (showAsPercent && suffix == '%') {
            value = value / 100;
            precision = (precision || 0) + 2;
        }
        var finalPrecision = NumberInput.normalizePrecision(precision, step);
        var result = NumberInput.normalizeValue(value, min, max, finalPrecision, resetValue, clearValueOnEmpty, this.isBig);
        onChange === null || onChange === void 0 ? void 0 : onChange(result);
    };
    NumberInput.prototype.handleFocus = function (e) {
        var onFocus = this.props.onFocus;
        this.setState({ focused: true });
        onFocus && onFocus(e);
    };
    NumberInput.prototype.handleBlur = function (e) {
        var onBlur = this.props.onBlur;
        this.setState({ focused: false });
        onBlur && onBlur(e);
    };
    NumberInput.prototype.handleClick = function (e) {
        e.stopPropagation();
    };
    NumberInput.prototype.handleEnhanceModeChange = function (action, e) {
        e.stopPropagation();
        var _a = this.props, value = _a.value, _b = _a.step, step = _b === void 0 ? 1 : _b, disabled = _a.disabled, readOnly = _a.readOnly, precision = _a.precision;
        // value为undefined会导致溢出错误
        var val = value || 0;
        if (disabled || readOnly) {
            return;
        }
        if (isNaN(Number(step)) || !Number(step)) {
            return;
        }
        var stepDecimal = getMiniDecimal__default["default"](step);
        if (action !== 'add') {
            stepDecimal = stepDecimal.negate();
        }
        var target = getMiniDecimal__default["default"](val).add(stepDecimal.toString());
        var getPrecision = function (numStr) {
            if (precision != null && precision >= 0) {
                return precision;
            }
            return Math.max(getMiniDecimal.getNumberPrecision(numStr), getMiniDecimal.getNumberPrecision(Number(step) || 1));
        };
        var triggerValueUpdate = function (newValue, userTyping) {
            var updateValue = newValue;
            var numStr = updateValue.toString();
            var mergedPrecision = getPrecision(numStr);
            if (mergedPrecision >= 0) {
                updateValue = getMiniDecimal__default["default"](getMiniDecimal.toFixed(numStr, '.', mergedPrecision));
            }
            return updateValue;
        };
        var updatedValue = triggerValueUpdate(target);
        if (this.isBig) {
            this.handleChange(updatedValue.toString());
        }
        else {
            val = Number(updatedValue.toString());
            this.handleChange(val);
        }
    };
    NumberInput.prototype.renderBase = function () {
        var _a;
        var _b = this.props, className = _b.className, ns = _b.classPrefix, cx = _b.classnames, step = _b.step, precision = _b.precision, disabled = _b.disabled, placeholder = _b.placeholder, showSteps = _b.showSteps, formatter = _b.formatter, suffix = _b.suffix, showAsPercent = _b.showAsPercent, parser = _b.parser, borderMode = _b.borderMode, readOnly = _b.readOnly, displayMode = _b.displayMode, inputRef = _b.inputRef, keyboard = _b.keyboard, inputControlClassName = _b.inputControlClassName, mobileUI = _b.mobileUI, name = _b.name, testIdBuilder = _b.testIdBuilder;
        var _c = this.props, value = _c.value, max = _c.max, min = _c.min;
        //需要展示百分号的情况下,数值乘100显示,注意精度丢失问题
        if (showAsPercent && suffix == '%' && value) {
            value = parseFloat((Number(value) * 100).toFixed(precision));
            max = max != null ? Math.round(Number(max) * 100) : max;
            min = min != null ? Math.round(Number(min) * 100) : min;
        }
        var precisionProps = {
            precision: NumberInput.normalizePrecision(precision, step)
        };
        return (_J$X_(InputNumber__default["default"], tslib.__assign({ name: name, className: cx(className, showSteps === false || readOnly ? 'no-steps' : '', displayMode === 'enhance'
                ? 'Number--enhance-input'
                : inputControlClassName, (_a = {},
                _a["Number--border".concat(amisCore.ucFirst(borderMode))] = borderMode,
                _a), {
                'is-mobile': mobileUI
            }), ref: inputRef, readOnly: readOnly, prefixCls: "".concat(ns, "Number"), value: value, step: step, max: max, min: min, formatter: formatter, parser: parser, onChange: this.handleChange, disabled: disabled, placeholder: placeholder, onFocus: this.handleFocus, onClick: this.handleClick, onBlur: this.handleBlur, stringMode: this.isBig ? true : false, keyboard: keyboard }, precisionProps, testIdBuilder === null || testIdBuilder === void 0 ? void 0 : testIdBuilder.getTestId())));
    };
    NumberInput.prototype.render = function () {
        var _a;
        var _this = this;
        var _b;
        var _c = this.props, cx = _c.classnames, value = _c.value, max = _c.max, min = _c.min, disabled = _c.disabled, showSteps = _c.showSteps, borderMode = _c.borderMode, readOnly = _c.readOnly, displayMode = _c.displayMode, inputControlClassName = _c.inputControlClassName; _c.mobileUI;
        return (_J$X_(React__default["default"].Fragment, null, displayMode === 'enhance' ? (_J$X_("div", { className: cx('Number--enhance', disabled ? 'Number--enhance-disabled' : '', showSteps === false ? 'Number--enhance-no-steps' : '', (_a = {},
                _a["Number--enhance-border".concat(amisCore.ucFirst(borderMode))] = borderMode,
                _a), inputControlClassName, ((_b = this.state) === null || _b === void 0 ? void 0 : _b.focused) && 'focused') },
            _J$X_("div", { className: cx('Number--enhance-left-icon', value && value === min ? 'Number--enhance-border-min' : '', disabled ? 'Number--enhance-border-disabled' : '', readOnly ? 'Number--enhance-border-readOnly' : ''), onClick: function (e) { return _this.handleEnhanceModeChange('subtract', e); } },
                _J$X_(icons.Icon, { icon: "minus", className: "icon", classNameProp: cx('InputNumber-enhance-minus icon'), iconContent: "InputNumber-enhance-minus" })),
            this.renderBase(),
            _J$X_("div", { className: cx('Number--enhance-right-icon', value && value === max ? 'Number--enhance-border-max' : '', disabled ? 'Number--enhance-border-disabled' : '', readOnly ? 'Number--enhance-border-readOnly' : ''), onClick: function (e) { return _this.handleEnhanceModeChange('add', e); } },
                _J$X_(icons.Icon, { icon: "plus", className: "icon", classNameProp: cx('InputNumber-enhance-plus icon'), iconContent: "InputNumber-enhance-plus" })))) : (this.renderBase())));
    };
    NumberInput.defaultProps = {
        step: 1,
        readOnly: false,
        borderMode: 'full',
        resetValue: ''
    };
    /**
     * 处理value值
     *
     * @param value value 值
     * @param min 最小值
     * @param max 最大值
     * @param precision 精度
     * @param resetValue 重置值
     * @param isBig 是否为大数模式
     */
    NumberInput.normalizeValue = function (value, min, max, precision, resetValue, clearValueOnEmpty, isBig) {
        /**
         * 输入不合法时重置为resetValue
         * 若resetValue为不合法数字，直接清空输入
         * 若resetValue为数字，则需要处理max，min，precision，保证抛出的值满足条件
         */
        if (!amisCore.isNumeric(value)) {
            if (!amisCore.isNumeric(resetValue)) {
                return clearValueOnEmpty ? undefined : '';
            }
            value = resetValue;
        }
        // 处理max & min
        if (typeof value === 'number') {
            if (typeof min === 'number') {
                value = Math.max(value, min);
            }
            if (typeof max === 'number') {
                value = Math.min(value, max);
            }
        }
        // 处理string类型输入
        if (typeof value === 'string') {
            var val = getMiniDecimal__default["default"](value);
            if (typeof min !== 'undefined') {
                var minValue = getMiniDecimal__default["default"](min);
                if (val.lessEquals(minValue)) {
                    value = min;
                }
            }
            if (typeof max !== 'undefined') {
                var maxValue = getMiniDecimal__default["default"](max);
                if (maxValue.lessEquals(val)) {
                    value = max;
                }
            }
        }
        /**
         * 非大数模式下，如果精度不满足要求，需要处理value值，只做精度处理，不做四舍五入
         */
        if (!isBig && getMiniDecimal.getNumberPrecision(value) !== precision) {
            var multiplier = Math.pow(10, precision);
            var truncatedValue = Math.trunc(getMiniDecimal__default["default"](value).multi(multiplier).toNumber()) /
                multiplier;
            value = getMiniDecimal__default["default"](truncatedValue).toNumber();
        }
        return value;
    };
    /**
     * 处理value值（仅使用 resetValue 和 clearValueOnEmpty）
     *
     * @param value value 值
     * @param resetValue 重置值
     * @param clearValueOnEmpty 是否在清空内容时从数据域中删除该表单项对应的值
     */
    NumberInput.normalizeValue2 = function (value, resetValue, clearValueOnEmpty) {
        if (!amisCore.isNumeric(value)) {
            if (!amisCore.isNumeric(resetValue)) {
                return clearValueOnEmpty ? undefined : '';
            }
            value = resetValue;
        }
        return value;
    };
    /**
     * 获取精度，合法的精度为0和正整数，不合法的精度统一转化为0
     * 若设置了step，则会基于step的精度生成，最终使用更高的精度
     *
     * @param precision 精度
     * @param step 步长
     */
    NumberInput.normalizePrecision = function (precision, step) {
        if (typeof precision === 'number' &&
            isInteger__default["default"](precision) &&
            precision >= 0) {
            return Math.max(precision, getMiniDecimal.getNumberPrecision(step !== null && step !== void 0 ? step : 1));
        }
        // 如果设置了step，就基于step和precision，选取更高精度
        if (step != null) {
            return Math.max(0, getMiniDecimal.getNumberPrecision(step));
        }
        return 0;
    };
    tslib.__decorate([
        amisCore.autobind,
        tslib.__metadata("design:type", Function),
        tslib.__metadata("design:paramtypes", [Object]),
        tslib.__metadata("design:returntype", void 0)
    ], NumberInput.prototype, "handleChange", null);
    tslib.__decorate([
        amisCore.autobind,
        tslib.__metadata("design:type", Function),
        tslib.__metadata("design:paramtypes", [Object]),
        tslib.__metadata("design:returntype", void 0)
    ], NumberInput.prototype, "handleFocus", null);
    tslib.__decorate([
        amisCore.autobind,
        tslib.__metadata("design:type", Function),
        tslib.__metadata("design:paramtypes", [Object]),
        tslib.__metadata("design:returntype", void 0)
    ], NumberInput.prototype, "handleBlur", null);
    tslib.__decorate([
        amisCore.autobind,
        tslib.__metadata("design:type", Function),
        tslib.__metadata("design:paramtypes", [Object]),
        tslib.__metadata("design:returntype", void 0)
    ], NumberInput.prototype, "handleClick", null);
    tslib.__decorate([
        amisCore.autobind,
        tslib.__metadata("design:type", Function),
        tslib.__metadata("design:paramtypes", [String, Object]),
        tslib.__metadata("design:returntype", void 0)
    ], NumberInput.prototype, "handleEnhanceModeChange", null);
    tslib.__decorate([
        amisCore.autobind,
        tslib.__metadata("design:type", Function),
        tslib.__metadata("design:paramtypes", []),
        tslib.__metadata("design:returntype", void 0)
    ], NumberInput.prototype, "renderBase", null);
    return NumberInput;
}(React__default["default"].Component));
var NumberInput$1 = amisCore.themeable(NumberInput);

exports.NumberInput = NumberInput;
exports["default"] = NumberInput$1;
