<template>
	<div class="contain">
		<navbar 
		title="电子签名" 
		v-if="!crosswise"
		leftClick 
		@leftClick="$utils.navigateBack"/>
		
		<view 
		class="electronic-contract"
		:class="{crosswise}">
			<canvas 
			canvas-id="mycanvas" 
			class="mycanvas" 
			:style="{height, width}"
			disable-scroll="true"
			@touchstart="ontouchstart" 
			@touchmove="touchmove"></canvas>
			<view class="title"
			v-if="crosswise">
				请旋转屏幕，按文字方向开始签名
			</view>
		</view>

		<view class="btn-list">
			<view class="uni-color-btn" @click="clear">
				清除
			</view>
			<view class="uni-color-btn" @click="close">
				完成
			</view>
		</view>
	</div>
</template>

<script>
	export default {
		data() {
			return {
				oc: null,
				points: [], //路径点集合
				show: true,
				height : '350rpx',
				width : '700rpx',
				crosswise : false,
				options : {},
				detail : {},
			}
		},
		onReady() {
			this.open()
		},
		onLoad(options) {
			this.options = options
		},
		onShow() {
			this.initPM()
			this.getDetail()
		},
		methods: {
			// 获取合同内容
			getDetail(){
				let data = {
					contractId: this.options.id
				}
				if (uni.getStorageSync('token')) {
					// data.token = uni.getStorageSync('token')
				}
				this.$api('queryContracById', data, res => {
					if (res.code == 200) {
						this.detail = res.result
					}
				})
			},
			initPM(){
				if(!this.crosswise) return
				let info = uni.getSystemInfoSync();
				console.log(info.windowWidth);
				console.log(info.windowHeight);
			},
			open() {
				this.initCanvas();
			},
			async save(imagePath){
				let graph = {}, pageNo = 1;
				
				if(this.role){
					graph = JSON.parse(this.detail.bossPosition)
					this.detail.bossImage = imagePath
					this.detail.bossStatus = 1
					pageNo = this.detail.bossPage
				}else{
					graph = JSON.parse(this.detail.employeePosition)
					this.detail.employeeImage = imagePath
					this.detail.employeeStatus = 1
					pageNo = this.detail.employeePage
				}
				
				for(let k in graph){
					graph[k] = (parseFloat(graph[k]) / 700.0).toFixed(2) 
				}
				
				let res = await this.$api('signPdf', {
					imageHeight : graph.h,
					imageWidth : graph.w,
					positionX : graph.x,
					positonY : graph.y,
					pdfPath : this.detail.contract,
					imagePath,
					// pdfPath : 'https://augcl.oss-cn-guangzhou.aliyuncs.com/test/mytest.pdf',
					// imagePath : 'https://augcl.oss-cn-guangzhou.aliyuncs.com/test/image.png',
					pageNo : parseInt(pageNo) + 1,
				})
				
				
				if(res.code != 200){
					uni.showToast({
						title: res.result || '签署失败',
						icon:'none',
					})
					return
				}
				
				// uni.downloadFile({
				// 	url : res.result,
				// 	success : res => {
				// 		uni.openDocument({
				// 			filePath: res.tempFilePath,
				// 		})
				// 	}
				// })
				
				// return
				
				delete this.detail.createBy
				delete this.detail.createTime
				delete this.detail.updateBy
				delete this.detail.updateTime
				
				this.detail.contract = res.result
				
				this.$api('updateContract', this.detail)
				.then(res => {
					if(res.code == 200){
						uni.navigateBack(-1)
					}
				})
				
			},
			close() {
				let self = this
				uni.canvasToTempFilePath({
					canvasId: "mycanvas",
					success: (res) => {
						console.log(res.tempFilePath);
						const imagePath = res.tempFilePath;
						
						// uni.setStorageSync('electronicSignature', imagePath)
						// let o = this.options
						// uni.navigateBack(-1)
						
						self.$Oss.ossUpload(imagePath).then(url => {
							self.save(url)
						})
						
					},
					fail(error) {
						console.error("转化图片错误!", error)
					}
				});
			},

			initCanvas() {
				this.oc = uni.createCanvasContext("mycanvas");
			},

			ontouchstart(e) {
				this.points = []

				const startX = e.changedTouches[0].x;
				const startY = e.changedTouches[0].y;

				let startPoint = {
					X: startX,
					Y: startY,
				};
				this.points.push(startPoint);
			},

			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(); //绘制路径
				}
			},

			draw() {
				if (this.points.length < 2) return;

				this.oc.beginPath();
				this.oc.moveTo(this.points[0].X, this.points[0].Y);

				// for (let i = 1; i < this.points.length; i++) {
				// 	let point = this.points[i];
				// 	this.oc.lineTo(point.X, point.Y);
				// }
				
				this.oc.lineTo(this.points[1].X, this.points[1].Y);
				
				this.points.shift()

				this.oc.setStrokeStyle('#000000');
				this.oc.setLineWidth(5);
				this.oc.setLineCap('round');
				this.oc.setLineJoin('round');
				this.oc.stroke();
				this.oc.draw(true);
			},
			//清空画布
			clear() {
				let that = this;
				uni.getSystemInfo({
					success: (res) => {
						let canvasw = res.windowWidth;
						let canvash = res.windowHeight;
						that.oc.clearRect(0, 0, canvasw, canvash);
						that.oc.draw(true);
					},
				});
			},
		}
	};
</script>

<style lang="scss" scoped>
	.contain {
		position: relative;
		.mycanvas {
			background-color: #fff;
			border-radius: 20rpx;
		}
		.electronic-contract{
			display: flex;
			justify-content: center;
			align-items: center;
			margin: 25rpx;
		}
		.crosswise{
			.title{
				writing-mode: vertical-lr; /* 垂直从上到下 */
				transform: skewY(180deg); /* 颠倒文本 */
				display: inline-block; /* 需要设置为内联块 */
			}
		}
		.btn-list {
			display: flex;
			padding: 20rpx;
			justify-content: space-around;

			.uni-color-btn {
				border-radius: 10rpx;
				margin: 0;
				padding: 20rpx 40rpx;
			}
		}
	}
</style>