import { Button, Image, message, Modal } from "antd";
import dayjs from "dayjs";
import { useEffect, useRef, useState } from "react";
import SignatureCanvas from "react-signature-canvas";
import { base642File } from "../../utils";

/**
 * 签字组件
 */
function Signature(props) {
  const {
    onConfirm,
    width = 752,
    height = 300,
    url = "",
    ...restProps
  } = props;

  const [signatureModalOpen, setSignatureModalOpen] = useState(false);
  const signatureCanvas = useRef(null);
  const [base64, setBase64] = useState("");
  useEffect(() => {
    setBase64(url);
  }, [url]);

  const onOk = () => {
    if (signatureCanvas.current.isEmpty()) {
      message.warning("请签名");
      return;
    }
    const base64 = signatureCanvas.current.toDataURL();
    setBase64(base64);
    onConfirm({
      time: dayjs().format("YYYY-MM-DD HH:mm:ss"),
      base64,
      file: base642File(base64),
    });
    signatureCanvas.current.clear();
    setSignatureModalOpen(false);
  };

  return (
    <>
      <div>
        <Button
          type="primary"
          onClick={() => {
            setSignatureModalOpen(true);
          }}
        >
          {base64 ? "重新签字" : "手写签字"}
        </Button>
      </div>
      {base64 && (
        <div style={{ border: "1px dashed #d9d9d9", width: "100%", height, marginTop: 16 }}>
          <Image src={base64} style={{ width: "100%", height, objectFit: "contain" }} />
        </div>
      )}
      <Modal
        title="签字"
        width={800}
        open={signatureModalOpen}
        maskClosable={false}
        onCancel={() => setSignatureModalOpen(false)}
        footer={[
          <Button key="clear" onClick={() => signatureCanvas.current.clear()}>重签</Button>,
          <Button
            key="cancel"
            onClick={() => {
              setSignatureModalOpen(false);
              signatureCanvas.current.clear();
            }}
          >
            取消
          </Button>,
          <Button key="ok" type="primary" onClick={onOk}>确定</Button>,
        ]}
      >
        <div style={{ border: "1px dashed #d9d9d9" }}>
          <SignatureCanvas
            ref={signatureCanvas}
            penColor="black"
            canvasProps={{ width, height }}
            backgroundColor="rgb(255,255,255)"
            {...restProps}
          />
        </div>
      </Modal>
    </>
  );
}

Signature.displayName = "Signature";

export default Signature;
