import {
  h, Component, useProp, useEvent, useRef,
} from "atomico";
import style from "./kun-upload-file.scss";
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 { useHoverHook } from "../../hooks/aync-hook/aync-hook";
import { CONST_SIX_CONFIG } from "../../common/config";

const KunUploadFile = () => {
  const [hoverRef, isHovered] = useHoverHook();
  const [kunImageUrl, setKunImageUrl] = useProp<string>("kunImageUrl");
  const refLabel = useRef<HTMLElement>();
  const updateImg = useEvent("MyChange", {
    composed: true,
    bubbles: true,
  });

  const updateImageFile = async (event: KeyboardEvent): Promise<void> => {
    await execWithSixLoad(async () => {
      const file = (event.target as unknown as any).files[0];
      const formData = new FormData();
      formData.set("file", file);
      const r = await requestUploadFile1(formData);
      const fileName = `${CONST_SIX_CONFIG.FILE_DOMAIN}${r.msg}`;
      updateImg({
        url: r.msg,
      });
      setKunImageUrl(fileName);
    });
  };

  const clk = (): void => {
    refLabel.current.click();
  };

  return (
    <host>
      <style>{style}</style>
      <div>
        <div class="flex flex-row image relative">
          {
            kunImageUrl != null && (
              <img src={kunImageUrl} onclick={clk} ref={hoverRef} class="cursor-pointer" />
            )
          }
          {
            kunImageUrl == null && (
            <div class="w-full w-full flex items-center hover:bg-orange-400 hover:text-white">
              <div class="cursor-pointer text-center mx-auto" onclick={clk}>请上传图片</div>
            </div>
            )
          }
          {
            isHovered && (
            <div class="cursor-pointer image-width text-center absolute bg-black-300 text-white bottom-0 mx-auto">上传图片</div>
            )
          }
        </div>

        <input type="file" class="none" ref={refLabel} id="asd" onchange={(evt) => updateImageFile(evt)} ignore />
      </div>
    </host>
  );
};

KunUploadFile.props = {
  kunImageUrl: {
    type: String,
    reflect: true,
  },
};

export default getComponentOrDefine("kun-upload-file", KunUploadFile);
