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($t('inputs.do.not.match'));
    }
    // 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: $t('set.new.password') },
      {
        pattern: /^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[\W_]).{13,18}$/g,
        message: $t('invalid.password.format'),
      },
    ],
    password: [
      { required: true, message: $t('confirm.new.password') },
      { validator: handlepassword, message: $t('passwords.do.not.match') },
    ],
  };

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

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

  return (
    <Form {...formLayout}>
      <Form.Item label={$t('username')}>{record.name}</Form.Item>
      <Form.Item label={$t('new.password')} extra={$t('1318.chars.uppercase.lowercase.digits.special.chars')}>
        {getFieldDecorator('newPassword', rulesHandler('newPassword'))(
          <Input
            type={inputType}
            onChange={e => handlePasswordChange(e, setInputType)}
            placeholder={$t('set.new.password')}
          />,
        )}
      </Form.Item>
      <Form.Item label={$t('confirm.password')}>
        {getFieldDecorator('password', rulesHandler('password'))(
          <Input
            type={confirmInputType}
            onChange={e => handlePasswordChange(e, setConfirmInputType)}
            placeholder={$t('confirm.new.password')}
          />,
        )}
      </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: $t('reset.successful'),
      });
      setConfirmLoading(false);
      onCancel();
    });
  };

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

  const modalProps = {
    title: $t('reset.password'),
    visible,
    confirmLoading,
    onCancel,
    onOk,
  };

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

export default forwardRef(ResetPasswordModal);
