<template>
	<view class="jnpf-qrcode">
		<template v-if="qrcode">
			<tki-qrcode ref="qrcode" :cid="cid" :val="qrcode" :size="width" :background="colorLight"
				:foreground="colorDark" :showLoading="false" onval loadMake :key="key" />
		</template>
	</view>
</template>
<script>
	import tkiQrcode from "./tki-qrcode/tki-qrcode.vue"
	let unique = 0

	export default {
		props: {
			dataType: {
				type: String,
				default: 'static'
			},
			colorLight: {
				type: String,
				default: '#000'
			},
			colorDark: {
				type: String,
				default: '#fff'
			},
			relationField: {
				type: String,
				default: ''
			},
			formData: {
				type: Object
			},
			width: {
				type: Number,
				default: 200
			},
			staticText: {
				type: String,
				default: ''
			}
		},
		components: {
			tkiQrcode
		},
		computed: {
			qrcode() {
				if (this.dataType === 'static') {
					return this.staticText
				} else if (this.dataType === 'relation') {
					return this.relationText.toString()
				} else {
					if (this.formData && this.dynamicModelExtra && this.dynamicModelExtra.id && this.dynamicModelExtra
						.modelId) {
						const json = {
							t: 'DFD',
							id: this.dynamicModelExtra.id,
							mid: this.dynamicModelExtra.modelId,
							mt: this.dynamicModelExtra.type,
							fid: this.dynamicModelExtra.flowId || '',
							pid: this.dynamicModelExtra.processId || '',
							ftid: this.dynamicModelExtra.taskId || '',
							opt: this.dynamicModelExtra.opType
						}
						return JSON.stringify(json)
					}
					return ''
				}
			},
			dynamicModelExtra() {
				return uni.getStorageSync('dynamicModelExtra') || null
			}
		},
		data() {
			return {
				cid: '',
				relationText: "",
				key: +new Date()
			}
		},
		created() {
			this.cid = this.uuid()
			uni.$on('upDateCode', (subVal, Vmodel) => {
				setTimeout(() => {
					this.$refs.qrcode._makeCode()
					this.key = +new Date()
				}, 200);
			})
		},
		watch: {
			formData: {
				handler: function(val) {
					if (val && this.dataType === 'relation' && this.relationField) {
						this.relationText = val[this.relationField]
					}
				},
				deep: true,
				immediate: true
			},
		},
		methods: {
			uuid() {
				const time = Date.now()
				const random = Math.floor(Math.random() * 1000000000)
				unique++
				return 'qrcode_' + random + unique + String(time)
			}
		},
	}
</script>
<style lang="scss" scoped>
	.jnpf-qrcode {
		width: 100%;
		overflow: hidden;
		margin-bottom: -20rpx;
	}
</style>