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

<script setup lang="ts">
  import { computed, ref, watch, nextTick } from 'vue';
  import LabelItem from './LabelItem.vue';
  import { storeToRefs } from 'pinia';
  import useMapEditor, { MapWorkShopInfoItem } from '../../stores/useMapEditor';
  import Konva from 'konva';

  const mapEditor = useMapEditor();
  const { showShops, bgImage, activeShopId } = storeToRefs(mapEditor);

  const emit = defineEmits(['onOpen']);

  const stageRef = ref<Konva.Stage>();
  const layerRef = ref<Konva.Layer>();
  const transformerRef = ref<Konva.Transformer>();

  const stageSize = computed(() => {
    return {
      width: 1920,
      height: 1080,
    };
  });

  const bgConfig = computed(() => {
    return {
      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 + '',
      draggable: true,
      name: 'group',
    };
  };

  const transformerConfig = {
    keepRatio: true,
    rotateEnabled: false,
    enabledAnchors: ['top-left', 'top-right', 'bottom-left', 'bottom-right'],
  };

  const handleStageMouseDown = (e) => {
    if (e.target.attrs.name === 'bg') {
      activeShopId.value = -1;
      updateTransformer();
    }

    if (e.target.parent.attrs.name === 'group') {
      if (e.target.parent.id() === activeShopId.value) {
        return;
      }
      activeShopId.value = e.target.parent.id();
      updateTransformer();
    }
  };

  const updateTransformer = () => {
    const transformerNode = transformerRef.value!.getNode();
    const layer = layerRef.value!.getNode().getLayer();
    if (activeShopId.value! >= 0) {
      const selectedNode = layer.findOne('#' + activeShopId.value);
      (transformerNode as Konva.Transformer).nodes([selectedNode!]);
    } else {
      (transformerNode as Konva.Transformer).nodes([]);
    }
  };

  const updateLayoutTransformer = () => {
    const transformerNode = transformerRef.value!.getNode();
    const layer = layerRef.value!.getNode().getLayer();
    (transformerNode as Konva.Transformer).nodes([]);
    const selectedNode = layer.findOne('#' + activeShopId.value);
    if (selectedNode) {
      nextTick(() => {
        (transformerNode as Konva.Transformer)?.nodes([selectedNode!]);
      });
    }
  };

  const handleClick = () => {
    emit('onOpen');
  };

  watch(activeShopId, () => {
    nextTick(() => {
      updateTransformer();
    });
  });

  const getLayout = () => {
    const json = stageRef.value?.getStage().toJSON();

    return json;
  };

  defineExpose({ getLayout, updateLayoutTransformer });
</script>

<style scoped></style>
