<template>
	<div class="pay-order-box">
		<div class="pay-order-item"><span class="label">订单编号：</span><span>{{orderNo}}</span></div>
		<div class="pay-order-item"><span class="label">支付方式：</span><span>微信支付</span></div>
		<div v-if="state === 'NOTPAY'">
			<el-skeleton :loading="loading" animated>
				<template slot="template">
					<div class="pay-img">
						<el-skeleton-item variant="image" style="width: 300px; height: 300px;"></el-skeleton-item>
					</div>
				</template>
				<template>
					<div class="pay-img" v-if="payUrl">
						<img :src="payUrl" alt="pay.png" />
					</div>
				</template>
			</el-skeleton>
		</div>
		<div v-else-if="state === 'SUCCESS'">
			<el-result icon="success" title="支付成功">
				<template slot="extra">
					<slot></slot>
				</template>
			</el-result>
		</div>
	</div>
</template>

<script>
	import {
		createPayQR,
		getOrderPayState
	} from '@/api/pay'
	export default {
		props: ['orderNo'],
		data() {
			return {
				payUrl: '',
				timer: null,
				state: 'NOTPAY',
				loading: false
			}
		},
		mounted() {
			this.init();
		},
		beforeDestroy() {
			this.stopTimer();
		},
		methods: {
			init() {
				this.loading = true;
				createPayQR(this.orderNo).then(res => {
					if (res.state) {
						this.payUrl = res.data.base64;
						this.findState();
					}
					this.loading = false;
				})
			},
			findState() {
				this.timer = setInterval(() => {
					getOrderPayState(this.orderNo).then(res => {
						if (res.state) {
							this.state = res.data;
							if (this.state !== 'NOTPAY') this.stopTimer();
							if (this.state === 'SUCCESS') this.$emit('callback', 'payState');
						}
					})
				}, 3000)
			},
			stopTimer() {
				if (!this.timer) return;
				clearTimeout(this.timer);
				this.timer = null;
			}
		},
	}
</script>

<style lang="scss">
	.pay-order-box {
		padding: 20px;

		.pay-order-item {
			margin-bottom: 10px;

			.label {
				font-weight: bold;
			}
		}

		.pay-img {
			display: flex;
			justify-content: center;
			align-items: center;

			img {
				width: 300px;
				height: 300px;
			}
		}
	}
</style>