import React, { PureComponent } from "react";
import { connect } from "dva";
import { Input, Icon } from "antd";
import styles from "./index.less";

class GoodsBuyIpt extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      val: this.props.num
    };
  }
  componentWillReceiveProps(nextProps) {
    this.setState({
      val: nextProps.num
    });
  }
  numChange(e) {
    e.preventDefault();
    let value = e.target.value == "" ? 0 : e.target.value;
    const { max } = this.props;
    if (max) {
      if (value >= max) {
        value = max;
      }
    }
    this.setState({
      val: value
    });
    this.props.onChange(value);
  }
  lessHandle(e) {
    e.preventDefault();
    let { val } = this.state;
    let { step } = this.props;
    val = parseFloat(val || "0");
    step = parseFloat(step || 1);
    if (val < step) {
      val = 0;
    } else {
      val -= step;
    }
    this.setState({
      val: val
    });
    this.props.onChange(val);
  }
  addHandle(e) {
    e.preventDefault();
    let { val } = this.state;
    let { max, step } = this.props;
    val = parseFloat(val || "0");
    step = parseFloat(step || 1);
    max = parseInt(max || "9999");
    if (val >= max - step) {
      val = max;
    } else {
      val += step;
    }
    this.setState({
      val: val
    });
    this.props.onChange(val);
  }
  render() {
    const { step, disabled } = this.props;
    const prefixHtml = () => (
      <Icon onClick={this.lessHandle.bind(this)} type="minus" />
    );
    const suffixHtml = () => (
      <Icon onClick={this.addHandle.bind(this)} type="plus" />
    );
    return (
      <div className={styles.goodsBuyIpt}>
        <Input
          disabled={disabled ? true : false}
          value={this.state.val}
          onChange={this.numChange.bind(this)}
          prefix={prefixHtml()}
          suffix={suffixHtml()}
        />
      </div>
    );
  }
}
export default GoodsBuyIpt;
