import { __decorate, __metadata } from 'tslib';
import { FocusMonitor } from '@angular/cdk/a11y';
import { UP_ARROW, DOWN_ARROW, ENTER } from '@angular/cdk/keycodes';
import { EventEmitter, ɵɵdirectiveInject, ElementRef, ChangeDetectorRef, ɵɵdefineComponent, ɵɵstaticViewQuery, ɵɵqueryRefresh, ɵɵloadQuery, ɵɵclassProp, ɵɵProvidersFeature, forwardRef, ɵɵNgOnChangesFeature, ɵɵelementStart, ɵɵlistener, ɵɵelement, ɵɵelementEnd, ɵɵadvance, ɵɵproperty, ɵɵattribute, ɵsetClassMetadata, Component, ChangeDetectionStrategy, ViewEncapsulation, Output, ViewChild, Input, ɵɵdefineNgModule, ɵɵdefineInjector, ɵɵsetNgModuleScope, NgModule } from '@angular/core';
import { NG_VALUE_ACCESSOR, DefaultValueAccessor, NgControlStatus, NgModel, FormsModule } from '@angular/forms';
import { isNotNil, InputBoolean } from 'ng-zorro-antd/core';
import { NzIconDirective, NzIconModule } from 'ng-zorro-antd/icon';
import { CommonModule } from '@angular/common';

