import React, { forwardRef, useImperativeHandle, useState, useRef, useEffect } from 'react';
import { Modal, Input, notification } from 'antd';
import { Form } from '@ant-design/compatible';

import { resetPassword } from '../../../service';

const FormComponent = props => {
  const { record = {}, form } = props;
  const { getFieldDecorator, setFieldsValue, getFieldValue } = form;
  const [inputType, setInputType] = useState('text');
  const [confirmInputType, setConfirmInputType] = useState('text');

  const handlepassword = (rule, value, callback) => {
    if (value && value !== getFieldValue('newPassword')) {
      callback('两次输入不一致！');
    }
    // Note: 必须总是返回一个 callback，否则 validateFieldsAndScroll 无法响应
    callback();
  };

  // 处理初始化密码自动填充函数
  const handlePasswordChange = (e, fn) => {
    if (e.target.value) {
      fn('password');
    } else {
      fn('text');
    }
  };

  const formLayout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 20 },
  };
  const formRules = {
    newPassword: [
      { required: true, message: '请设置新密码' },
      {
        pattern: /^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[\W_]).{13,18}$/g,
        message: '密码格式错误',
      },
    ],
    password: [
      { required: true, message: '请确认新密码' },
      { validator: handlepassword, message: '两次密码不一致' },
    ],
  };

  const rulesHandler = name => ({
    rules: formRules[name],
  });

  useEffect(() => {
    setFieldsValue(record);
  }, [record]);

  return (
    <Form {...formLayout}>
      <Form.Item label="用户名">{record.name}</Form.Item>
      <Form.Item label="新密码" extra="限13-18字符，包含大小写字母、数字和特殊字符">
        {getFieldDecorator('newPassword', rulesHandler('newPassword'))(
          <Input
            type={inputType}
            onChange={e => handlePasswordChange(e, setInputType)}
            placeholder="请设置新密码"
          />,
        )}
      </Form.Item>
      <Form.Item label="确认密码">
        {getFieldDecorator('password', rulesHandler('password'))(
          <Input
            type={confirmInputType}
            onChange={e => handlePasswordChange(e, setConfirmInputType)}
            placeholder="请确认新密码"
          />,
        )}
      </Form.Item>
    </Form>
  );
};

const FormWarpper = Form.create({})(forwardRef(FormComponent));

const ResetPasswordModal = (props, ref) => {
  const formRef = useRef();
  const [visible, setVisible] = useState(false);
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [record, setRecord] = useState({
    name: '',
    id: '',
  });

  const open = item => {
    setVisible(true);
    const { name, id } = item;
    // 初始化数据
    setRecord({
      name,
      id,
    });
  };

  const onCancel = () => {
    setVisible(false);
    setConfirmLoading(false);
    formRef.current.resetFields();
  };

  const onOk = () => {
    formRef.current.validateFields(async (err, fieldsValue) => {
      console.log('fieldsValue :>>', fieldsValue);
      if (err) {
        return;
      }
      setConfirmLoading(true);
      const { password } = fieldsValue;
      const params = {
        id: record.id,
        password,
      };
      const res = await resetPassword(params);
      setConfirmLoading(false);
      if (res.code !== 2000) {
        notification.warning({
          message: res.detail,
        });
        return;
      }
      notification.success({
        message: '重置成功',
      });
      setConfirmLoading(false);
      onCancel();
    });
  };

  useImperativeHandle(ref, () => ({
    open,
  }));

  const modalProps = {
    title: '重置密码',
    visible,
    confirmLoading,
    onCancel,
    onOk,
  };

  return (
    <Modal {...modalProps}>
      <FormWarpper ref={formRef} record={record} />
    </Modal>
  );
};

export default forwardRef(ResetPasswordModal);
