import {
  h, Component, useProp, useEvent, useRef,
} from "atomico";
import "../kun-image/kun-image";
import "../kun-icon/kun-icon";
import { getComponentOrDefine } from "../../hooks/aync-hook/redirect";
import { requestUploadFile1 } from "../kun-editor/req-upload-file";
import { execWithSixLoad } from "../../common/exec-confirm";
import { mockStyle } from "../../common/mock-style";

const Comp = () => {
  const refLabel = useRef<HTMLElement>();
  const updateImg = useEvent("MyChange", {
    composed: true,
    bubbles: true,
  });

  const updateImageFile = async (event): Promise<void> => {
    console.log("upload image");
    await execWithSixLoad(async () => {
      const file = event.target.files[0];
      const formData = new FormData();
      formData.set("file", file);
      const r = await requestUploadFile1(formData);
      updateImg({
        url: r.msg,
      });
    });
  };

  const clk = (): void => {
    console.log("clik");
    refLabel.current.click();
  };

  return (
    <host>
      <style>{mockStyle}</style>
      <div class="flex flex-row">
        <kun-icon iconType="tupian" iconWidth={18} iconHeight={18} onclick={clk} />
        <div
          className="none display-none hidden ml-4 cursor-pointer rounded-lg flex leading-normal bg-orange-400 text-white h-8 px-8 items-center"
        >
          图片
        </div>
        <input
          type="file"
          className="none display-none hidden"
          ref={refLabel}
          id="asd"
          onchange={(evt) => updateImageFile(evt)}
          ignore
        />
      </div>
    </host>
  );
};

Comp.props = {
};

export default getComponentOrDefine("kun-image-upload", Comp);
