<template>
<view class="sign">
	<view style="width: 100vw; height: 100vh;">
		<l-signature disableScroll backgroundColor="#ddd" 
		ref="signatureRef" 
		:penColor="penColor" 
		:penSize="penSize" 
		:landscape="true"
		:openSmooth="openSmooth" ></l-signature>
	</view>
	<view class="btn">
		<button @click="onClick('clear')">清空</button>
		<button @click="onClick('undo')">撤消</button>
		<button @click="onClick('save')">保存</button>
	</view>
</view>
</template>

<script>
	import {getToken} from '@/common/auth.js'
import {updateUserInfo} from '@/common/api.js'
var base64Img = require('base64-img');
export default{
	data(){
		return{
			title: 'Hello',
			penColor: '#000000',
			penSize: 5,
			picurl: '',
			landscape:true,
			openSmooth: false
		}
	},
	methods: {
		base64toBlob(dataurl) {
		    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 Blob([u8arr], { type: mime });
		},
		onClick(type) {
			 if(type == 'openSmooth') {
				 this.openSmooth = !this.openSmooth
				 return
			 }
			if (type == 'save') {
				this.$refs.signatureRef.canvasToTempFilePath({
					success: (res) => {
						
						if(res.isEmpty){
							uni.$u.toast("请签名")
							return;
						}
						var path = URL.createObjectURL(this.base64toBlob(res.tempFilePath))
						uni.uploadFile({
							url: this.baseUrl+'api/common/upload', 
							filePath: path,
							name: 'file',
							header:{
								token:getToken()
							},
							formData: {
							},
							success: (res) => {
								console.log(JSON.parse(res.data),"00")
								if(JSON.parse(res.data).code==1){
									setTimeout(() => {
										this.saveSignPic(JSON.parse(res.data).data.url)
										
									}, 1000)
								}else{
									uni.$u.toast(JSON.parse(res.data).msg)
									
								}
							},
							fail: (res) => {
								console.log(res,"rrr")
							}
						});
					}
				})
				return
			}
			if (this.$refs.signatureRef)
				this.$refs.signatureRef[type]()
		},
		
		saveSignPic(picurl){
			console.log(picurl)
			updateUserInfo({sign_image:picurl}).then(res=>{
				console.log(res,"ooooo")
				if(res.code==1){
					uni.switchTab({
						url:"/pages/qianggou/qianggou"
					})
				}
			})
		}
	}
}
</script>

<style lang="scss" scoped>
.sign{
   height:calc(100vh);
   overflow: hidden;
   .btn{
	  // transform: rotate(90deg);
	  display: flex;
	  position: fixed;
	  bottom:10px;
	  width:100%;
	  button{
		  flex:1;
		  margin:0 10rpx;
		  background-color: $base;
		  color:#fff;
		  font-size: 28rpx;
	  }
   }
}
</style>