<template>
	<div>
		<ErrorMessage
			class="mt-3"
			:message="$resources.createAlipayOrder.error || error"
		/>
		<div class="mt-4 flex w-full justify-end">
			<Button
				variant="solid"
				class="alipay-btn"
				:loading="$resources.createAlipayOrder.loading || loading"
				@click="processAlipayPayment"
			>
				使用支付宝支付
			</Button>
		</div>
	</div>
</template>

<script>
import { toast } from 'vue-sonner';
import { DashboardError } from '../utils/error';

export default {
	name: 'BuyPrepaidCreditsAlipay',
	props: {
		amount: {
			default: 0
		},
		minimumAmount: {
			default: 0
		},
		isOnboarding: {
			default: false
		}
	},
	data() {
		return {
			loading: false,
			error: null
		};
	},
	resources: {
		createAlipayOrder() {
			return {
				url: 'jcloud.api.billing.create_alipay_order_for_recharge',
				params: {
					amount: this.amount
				},
				validate() {
					if (this.amount <= 0) {
						throw new DashboardError('支付金额必须大于0');
					}
					if (this.amount < this.minimumAmount) {
						throw new DashboardError('金额低于最低要求金额');
					}
				},
				onSuccess(response) {
					window.open(response.payment_url, '_blank');
					
					toast.success('支付页面已在新窗口打开');
					
					// 如果需要检查支付状态
					// this.checkPaymentStatus(response.order_id);
				}
			};
		}
	},
	methods: {
		processAlipayPayment() {
			this.$resources.createAlipayOrder.submit();
		},
		
		// 可选：检查支付状态的方法
		checkPaymentStatus(orderId) {
			const checkInterval = setInterval(() => {
				this.$call('jcloud.api.billing.check_payment_status', {
					order_id: orderId,
					payment_type: 'alipay'
				}).then(result => {
					if (result && result.status === 'Success') {
						clearInterval(checkInterval);
						toast.success('支付成功！账户已充值');
						this.$emit('payment-success');
					}
				}).catch(err => {
					console.error('检查支付状态出错:', err);
				});
			}, 3000);
			
			// 5分钟后停止检查
			setTimeout(() => {
				clearInterval(checkInterval);
			}, 300000);
		}
	}
};
</script>

<style scoped>
.alipay-btn {
	background-color: #1677FF !important;
	border: none;
	color: white;
	border-radius: 4px;
	font-size: 1rem;
	padding: 0.625rem 1.25rem;
	transition: all 0.2s ease;
	box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.alipay-btn:hover {
	background-color: #0e66e7 !important;
	transform: translateY(-1px);
	box-shadow: 0 3px 8px rgba(0, 0, 0, 0.15);
}
</style> 