<template>
  <div>
    <v-stage ref="stageRef" :config="stageSize">
      <v-layer ref="layerRef">
        <v-image :config="bgConfig" />
        <v-group v-for="item in props.showShops" :key="item.id" :config="getGroupConfig(item)">
          <LabelItem :shop="item" />
        </v-group>
        <!-- <v-transformer ref="transformerRef" :config="transformerConfig" /> -->
      </v-layer>
    </v-stage>
  </div>
</template>

<script setup lang="ts">
  import { ref, watch } from 'vue';
  import LabelItem from './LabelItem.vue';
  // import { storeToRefs } from 'pinia';
  import { MapWorkShopInfoItem } from '../../stores/useMapEditor';
  import Konva from 'konva';
  import { useGlobSetting } from '@/hooks/setting';
  import urlJoin from 'url-join';

  const globSetting = useGlobSetting();
  const props = defineProps<{ showShops?; bgImageUrl? }>();
  const bgImage = ref<HTMLImageElement>(new Image());
  const stageRef = ref<Konva.Stage>();
  const layerRef = ref<Konva.Layer>();

  const stageSize = ref({
    width: 182,
    height: 114,
  });

  const bgConfig = ref({
    width: 1920,
    height: 1080,
    image: bgImage.value,
    name: 'bg',
  });

  const getGroupConfig = (shop: MapWorkShopInfoItem) => {
    return {
      x: shop.x,
      y: shop.y,
      scaleX: shop.scaleX,
      scaleY: shop.scaleY,
      id: shop.id + '',
      name: 'group',
    };
  };

  const addBg = () => {
    return new Promise((resolve) => {
      const imgUrl = urlJoin(globSetting.imgUrl!, props.bgImageUrl);
      console.log('imgUrlPromise', imgUrl);

      const tempImg = new Image();
      tempImg.src = imgUrl;
      tempImg.onload = () => {
        bgConfig.value.image = tempImg;
      };
      resolve(null);
    });
  };

  const zoomOut = () => {
    const stage = stageRef.value!.getStage();
    if (!stage) return;

    const targetWidth = 182;
    const targetHeight = 114;
    const fixWidth = 1920;
    const fixHeight = 1080;
    //得到缩放比
    const scaleX = targetWidth / fixWidth;
    const scaleY = targetHeight / fixHeight;

    //背景图片缩小
    bgConfig.value.width = targetWidth;
    bgConfig.value.height = targetHeight;

    //缩小group
    const children = stage.find('.group');
    children.forEach((node) => {
      const newScaleX = node.attrs.scaleX * scaleX;
      const newScaleY = node.attrs.scaleY * scaleY;
      node.attrs.scaleX = newScaleX;
      node.attrs.scaleY = newScaleY;
      node.x(node.x() * scaleX);
      node.y(node.y() * scaleY);
    });
    stage.batchDraw();
  };

  watch(
    () => props.bgImageUrl,
    () => {
      addBg().then(() => {
        zoomOut();
      });
    },
    { immediate: true },
  );
</script>

<style scoped></style>
