<template>
	<view v-if="qrcodeShow">
		<QRCode ref="qrcode" :qrcodeValue="value" :size="400" foregroundImageSrc="/static/login/logo.png">
		</QRCode>
	</view>
</template>

<script>
	import {
		genPayCode,
		genReceiveCode
	} from '@/api/home/qrcode.js'
	import {
		getUserAccInfo
	} from '@/api/login.js'
	import QRCode from '@/components/QRCode/QRCode.vue'
	export default {
		components: {
			QRCode
		},
		props: {
			type: {
				typeof: String,
				default: "P" //P 支付   R 收款
			},
			amount: {
				typeof: Number,
				default: 0
			}
		},
		data() {
			return {
				//code
				value: "",
				qrcodeShow: false,
				timer: null, //定时
				//付款码
				payParam: {
					toId: null,
					toAccount: null
				},
				//收款码
				receiveParam: {
					fromId: null,
					fromAccount: null,
					amount: null
				}
			}
		},
		onLoad() {
			// 每60秒自动刷新
			this.timer = setInterval(() => {
				this.handleRefresh()
			}, 60000)
		},
		onUnload() {
			if (this.timer) {
				clearInterval(this.timer)
			}
		},
		methods: {
			getUserInfo() {
				this.value = "";
				getUserAccInfo().then(res => {
					if (res.code == 200) {
						if (this.type == 'P') {
							//付款码
							//目标id
							this.payParam.toId = res.data.userId;
							//目标账号
							this.payParam.toAccount = res.data.accountId;
							this.genPayCode();
						} else {
							//收款码
							//来源id
							this.receiveParam.fromId = res.data.userId;
							//来源账号
							this.receiveParam.fromAccount = res.data.accountId;
							this.receiveParam.amount = this.amount;
							this.genReceiveCode();
						}
					} else {
						uni.showToast({
							title: this.$languageData.settings.getUserInfoEx,
							icon: "none",
						});
					}
				}).finally(()=>{
					this.qrcodeShow = true;
				})
			},
			//生成付款码
			genPayCode() {
				genPayCode(JSON.stringify(this.payParam)).then(res => {
					if (res.code == 200) {
						//付款码
						this.value = res.data;
						this.qrcodeShow = true;
					} else {
						uni.showToast({
							title: this.$languageData.settings.genPayCodeEx,
							icon: "none",
						});
					}
				})
			},
			//生成收款码
			genReceiveCode() {
				genReceiveCode(JSON.stringify(this.receiveParam)).then(res => {
					if (res.code == 200) {
						//付款码
						this.value = res.data;
						this.qrcodeShow = true;
					} else {
						uni.showToast({
							title: this.$languageData.settings.genRecCodeEx,
							icon: "none",
						});
					}
				})
			},
			handleRefresh() {
				this.qrcodeShow = false;
				this.qrcodeShow = true;
			},
			saveQrCode() {
				this.$nextTick(() => {
					this.$refs.qrcode.saveImageToAlbum();
				})
			}
		}
	}
</script>

<style>
</style>