import React from 'react';
import { View } from '@tarojs/components';
import { Field, Button } from '@antmjs/vantui';
import { getCaptcha } from '@/services/comm';

export default (props) => {
  const { onNext } = props;

  const [loading, setLoading] = React.useState(false);
  const [phone, setPhone] = React.useState();
  const [phoneErr, setPhoneErr] = React.useState();
  const [captcha, setCaptcha] = React.useState();
  const [captchaErr, setCaptchaErr] = React.useState();
  const [disabled, setDisabled] = React.useState(false);
  const [sec, setSec] = React.useState(0);

  const btnText = disabled ? `剩余 ${sec} 秒` : '获取验证码';

  const onCaptcha = () => {
    if (!phone || phone.length != 11) {
      setPhoneErr('请输入正确的手机号')
      return;
    } else {
      setPhoneErr();
    }
    
    setLoading(true);
    getCaptcha(phone).then(() => {
      setLoading(false);
      let left = 60;
      
      setDisabled(true);
      setSec(left --);
      const ticker = setInterval(() => {
        left -= 1;
        setSec(left);
  
        if (left <= 1) {
          setDisabled(false);
          clearInterval(ticker);
        }
      }, 1000);
    }).catch(() => {
      setLoading(false);
    });
  }

  const handleNext = () => {
    if (!phone) {
      setPhoneErr('请输入手机号');
    }

    if (!captcha) {
      setCaptchaErr('请输入验证码')
    }

    if (!phone || !captcha) {
      return;
    }

    onNext({phone, captcha});
  }
  
  return (
    <View>
      <View className="title">找回密码</View>
      <View className="form-box">
        <Field
          value={phone}
          loading={loading}
          placeholder="请输入注册手机号"
          onChange={e => setPhone(e.detail)}
          errorMessage={phoneErr}
          renderButton={
            <Button
              round
              size="small"
              type="primary"
              disabled={disabled}
              onClick={onCaptcha}
            >
              {btnText}
            </Button>
          }
        ></Field>
        <Field
          value={captcha}
          placeholder="请输入验证码"
          errorMessage={captchaErr}
          onChange={e => setCaptcha(e.detail)}
        ></Field>
      </View>
      <View className="form-act">
        <View>
        </View>
        <View>
          <Button block type="primary" size="small" onClick={handleNext}>下一步</Button>
        </View>
      </View>
    </View>
  )
}
