import './index.less'
import {Input as TInput} from 'tdesign-react';
import {Component} from "react";

class InputNumber extends Component<any, any> {
    constructor(props) {
        super(props);
        this.state = {
            value: this.props.value,
        }
        this.name = props.name ?? '';
    }

    onSet = (value: number) => {
        this.setState({
            value: value
        })
    }
    onReduce = () => {
        const {value} = this.props;
        this.onSet(value - 1);
        this.inputChange(value - 1);
    }

    onAdd = () => {
        const {value} = this.props;
        this.onSet(value + 1);
        this.inputChange(value + 1);
    }

    inputChange = (value: number) => {
        // 提交输入框的值
        if (this.props.onChange) {
            this.props.onChange(value, this.name);
        }
    }

    render() {
        const {align, addAndSubtract} = this.props;
        const realAlign = align ?? 'left';
        // 是否显示加减按钮
        const realAddAndSubtract = addAndSubtract ?? true;
        return (
            <div
                className={['c-reset-input-number-box', realAddAndSubtract ? 'c-reset-input-number-add' : ''].join(' ')}>
                {
                    realAddAndSubtract && (
                        <div className='reduce' onClick={this.onReduce}>-</div>
                    )
                }
                <TInput className={'c-reset-input-number'} align={realAlign} type={'number'}
                        onChange={this.inputChange}
                        value={this.props.value}
                />
                {
                    realAddAndSubtract && (
                        <div className='add' onClick={this.onAdd}>+</div>
                    )
                }
            </div>
        );
    }
}

export default InputNumber;

