<template>
	<view class="content">
		<view class="canvasBox" style="display: none;"></view>
	</view>
</template>

<script>
	import jsqr from './jsQR.js'

	export default {
		data() {
			return {
				qrcodeData: '',
				c: undefined,
			}
		},
		mounted() {
			this.$nextTick(() => {
				this.c = document.createElement('canvas')
				this.c.id = 'c'
				this.c.width = 600
				this.c.height = 600
				document.querySelector('.canvasBox').append(this.c)
			})
		},
		methods: {
			getData() {
				this.$emit('callback', this.qrcodeData)
			},

			getQrcode() {
				uni.chooseImage({
					count: 1,
					sourceType: ['album'],
					success: (res) => {
						const imgFile = res.tempFilePaths[0]
						this.beforeAvatarUpload(imgFile)
					}
				})
			},

			analysisQrcode(file) {
				return new Promise((resolve) => {
					const img = new Image();
					const myCanvaswd = this.c.getContext('2d');

					img.src = file;
					img.onload = function() {
						myCanvaswd.drawImage(img, 0, 0, 600, 600);
						const imageData = myCanvaswd.getImageData(0, 0, 600, 600);
						const data = {
							qrcode: '',
							isqrcode: true
						}
						data.qrcode = jsqr(imageData.data, imageData.width, imageData.height, {
							inversionAttempts: "dontInvert",
						});
						if (data.qrcode == null) {
							data.isqrcode = false
						}
						resolve(data)
					}
				})
			},
			//上传成功前的回调
			async beforeAvatarUpload(file) {
				let data = await this.analysisQrcode(file)
				if (data.isqrcode) {
					data = data.qrcode.data
					this.qrcodeData = data
					this.getData()
				} else {
					console.log('没有识别到二维码')
				}
			}
		}
	}
</script>

<style>
	.upload {
		position: relative;
		width: 350rpx;
		height: 100rpx;
		padding: 20rpx;
		background-color: #007AFF;
		display: inline-block;
	}

	.in {
		position: absolute;
		opacity: 0;
		top: 0;
		bottom: 0;
		right: 0;
		left: 0;
	}
</style>
