import React, { useState } from 'react';
import { Form, Input, Button, Modal } from 'antd';
import md5 from 'md5';
import { changePassword } from '@/services/user'

const layout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 14 },
};
const tailLayout = {
  wrapperCol: { offset: 6, span: 14 },
};

export default (props) => {
  const { visible, onSuccess, onCancel } = props

  const [loading, setLoading] = useState(false)

  const handleFinish = (values) => {
    const data = {
      originPassword: md5(values.originPassword),
      newPassword: md5(values.newPassword)
    }

    setLoading(true)
    changePassword(data).then(() => {
      setLoading(false)
      if (onSuccess) {
        onSuccess()
      }
    })
      .catch((err) => {
        console.log(err.message)
        setLoading(false)
      });
  }

  const handleCancel = () => {
    if (onCancel) {
      onCancel()
    }
  }

  return (
    <Modal visible={visible} title="修改密码" footer={null} onCancel={handleCancel}>
      <Form {...layout} onFinish={handleFinish}>
        <Form.Item
          name="originPassword"
          label="原密码"
          rules={[{ required: true, message: '请填写原密码!' }]}
        >
          <Input.Password placeholder="请填写原密码" />
        </Form.Item>
        <Form.Item
          name="newPassword"
          label="新密码"
          rules={[{ required: true, message: '请填写新密码!' }]}
        >
          <Input.Password placeholder="请填写新密码" />
        </Form.Item>
        <Form.Item
          name="newPassword2"
          label="确认密码"
          rules={[
            { required: true, message: '请填写新密码!' },
            ({ getFieldValue }) => ({
              validator(_, value) {
                if (!value || getFieldValue('newPassword') === value) {
                  return Promise.resolve();
                }
                return Promise.reject(new Error('两次输入密码不一致!'));
              },
            })
          ]}
        >
          <Input.Password placeholder="确认密码需要与新密码保持一致" />
        </Form.Item>
        <Form.Item {...tailLayout}>
          <Button loading={loading} type="primary" htmlType="submit">
            提交
          </Button>
          <Button htmlType="button" onClick={handleCancel} style={{ marginLeft: '4em' }}>
            取消
          </Button>
        </Form.Item>
      </Form>
    </Modal>
  )
}
