<template>
	<view class="signature_info">
		<u--form :model="inputForm" labelWidth="100px" class="u-form" labelPosition="left" ref="inputForm">
			<u-form-item label="旧签名" borderBottom prop="signPic">
				<u--image :showLoading="true" :src="BASE_URL + inputForm.signPic " width="100px"
					height="40px"></u--image>
			</u-form-item>
			<u-form-item label="上传签字图片" borderBottom prop="signPic">
				<lsj-upload v-if="fileList.length == 0" ref="lsjUpload" childId="upload1" width="250rpx" height="200rpx" :option="option"
					:debug="false" :instantly="false" @uploadEnd="onuploadEnd" @change="afterRead">
					<view class="addfile flex">
						<u-icon size="20" bold name="plus"></u-icon>
					</view>
				</lsj-upload>
				<u-upload :fileList="fileList" @delete="deletePic" :maxCount="fileList.length"
					:previewFullImage="true"></u-upload>
			</u-form-item>
			<u--text size="10" type="warning" text="有签名图片,请上传,无,请点击下面签字生成"></u--text>
			<u-form-item label="签字" borderBottom prop="signPic">
				<signInput ref="sign" canvasId="twoDrowCanvas" canvasIds="twoRotateCanvas" :header="header"
					:action="action" @signToUrl="signToUrl">
				</signInput>
			</u-form-item>

			<view class="padding-xl">
				<u-button type="primary" @click="formSubmit" text="提交"></u-button>
			</view>
		</u--form>
	</view>
</template>

