import React, { useEffect, useState } from 'react'
import { Input, InputNumber, Tooltip } from 'antd'

const isEmpty = v => v === undefined || v === null

export default (props) => {
  const [preVal, setPreVal] = useState(props.value)
  const [val1, setVal1] = useState(null)
  const [val2, setVal2] = useState(null)

  const handleChange = inx => e => {
    const val = e.target.value
    let v1 = val1
    let v2 = val2
    if (inx === 0) {
      v1 = val
      setVal1(val)
    } else {
      v2 = val
      setVal2(val)
    }

    if (!isEmpty(v1) && !isEmpty(v2)) {
      const lastVal = `${v1},${v2}`
      props.onChange(lastVal)
    }
  }

  useEffect(() => {
    if (!preVal && props.value) {
      const vals = (props.value || '').split(',')
      if (val1 !== vals[0]) {
        setVal1(vals[0])
      }
      if (val2 !== vals[1]) {
        setVal2(vals[1])
      }
      setPreVal(props.value)
    }
  }, [preVal, props.value])

  return (
    <Tooltip title={props.tip}>
      <Input.Group compact>
        <Input
          value={val1}
          onChange={handleChange(0)}
          style={{ width: 'calc(50% - 15px)', textAlign: 'center', borderRight: 0  }}
          placeholder="小值"
        />
        <Input
          style={{
            width: '30px',
            borderLeft: 0,
            borderRight: 0,
            pointerEvents: 'none',
            backgroundColor: '#fff',
          }}
          value="-"
        />
        <Input
          value={val2}
          onChange={handleChange(1)}
          style={{ width: 'calc(50% - 15px)', textAlign: 'center', borderLeft: 0 }}
          placeholder="大值"
        />
      </Input.Group>
    </Tooltip>
  )
}
