import React, { useState } from 'react';
import { connect } from 'dva';
import md5 from "md5";
import { Form, Input, Button } from 'antd'
import styles from './style.less';

const buttonItemLayout = {
  wrapperCol: { span: 14, offset: 4 },
}

const formItemLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 18 },
}

const LoginForm = React.forwardRef((props, ref) => {
  const { form, dispatch } = props;
  const { getFieldDecorator, validateFields } = form;

  const [loading, setLoading] = useState(false)

  const handleSubmit = (e) => {
    e.preventDefault();
    validateFields((err, values) => {
      if (!err) {
        try {
          setLoading(true)
          dispatch({
            type: 'login/login',
            payload: { ...values, loginPassword: md5(values.loginPassword) },
          }).then(() => {
            setLoading(false)
          });
        } catch (e) {
          console.error(e)
          setLoading(false)
        }
      }
    });
  }

  return (
    <div className={styles['login-form-wapper']}>
      <div className={styles.main}>
        <div className={styles['login-wedget']}>
          <h3>欢迎来到新联家</h3>
          <img src="http://yz-websit.oss-cn-hangzhou.aliyuncs.com/xlk/login-wedget.png" alt="" />
        </div>
        <div className={styles['login-form']}>
          <Form onSubmit={handleSubmit}>
            <Form.Item label="用户名" {...formItemLayout} colon={false}>
              {getFieldDecorator('loginName', {
                rules: [{ required: true, message: '请输入用户名' }]
              })(<Input />)}          
            </Form.Item>
            <Form.Item label="密 码" {...formItemLayout} colon={false}>
              {getFieldDecorator('loginPassword', {
                rules: [{ required: true, message: '请输入密码' }]
              })(<Input.Password visibilityToggle={false}/>)}          
            </Form.Item>

            <Button
              loading={loading}
              htmlType="submit"
              className={styles['login-form-button']}
            >登录</Button>
          </Form>
        </div>
      </div>
    </div>
  )
});

export default connect(({ login, loading }) => ({
  userLogin: login,
  submitting: loading.effects['login/login'],
}))(Form.create({})(LoginForm));
