import { Dict_Imgs } from "@/dict";
import { useEditor } from "@/modules/editor";
import { AnyFun } from "queenjs/typing";
import { effect, reactive, watchEffect } from "vue";

export function useImage(
  getVal: () => {
    value: {
      url: string;
      x: number;
      y: number;
      s: number;
    };
    size?: number[];
  }
) {
  const { helper } = useEditor();
  const state = reactive({
    url: Dict_Imgs.Default,
    style: {} as any,
  });

  const image = new Image();
  image.crossOrigin = "anonymous";

  let watchStop: AnyFun | null = null;

  image.onload = function () {
    watchStop = watchEffect(() => {
      const { value, size = [] } = getVal();
      const { url, x = 0, y = 0, s = 1 } = value;
      const ratio = image.naturalWidth / image.naturalHeight;
      const w = size[0] || 750;
      const h = size[1] || w / ratio;
      const style: any = {};
      const currRatio = w / h;
      if (currRatio > ratio) {
        const imgH = w / ratio;
        style.width = helper.designToNaturalSize(w);
        style.height = helper.designToNaturalSize(imgH);
        style.marginTop = helper.designToNaturalSize((h - imgH) / 2);
      } else {
        const imgW = h * ratio;
        style.height = helper.designToNaturalSize(h);
        style.width = helper.designToNaturalSize(imgW);
        style.marginLeft = helper.designToNaturalSize((w - imgW) / 2);
      }
      style.transform = `translate(${x}%,${y}%) scale(${s})`;
      state.style = style;
      state.url = url;
    });
  };

  image.onerror = function () {
    state.style = {
      width: "100%",
      height: "100%",
    };
    state.url = Dict_Imgs.Default;
  };

  watchEffect(() => {
    if (watchStop) watchStop();
    image.src = getVal().value.url;
  });

  return state;
}
