// 核心库
import React, { Component } from 'react'
import { connect } from 'dva'
import { withRouter } from 'dva/router'
// 组件库
import { Modal, Form, Input, Icon, message } from 'antd'
import MD5 from 'md5'

const FormItem = Form.Item

class ModifyPassword extends Component {
  constructor (props) {
    super(props)
    this.state = {
      visible: false
    }
  }

  visibleModal = () => {
    this.setState({ visible: true })
  }

  handleCancelModifyPass = () => { // 退出修改密码
    const { form } = this.props
    form.resetFields()
    this.setState({ visible: false })
  };

  saveModifiedPassword = () => {
    const { login, form, dispatch } = this.props
    const UserId = login.userId
    form.validateFields((err, values) => {
      if (!err) {
        const { originalPass, newPassword, confirmPassword } = values
        if (newPassword === confirmPassword) {
          dispatch({
            type: "login/modifyPassword",
            payload: {
              Keyword: UserId,
              Parameter1: MD5(originalPass),
              Parameter2: MD5(newPassword)
            }
          }).then(res => {
            if (res) {
              message.success("密码修改成功，请重新登录")
              localStorage.removeItem("accessToken")
              this.props.history.push({ pathname: '/login' })
            }
          })
        }
      }
    })
  }

  render () {
    const { children, form } = this.props
    const { getFieldDecorator } = form
    const { visible } = this.state
    const isComplex = (rule, value, callBack) => {
      let passwordReg =/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,15}$/;
      if (!passwordReg.test(value)) {
        callBack('请设置6-15位的密码,至少包含字母、数字')
      } else {
        callBack()
      }
    }
    const customValidator = (rule, value, callBack) => {
      const newPassword = form.getFieldValue("newPassword")
      if (newPassword !== value) {
        callBack('密码输入不一致，请重新输入！')
      } else {
        callBack()
      }
    }

    return <React.Fragment>
      <span onClick={this.visibleModal}>{children}</span>
      <Modal
        title="修改密码"
        width={300}
        maskClosable={false}
        visible={visible}
        onOk={this.saveModifiedPassword}
        onCancel={this.handleCancelModifyPass}>
        <Form className="login-form">
          <FormItem>
            {getFieldDecorator('originalPass', {
              validateTrigger: 'onBlur',
              rules: [
                { required: true, whitespace: true, message: '请输入原密码!' },
              ],
            })(
              <Input
                prefix={<Icon type="key"
                  style={{ color: 'rgba(0,0,0,.25)' }} />}
                type="password"
                placeholder="原密码"
              />
            )}
          </FormItem>
          <FormItem>
            {getFieldDecorator('newPassword', {
              validateTrigger: 'onBlur',
              rules: [
                { required: true, whitespace: true, message: '请输入新密码!' },
                { validator: isComplex },
              ],
            })(
              <Input
                prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />}
                type="password"
                placeholder="新密码"
              />
            )}
          </FormItem>
          <FormItem>
            {getFieldDecorator('confirmPassword', {
              validateTrigger: 'onBlur',
              rules: [
                { required: true, whitespace: true, message: '请输入新密码!' },
                { validator: customValidator },
              ],
            })(
              <Input
                prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />}
                type="password"
                placeholder="确认密码"
              />
            )}
          </FormItem>
        </Form>
      </Modal>
    </React.Fragment>
  }
}

export default withRouter(connect(({ login }) => ({ login }))(Form.create()(ModifyPassword)))
