import { Image as AntdImage, Button, Popup, Toast } from "antd-mobile";
import dayjs from "dayjs";
import { useEffect, useRef, useState } from "react";
import SignatureCanvas from "react-signature-canvas";
import { base642File } from "zy-react-library/utils";

const SignatureH5 = (props) => {
  const [signatureModalOpen, setSignatureModalOpen] = useState(false);
  const signatureCanvas = useRef(null);
  const [base64, setBase64] = useState("");
  const [signatureClientHeight, setSignatureClientHeight] = useState("");
  const [signatureClientWidth, setSignatureClientWidth] = useState("");

  useEffect(() => {
    if (signatureModalOpen) {
      // setSignatureClientHeight(document.querySelector(".adm-popup-body").clientHeight - 50);
      // setSignatureClientWidth(document.querySelector(".adm-popup-body").clientWidth - 100);
      setSignatureClientHeight(window.innerHeight - 50);
      setSignatureClientWidth(window.innerWidth - 100);
    }
  }, [signatureModalOpen]);
  useEffect(() => {
    setBase64(props.url);
  }, [props.url]);

  const rotateBase64Img = (src) => {
    return new Promise((resolve) => {
      const canvas = document.createElement("canvas");
      const ctx = canvas.getContext("2d");
      let imgW;
      let imgH;
      let size;
      const cutCor = { sx: 0, sy: 0, ex: 0, ey: 0 };
      const image = new Image();
      image.crossOrigin = "anonymous";
      image.src = src;
      image.onload = function () {
        imgW = image.width;
        imgH = image.height;
        size = imgW > imgH ? imgW : imgH;
        canvas.width = size * 2;
        canvas.height = size * 2;
        cutCor.sx = size;
        cutCor.sy = size - imgW;
        cutCor.ex = size + imgH;
        cutCor.ey = size + imgW;
        ctx.translate(size, size);
        ctx.rotate((270 * Math.PI) / 180);
        // ctx.scale(0.16, 0.16);
        ctx.drawImage(image, 0, 0);
        const imgData = ctx.getImageData(
          cutCor.sx,
          cutCor.sy,
          cutCor.ex,
          cutCor.ey,
        );
        canvas.width = imgH;
        canvas.height = imgW;
        ctx.putImageData(imgData, 0, 0);
        resolve(canvas.toDataURL("image/png"));
      };
    });
  };

  const onOk = async () => {
    if (signatureCanvas.current.isEmpty()) {
      Toast.show({
        icon: "fail",
        content: "请签名",
      });
      return;
    }
    const result = signatureCanvas.current.toDataURL();
    const base64 = await rotateBase64Img(result);
    setBase64(base64);
    props.onConfirm?.({
      time: dayjs().format("YYYY-MM-DD HH:mm:ss"),
      base64,
      file: base642File(base64),
    });
    signatureCanvas.current.clear();
    setSignatureModalOpen(false);
  };

  return (
    <div>
      <div>
        <Button
          color="primary"
          onClick={() => {
            setSignatureModalOpen(true);
          }}
        >
          {base64 ? "重新签字" : "手写签字"}
        </Button>
      </div>
      {base64 && (
        <div style={{ border: "1px dashed #d9d9d9", width: "90%", height: "200px", marginTop: "16px", margin: "16px auto" }}>
          <AntdImage src={base64} style={{ width: "100%", height: "200px", objectFit: "contain" }} />
        </div>
      )}
      <Popup
        position="right"
        visible={signatureModalOpen}
        bodyStyle={{ width: "100vw", height: "100vh" }}
      >
        <div style={{ backgroundColor: "#f5f5f5", width: "100%", height: "100%" }}>
          <div style={{
            position: "absolute",
            left: "-200px",
            top: "50%",
            transform: "rotate(90deg)",
            display: "flex",
            gap: "30px",
          }}
          >
            <Button style={{ padding: "7px 50px" }} onClick={() => signatureCanvas.current.clear()}>重签</Button>
            <Button
              style={{ padding: "7px 50px" }}
              onClick={() => {
                setSignatureModalOpen(false);
                signatureCanvas.current.clear();
              }}
            >
              取消
            </Button>
            <Button style={{ padding: "7px 50px" }} color="primary" onClick={onOk}>确定</Button>
          </div>
          <div style={{
            border: "1px dashed #d9d9d9",
            width: signatureClientWidth,
            height: signatureClientHeight,
            position: "absolute",
            left: "55px",
            top: "25px",
            backgroundColor: "#fff",
          }}
          >
            <SignatureCanvas
              ref={signatureCanvas}
              penColor="black"
              canvasProps={{ width: signatureClientWidth, height: signatureClientHeight }}
            />
          </div>
          <div style={{
            position: "absolute",
            top: "50%",
            right: "-18px",
            transform: "rotate(90deg)",
            fontSize: "18px",
          }}
          >
            请横屏签字
          </div>
        </div>
      </Popup>
    </div>
  );
};

export default SignatureH5;
