import React, { Component } from 'react';
import { List, InputItem } from 'antd-mobile';
import { createForm } from 'rc-form';
import './view.scss';

// 通过自定义 moneyKeyboardWrapProps 修复虚拟键盘滚动穿透问题
// https://github.com/ant-design/ant-design-mobile/issues/307
// https://github.com/ant-design/ant-design-mobile/issues/163
const isIPhone = new RegExp('\\biPhone\\b|\\biPod\\b', 'i').test(window.navigator.userAgent);
let moneyKeyboardWrapProps;
if (isIPhone) {
  moneyKeyboardWrapProps = {
    onTouchStart: e => e.preventDefault(),
  };
}
class H5NumberInput extends Component {
  constructor(props) {
    super(props);
    this.teReg1 = /^(([1-9]\d*)|0)(\.\d{0,2}?)?$/;
    this.teReg2 = /^(([1-9]\d*)|0)?$/;
    this.state = {
      type: 'money',
      teReg: this.props.currency !== 'JPY' ? this.teReg1 : this.teReg2,
    };
  }
  componentWillReceiveProps(nextProps) {
    if (nextProps.currency === 'JPY') {
      this.setState({
        teReg: this.teReg2,
      });
    } else {
      this.setState({
        teReg: this.teReg1,
      });
    }
  }

  handleInputChange(value) {
    const reg = this.state.teReg;
    let inAmount = value;
    if (/^0[1-9]$/.test(inAmount)) {
      inAmount = Number(inAmount);
    }
    if (inAmount && !reg.test(inAmount)) {
      if (inAmount === '.') {
        inAmount = '0.';
      } else {
        inAmount = this.props.value;
      }
    }
    this.props.getInputValue(inAmount);
  }
  render() {
    const { type } = this.state;
    return (
      <div className="H5NumberInputWrap">
        <List className="H5NumberInput">
          <InputItem
            type={type}
            value={this.props.value}
            placeholder={this.props.placeHolder || '请输入交易金额'}
            moneyKeyboardAlign="left"
            onChange={value => this.handleInputChange(value)}
            onBlur={this.props.onBlur}
            clear
            moneyKeyboardWrapProps={moneyKeyboardWrapProps}
          />
        </List>
      </div>
    );
  }
}
export default H5NumberInput;
