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

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

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


  function changeInput(){
    const { login , password } = getFieldsValue();
    if(login && password){
      setActive(true);
    }else{
      setActive(false);
    }
  }
  function loginFunc() {
    validateFields((error,values)=>{
      if(!error){
        setLoading(true);
        const url = `/accounts/login.json`;
        axios.post(url,{
          ...values
        }).then(result=>{
          successFunc(result.data.data);
          setLoading(false);
          if(!values.savePass){
            setFieldsValue({
              login:undefined,
              password:undefined,
              savePass:false
            })
          }
        }).catch(error=>{})
      }
    })
  }
  return(
    <Form>
      <Form.Item>
        {getFieldDecorator("login",{
          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>
      {
        active ?
        <Button className="subbtn activeBtn" loading={loading} onClick={loginFunc}>登录</Button>
        :
        <span className="subbtn">登录</span>
      }
      <Form.Item className="saveitem">
        {getFieldDecorator("savePass",
          {rules:[]},{valuePropName:"checked"}
        )(
          <Checkbox>记住密码</Checkbox>
        )}
      </Form.Item>
    </Form>
  )
}
export default Form.create()(forwardRef(LoginModal));