import { c, useRef, useEvent, h } from 'atomico';
import html2canvas from '@crcastle/html2canvas';

var style = ":host {\n}\n";

function getComponentOrDefine(name, comp) {
  if (!customElements.get(name)) { customElements.define(name, c(comp)); }
  // customElement(name, comp as Component); }
  return customElements.get(name);
}

const baseUrl = "https://www.xunlianying.vip";

function post(url, data, isFormData) {
  const header = {
    authorization: `${localStorage.getItem("AUTH")}`,
  };

  const headerJson = {
    authorization: `${localStorage.getItem("AUTH")}`,
    "content-type": "application/json",
  };

  const options = {
    method: "POST",
    body: isFormData !== true ? JSON.stringify(data) : data ,
    headers: isFormData !== true ? { ...header, ...headerJson } : header,
  };
  return fetch(`${baseUrl}${url}`, options).then((res) => res.json()).catch((r) => r).then((rr) => rr);
}






const requestUploadFile1 = async (data) => await post("/horse/v1/card/image/save", data, true) ;

const _jsxFileName = "/Users/rang/rang/frond_ng/packages/six/src/components/kun-canvas-upload/kun-canvas-upload.tsx";
const KunCanvasUpload = ({ children, message }) => {
  const canvasRef = useRef();
  const canvasRef1 = useRef();

  const updateImageEvent = useEvent("UpdateImage", {
    bubbles: true,
    composed: true,
  });

  const addClick = () => {
    console.log("canva", canvasRef.current);
    html2canvas(canvasRef.current,
      {
        useCORS: true,
        allowTaint: true,
      }).then((canvas) => {
      canvasRef1.current.appendChild(canvas);
      canvas.toBlob(async (blob) => {
        const file = new File([blob], "filename.jpeg");
        const formdata = new FormData();
        formdata.append("file", file);
        const r = await requestUploadFile1(formdata);
        updateImageEvent(r);
      }, "image/jpeg", 0.95);
    });
  };

  return (
    h('host', { shadowDom: true, __self: undefined, __source: {fileName: _jsxFileName, lineNumber: 37}}
      , h('style', {__self: undefined, __source: {fileName: _jsxFileName, lineNumber: 38}}, style)
      , h('button', { type: "button", onclick: addClick, __self: undefined, __source: {fileName: _jsxFileName, lineNumber: 39}}, "Submit")
      , h('div', { ref: canvasRef1, __self: undefined, __source: {fileName: _jsxFileName, lineNumber: 40}}
        , h('slot', { name: "content", __self: undefined, __source: {fileName: _jsxFileName, lineNumber: 41}}
          , children
        )
      )
    )
  );
};

KunCanvasUpload.props = {
  message: {
    type: String,
    value: "kun-canvas-upload",
    reflect: true,
    event: {
      type: "changeMessage",
    },
  },
};

var kunCanvasUpload = getComponentOrDefine("kun-canvas-upload", KunCanvasUpload);

export default kunCanvasUpload;