var _c0 = ["inputElement"];
var NzInputNumberComponent = /** @class */ (function () {
    function NzInputNumberComponent(elementRef, cdr, focusMonitor) {
        this.elementRef = elementRef;
        this.cdr = cdr;
        this.focusMonitor = focusMonitor;
        this.isFocused = false;
        this.disabledUp = false;
        this.disabledDown = false;
        this.onChange = function () { };
        this.onTouched = function () { };
        this.nzBlur = new EventEmitter();
        this.nzFocus = new EventEmitter();
        this.nzSize = 'default';
        this.nzMin = -Infinity;
        this.nzMax = Infinity;
        this.nzParser = function (value) {
            return value
                .trim()
                .replace(/。/g, '.')
                .replace(/[^\w\.-]+/g, '');
        };
        this.nzPrecisionMode = 'toFixed';
        this.nzPlaceHolder = '';
        this.nzStep = 1;
        this.nzId = null;
        this.nzDisabled = false;
        this.nzAutoFocus = false;
        this.nzFormatter = function (value) { return value; };
    }
    NzInputNumberComponent.prototype.onModelChange = function (value) {
        this.parsedValue = this.nzParser(value);
        this.inputElement.nativeElement.value = "" + this.parsedValue;
        var validValue = this.getCurrentValidValue(this.parsedValue);
        this.setValue(validValue);
    };
    NzInputNumberComponent.prototype.getCurrentValidValue = function (value) {
        var val = value;
        if (val === '') {
            val = '';
        }
        else if (!this.isNotCompleteNumber(val)) {
            val = "" + this.getValidValue(val);
        }
        else {
            val = this.value;
        }
        return this.toNumber(val);
    };
    // '1.' '1x' 'xx' '' => are not complete numbers
    NzInputNumberComponent.prototype.isNotCompleteNumber = function (num) {
        return isNaN(num) || num === '' || num === null || !!(num && num.toString().indexOf('.') === num.toString().length - 1);
    };
    NzInputNumberComponent.prototype.getValidValue = function (value) {
        var val = parseFloat(value);
        // https://github.com/ant-design/ant-design/issues/7358
        if (isNaN(val)) {
            return value;
        }
        if (val < this.nzMin) {
            val = this.nzMin;
        }
        if (val > this.nzMax) {
            val = this.nzMax;
        }
        return val;
    };
    NzInputNumberComponent.prototype.toNumber = function (num) {
        if (this.isNotCompleteNumber(num)) {
            return num;
        }
        var numStr = String(num);
        if (numStr.indexOf('.') >= 0 && isNotNil(this.nzPrecision)) {
            if (typeof this.nzPrecisionMode === 'function') {
                return this.nzPrecisionMode(num, this.nzPrecision);
            }
            else if (this.nzPrecisionMode === 'cut') {
                var numSplit = numStr.split('.');
                numSplit[1] = numSplit[1].slice(0, this.nzPrecision);
                return Number(numSplit.join('.'));
            }
            return Number(Number(num).toFixed(this.nzPrecision));
        }
        return Number(num);
    };
    NzInputNumberComponent.prototype.getRatio = function (e) {
        var ratio = 1;
        if (e.metaKey || e.ctrlKey) {
            ratio = 0.1;
        }
        else if (e.shiftKey) {
            ratio = 10;
        }
        return ratio;
    };
    NzInputNumberComponent.prototype.down = function (e, ratio) {
        if (!this.isFocused) {
            this.focus();
        }
        this.step('down', e, ratio);
    };
    NzInputNumberComponent.prototype.up = function (e, ratio) {
        if (!this.isFocused) {
            this.focus();
        }
        this.step('up', e, ratio);
    };
    NzInputNumberComponent.prototype.getPrecision = function (value) {
        var valueString = value.toString();
        if (valueString.indexOf('e-') >= 0) {
            return parseInt(valueString.slice(valueString.indexOf('e-') + 2), 10);
        }
        var precision = 0;
        if (valueString.indexOf('.') >= 0) {
            precision = valueString.length - valueString.indexOf('.') - 1;
        }
        return precision;
    };
    // step={1.0} value={1.51}
    // press +
    // then value should be 2.51, rather than 2.5
    // if this.props.precision is undefined
    // https://github.com/react-component/input-number/issues/39
    NzInputNumberComponent.prototype.getMaxPrecision = function (currentValue, ratio) {
        if (isNotNil(this.nzPrecision)) {
            return this.nzPrecision;
        }
        var ratioPrecision = this.getPrecision(ratio);
        var stepPrecision = this.getPrecision(this.nzStep);
        var currentValuePrecision = this.getPrecision(currentValue);
        if (!currentValue) {
            return ratioPrecision + stepPrecision;
        }
        return Math.max(currentValuePrecision, ratioPrecision + stepPrecision);
    };
    NzInputNumberComponent.prototype.getPrecisionFactor = function (currentValue, ratio) {
        var precision = this.getMaxPrecision(currentValue, ratio);
        return Math.pow(10, precision);
    };
    NzInputNumberComponent.prototype.upStep = function (val, rat) {
        var precisionFactor = this.getPrecisionFactor(val, rat);
        var precision = Math.abs(this.getMaxPrecision(val, rat));
        var result;
        if (typeof val === 'number') {
            result = ((precisionFactor * val + precisionFactor * this.nzStep * rat) / precisionFactor).toFixed(precision);
        }
        else {
            result = this.nzMin === -Infinity ? this.nzStep : this.nzMin;
        }
        return this.toNumber(result);
    };
    NzInputNumberComponent.prototype.downStep = function (val, rat) {
        var precisionFactor = this.getPrecisionFactor(val, rat);
        var precision = Math.abs(this.getMaxPrecision(val, rat));
        var result;
        if (typeof val === 'number') {
            result = ((precisionFactor * val - precisionFactor * this.nzStep * rat) / precisionFactor).toFixed(precision);
        }
        else {
            result = this.nzMin === -Infinity ? -this.nzStep : this.nzMin;
        }
        return this.toNumber(result);
    };
    NzInputNumberComponent.prototype.step = function (type, e, ratio) {
        var _this = this;
        if (ratio === void 0) { ratio = 1; }
        this.stop();
        e.preventDefault();
        if (this.nzDisabled) {
            return;
        }
        var value = this.getCurrentValidValue(this.parsedValue) || 0;
        var val = 0;
        if (type === 'up') {
            val = this.upStep(value, ratio);
        }
        else if (type === 'down') {
            val = this.downStep(value, ratio);
        }
        var outOfRange = val > this.nzMax || val < this.nzMin;
        if (val > this.nzMax) {
            val = this.nzMax;
        }
        else if (val < this.nzMin) {
            val = this.nzMin;
        }
        this.setValue(val);
        this.updateDisplayValue(val);
        this.isFocused = true;
        if (outOfRange) {
            return;
        }
        this.autoStepTimer = setTimeout(function () {
            _this[type](e, ratio);
        }, 300);
    };
    NzInputNumberComponent.prototype.stop = function () {
        if (this.autoStepTimer) {
            clearTimeout(this.autoStepTimer);
        }
    };
    NzInputNumberComponent.prototype.setValue = function (value) {
        if ("" + this.value !== "" + value) {
            this.onChange(value);
        }
        this.value = value;
        this.parsedValue = value;
        this.disabledUp = this.disabledDown = false;
        if (value || value === 0) {
            var val = Number(value);
            if (val >= this.nzMax) {
                this.disabledUp = true;
            }
            if (val <= this.nzMin) {
                this.disabledDown = true;
            }
        }
    };
    NzInputNumberComponent.prototype.updateDisplayValue = function (value) {
        var displayValue = isNotNil(this.nzFormatter(value)) ? this.nzFormatter(value) : '';
        this.displayValue = displayValue;
        this.inputElement.nativeElement.value = "" + displayValue;
    };
    NzInputNumberComponent.prototype.onKeyDown = function (e) {
        if (e.keyCode === UP_ARROW) {
            var ratio = this.getRatio(e);
            this.up(e, ratio);
            this.stop();
        }
        else if (e.keyCode === DOWN_ARROW) {
            var ratio = this.getRatio(e);
            this.down(e, ratio);
            this.stop();
        }
        else if (e.keyCode === ENTER) {
            this.updateDisplayValue(this.value);
        }
    };
    NzInputNumberComponent.prototype.writeValue = function (value) {
        this.value = value;
        this.setValue(value);
        this.updateDisplayValue(value);
        this.cdr.markForCheck();
    };
    NzInputNumberComponent.prototype.registerOnChange = function (fn) {
        this.onChange = fn;
    };
    NzInputNumberComponent.prototype.registerOnTouched = function (fn) {
        this.onTouched = fn;
    };
    NzInputNumberComponent.prototype.setDisabledState = function (disabled) {
        this.nzDisabled = disabled;
        this.cdr.markForCheck();
    };
    NzInputNumberComponent.prototype.focus = function () {
        this.focusMonitor.focusVia(this.inputElement, 'keyboard');
    };
    NzInputNumberComponent.prototype.blur = function () {
        this.inputElement.nativeElement.blur();
    };
    NzInputNumberComponent.prototype.ngOnInit = function () {
        var _this = this;
        this.focusMonitor.monitor(this.elementRef, true).subscribe(function (focusOrigin) {
            if (!focusOrigin) {
                _this.isFocused = false;
                _this.updateDisplayValue(_this.value);
                _this.nzBlur.emit();
                Promise.resolve().then(function () { return _this.onTouched(); });
            }
            else {
                _this.isFocused = true;
                _this.nzFocus.emit();
            }
        });
    };
    NzInputNumberComponent.prototype.ngOnChanges = function (changes) {
        if (changes.nzFormatter && !changes.nzFormatter.isFirstChange()) {
            var validValue = this.getCurrentValidValue(this.parsedValue);
            this.setValue(validValue);
            this.updateDisplayValue(validValue);
        }
    };
    NzInputNumberComponent.prototype.ngAfterViewInit = function () {
        if (this.nzAutoFocus) {
            this.focus();
        }
    };
    NzInputNumberComponent.prototype.ngOnDestroy = function () {
        this.focusMonitor.stopMonitoring(this.elementRef);
    };
    /** @nocollapse */ NzInputNumberComponent.ɵfac = function NzInputNumberComponent_Factory(t) { return new (t || NzInputNumberComponent)(ɵɵdirectiveInject(ElementRef), ɵɵdirectiveInject(ChangeDetectorRef), ɵɵdirectiveInject(FocusMonitor)); };
    /** @nocollapse */ NzInputNumberComponent.ɵcmp = ɵɵdefineComponent({ type: NzInputNumberComponent, selectors: [["nz-input-number"]], viewQuery: function NzInputNumberComponent_Query(rf, ctx) { if (rf & 1) {
            ɵɵstaticViewQuery(_c0, true);
        } if (rf & 2) {
            var _t;
            ɵɵqueryRefresh(_t = ɵɵloadQuery()) && (ctx.inputElement = _t.first);
        } }, hostVars: 10, hostBindings: function NzInputNumberComponent_HostBindings(rf, ctx) { if (rf & 2) {
            ɵɵclassProp("ant-input-number", true)("ant-input-number-focused", ctx.isFocused)("ant-input-number-lg", ctx.nzSize === "large")("ant-input-number-sm", ctx.nzSize === "small")("ant-input-number-disabled", ctx.nzDisabled);
        } }, inputs: { nzSize: "nzSize", nzMin: "nzMin", nzMax: "nzMax", nzParser: "nzParser", nzPrecision: "nzPrecision", nzPrecisionMode: "nzPrecisionMode", nzPlaceHolder: "nzPlaceHolder", nzStep: "nzStep", nzId: "nzId", nzDisabled: "nzDisabled", nzAutoFocus: "nzAutoFocus", nzFormatter: "nzFormatter" }, outputs: { nzBlur: "nzBlur", nzFocus: "nzFocus" }, exportAs: ["nzInputNumber"], features: [ɵɵProvidersFeature([
                {
                    provide: NG_VALUE_ACCESSOR,
                    useExisting: forwardRef((function () { return NzInputNumberComponent; })),
                    multi: true
                }
            ]), ɵɵNgOnChangesFeature], decls: 8, vars: 12, consts: [[1, "ant-input-number-handler-wrap"], ["unselectable", "unselectable", 1, "ant-input-number-handler", "ant-input-number-handler-up", 3, "mousedown", "mouseup", "mouseleave"], ["nz-icon", "", "nzType", "up", 1, "ant-input-number-handler-up-inner"], ["unselectable", "unselectable", 1, "ant-input-number-handler", "ant-input-number-handler-down", 3, "mousedown", "mouseup", "mouseleave"], ["nz-icon", "", "nzType", "down", 1, "ant-input-number-handler-down-inner"], [1, "ant-input-number-input-wrap"], ["autocomplete", "off", 1, "ant-input-number-input", 3, "disabled", "placeholder", "ngModel", "keydown", "keyup", "ngModelChange"], ["inputElement", ""]], template: function NzInputNumberComponent_Template(rf, ctx) { if (rf & 1) {
            ɵɵelementStart(0, "div", 0);
            ɵɵelementStart(1, "span", 1);
            ɵɵlistener("mousedown", function NzInputNumberComponent_Template_span_mousedown_1_listener($event) { return ctx.up($event); })("mouseup", function NzInputNumberComponent_Template_span_mouseup_1_listener() { return ctx.stop(); })("mouseleave", function NzInputNumberComponent_Template_span_mouseleave_1_listener() { return ctx.stop(); });
            ɵɵelement(2, "i", 2);
            ɵɵelementEnd();
            ɵɵelementStart(3, "span", 3);
            ɵɵlistener("mousedown", function NzInputNumberComponent_Template_span_mousedown_3_listener($event) { return ctx.down($event); })("mouseup", function NzInputNumberComponent_Template_span_mouseup_3_listener() { return ctx.stop(); })("mouseleave", function NzInputNumberComponent_Template_span_mouseleave_3_listener() { return ctx.stop(); });
            ɵɵelement(4, "i", 4);
            ɵɵelementEnd();
            ɵɵelementEnd();
            ɵɵelementStart(5, "div", 5);
            ɵɵelementStart(6, "input", 6, 7);
            ɵɵlistener("keydown", function NzInputNumberComponent_Template_input_keydown_6_listener($event) { return ctx.onKeyDown($event); })("keyup", function NzInputNumberComponent_Template_input_keyup_6_listener() { return ctx.stop(); })("ngModelChange", function NzInputNumberComponent_Template_input_ngModelChange_6_listener($event) { return ctx.onModelChange($event); });
            ɵɵelementEnd();
            ɵɵelementEnd();
        } if (rf & 2) {
            ɵɵadvance(1);
            ɵɵclassProp("ant-input-number-handler-up-disabled", ctx.disabledUp);
            ɵɵadvance(2);
            ɵɵclassProp("ant-input-number-handler-down-disabled", ctx.disabledDown);
            ɵɵadvance(3);
            ɵɵproperty("disabled", ctx.nzDisabled)("placeholder", ctx.nzPlaceHolder)("ngModel", ctx.displayValue);
            ɵɵattribute("id", ctx.nzId)("autofocus", ctx.nzAutoFocus ? "autofocus" : null)("min", ctx.nzMin)("max", ctx.nzMax)("step", ctx.nzStep);
        } }, directives: [NzIconDirective, DefaultValueAccessor, NgControlStatus, NgModel], encapsulation: 2, changeDetection: 0 });
    __decorate([
        InputBoolean(),
        __metadata("design:type", Object)
    ], NzInputNumberComponent.prototype, "nzDisabled", void 0);
    __decorate([
        InputBoolean(),
        __metadata("design:type", Object)
    ], NzInputNumberComponent.prototype, "nzAutoFocus", void 0);
    return NzInputNumberComponent;
}());
/*@__PURE__*/ (function () { ɵsetClassMetadata(NzInputNumberComponent, [{
        type: Component,
        args: [{
                selector: 'nz-input-number',
                exportAs: 'nzInputNumber',
                template: "\n    <div class=\"ant-input-number-handler-wrap\">\n      <span\n        unselectable=\"unselectable\"\n        class=\"ant-input-number-handler ant-input-number-handler-up\"\n        (mousedown)=\"up($event)\"\n        (mouseup)=\"stop()\"\n        (mouseleave)=\"stop()\"\n        [class.ant-input-number-handler-up-disabled]=\"disabledUp\"\n      >\n        <i nz-icon nzType=\"up\" class=\"ant-input-number-handler-up-inner\"></i>\n      </span>\n      <span\n        unselectable=\"unselectable\"\n        class=\"ant-input-number-handler ant-input-number-handler-down\"\n        (mousedown)=\"down($event)\"\n        (mouseup)=\"stop()\"\n        (mouseleave)=\"stop()\"\n        [class.ant-input-number-handler-down-disabled]=\"disabledDown\"\n      >\n        <i nz-icon nzType=\"down\" class=\"ant-input-number-handler-down-inner\"></i>\n      </span>\n    </div>\n    <div class=\"ant-input-number-input-wrap\">\n      <input\n        #inputElement\n        autocomplete=\"off\"\n        class=\"ant-input-number-input\"\n        [attr.id]=\"nzId\"\n        [attr.autofocus]=\"nzAutoFocus ? 'autofocus' : null\"\n        [disabled]=\"nzDisabled\"\n        [attr.min]=\"nzMin\"\n        [attr.max]=\"nzMax\"\n        [placeholder]=\"nzPlaceHolder\"\n        [attr.step]=\"nzStep\"\n        (keydown)=\"onKeyDown($event)\"\n        (keyup)=\"stop()\"\n        [ngModel]=\"displayValue\"\n        (ngModelChange)=\"onModelChange($event)\"\n      />\n    </div>\n  ",
                providers: [
                    {
                        provide: NG_VALUE_ACCESSOR,
                        useExisting: forwardRef((function () { return NzInputNumberComponent; })),
                        multi: true
                    }
                ],
                changeDetection: ChangeDetectionStrategy.OnPush,
                encapsulation: ViewEncapsulation.None,
                host: {
                    '[class.ant-input-number]': 'true',
                    '[class.ant-input-number-focused]': 'isFocused',
                    '[class.ant-input-number-lg]': "nzSize === 'large'",
                    '[class.ant-input-number-sm]': "nzSize === 'small'",
                    '[class.ant-input-number-disabled]': 'nzDisabled'
                }
            }]
    }], function () { return [{ type: ElementRef }, { type: ChangeDetectorRef }, { type: FocusMonitor }]; }, { nzBlur: [{
            type: Output
        }], nzFocus: [{
            type: Output
        }], inputElement: [{
            type: ViewChild,
            args: ['inputElement', { static: true }]
        }], nzSize: [{
            type: Input
        }], nzMin: [{
            type: Input
        }], nzMax: [{
            type: Input
        }], nzParser: [{
            type: Input
        }], nzPrecision: [{
            type: Input
        }], nzPrecisionMode: [{
            type: Input
        }], nzPlaceHolder: [{
            type: Input
        }], nzStep: [{
            type: Input
        }], nzId: [{
            type: Input
        }], nzDisabled: [{
            type: Input
        }], nzAutoFocus: [{
            type: Input
        }], nzFormatter: [{
            type: Input
        }] }); })();

