import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import { Form, Icon, Input, Button, notification } from 'antd';
const FormItem = Form.Item;
import styles from './index.less';


class UpdatePassWord extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      submitting: false,
    };
  }
  componentWillMount() {
    const { dispatch } = this.props;
    const additems = [
      {
        key: "/buyer/updatePassword",
        title: "修改密码"
      }
    ];
    dispatch({
      type: "global/additems",
      additems: additems
    });
  }
  handleSubmit = (e) => {
    e.preventDefault();
    const { dispatch } = this.props;
    this.props.form.validateFields((err, values) => {
      if (values.modifyPassword != values.confirmPassword) {
        return false;
      }
      if (!err) {
        this.setState({
          submitting: true
        });
        dispatch({
          type: 'login/updatePassword',
          payload: {
            password: values.modifyPassword
          },
        }).finally(() => {
          const { updateResult, hideModel } = this.props;
          if (updateResult && updateResult.status === 1) {
            localStorage.setItem("lastLoginIsRemember", false);
            if (hideModel) {
              hideModel();
              dispatch(routerRedux.push("./"));
            } else {
              notification.success({
                message: "修改成功",
                description: `密码修改成功,2秒后跳转到登录页面，请使用新密码进行登录！`,
                duration: 2
              });
              setTimeout(() => {
                dispatch(routerRedux.push("/gotoLogin"));
              }, 2000);
            }
          } else {
            notification.error({
              message: "修改失败",
              description: `密码修改失败：${updateResult.msg || ""}`,
              duration: 2
            });
          }
          this.setState({
            submitting: false
          });
        });
      }
    });
  };
  checkPassword = (rule, value, callback) => {
    const form = this.props.form;
    if (value && value !== form.getFieldValue('modifyPassword')) {
      callback("与新密码不一致，请重新输入!");
    } else {
      callback();
    }
  }
  render() {
    const { submitting } = this.state;
    const { width } = this.props;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 14 },
      },
    };
    const tailFormItemLayout = {
      wrapperCol: {
        xs: {
          span: 24,
          offset: 0,
        },
        sm: {
          span: 14,
          offset: 6,
        },
      },
    };
    const { getFieldDecorator } = this.props.form;
    const newRules = [
      { required: true, message: '请输入新密码!' },
      { min: 6, message: '密码长度至少6位字符!' },
    ];
    const confirmRules = [
      { required: true, message: '请输入确认密码!' },
      { validator: this.checkPassword.bind(this) }
    ];
    const style = {
      width: width ? `${width}px` : "1200px"
    };
    return (
      <div className={styles.updatePassWordBox} style={style}>
        <Form onSubmit={this.handleSubmit} className={styles.fromBox}>
          <FormItem
            {...formItemLayout}
            label="新密码："
          >
            {getFieldDecorator('modifyPassword', {
              rules: newRules,
            })(
              <Input className={styles.input_40} prefix={<Icon type="lock" style={{ fontSize: 13 }} />} type="password" placeholder="请输入新密码" />
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="确认密码："
          >
            {getFieldDecorator('confirmPassword', {
              rules: confirmRules,
            })(
              <Input className={styles.input_40} prefix={<Icon type="lock" style={{ fontSize: 13 }} />} type="password" placeholder="请输入确认密码" />
            )}
          </FormItem>
          <FormItem
            {...tailFormItemLayout}
          >
            <Button className={styles.input_40} loading={this.state.submitting} style={{ width: "100%" }} type="primary" htmlType="submit">
              完成
            </Button>
          </FormItem>
        </Form>
      </div>
    );
  }
}

export default connect(state => ({
  updateResult: state.login.updateResult
}))(Form.create()(UpdatePassWord));

