<template>
	<view class="signature-box">
		<!-- 签名 -->
		<view class="signature" v-show="showCanvas">
			<canvas class="mycanvas" canvas-id="mycanvas" @touchstart="touchstart" @touchmove="touchmove"
				@touchend="touchend"></canvas>
			<view class="footer">
			<!-- 	<u-button @click="finish" type="primary" :plain="true" :ripple="true" ripple-bg-color="#909399">保存
				</u-button> -->
			<!-- 	<u-button @click="clear" type="warning" :plain="true" :ripple="true" ripple-bg-color="#909399">清除
				</u-button> -->
				<!-- <view class="imgBox" style="margin-top: 20rpx;">
					<image src="../../static/clear.png" @click="clear" mode="widthFix"></image>
				</view> -->
				<!-- <u-button @click="close" type="error" :plain="true" :ripple="true" ripple-bg-color="#909399">关闭
				</u-button> -->
			</view>
		</view>
		<!-- 签完名后生成的图片 -->
	<!-- 	<view v-show="SignatureImg" class="SignatureImg">
			<image :src="SignatureImg" mode=""></image>
		</view> -->
		<!-- 清除签完名后生成的图片 -->
		<!-- <u-button v-show="SignatureImg" @click="obliterate" type="error" :plain="true" :ripple="true"
			ripple-bg-color="#909399" size="medium">清除签名</u-button> -->
	</view>
</template>
<script>
	import { pathToBase64 } from '@/util/jssdk_image_tools.js'
	var x = 20;
	var y = 20;
	export default {
		name:'eSignature',
		data() {
			return {
				//绘图图像
				ctx: '',
				//路径点集合
				points: [],
				//签名图片
				SignatureImg: '',
				hasSign: false,
				isDrawing: false // 新增绘制状态
			};
		},
		props: ['showCanvas'],
		emits: ['sendImage','closeCanvas'],
		methods: {
			//清除签名的图片
			obliterate() {
				if (this.SignatureImg) {
					this.SignatureImg = '';
				}
				this.close();
			},
			//关闭并清空画布
			close() {
				this.$emit('closeCanvas');
				this.clear();
			},
			//创建并显示画布
			createCanvas() {
				this.ctx = uni.createCanvasContext('mycanvas', this); //创建绘图对象
				this.ctx.setFillStyle('#000000')
				this.ctx.fillStyle = '#000000'
				//设置画笔样式
				this.ctx.lineWidth = 4;
				this.ctx.lineCap = 'round';
				this.ctx.lineJoin = 'round';
			},
			// //触摸开始，获取到起点
			// touchstart(e) {
			// 	let startX = e.changedTouches[0].x;
			// 	let startY = e.changedTouches[0].y;
			// 	let startPoint = {
			// 		X: startX,
			// 		Y: startY
			// 	};
			// 	this.points.push(startPoint);
			// 	//每次触摸开始，开启新的路径
			// 	this.ctx.beginPath();
			// },
			 // 触摸开始，获取到起点 - 修改后的方法
			    touchstart(e) {
			      this.isDrawing = true;
			      let startX = e.changedTouches[0].x;
			      let startY = e.changedTouches[0].y;
			      let startPoint = {
			        X: startX,
			        Y: startY
			      };
			      this.points.push(startPoint);
			      this.ctx.beginPath();
			      
			      // 阻止事件冒泡
			      e.stopPropagation();
			      return false;
			    },
			// //触摸移动，获取到路径点
			// touchmove(e) {
			// 	let moveX = e.changedTouches[0].x;
			// 	let moveY = e.changedTouches[0].y;
			// 	let movePoint = {
			// 		X: moveX,
			// 		Y: moveY
			// 	};
			// 	this.points.push(movePoint); //存点
			// 	let len = this.points.length;
			// 	if (len >= 2) {
			// 		this.draw(); //绘制路径
			// 	}
			// },
			// 触摸移动，获取到路径点 - 修改后的方法
			    touchmove(e) {
			      if (!this.isDrawing) return;
			      
			      let moveX = e.changedTouches[0].x;
			      let moveY = e.changedTouches[0].y;
			      let movePoint = {
			        X: moveX,
			        Y: moveY
			      };
			      this.points.push(movePoint);
			      let len = this.points.length;
			      if (len >= 2) {
			        this.draw();
			      }
			      
			      // 阻止事件冒泡
			      e.stopPropagation();
			      return false;
			    },
			// // 触摸结束，将未绘制的点清空防止对后续路径产生干扰
			// touchend() {
			// 	this.points = [];
			// },
			// 触摸结束 - 修改后的方法
			    touchend() {
			      this.isDrawing = false;
			      this.points = [];
			      
			      // 阻止事件冒泡
			      if (e) {
			        e.stopPropagation();
			      }
			      return false;
			    },
			//绘制笔迹
			draw() {
				let point1 = this.points[0];
				let point2 = this.points[1];
				this.points.shift();
				this.ctx.moveTo(point1.X, point1.Y);
				this.ctx.lineTo(point2.X, point2.Y);
				this.ctx.stroke();
				this.ctx.draw(true);
				this.hasSign = true
			},
			//清空画布
			clear() {
				this.hasSign = false
				let that = this;
				uni.getSystemInfo({
					success: function(res) {
						let canvasw = res.windowWidth;
						let canvash = res.windowHeight;
						that.ctx.clearRect(0, 0, canvasw, canvash);
						that.ctx.draw(true);
					}
				});
			},
			//完成绘画并保存到本地
			finish() {
				if (!this.hasSign) {
					uni.showToast({
						title: '签名为空不能保存',
						icon: 'none',
						duration: 2000
					})
					return
				}
				let that = this;
				uni.canvasToTempFilePath({
						canvasId: 'mycanvas',
						success: function(res) {
							if(!res || !res.tempFilePath) {
								that.SignatureImg = res.tempFilePath;
								that.$emit('sendImage', that.SignatureImg);
								that.close();
							}else{
								//用来解决安卓真机获取到的是canvas图片的临时路径，转成base64格式
								pathToBase64(res.tempFilePath).then(re => {
									that.SignatureImg = re;
									that.$emit('sendImage', that.SignatureImg);
									that.close();
								})
							}
						}
					}
				);
			}
		},
		mounted() {
			this.createCanvas();
			// 新增代码
			// 在组件挂载时添加额外的事件监听
			    // #ifdef H5
			    const canvas = document.querySelector('.mycanvas');
			    if (canvas) {
			      canvas.addEventListener('touchmove', (e) => {
			        if (this.isDrawing) {
			          e.preventDefault();
			        }
			      }, { passive: false });
			    }
			    // #endif
		}
	};
</script>
<style lang="less" scoped>
	.signature-box {
		display: flex;
		flex-direction: column;
		align-items: center;
		background: #fff;
		//签名模块
		.signature {
			touch-action: none; /* 禁用触摸操作 */
			width: 96%;
			//canvas
			.mycanvas {
				touch-action: none; /* 禁用触摸操作 */
				width: 100%;
				height: calc(100vh - 600rpx);
				background-color: #f9f9f9;
				border-radius: 10px 10px 0 0;
			}
			//底部按钮
			.footer {
				display: flex;
				justify-content: space-around;
			}
		}
		//生成的图片
		.SignatureImg {
			image {
				width: 750rpx;
				height: 750rpx;
			}
		}
		.imgBox{
			width: 120rpx;
			height: 120rpx;
		}
	}
</style>

