<!-- 用view渲染二维码，需要给定宽高和单位和数据：<cus-qrcode width="400" height="400" unit="rpx" data="baidu.com"></cus-qrcode> -->
<template>
	<view class="qr-wrapper" :style="{ width:`${width}${unit}`,height:`${height}${unit}` }">
		<!-- 绘制中, loading状态 -->
		<view class="qr-loading" v-if="loading">
			<slot name="loading">
				<image class="qr-loading-icon" src="data:image/gif;base64,[encoded data, 7724 characters]" />
			</slot>
		</view>
		<view v-else v-for="(row, rowI) in modules" :key="rowI" class="qr-content">
			<view v-for="(col, colI) in row" :key="colI">
				<view :style="{ width:`${per}${unit}`,height:`${per}${unit}`,backgroundColor: `${color || 'black'}`}" v-if="col.isBlack">
					<!-- 内容色码点 -->
				</view>
				<view v-else style="background-color: white;" :style="{ width:`${per}${unit}`,height:`${per}${unit}` }">
					<!-- 空白码点 -->
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import UQRCode from './uqrcode_latest.js';
	export default {
		name: 'ikunQrcode',
		props: ['width', 'height', 'unit', 'data', 'color'],
		data() {
			return {
				per: 1, // 每一个小方块的单位长宽
				modules: [], // 二维码数据
				loading: true, // 绘制状态
			}
		},
		mounted() {
			this.init()
		},
		watch: {
			// 监听数据改变， 重新绘制
			data: {
				handler(val) {
					if (val) {
						this.init()
					}
				}
			}
		},
		methods: {
			init() {
				const qr = new UQRCode();
				qr.data = this.data
				if (!this.data) return // 数据为空不渲染
				this.loading = true
				try {
					qr.make();
					this.modules = qr.modules;
				} finally {
					this.loading = false
				}
				this.per = this.width / this.modules.length
			}
		}
	}
</script>

<style scoped>
	.qr-wrapper {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
	}
	.qr-loading {
		width: 100%;
		height: 100%;
		text-align: center;
	}
	.qr-loading-icon {
		width: 50%;
		height: 50%;
	}
	.qr-content {
		display: flex;
		flex-direction: row;
		justify-content: center;
		align-items: center;
	}
</style>