import React, { useEffect, useState } from 'react'
import { fetch, apis } from '@/utils/request'

const getCaptcha = fetch(apis.image.captcha)

export default props => {
  const [ver, setVer] = useState(0)
  const [captcha, setCaptcha] = useState({image: '验证码'})

  const handleClick = () => {
    setVer(ver + 1)
  }

  useEffect(() => {
    getCaptcha().then(res => {
      setCaptcha(res)
      if (props.onChange) {
        props.onChange(res.key)
      }
    })
  }, [ver])

  return (
    <img src={captcha.image} width="100%" height="40" onClick={handleClick} style={{cursor: 'pointer'}} />
  )
}
