<template>
    <view>
		<!-- #ifdef MP-WEIXIN  -->
		<canvas :canvas-id="item.id" :id="item.id" :style="{width:width,height: height}" v-for="(item,index) in listCode" :key="item.id" />
		<!-- #endif -->
		
		<!-- #ifndef MP-WEIXIN -->
		<canvas :canvas-id="id" :id="id" :style="{width:width,height: height}" />
		<!-- #endif -->
	</view>
</template>
<script>
	import QRCODE from './index.js';
	import { getUUid, deepClone } from './helper.js'
	export default {
		name: 'WBarcode',
		props:{
			options:{
				type: Object,
				required: true,
				default: () =>{
					return {
						
					}
				}
			}
		},
		data () {
			return {
				listCode: [],
				id: getUUid(),
				height: null,
				width: null,
			}
		},
		created() {
			// https://ext.dcloud.net.cn/plugin?id=4662
			this.height = this.options.height + 'rpx';
			this.width = this.options.width + 'rpx';
			this.SpecialTreatment(this.options)
			this.$nextTick(()=>{
				this.generateCode();
			})
		},
		watch: {
			options:{
				deep: true,
				handler (val) {
					this.height = val.height + 'rpx';
					this.width = val.width + 'rpx';
					this.SpecialTreatment(val)
					// #ifdef H5
					setTimeout(()=>{// h5平台动态改变canvas大小
						this.generateCode();
					},50)
					// #endif
					
					// #ifdef APP-NVUE || APP-PLUS || MP || QUICKAPP-WEBVIEW || QUICKAPP-WEBVIEW-HUAWEI || QUICKAPP-WEBVIEW-UNION
					this.generateCode();
					// #endif
				}
			}
		},
		methods: {
			SpecialTreatment (val) {//微信小程序渲染多个canvas特殊处理
				// #ifdef MP-WEIXIN
					let obj = deepClone(val);
					this.id = obj.id = getUUid();
					this.listCode = [obj]
				// #endif
			},
			generateCode () {
				try{
					const parameter = {...this.options,id: this.id,ctx: this};
					QRCODE.BarCode(parameter,(res)=>{
						this.$emit('generate',res)
					})
				}catch(err){}
			},
			async saveImg (){
				try{
					const res = await QRCODE.SaveImg({id: this.id,width: this.width,height: this.width,ctx: this});
					return res
				}catch(e){}
			}
		}
	}
</script>