import './index.less'
import {InputNumber as TInputNumber} from 'tdesign-react';
import {useState, Component} from "react";

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

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

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

    inputChange = (value: number) => {

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

    }

    render() {
        const {align, addAndSubtract, onChange} = 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>
                    )
                }
                <TInputNumber className={'c-reset-input-number'} align={realAlign}
                              onChange={this.inputChange}
                              theme="normal"
                              defaultValue={1}
                              value={this.props.value}
                />
                {
                    realAddAndSubtract && (
                        <div className='add' onClick={this.onAdd}>+</div>
                    )
                }
            </div>
        );
    }
}

export default InputNumber;

