import { message, Form, Input, Modal } from 'antd';
import { history, useModel } from 'umi';
import md5 from 'js-md5';
import { updatePwd } from '@/services/ant-design-pro/api';

/**
 * 修改密码
 * @param props
 * @constructor
 */
const UpdatePassword = (props: any) => {
  const { initialState, setInitialState } = useModel('@@initialState');
  const { visible, onCancel } = props;
  const [form] = Form.useForm();

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

  const onFinish = () => {
    form.validateFields().then((values) => {
      // const reg = /^(?=.*\d)(?=.*[a-zA-Z])(?=.*[~!@#$%^&*])[\da-zA-Z~!@#$%^&*]{8,}$/;
      // if (!reg.test(values.new_password)) {
      //   message.warning('密码必须为数字、字母和特殊字符(!@#$%^&*)的组合，且不能小于8位');
      //   return;
      // }
      const formData = {
        old_password: md5(values.old_password),
        new_password: md5(values.new_password),
      };
      updatePwd(formData).then((res: any) => {
        if (res.code === 0) {
          message.success('密码更新成功！');
          console.log(initialState);
          setInitialState((s) => ({ ...s, currentUser: undefined }));
          history.push(`/user/login`);
        }
      });
    });
  };

  const formItemLayout = {
    labelCol: {
      span: 6,
    },
    wrapperCol: {
      span: 16,
    },
  };

  return (
    <Modal title="修改密码" open={visible} width={500} onOk={onFinish} onCancel={handleCancel}>
      <Form form={form}>
        <Form.Item
          {...formItemLayout}
          name="old_password"
          label="旧密码"
          hasFeedback
          rules={[{ required: true, message: '请输入旧密码' }]}
        >
          <Input type="password" placeholder="请输入旧密码" />
        </Form.Item>
        <Form.Item
          {...formItemLayout}
          name="new_password"
          label="新密码"
          hasFeedback
          rules={[{ required: true, message: '请输入新密码' }]}
        >
          <Input type="password" placeholder="请输入新密码" />
        </Form.Item>
        <Form.Item
          {...formItemLayout}
          name="confirm_new_password"
          label="确认新密码"
          hasFeedback
          rules={[
            { required: true, message: '请输入确认新密码' },
            ({ getFieldValue }) => ({
              validator(_, value) {
                if (!value || getFieldValue('new_password') === value) {
                  return Promise.resolve();
                }
                return Promise.reject(new Error('两次密码输入不一致！'));
              },
            }),
          ]}
        >
          <Input type="password" placeholder="请再次输入新密码" />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default UpdatePassword;
