<template>
	<view>
		<canvas :canvas-id="canvasId" v-show="qrShow" :style="qrShowStyle" />
	</view>
</template>

<script>
	import uQRCode from './qrcode.js'
	export default {
		props: {
			canvasId: {
				type: String,
				default: 'qrcode' //canvas-id
			},
			text: {
				type: String,
				default: 'hello' //二维码内容
			},
			size: {
				type: Number,
				default: 150 //二维码大小
			},
			margin: {
				type: Number,
				default: 0 //二维码边距
			},
			level: {
				type: String,
				default: 'L' //二维码质量L/M/Q/H
			},
			bColor: {
				type: String,
				default: '#ffffff' //二维码背景颜色
			},
			fColor: {
				type: String,
				default: '#000000' //二维码颜色
			},
			fileType: {
				type: String,
				default: 'png' //二维码图片类型
			}
		},
		data() {
			return {
				qrShow: false,
				qrShowStyle: {
					"width": "150px",
					"height": "150px",
				}
			}
		},
		watch: {
			text(newVal, oldVal) {
				this.onQrFun()
			}
		},
		mounted() {
			this.onQrFun()
		},
		methods: {
			onQrFun() {
				this.qrShow = this.text != ''
				if(this.qrShow){
					this.qrShowStyle.width = this.size+"px"
					this.qrShowStyle.height = this.size+"px"
					let level;
					switch (this.level) {
						case "M":
						case "m":
							level = uQRCode.errorCorrectLevel.M
							break;
						case "Q":
						case "q":
							level = uQRCode.errorCorrectLevel.Q
							break;
						case "H":
						case "h":
							level = uQRCode.errorCorrectLevel.H
							break;
						default:
							level = uQRCode.errorCorrectLevel.L
							break;
					}
					uQRCode.make({
						canvasId: this.canvasId,
						componentInstance: this,
						text: this.text,
						size: this.size,
						margin: this.margin,
						backgroundColor: this.bColor,
						foregroundColor: this.fColor,
						fileType: this.fileType,
						errorCorrectLevel: level,
						success: res => {}
					})
					
					setTimeout(() => {
						uni.canvasToTempFilePath({
							canvasId: this.canvasId,
							success: (res) => {
								// 在H5平台下，tempFilePath 为 base64
								this.$emit("update:filePath", res.tempFilePath);
							}
						}, this);			
					}, 600)
				}
				
			}
		}
	}
</script>

<style>
</style>