<template>
  <v-group :config="groupConfig" v-if="groupConfig" ref="shape">
    <v-image
      :config="{
        ...data,
        ...config,
        zIndex: undefined,
      }"
      v-if="image"
    />
  </v-group>
</template>

<script lang="ts" setup>
import { defaultStyle, BGImageData } from "./index.ts";
import { computed, ref, watch } from "vue";
import { getImage } from "@/utils/resource.ts";
import { useResize } from "@/core/hook/use-event.ts";
import { Transform } from "konva/lib/Util";
import { Group } from "konva/lib/Group";
import { DC } from "@/deconstruction.js";

const props = defineProps<{ data: BGImageData; addMode?: boolean }>();
const data = computed(() => ({ ...defaultStyle, ...props.data }));
const image = ref<HTMLImageElement | null>(null);
const shape = ref<DC<Group>>();

defineExpose({
  get shape() {
    return shape.value;
  },
});

watch(
  () => data.value.url,
  async (url) => {
    image.value = null;
    image.value = await getImage(url);
  },
  { immediate: true }
);

const size = useResize();
const config = computed(() => {
  let w = data.value.width;
  let h = data.value.height;

  // 认为是百分比
  if (image.value && size.value && (w <= 1 || h <= 1)) {
    w = w <= 1 ? size.value.width * w : w;
    h = h <= 1 ? size.value.height * h : h;
    w = w || (image.value.width / image.value.height) * h;
    h = h || (image.value.height / image.value.width) * w;
  }
  w = w || image.value?.width || 0;
  h = h || image.value?.height || 0;

  return {
    image: image.value,
    opacity: props.addMode ? 0.3 : data.value.opacity,
    width: w,
    height: h,
    offset: {
      x: w / 2,
      y: h / 2,
    },
  };
});

const groupConfig = computed(() => {
  return {
    ...new Transform(data.value.mat).decompose(),
  };
});
</script>