<script>
	import {
		isImageFormat
	} from "@/common/util.js"
	import userService from "@/api/sys/userService"
	import * as $auth from "@/common/auth.js"
	import BASE_URL from '@/config.js'
	import signInput from "@/components/am-sign-input/am-sign-input.vue"
	export default {

		components: {
			signInput
		},
		data() {
			return {
				action: this.BASE_URL + '/gwfile/upload?uploadPath=sign', //上传服务器的地址
				header: {
					"token": this.$auth.getUserToken()
				}, //图片上传携带头部信息
				loading: false,
				inputForm: this.$auth.getUserInfo(),
				fileList: [],
				files:[],
				signPic: '',
				// 上传接口参数
				option: {
					url: BASE_URL + '/gwfile/upload?uploadPath=sign',
					name: 'file',
					header: {
						"token": $auth.getUserToken()
					},
				},
			}
		},

		methods: {
			/**
			 * @param {Object} e
			 * 签名完成回调
			 */
			signToUrl(e) {
				this.signPic = e.data
				if (e.error_code && e.error_code === '201') {
					uni.showToast({
						title: e.msg,
						icon: 'none'
					})
					return
				}
			},
			// 删除图片
			deletePic(event) {
				this.fileList.splice(event.index, 1)
			},
			// 新增图片
			afterRead(files) {
				uni.showLoading({
					title: "上传中"
				})
				let lists = [...files.values()]
				this.files = files
				for (let i = 0; i < lists.length; i++) {
					if (lists[i].type == 'success') continue;
					if (!isImageFormat(lists[i].name)) {
						uni.showToast({
							title: '请上传图片',
							icon: 'error'
						})
					} else {
						if (lists[i].size > 200 * 1024) {
							this.compressAPP(lists[i], 150).then(res => {
								this.files.get(lists[i].name).file = res
								this.upload(lists[i].name)
							})
						} else {
							this.upload(lists[i].name)
						}
					}
				}
			
			},
			// app图片压缩
			compressAPP(urlData, targetSizeKB, initialQuality = 1.0) {
				const maxQuality = 1.0;
				const minQuality = 0.0;
				const tolerance = 0.01; // 根据需要调整公差
				let that = this
				return new Promise((resolve, reject) => {
			
					let binarySearch = (min, max) => {
						const midQuality = (min + max) / 2;
						uni.getImageInfo({
							src: urlData.path,
							success: function(res) {
								let img = new Image()
								img.src = res.path
								img.onload = function() {
									const canvas = document.createElement('canvas');
									const ctx = canvas.getContext('2d');
			
									canvas.width = img.width;
									canvas.height = img.height;
			
									ctx.clearRect(0, 0, canvas.width, canvas.height);
									ctx.drawImage(img, 0, 0, canvas.width, canvas
										.height);
			
									// 使用异步的 toBlob 方法
									canvas.toBlob(async (blob) => {
										const fileSizeKB = blob.size / 1024;
										if (Math.abs(fileSizeKB -
												targetSizeKB) <
											tolerance || max - min <
											tolerance) {
			
											// 当前质量足够接近目标大小，使用当前质量解析
											const file = new File([blob], urlData
												.name, {
													type: blob.type,
													lastModified: new Date()
														.getTime(), // 使用当前时间作为最后修改时间
												});
											setTimeout(() => {
												resolve(file)
											}, 300)
										} else if (fileSizeKB >
											targetSizeKB) {
											// 如果文件大小太大，降低质量，继续二分查找
											binarySearch(min, midQuality);
										} else {
											// 如果文件大小太小，增加质量，继续二分查找
											binarySearch(midQuality, max);
										}
									}, urlData.file.type, midQuality);
								};
							},
							fail: function(err) {
								resolve(false);
							}
						});
			
			
					}
					// 开始二分查找
					binarySearch(minQuality, maxQuality);
				})
			},
			// APP手动上传
			upload(name) {
				// name=指定文件名，不指定则上传所有type等于waiting和fail的文件
				this.$refs['lsjUpload'].upload(name);
			},
			onuploadEnd(item) {
				console.log(`${item.name}已上传结束，上传状态=${item.type}`);
			
				// 更新当前窗口状态变化的文件
				this.files.set(item.name, item);
				let file = {
					name: item.name,
					path: item.responseText
				}
				this.fileList.push(file)
				uni.hideLoading()
				// 微信小程序Map对象for循环不显示，所以转成普通数组，
				// 如果你用不惯Map对象，也可以像这样转普通数组，组件使用Map主要是避免反复文件去重操作
				// #ifdef MP-WEIXIN
				this.wxFiles = [...this.files.values()];
				// #endif
			
				// 强制更新视图
				this.$forceUpdate();
			
				// ---可删除--演示判断是否所有文件均已上传成功
				let isAll = [...this.files.values()].find(item => item.type !== 'success');
				if (!isAll) {
			
				} else {
					console.log(isAll.name + '待上传');
				}
			
			},
			formSubmit: function(e) {
				//定义表单规则
				// this.$refs.inputForm.validate().then(res => {
				uni.showLoading()
				let files = []
				if (this.fileList.length > 0) {
					this.fileList.forEach(item => {
						files.push(item.path)
					})
					this.inputForm.signPic = files.join(",");

				} else {
					this.inputForm.signPic = this.signPic
				}
				userService.saveInfo(this.inputForm).then((data) => {
					$auth.setUserInfo(this.inputForm)
					uni.showToast({
						title: data,
						icon: "success",
						complete: function(res) {
							uni.redirectTo({
								url: '/pages/index/index'
							})
						}
					});

				})
			}
		}
	}
</script>

<style>
	.btn-logout {
		margin-top: 100upx;
		width: 80%;
		border-radius: 50upx;
		font-size: 16px;
		color: #fff;
		background: linear-gradient(to right, #365fff, #36bbff);
	}

	.addfile {
		width: 80px;
		height: 80px;
		background-color: #eee;
		padding-left: 24%;
		margin: 10px;
	}

	.signature_info .takephoto {
		padding-left: 12%;
	}

	.btn-logout-hover {
		background: linear-gradient(to right, #365fdd, #36bbfa);
	}

	.cu-form-group .title {
		min-width: calc(4em + 40px);
	}
</style>