import { ModalForm, ProFormText } from '@ant-design/pro-components';
import { Form, message } from 'antd';
import React from 'react';
import { UserController } from '../../../services';
import validator from '../../../utils/validator';
interface PasswordFormProps {
  title: string;
  trigger: JSX.Element;
  value?: UserController.UserFields;
  onOk: () => void;
}

const PasswordForm: React.FC<PasswordFormProps> = ({
  trigger,
  title,
  value,
  onOk,
}) => {
  const [form] = Form.useForm<UserController.UserFields>();
  return (
    <ModalForm<UserController.UserFields>
      labelCol={{ span: 6 }}
      wrapperCol={{ span: 14 }}
      layout="horizontal"
      title={title}
      trigger={trigger}
      form={form}
      autoFocusFirstInput
      modalProps={{
        destroyOnClose: true,
      }}
      submitTimeout={2000}
      onFinish={async ({ password = '' }) => {
        await UserController.resetPasswordApi({
          userId: value?.userId || '',
          password,
        });
        message.success('提交成功');
        onOk();
        return true;
      }}
    >
      <ProFormText
        name="userName"
        label="用户名称"
        disabled
        initialValue={value?.userName}
        placeholder="请输入用户名称"
      />
      <ProFormText.Password
        name="password"
        required
        label="新密码"
        placeholder="请输入新密码"
        rules={[
          {
            validator: async (rule, value) => {
              if (!validator.isPass(value)) {
                throw new Error(
                  '请输入8-18位字符，包含大小写字母、数字、特殊字符四者组合',
                );
              }
            },
          },
        ]}
      />
      <ProFormText.Password
        name="password_sure"
        label="确认密码"
        required
        placeholder="请输入确认密码"
        rules={[
          {
            validator: async (rule, value) => {
              if (form.getFieldValue('password') !== value) {
                throw new Error('密码不一致');
              }
            },
          },
        ]}
      />
    </ModalForm>
  );
};

export default PasswordForm;
