import React, {PureComponent} from 'react';
import { Input } from 'antd';
import styles from '../index.less'

const formatNumber = (value) => {
    value += '';
    const list = value.split('.');
    const prefix = list[0].charAt(0) === '-' ? '-' : '';
    let num = prefix ? list[0].slice(1) : list[0];
    let result = '';
    while (num.length > 3) {
        result = `,${num.slice(-3)}${result}`;
        num = num.slice(0, num.length - 3);
    }
    if (num) {
        result = num + result;
    }
    return `${prefix}${result}${list[1] ? `.${list[1]}` : ''}`;
}

class NumberInput extends PureComponent {
    onChange = e => {
        const { value } = e.target;
        const reg = /^\d*?$/;
        if ((!isNaN(value) && reg.test(value)) || value === '') {
            this.props.onChange(value);
        }
    };

    // '.' at the end or only '-' in the input box.
    onBlur = () => {
        const { value, onBlur, onChange } = this.props;
        let valueTemp = value;
        if (value.charAt(value.length - 1) === '.') {
            valueTemp = value.slice(0, -1);
        }
        onChange(valueTemp.replace(/0*(\d+)/, '$1'));
        if (onBlur) {
            onBlur();
        }
    };

    render() {
        const { placeholder, min } = this.props;

        return (
            <Input
                min={min !== 0 ? min : 0}
                {...this.props}
                onChange={this.onChange}
                // onBlur={this.onBlur}
                placeholder={placeholder !== "" ? placeholder : ""}
                // maxLength={25}
            />
        );
    }
}

export default NumberInput;
