<template>
	<div>
		<p v-if="$team.pg.currency === 'CNY'" class="mt-3 text-p-sm">
			如果您选择 Razorpay，您可以使用信用卡、借记卡、网上银行、UPI、钱包等方式支付。如果您使用网上银行，余额可能需要最多 5 天才能到账。
		</p>
		<ErrorMessage
			class="mt-3"
			:message="$resources.createRazorpayOrder.error"
		/>
		<div class="mt-4 flex w-full justify-between">
			<div></div>
			<Button
				variant="solid"
				:loading="$resources.createRazorpayOrder.loading"
				v-if="!isPaymentComplete"
				@click="buyCreditsWithRazorpay"
			>
				使用 Razorpay 继续支付
			</Button>
			<Button v-else variant="solid" :loading="isVerifyingPayment"
				>正在确认支付</Button
			>
		</div>
	</div>
</template>
<script>
import { toast } from 'vue-sonner';
import { DashboardError } from '../utils/error';

export default {
	name: 'BuyPrepaidCreditsRazorpay',
	props: {
		amount: {
			default: 0
		},
		minimumAmount: {
			default: 0
		},
		isOnboarding: {
			default: false
		}
	},
	data() {
		return {
			isPaymentComplete: false,
			isVerifyingPayment: false
		};
	},
	mounted() {
		this.razorpayCheckoutJS = document.createElement('script');
		this.razorpayCheckoutJS.setAttribute(
			'src',
			'https://checkout.razorpay.com/v1/checkout.js'
		);
		this.razorpayCheckoutJS.async = true;
		document.head.appendChild(this.razorpayCheckoutJS);
	},
	resources: {
		createRazorpayOrder() {
			return {
				url: 'jcloud.api.billing.create_razorpay_order',
				params: {
					amount: this.amount
				},
				onSuccess(data) {
					this.processOrder(data);
				},
				validate() {
					if (this.amount < this.minimumAmount) {
						throw new DashboardError(
							'金额低于最低要求金额'
						);
					}
				}
			};
		},
		handlePaymentFailed() {
			return {
				url: 'jcloud.api.billing.handle_razorpay_payment_failed',
				onSuccess() {
					console.log('支付失败。');
				}
			};
		}
	},
	methods: {
		buyCreditsWithRazorpay() {
			this.$resources.createRazorpayOrder.submit();
		},
		processOrder(data) {
			const options = {
				key: data.key_id,
				order_id: data.order_id,
				name: 'Jingrow',
				image: '/assets/jcloud/images/jingrow-cloud-logo.png',
				prefill: {
					email: this.$team.pg.user
				},
				handler: this.handlePaymentSuccess,
				theme: { color: '#171717' }
			};

			const rzp = new Razorpay(options);

			// 打开支付结账窗口
			rzp.open();

			// 附加失败处理程序
			rzp.on('payment.failed', this.handlePaymentFailed);
			// rzp.on('payment.success', this.handlePaymentSuccess);
		},
		handlePaymentFailed(response) {
			this.$resources.handlePaymentFailed.submit({ response });
			toast.error('支付失败');
		},
		handlePaymentSuccess() {
			this.isPaymentComplete = true;
			if (this.isOnboarding) {
				this.checkForOnboardingPaymentCompletion();
			} else {
				this.$emit('success');
				toast.success('支付成功');
			}
		},
		async checkForOnboardingPaymentCompletion() {
			this.isVerifyingPayment = true;
			await this.$team.reload();
			if (!this.$team.pg.payment_mode) {
				setTimeout(this.checkForOnboardingPaymentCompletion, 2000);
			} else {
				this.isVerifyingPayment = false;
				this.$emit('success');
			}
		}
	},
	beforeUnmount() {
		this.razorpayCheckoutJS?.remove();
	}
};
</script>