<template>
	<!-- 手写签名组件 -->
	<div class="page sign-page">
		<div class="content">

			<div class="sm">
			  <p class="title" style="text-align: center;">签收</p>
			  <!-- <img src="../assets/images/phone.jpg" alt="" @click="chooseImage()"/> -->
			  <van-uploader  :after-read="afterRead">
			    <img src="../assets/images/phone.jpg"/>
			  </van-uploader>
			</div>

			<div class="whrite-content">
				<p>快递单号：{{expressNoList}}</p>
				<div class="sign-wrap" id="signWrap" v-if="isOrNo == 0">
					<canvas id="myCanvas" width="400px" height="100%"></canvas>
				</div>

        <div class="sign-wrap"  style="display: flex; align-items: center;" v-else>
        	<img style="width: 100%;" :src="phoneImage"/>
        </div>

        <van-field type="text" v-model="remark" label="快递备注" placeholder="输入快递备注" />
				<div class="con-btn">
					<span class="staging-btn size14" @click="clearArea()">清除签名</span>
					<span class="submit-btn size14" @click="saveSign()">确认签名</span>
				</div>
			</div>

		</div>

	</div>
</template>

<script>
	import {
		Toast,
		Dialog
	} from 'vant'
	export default {
		name: "signature",
		data() {
			return {
				image: "",
				mousePressed: false,
				c: "",
				ctx: "",
				lastX: 0,
				lastY: 0,
				expressNoList: '',
        phoneImage:"",
        isOrNo: 0,
        File:'',
        remark: '', //快递备注
			};
		},
		created() {
			this.isLogin();
			this.expressNoList = this.$route.query.expressNoList
		},
		mounted() {
			this.image = "";
			this.mousePressed = false;
			var lastX, lastY;
			this.ctx = document.getElementById("myCanvas").getContext("2d");
			this.c = document.getElementById("myCanvas");
			var signWrap = document.getElementById("signWrap");
			this.c.width = signWrap.clientWidth; // 设置宽度
			this.c.height = signWrap.clientHeight; // 设置高度
			// 监听touchstart事件，touchmove事件，touchend事件等事件
			this.InitThis();
		},
		methods: {
      //限制
      onOversize(file){
      	Toast('文件大小不能超过 50M');
      },
      //图片上传
      afterRead(file){
        this.isOrNo = 1
        this.phoneImage = file.content
        this.File = file.file
      },
			InitThis() {
				// 触摸屏
				var that = this;
				this.c.addEventListener(
					"touchstart",
					function(event) {
						if (event.targetTouches.length == 1) {
							event.preventDefault(); // 阻止浏览器默认事件，重要
							var touch = event.targetTouches[0];
							this.mousePressed = true;
							that.Draw(
								touch.pageX - this.offsetLeft,
								touch.pageY - this.offsetTop,
								false
							);
						}
					},
					false
				);
				this.c.addEventListener(
					"touchmove",
					function(event) {
						if (event.targetTouches.length == 1) {
							event.preventDefault(); // 阻止浏览器默认事件，重要
							var touch = event.targetTouches[0];
							if (this.mousePressed) {
								that.Draw(
									touch.pageX - this.offsetLeft,
									touch.pageY - this.offsetTop,
									true
								);
							}
						}
					},
					false
				);
				this.c.addEventListener(
					"touchend",
					function(event) {
						if (event.targetTouches.length == 1) {
							event.preventDefault(); // 阻止浏览器默认事件，防止手写的时候拖动屏幕，重要
							this.mousePressed = false;
						}
					},
					false
				);
				// 鼠标
				this.c.onmousedown = function(event) {
					this.mousePressed = true;
					that.Draw(
						event.pageX - this.offsetLeft,
						event.pageY - this.offsetTop,
						false
					);
				};
				this.c.onmousemove = function(event) {
					if (this.mousePressed) {
						that.Draw(
							event.pageX - this.offsetLeft,
							event.pageY - this.offsetTop,
							true
						);
					}
				};
				this.c.onmouseup = function(event) {
					this.mousePressed = false;
				};
			},
			Draw(x, y, isDown) {
				if (isDown) {
					this.ctx.beginPath();
					this.ctx.strokeStyle = "#000"; // 颜色
					this.ctx.lineWidth = 3; // 线宽
					this.ctx.lineJoin = "round";
					this.ctx.lineMax = 10; // 设置画笔最大线宽
					this.ctx.lineMin = 3; // 设置画笔最小线宽
					this.ctx.linePressure = 1.2; // 设置画笔笔触压力
					this.ctx.smoothness = 30; // 设置画笔笔触大小变化的平滑度
					this.ctx.moveTo(this.lastX, this.lastY);
					this.ctx.lineTo(x, y);
					this.ctx.closePath();
					this.ctx.stroke();
				}
				this.lastX = x;
				this.lastY = y;
			},
			// 清空画板
			clearArea() {
				if(this.isOrNo == 0){//画板
				  this.ctx.setTransform(1, 0, 0, 1, 0, 0);
				  this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height);
				}else{
				  this.phoneImage = ''
				  this.isOrNo = 0;
				  setTimeout(() => {
				  	this.image = "";
				  	this.mousePressed = false;
				  	var lastX, lastY;
				  	this.ctx = document.getElementById("myCanvas").getContext("2d");
				  	this.c = document.getElementById("myCanvas");
				  	var signWrap = document.getElementById("signWrap");
				  	this.c.width = signWrap.clientWidth; // 设置宽度
				  	this.c.height = signWrap.clientHeight; // 设置高度
				  	// 监听touchstart事件，touchmove事件，touchend事件等事件
				  	this.InitThis();
				  }, 300)
				}

			},
			// 提交签名
			saveSign() {
				if(this.isOrNo == 0){
				  this.checkEmpty(); // 调用 表单非空验证
				}else{
				  console.log("拍照上传文件:" + this.File)

				  Toast.loading({duration: 0,forbidClick: true, message: "上传中..." });
				       	let fd=new FormData()
				       	let signType = '2';
				       	fd.append("file",this.File)
				       	fd.append("expressNoList", this.expressNoList);
				       	fd.append("signType", signType);
				       	fd.append("remark",this.remark);
				       	this.$http.post(this.$store.state.host + "/solic/uploadpict2", fd,{ emulateJSON: true })
				       	.then(res => {
				       	   //发送成功
				       	   if (res.body.msg == 'success') {
				       	   	//签收成功
				       	   	Toast.success('签收成功')
				            setTimeout(() => {
				            	this.$router.push({
				            		path: '/',
				            		query: {}
				            	});
				            }, 2000)
				       	   } else {
				       	   	Toast.fail('签收失败')
				       	   }
				       	},res=>{

				       	});
				}
			},
			checkEmpty() {
				var c = document.getElementById("myCanvas"); // 获取html的canvas对象，我这个id="myCanvas"
				if (this.isCanvasBlank(c)) {
					Toast("请在签名区域签名后再次确认");
					return;
				} else {
					var image = this.c.toDataURL("image/png"); // 得到生成后的签名base64位  url 地址
					// 调用
					/* let blob = this.dataURLtoBlob(image);
					let file = this.blobToFile(blob, this.expressNo + ".jpg");
					console.log(file) */
					let signType = '2';
					var file = this.dataURLtoFile(image, this.expressNo + signType +".jpg");
					let fd = new FormData();
					fd.append("files", file);
					fd.append("expressNoList", this.expressNoList);
					fd.append("signType", signType);
          fd.append("remark",this.remark);
					this.$http.post(this.$store.state.host + "/solic/saveEnclosureImg2.do", fd)
						.then(res => {
							//发送成功
							if (res.body.msg == 'success') {
								//签收成功
								Toast.success('签字成功')

								setTimeout(() => {
									this.$router.push({
										path: '/',
										query: {}
									});
								}, 2000)
							} else {
								Toast.fail('签字失败')
							}
						}, res => {
							//发送失败
							Toast("网络错误!")
						})
				}
			},
			// 验证canvas画布是否为空函数
			isCanvasBlank(canvas) {
				var blank = document.createElement("canvas"); // 系统获取一个空canvas对象
				blank.width = canvas.width;
				blank.height = canvas.height;
				return canvas.toDataURL() == blank.toDataURL(); // 比较值相等则为空
			},
			// 将base64转换为blob
			dataURLtoBlob(dataurl) {
				let arr = dataurl.split(","),
					mime = arr[0].match(/:(.*?);/)[1],
					bstr = atob(arr[1]),
					n = bstr.length,
					u8arr = new Uint8Array(n);
				while (n--) {
					u8arr[n] = bstr.charCodeAt(n);
				}
				return new Blob([u8arr], {
					type: mime
				});
			},
			// 将blob转换为file
			blobToFile(theBlob, fileName) {
				theBlob.lastModifiedDate = new Date();
				theBlob.name = fileName;
				return theBlob;
			},
			//将base64转换为文件
			dataURLtoFile(dataurl, filename) {
				var arr = dataurl.split(','),
					mime = arr[0].match(/:(.*?);/)[1],
					bstr = atob(arr[1]),
					n = bstr.length,
					u8arr = new Uint8Array(n);
				while (n--) {
					u8arr[n] = bstr.charCodeAt(n);
				}
				return new File([u8arr], filename, {
					type: mime
				});
			},
		},
	};
