<script lang="ts" setup>
import { onMounted, ref } from 'vue';
import { useEventListener, useWindowSize } from '@vueuse/core';
import Konva from 'konva/lib';
import { rect1, rect2, selectionRectangle } from '@/views/select/basic/rect.ts';
import { stageEvent } from '@/views/select/basic/stageEvent.ts';
import { drawLine } from '@/views/select/basic/line.ts';
import { Stage } from 'konva/lib/Stage';
import { Layer } from 'konva/lib/Layer';

const { width, height } = useWindowSize();
// let stage, layer;

const stage = ref<Stage>();
const layer = ref<Layer>();
const tr = ref();
const SCALE_BY = 1.1;

const zoomed = () => {
	stage.value?.on('wheel', ev => {
		if (!stage.value) return;

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

		const pointer = stage.value?.getPointerPosition();
		const mousePointTo = {
			x: (pointer!.x - stage.value?.x()) / scaleX,
			y: (pointer!.y - stage.value?.y()) / scaleY,
		};

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

		const x = direction > 0 ? scaleX * SCALE_BY : scaleX / SCALE_BY;
		const y = direction > 0 ? scaleY * SCALE_BY : scaleY / SCALE_BY;
		stage.value?.scale({ x, y });

		const position = {
			x: pointer!.x - mousePointTo.x * x,
			y: pointer!.y - mousePointTo.y * y,
		};
		stage.value?.position(position);
	});
};

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

	drawLine(stage.value, layer.value);

	rect1(layer.value);
	rect2(layer.value);

	// 添加缩放
	tr.value = new Konva.Transformer();
	layer.value.add(tr.value);

	stageEvent(stage.value, selectionRectangle(layer.value), tr.value);
};

onMounted(() => {
	initial();
	useEventListener(window, 'resize', function () {
		stage.value?.width(width.value);
		stage.value?.height(height.value);

		// tr.value.forceUpdate();
	});

	zoomed();
});
</script>

<template>
	<div id="container"></div>
</template>
