import React, { useState , forwardRef , useEffect } from 'react';
import { Form , Input , Button } from 'antd';
import "./Index.scss";
import axios from 'axios';

function Register({ form , successFunc , visible }){
  const [ active , setActive ] = useState(false);
  const [ loading , setLoading ] = useState(false);

  const { getFieldDecorator, validateFields , setFieldsValue , getFieldsValue } = form;

  useEffect(()=>{
    if(!visible){
      setFieldsValue({
        mail:undefined,
        password:undefined,
        passwordAgain:undefined
      })
    }
  },[visible])

  function changeInput(){
    const { mail , password , passwordAgain } = getFieldsValue();
    if(mail && password && passwordAgain){
      setActive(true);
    }else{
      setActive(false);
    }
  }

  function registerFunc(){
    validateFields((error,values)=>{
      if(!error){
        setLoading(true);
        const url = `/accounts/register.json`;
        axios.post(url,{
          ...values
        }).then(result=>{
          if(result && result.data && result.data.status === 0){
            successFunc(result.data.data);
            setLoading(false);
            setFieldsValue({
              mail:undefined,
              password:undefined,
              passwordAgain:undefined
            })
          }
        }).catch(error=>{})
      }
    })
  }

  function checkRepeat(rule, value, callback){
    const { password } = getFieldsValue();
    if(!value){
      callback();
    }else if(value !== password){
      callback("两次输入的密码不一致！");
    }else{
      callback();
    }
    callback();
  }
  return(
    <Form>
      <Form.Item>
        {getFieldDecorator("mail",{
          rules:[{required:true,message:"请输入注册账号"}]
        })(
          <Input placeholder="请输入邮箱账号" onChange={changeInput}/>
        )}
      </Form.Item>
      <Form.Item >
        {getFieldDecorator("password",{
          rules:[{required:true,message:"请输入注册密码"}]
        })(
          <Input.Password placeholder="请输入注册密码" onChange={changeInput}/>
        )}
      </Form.Item>
      <Form.Item >
        {getFieldDecorator("passwordAgain",{
          rules:[
            {required:true,message:"请再次输入密码"},
            {validator:checkRepeat}
          ]
        })(
          <Input.Password placeholder="请再次输入密码" onChange={changeInput}/>
        )}
      </Form.Item>
      {
        active ?
        <Button className="subbtn activeBtn" loading={loading} onClick={registerFunc}>注册</Button>
        :
        <span className="subbtn">注册</span>
      }
    </Form>
  )
}
export default Form.create()(forwardRef(Register));