</script>

<style lang="less" scoped>
	.page {
		// width: 400px;
		padding-bottom: .3rem;

		.content {
			text-align: center;
			padding: 0rem .37rem;

      .sm {
        display: flex;
        margin-bottom: .2rem;
        justify-content: space-between;
        align-items: center;

        img {
          width: .4rem;
          height: .4rem;

        }
      }

			.title {
				font-size: .36rem;
				padding: .3rem 0rem;
			}

			.whrite-content {
				background: white;
				width: 100%;
				margin: 0 auto;
				padding: .3rem 0rem;
				border-radius: .05rem;

				>p {
					font-size: .3rem;
					text-align: left;
					width: 85%;
					display: block;
					margin: 0 auto;
					padding-bottom: .3rem;
				}
			}

			background-size: 100% 100%;
			background-position: center center;

			.sign-wrap {
				box-shadow: 0px 0px .1rem #e3e3e3;
				width: 85%;
				margin: 0 auto;
				height: 400px;
			}
		}

		.con-btn {
			width: 85%;
			margin: .5rem auto 0px;
			display: flex;
			align-content: center;
			justify-content: space-between;
			opacity: 0.75;

			span {
				font-size: 0.14rem;
				width: 45%;
				height: 0.48rem;
				display: flex;
				align-items: center;
				justify-content: center;
				padding: .2rem 0rem;
				border-radius: .05rem;
			}

			.staging-btn {
				color: #02bfb3;
				background: #fff;
				border: .01rem solid #02bfb3
			}

			.submit-btn {
				color: #fff;
				background: #02bfb3;
			}
		}
	}
</style>
