import { updatePwd } from "@/api";
import { logout } from "@/utils";
import { Base64 } from "@dage/utils";
import { encodeStr } from "@dage/pc-components";
import { Form, FormInstance, Input, Modal, ModalProps, message } from "antd";
import { FC, useRef, useState } from "react";

export interface ResetPasswordProps extends Pick<ModalProps, "onCancel"> {
  visible: boolean;
}

export const ResetPassword: FC<ResetPasswordProps> = ({ visible, ...rest }) => {
  // 拿到新密码的输入框的值
  const oldPasswordValue = useRef("");
  const formRef = useRef<FormInstance>(null);
  const [confirmLoading, setConfirmLoading] = useState(false);

  const checkPassWord = (rule: any, value = "") => {
    if (value !== oldPasswordValue.current)
      return Promise.reject("新密码不一致!");
    else return Promise.resolve(value);
  };

  const onFinish = async () => {
    setConfirmLoading(true);
    try {
      if (!(await formRef.current?.validateFields())) return;

      const value = formRef.current?.getFieldsValue();
      const obj = {
        oldPassword: encodeStr(Base64.encode(value.oldPassword)),
        newPassword: encodeStr(Base64.encode(value.newPassword)),
      };
      await updatePwd(obj);

      message.open({
        type: "success",
        content: "修改成功!",
      });
      logout();
    } finally {
      setConfirmLoading(false);
    }
  };

  return (
    <Modal
      open={visible}
      title="修改密码"
      {...rest}
      maskClosable={false}
      destroyOnClose={true}
      confirmLoading={confirmLoading}
      onOk={onFinish}
    >
      <Form
        ref={formRef}
        labelCol={{ span: 5 }}
        wrapperCol={{ span: 16 }}
        onFinish={onFinish}
        autoComplete="off"
      >
        <Form.Item
          label="旧密码"
          name="oldPassword"
          rules={[{ required: true, message: "不能为空!" }]}
        >
          <Input.Password maxLength={15} />
        </Form.Item>

        <Form.Item
          label="新密码"
          name="newPassword"
          rules={[
            { required: true, message: "不能为空!" },
            { min: 6, max: 15, message: "密码长度为6-15个字符!" },
          ]}
        >
          <Input.Password
            maxLength={15}
            onChange={(e) => (oldPasswordValue.current = e.target.value)}
          />
        </Form.Item>

        <Form.Item
          label="确定新密码"
          name="checkPass"
          rules={[{ validator: checkPassWord }]}
        >
          <Input.Password maxLength={15} />
        </Form.Item>
      </Form>
    </Modal>
  );
};