/**
 * @license
 * Copyright Alibaba.com All Rights Reserved.
 *
 * Use of this source code is governed by an MIT-style license that can be
 * found in the LICENSE file at https://github.com/NG-ZORRO/ng-zorro-antd/blob/master/LICENSE
 */
var NzInputNumberModule = /** @class */ (function () {
    function NzInputNumberModule() {
    }
    /** @nocollapse */ NzInputNumberModule.ɵmod = ɵɵdefineNgModule({ type: NzInputNumberModule });
    /** @nocollapse */ NzInputNumberModule.ɵinj = ɵɵdefineInjector({ factory: function NzInputNumberModule_Factory(t) { return new (t || NzInputNumberModule)(); }, imports: [[CommonModule, FormsModule, NzIconModule]] });
    return NzInputNumberModule;
}());
(function () { (typeof ngJitMode === "undefined" || ngJitMode) && ɵɵsetNgModuleScope(NzInputNumberModule, { declarations: [NzInputNumberComponent], imports: [CommonModule, FormsModule, NzIconModule], exports: [NzInputNumberComponent] }); })();
/*@__PURE__*/ (function () { ɵsetClassMetadata(NzInputNumberModule, [{
        type: NgModule,
        args: [{
                imports: [CommonModule, FormsModule, NzIconModule],
                declarations: [NzInputNumberComponent],
                exports: [NzInputNumberComponent]
            }]
    }], null, null); })();

/**
 * @license
 * Copyright Alibaba.com All Rights Reserved.
 *
 * Use of this source code is governed by an MIT-style license that can be
 * found in the LICENSE file at https://github.com/NG-ZORRO/ng-zorro-antd/blob/master/LICENSE
 */

/**
 * Generated bundle index. Do not edit.
 */

export { NzInputNumberComponent, NzInputNumberModule };
//# sourceMappingURL=ng-zorro-antd-input-number.js.map
