import { Dict_Imgs } from "@/dict";
import { useEditor } from "@/modules/editor";
import { defineComponent, watch } from "vue";
import { string } from "vue-types";
import { useCompData } from ".";
import { View } from "../View";

export const Component = defineComponent({
  props: {
    compId: string().isRequired,
  },
  setup(props) {
    const comp = useCompData(props.compId);

    const { actions, helper, store, controls } = useEditor();

    function setImageSize(url: string) {
      if (!helper.isStreamCardChild(props.compId)) return;
      const temImg = new Image();
      temImg.src = url;

      temImg.onload = function () {
        comp.setH(comp.getW() / (temImg.width / temImg.height));
        actions.onCompLayoutUpdated(comp);
        helper.extendStreamCard(store.currStreamCardId);
      };
    }

    async function changeVal() {
      try {
        const url = await controls.pickCtrl.pickOneImage();
        if (!url) return;

        comp.value.url = url;
        comp.value.x = 0;
        comp.value.y = 0;
        comp.value.s = 1;
      } catch (error) {
        console.log(error);
      }
    }

    watch(
      () => comp.value.url,
      (value, oldValue) => {
        if (oldValue !== Dict_Imgs.Default) return;
        setImageSize(value);
      }
    );

    return () => {
      const value = comp.value;
      const scale = value?.s || 1;
      const ox = value?.x || 0;
      const oy = value?.y || 0;
      const objectFit =
        scale + "" == "1" && ox + "" == "0" && oy + "" == "0"
          ? "cover"
          : "contain";

      return (
        <View
          class="overflow-hidden"
          compId={props.compId}
          onDblclick={store.isEditMode ? changeVal : undefined}
          onClick={() => {
            if (value.showLink && value.link && !store.isEditMode) {
              window.location.href = value.link;
            } else {
              controls.wxCtrl.setPreviewData(value.url, store.previewImageList);
            }
          }}
        >
          <img
            crossorigin="anonymous"
            class={"w-1/1 h-1/1 object-cover pointer-events-none"}
            style={{
              transform: `scale(${scale}) translate(${ox}%,${oy}%)`,
              objectFit,
            }}
            src={
              value.url.startsWith("data:image/png")
                ? value.url
                : value.url + "?editMode=" + store.isEditMode
            }
          />
        </View>
      );
    };
  },
});
