<template>
	<!-- pages/signature/signature.wxml -->
	<view class="signature-container">
		<!-- 签名画布 -->
		<canvas canvas-id="signatureCanvas" disable-scroll="true" bindtouchstart="handleTouchStart"
			bindtouchmove="handleTouchMove" bindtouchend="handleTouchEnd"
			style="width: 100%; border: 1px solid #ccc;"></canvas>

		<!-- 操作按钮 -->
		<view class="button-group">
			<button bindtap="clearCanvas">清除</button>
			<button bindtap="saveSignature" type="primary">保存签名</button>
		</view>

		<!-- 签名预览 -->
		<image wx:if="signatureImage" :src="signatureImage" style="width: 100%; margin-top: 20px;"></image>
	</view>
</template>

<script>
	export default {
		name: "signature",
		data() {
			return {
				signatureImage: '', // 保存的签名图片
				ctx: null, // Canvas 上下文
				points: [], // 记录绘制路径
			};
		},
		onReady() {
			// 初始化 Canvas 上下文
			this.setData({
				ctx: wx.createCanvasContext('signatureCanvas')
			});
		},

		// 触摸开始
		handleTouchStart(e) {
			const {
				x,
				y
			} = e.touches[0];
			this.data.points = [{
				x,
				y
			}];
		},

		// 触摸移动
		handleTouchMove(e) {
			const {
				x,
				y
			} = e.touches[0];
			const points = this.data.points;
			points.push({
				x,
				y
			});

			// 绘制路径
			if (points.length >= 2) {
				this.drawLine(points[points.length - 2], points[points.length - 1]);
			}
		},

		// 触摸结束
		handleTouchEnd() {
			this.data.points = [];
		},

		// 绘制线段
		drawLine(start, end) {
			const ctx = this.data.ctx;
			ctx.setStrokeStyle('#000'); // 线条颜色
			ctx.setLineWidth(3); // 线条宽度
			ctx.setLineCap('round'); // 圆角线条
			ctx.beginPath();
			ctx.moveTo(start.x, start.y);
			ctx.lineTo(end.x, end.y);
			ctx.stroke();
			ctx.draw(true); // 实时绘制
		},

		// 清除画布
		clearCanvas() {
			this.data.ctx.clearRect(0, 0, 300, 400); // 需根据实际画布宽高调整
			this.data.ctx.draw(true);
			this.setData({
				signatureImage: ''
			});
		},

		// 保存签名
		saveSignature() {
			wx.canvasToTempFilePath({
				canvasId: 'signatureCanvas',
				success: (res) => {
					console.log(res.tempFilePath)
					this.setData({
						signatureImage: res.tempFilePath
					});
					wx.showToast({
						title: '签名已保存'
					});
					// 这里可以上传到服务器或传递给其他页面
				},
				fail: (err) => {
					console.error('保存失败:', err);
				}
			});
		}
	}
</script>

<style scoped>
/* pages/signature/signature.wxss */
.signature-container {
  padding: 20px;
  height: 60vh;
}

.button-group {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}

button {
  flex: 1;
  margin: 0 10px;
}
</style>