<template>
  <v-group :config="groupConfig" v-if="groupConfig" ref="shape">
    <v-image
      :config="{
        ...data,
        ...config,
        shadowForStrokeEnabled: true,
        id: undefined,
        zIndex: undefined,
        name: 'repShape',
      }"
    />
    <!-- <v-rect
      :config="{
        width: config.width,
        height: config.height,
        offset: config.offset,
        fill: '#ff0000',
        opacity: 0.3,
      }"
    /> -->
  </v-group>
</template>

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

const props = defineProps<{ data: ImageData; 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;
    if (url) {
      image.value = await getImage(window.platform.getResource(url));
    }
  },
  { immediate: true }
);

// const size = useViewSize();
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 {
    id: data.value.id,
    ...new Transform(data.value.mat).decompose(),
  };
});
</script>
