import { ModalForm, ProFormText } from '@ant-design/pro-components';
import { Form, message } from 'antd';
import React, { PropsWithChildren } from 'react';
import validator from '../../../utils/validator';
import { updatePass } from '../../../services/CommonController';
import { CommonController } from '../../../services';
import { LOGIN_PATHNAME } from '../../../constants';
import { sessionStore } from '../../../utils/store';
import { pathHolder } from '../../../utils/route';

type PassProps = Record<string, any>;

interface PasswordFormProps {
  title: string;
}

const PasswordForm: React.FC<PropsWithChildren<PasswordFormProps>> = ({
  title,
  children,
}) => {
  const [form] = Form.useForm<PassProps>();
  return (
    <ModalForm<PassProps>
      labelCol={{ span: 6 }}
      wrapperCol={{ span: 14 }}
      layout="horizontal"
      title={title}
      trigger={children as JSX.Element}
      form={form}
      autoFocusFirstInput
      modalProps={{
        destroyOnClose: true,
      }}
      submitTimeout={2000}
      onFinish={async () => {
        const values = await form.validateFields();
        const { oldPass, newPass } = values || {};
        const formdata = new FormData();
        formdata.append('oldPass', oldPass);
        formdata.append('newPass', newPass);
        await updatePass(formdata);
        form.resetFields();
        await message.success('操作成功');
        await CommonController.logoutApi();
        sessionStore.set('login-info', undefined);
        const href = `${location.origin}${pathHolder(LOGIN_PATHNAME)}`;
        location.replace(href);
        return true;
      }}
    >
      <ProFormText.Password
        width="md"
        name="oldPass"
        label="原密码"
        rules={[{ required: true }]}
      />
      <ProFormText.Password
        width="md"
        name="newPass"
        label="新密码"
        required
        rules={[
          {
            validator: async (rule, value) => {
              if (!validator.isPass(value)) {
                throw new Error(
                  '请输入8-18位字符，包含大小写字母、数字、特殊字符四者组合',
                );
              }
            },
          },
        ]}
      />
      <ProFormText.Password
        width="md"
        name="newPassSure"
        label="确认密码"
        rules={[
          {
            validator: async (rule, value) => {
              if (form.getFieldValue('newPass') !== value) {
                throw new Error('密码不一致');
              }
            },
          },
        ]}
      />
    </ModalForm>
  );
};

export default PasswordForm;
