<template>
	<div>
		<el-dialog
		  title="船长签名"
		  v-model="drawer"
		  width="540px"
		  top="5vh"
		  append-to-body
		  @close="handleClose"
		>
			<canvas id="canvas" width="500" height="200"
				@mousedown="down" 
				@mousemove="move"  
				@mouseup="up" 
				@mouseleave="leave"
				style="border:1px solid #000;"
			></canvas>
			<div class="text-center">
				<el-button size="small" type="danger" plain @click="clearCanvas">清空画布</el-button>
				<el-button size="small" type="primary" @click="saveImgInfo">保存签名</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script setup>
	var myCanvas, ctx = null;
	var isMouseMove = false,linCor = "#000";
	var lastX, lastY;
	const store = useStore();
	const emit = defineEmits();
	const drawer = ref(false);
	// 关闭操作
	function handleClose() {
		drawer.value = false;
		clearCanvas();
	}
	// 显示弹框
	function show() {
		drawer.value = true;
		let _ais = store.state.settings.sideTheme;
		linCor = (_ais.indexOf("dark") != -1)?"#fff":"#000";
		if(ctx == null){
			nextTick(() => {
				initCanvas();
			})
		}
	};
	function down(e){
		isMouseMove = true;
		drawLine(
			e.offsetX,
			e.offsetY,
			false
		);
	};
	function move(e){
		if(isMouseMove){
			drawLine(
				e.offsetX,
				e.offsetY,
				true
			);
		}
	};
	function up(e){
		isMouseMove = false;
	};
	function leave(e){
		isMouseMove = false;
	};
	function drawLine(x, y, isT){
		if(isT){
			ctx.beginPath();
			ctx.lineWidth = 4;
			ctx.strokeStyle = linCor;
			ctx.lineCap = "round";
			ctx.lineJoin = "round";
			ctx.moveTo(lastX, lastY);
			ctx.lineTo(x, y);
			ctx.stroke();
			ctx.closePath();
		}
		lastX = x;
		lastY = y;
	};
	function clearCanvas(){
		ctx.beginPath();
		ctx.clearRect(0, 0, myCanvas.width, myCanvas.height);
		ctx.closePath();
	};
	function saveImgInfo(){
		let images = myCanvas.toDataURL("image/png");
		drawer.value = false;
		emit("finsh",images);
		clearCanvas();
	};
	function initCanvas() {
		myCanvas = document.getElementById("canvas");
		ctx = myCanvas.getContext("2d");
	}
	defineExpose({
		show,
		initCanvas
	});
</script>

<style>
</style>