<template>
	<view class="root-view">
		<view class="wrapper">
			<view class="handCenter">
				<canvas class="handWriting" :disable-scroll="true" @touchstart="uploadScaleStart"
					@touchmove="uploadScaleMove" canvas-id="handWriting"></canvas>
				<canvas canvas-id="protocol" style="width: 595px;height: 842px; position:fixed;left:100%;"></canvas>
			</view>
			<view class="btn-box">
				<view @click="retDraw" class="btn delBtn">重写</view>
				<view @click="saveCanvasAsImg" class="btn saveBtn">保存</view>
			</view>
		</view>
	</view>
</template>

<script>
	import { requestApi , requestFileApi } from '@/api/request.js';
	export default {
		data() {
			return {
				canvasName: 'handWriting',
				ctx: '',
				ctx2: '',
				startX: null,
				startY: null,
				startX2: null,
				startY2: null,
				canvasWidth: 0,
				canvasHeight: 0,
				selectColor: 'black',
				lineColor: '#1A1A1A', // 颜色
				lineSize: 5, // 笔记倍数
				name:'', //用来区分多个签字
				protocolText:'',
			};
		},
		onLoad({name = ''}) {
			// console.log('name',name);
			this.name = name
			this.ctx = uni.createCanvasContext("handWriting");
			
			this.ctx2 =  uni.createCanvasContext("protocol", this);
			
			const getProtocol =  requestApi(
			'/admin/borrow.BorrowApply/getProtocol?server=1','GET'
			).then(ret => {
				console.log(ret)
				if(ret.code == 1){
					this.protocolText = ret.data.data1;
					this.setCanvasP();
				}
			})
			
			this.$nextTick(() => {
				uni.createSelectorQuery().select('.handCenter').boundingClientRect(rect => {
						this.canvasWidth = rect.width;
						this.canvasHeight = rect.height;
						/* 将canvas背景设置为 白底，不设置  导出的canvas的背景为透明 */
						this.setCanvasBg('#fff');
					})
					.exec();
			});
		},
		methods: {
			// 笔迹开始
			uploadScaleStart(e) {
				this.startX = e.changedTouches[0].x 
				this.startY = e.changedTouches[0].y 
				//设置画笔参数
				//画笔颜色
				this.ctx.setStrokeStyle(this.lineColor)
				//设置线条粗细
				this.ctx.setLineWidth(this.lineSize)
				//设置线条的结束端点样式
				this.ctx.setLineCap("round") //'butt'、'round'、'square'
				//开始画笔
				this.ctx.beginPath()
				
				this.startX2 = e.changedTouches[0].x
				this.startY2 = e.changedTouches[0].y + 400
				this.ctx2.setStrokeStyle(this.lineColor)
				//设置线条粗细
				this.ctx2.setLineWidth(this.lineSize)
				//设置线条的结束端点样式
				this.ctx2.setLineCap("round") //'butt'、'round'、'square'
				//开始画笔
				this.ctx2.beginPath()
			},
			// 笔迹移动
			uploadScaleMove(e) {
				//取点
				let temX = e.changedTouches[0].x 
				let temY = e.changedTouches[0].y 
				//画线条
				this.ctx.moveTo(this.startX, this.startY)
				this.ctx.lineTo(temX, temY)
				this.ctx.stroke()
				this.startX = temX 
				this.startY = temY
				this.ctx.draw(true)
				
				
				let temX2 = e.changedTouches[0].x
				let temY2 = e.changedTouches[0].y + 400
				//画线条
				this.ctx2.moveTo(this.startX2, this.startY2)
				this.ctx2.lineTo(temX2, temY2)
				this.ctx2.stroke()
				this.startX2 = temX2 
				this.startY2 = temY2 
				this.ctx2.draw(true)
				
			},
			/**
			 * 重写
			 */
			retDraw() {
				this.ctx.clearRect(0, 0, 700, 730);
				this.ctx.draw();
				//设置canvas背景
				this.setCanvasBg('#fff');
				this.ctx2.clearRect(0, 0, 700, 730);
				this.ctx2.draw();
				this.setCanvasP()
 			},

	
			//生成图片
			saveCanvasAsImg() {
				
				if(!this.startX || !this.startY){
					uni.showToast({
						title:'请签字',
						icon:'none'
					})
					return
				}
				
				uni.canvasToTempFilePath({
					canvasId: 'protocol',
					fileType: 'png',
					destWidth: 595,
					destHeight: 842,
					quality: 0.001, //图片质量
					success:(res)=> {
						console.log(res.tempFilePath)
						uni.$emit('q-sign',{name:this.name,tempFilePath:res.tempFilePath})
						uni.navigateBack({
							delta:1
						})
					}
				});
				
				// uni.canvasToTempFilePath({
				// 	canvasId: 'handWriting',
				// 	fileType: 'png',
				// 	quality: 1, //图片质量
				// 	success:(res)=> {
				// 		// console.log(res.tempFilePath)
				// 		// uni.$emit('q-sign',{name:this.name,tempFilePath:res.tempFilePath})
				// 		// uni.navigateBack({
				// 		// 	delta:1
				// 		// })
				// 	}
				// });
			},

			//设置canvas背景色  不设置  导出的canvas的背景为透明
			//@params：字符串  color
			setCanvasBg(color) {

				/* 将canvas背景设置为 白底，不设置  导出的canvas的背景为透明 */
				//rect() 参数说明  矩形路径左上角的横坐标，左上角的纵坐标, 矩形路径的宽度, 矩形路径的高度
				//这里是 canvasHeight - 4 是因为下边盖住边框了，所以手动减了写
				this.ctx.rect(0, 0, this.canvasWidth, this.canvasHeight - 4);
				// ctx.setFillStyle('red')
				this.ctx.setFillStyle(color);
				this.ctx.fill(); //设置填充
				this.ctx.draw(); //开画
				
			},
			
			//设置canvas背景色  不设置  导出的canvas的背景为透明
			//@params：字符串  color
			setCanvasP(color) {
			
				/* 将canvas背景设置为 白底，不设置  导出的canvas的背景为透明 */
				//rect() 参数说明  矩形路径左上角的横坐标，左上角的纵坐标, 矩形路径的宽度, 矩形路径的高度
				//这里是 canvasHeight - 4 是因为下边盖住边框了，所以手动减了写
				this.ctx2.rect(0, 0, 595, 842);
				// ctx.setFillStyle('red')
				this.ctx2.setFillStyle('#fff');
				this.ctx2.fill(); //设置填充
				
				const text = this.protocolText;
				
				 // 设置Canvas属性
				this.ctx2.font = '20px Microsoft YaHei'; // 设置字体大小以模拟打印效果
				this.ctx2.textAlign = 'left';
				this.ctx2.fillStyle = '#000000';
				this.ctx2.fillText("桂林理工大学测绘地理信息学院仪器借用承诺书",83, 50);
				
				this.ctx2.font = '15px Microsoft YaHei'; // 设置字体大小以模拟打印效果
				var strArr = [];
				for (let i = 0; i <text.length ; i++) {
					strArr.push(text.slice(i,i+1))
				}		
				 
				let line = '';
				let y = 120;
				strArr.forEach(char => {
					const testLine = line + char;
					const metrics = this.ctx2.measureText(testLine);
					const testWidth = metrics.width;
					// console.log(testLine,metrics.width,ctx.width)
					if (testWidth + 24 > 555) { // 减去左右边距
					  if (line.trim() === '') {
						// 如果当前行没有内容，直接添加字符
						line += char;
					  } else {
						// 否则，绘制当前行并开始新行
						this.ctx2.fillText(line, 33, y);
						line = char;
						y += 20; // 行间距
					  }
					} else {
					  line += char;
					}
				});
				if (line.trim() !== '') {
					this.ctx2.fillText(line, 33, y);
				}
				
				this.ctx2.draw(true, () => {
					console.log(123)
					uni.canvasToTempFilePath({
						x: 0,
						y: 0,
						width: 595,
						height: 842,
						destWidth: 595,
						destHeight: 842,
						canvasId: 'myCanvasP',
						success: function(res) {
						  console.log(res.tempFilePath);
						  // 假设uni.$emit是您项目中用于事件通信的方法
						  uni.$emit('qing', { tempFilePath: res.tempFilePath });
						},
						error:function(res) {
						  console.log(res);
						  // 假设uni.$emit是您项目中用于事件通信的方法
						  // uni.$emit('qing', { tempFilePath: res.tempFilePath });
						},
					},this);
				});
				 
			}
		}
	};
</script>

<style>
	.root-view {
		background: #f6f6f6;
		height: calc(100vh - 44px);
		display: flex;
		/* align-items: center; */
		justify-content: center;
		padding: 27px;
	}
	.btn-box{
		display: flex;
		justify-content: flex-end;
		align-items: center;
	}
	.btn{
		width: 177rpx;
		height: 65rpx;
		border-radius: 20rpx;
		background: #fff;
		line-height: 65rpx;
		text-align: center;
		font-weight: 500;
		font-size: 24rpx;
	}
	.delBtn{
		border: 1rpx solid #3238ec;
		color: #333333;
		margin-right: 32rpx;
	}
	.saveBtn{
		background: #3238ec;
		color: #ffffff;
	}
	.handWriting {
		background: #fff;
		width: 680rpx;
		height: 783rpx;
		border-radius: 20rpx;
	}
	.handCenter{
		margin-bottom: 36rpx;
	}
	
</style>
