<script lang="ts" setup>
import { useWindowSize } from '@vueuse/core';
import { onMounted, ref } from 'vue';
import Konva from 'konva/lib';
import { Group } from 'konva/lib/Group';
import { Rect } from 'konva/lib/shapes/Rect';
import { Stage } from 'konva/lib/Stage';

const { width, height } = useWindowSize();
const yellowGroup = ref<Group>();
const blueGroup = ref<Group>();
const box = ref<Rect>();
const SCALE_BY = 1.1;
const stage = ref<Stage>();

/**
 * * 缩放画布
 */
const zoomed = () => {
	stage.value?.on('wheel', ev => {
		if (!stage.value) {
			return;
		}

		// 之前缩放比例
		const oldScaleX = stage.value?.scaleX();
		const oldScaleY = stage.value?.scaleY();

		// 当前鼠标位置
		const pointer = stage.value?.getPointerPosition();
		const mousePointTo = {
			x: (pointer!.x - stage.value?.x()) / oldScaleX,
			y: (pointer!.y - stage.value?.y()) / oldScaleY,
		};

		// 判断鼠标向上滚动还是向下滚动
		const direction = ev.evt.deltaY > 0 ? -1 : 1;

		// 新的缩放比例
		const newScaleX = direction > 0 ? oldScaleX * SCALE_BY : oldScaleX / SCALE_BY;
		const newScaleY = direction > 0 ? oldScaleY * SCALE_BY : oldScaleY / SCALE_BY;
		stage.value?.scale({ x: newScaleX, y: newScaleY });

		// 设置鼠标移动，保持指针在画布上不变
		const newPosition = {
			x: pointer!.x - mousePointTo.x * newScaleX,
			y: pointer!.y - mousePointTo.y * newScaleY,
		};
		stage.value!.position(newPosition);
	});
};

const initial = () => {
	stage.value = new Konva.Stage({ container: 'container', width: width.value, height: height.value });
	const layer = new Konva.Layer();
	stage.value.add(layer);

	yellowGroup.value = new Konva.Group({
		x: 100,
		y: 100,
		draggable: true,
	});

	blueGroup.value = new Konva.Group({
		x: 300,
		y: 80,
		draggable: true,
	});

	box.value = new Konva.Rect({
		x: 10,
		y: 10,
		width: 100,
		height: 50,
		fill: 'red',
		stroke: 'black',
	});

	const yellowCircle = new Konva.Circle({
		x: 0,
		y: 0,
		radius: 50,
		fill: 'yellow',
		stroke: 'black',
	});

	const blueCircle = new Konva.Circle({
		x: 0,
		y: 0,
		radius: 50,
		fill: 'blue',
		stroke: 'black',
	});

	zoomed();
	yellowGroup.value.add(yellowCircle);
	yellowGroup.value.add(box.value);
	blueGroup.value.add(blueCircle);
	layer.add(yellowGroup.value);
	layer.add(blueGroup.value);
	stage.value.add(layer);
};

/**
 * * 移动到蓝色组
 */
const toBlue = () => {
	box.value?.moveTo(blueGroup.value);
};

/**
 * * 移动到黄色
 */
const toYellow = () => {
	box.value?.moveTo(yellowGroup.value);
};

onMounted(() => {
	initial();
});
</script>

<template>
	<div class="container-fluid">
		<button id="toBlue" class="btn btn-primary" @click="toBlue">Move red box to blue group</button>
		<button id="toYellow" class="btn btn-warning" @click="toYellow">Move red box to yellow group</button>
		<div id="container"></div>
	</div>
</template>

<style lang="scss" scoped></style>
