<template>
	<view class="payment-container">
		<!-- 订单状态 -->
		<view class="status-card">
			<view class="status-icon-wrapper">
				<view class="status-icon" :class="orderStatus.class">
					<text class="icon-text">💳</text>
				</view>
			</view>
			<view class="status-text">{{ orderStatus.text }}</view>
			<view class="status-desc">{{ orderStatus.desc }}</view>
		</view>

		<!-- 订单信息 -->
		<view class="order-card">
			<view class="card-header">
				<view class="card-title">{{ $t('payment.orderInfo') }}</view>
			</view>
			<view class="info-item">
				<text class="label">{{ $t('order.orderNo') }}</text>
				<text class="value">{{ orderInfo.orderNo || '-' }}</text>
			</view>
			<view class="info-item">
				<text class="label">{{ $t('order.deviceNo') }}</text>
				<text class="value">{{ orderInfo.deviceNo || '-' }}</text>
			</view>
			<view class="info-item">
				<text class="label">{{ $t('payment.createTime') }}</text>
				<text class="value">{{ orderInfo.createTime || '-' }}</text>
			</view>
		</view>

		<!-- 费用信息 -->
		<view class="price-card">
			<view class="card-header">
				<view class="card-title">{{ $t('payment.feeInfo') }}</view>
			</view>
			<view class="price-item">
				<text class="label">{{ $t('payment.deposit') }}</text>
				<text class="value">￥{{ orderInfo.deposit || '99.00' }}</text>
			</view>
			<!-- <view class="price-divider"></view> -->
			<view class="price-item total">
				<text class="label">{{ $t('payment.total') }}</text>
				<text class="value">￥{{ totalAmount }}</text>
			</view>
		</view>

		<!-- 支付方式选择 -->
		<view class="payment-methods" v-if="paymentMethods.length > 0">
			<view class="card-header">
				<view class="card-title">支付方式</view>
			</view>
			<view class="method-item" v-for="method in paymentMethods" :key="method?.paymentMethodType"
				:class="{ active: selectedPaymentMethod === method?.paymentMethodType }"
				@click="selectPaymentMethod(method?.paymentMethodType)">
				<view class="method-info">
					<view class="method-icon">
						<image :src="method?.logo?.logoUrl" mode="aspectFit" style="width: 48rpx; height: 48rpx;">
						</image>
					</view>
					<text class="method-name">{{ method?.logo?.logoName }}</text>
				</view>
				<view class="method-radio" :class="{ checked: selectedPaymentMethod === method?.paymentMethodType }">
				</view>
			</view>
		</view>

		<!-- 底部操作栏 -->
		<view class="bottom-bar">
			<view class="total-amount">
				<text class="label-text">{{ $t('payment.total') }}：</text>
				<text class="amount">￥{{ totalAmount }}</text>
			</view>
			<view class="pay-btn" @click="handlePayment">
				<text>{{ $t('payment.payNow') }}</text>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		computed,
		reactive,
		onMounted
	} from 'vue'
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import {
		queryById,
		createAntomPayment,
		getAntomPaymentMethods,
		getAntomPaymentStatus
	} from '@/config/api/order.js'
	import {
		getDeviceInfo
	} from '@/config/api/device.js'
	import {
		updateUserBalance
	} from '@/config/api/user.js'
	import {
		useI18n
	} from '@/utils/i18n.js'

	const {
		t
	} = useI18n()
	
	const orderId = ref(null)
	const deviceNo = ref(null)
	const orderInfo = ref({})
	const deviceInfo = ref(null)
	const passedTotalAmount = ref(null)
	const passedDepositAmount = ref(null)

	// 支付方式相关
	const paymentMethods = ref([])
	const selectedPaymentMethod = ref('ALIPAY') // 默认选择支付宝

	const orderStatus = reactive({
		get text() {
			return t('payment.waitingForPayment')
		},
		get desc() {
			return t('payment.pleasePayIn15Min')
		},
		class: 'waiting'
	})

	const totalAmount = computed(() => {
		if (passedTotalAmount.value !== null) {
			return parseFloat(passedTotalAmount.value).toFixed(2);
		}
		const deposit = parseFloat(orderInfo.value.deposit || passedDepositAmount.value || 99)
		return deposit.toFixed(2)
	})

	// 加载订单信息
	const loadOrderInfo = async () => {
		// 检查 orderId 是否存在，如果不存在则尝试从缓存获取
		if (!orderId.value) {
			// #ifdef H5
			const cachedOrderId = uni.getStorageSync('pendingPaymentNo');
			if (cachedOrderId) {
				orderId.value = cachedOrderId;
			}
			// #endif
		}

		// 如果两种方式都获取不到 orderId，提示并跳转
		if (!orderId.value) {
			uni.showToast({
				title: t('order.orderNotExist'),
				icon: 'none'
			});
			setTimeout(() => {
				uni.switchTab({
					url: '/pages/index/index'
				});
			}, 1500);
			return;
		}

		try {
			uni.showLoading({
				title: t('common.loading')
			})

			const res = await queryById(orderId.value)
			if (res.code === 200 && res.data) {
				const orderData = res.data

				// 处理创建时间
				let formattedTime;
				try {
					if (orderData.createTime) {
						formattedTime = formatTime(new Date(orderData.createTime));
					} else {
						formattedTime = formatTime(new Date());
					}
				} catch (e) {
					console.error('时间格式化错误:', e);
					formattedTime = formatTime(new Date());
				}

				orderInfo.value = {
					orderNo: orderData.orderNo || orderData.orderId,
					deviceNo: orderData.deviceNo,
					createTime: formattedTime,
					deposit: passedDepositAmount.value || orderData.depositAmount || '99.00',
				}

				deviceNo.value = orderData.deviceNo;
				await loadDeviceInfo();
				await loadPaymentMethods();
			} else {
				throw new Error(t('order.getOrderFailed'))
			}
		} catch (error) {
			console.error('获取订单信息失败:', error)
			uni.showToast({
				title: error.message || t('order.getOrderFailed'),
				icon: 'none'
			})
		} finally {
			uni.hideLoading()
		}
	}

	// 加载设备信息
	const loadDeviceInfo = async () => {
		if (!deviceNo.value) return;

		try {
			const res = await getDeviceInfo(deviceNo.value);
			if (res.code === 200 && res.data) {
				deviceInfo.value = res.data.device;

				if (deviceInfo.value && deviceInfo.value.depositAmount) {
					orderInfo.value.deposit = deviceInfo.value.depositAmount;
				}
			}
		} catch (error) {
			console.error('获取设备信息失败:', error);
		}
	}

	// 获取操作系统类型
	const getOsType = () => {
		const systemInfo = uni.getSystemInfoSync();
		console.log(uni.getSystemInfoSync());

		const platform = systemInfo.platform;
		console.log('当前系统类型:', uni.getSystemInfoSync().platform);

		// 根据平台返回对应的 osType
		if (platform === 'android') {
			return 'ANDROID';
		} else if (platform === 'ios') {
			return 'IOS';
		} else {
			// 默认返回 ANDROID
			return 'ANDROID';
		}
	}

	// 加载支付方式列表
	const loadPaymentMethods = async () => {
		if (!orderInfo.value.orderNo) return;

		try {
			const osType = getOsType();
			console.log('当前系统类型:', osType);

			const res = await getAntomPaymentMethods(orderInfo.value.orderNo, osType);
			if (res.code === 200 && res.data && res.data.paymentOptions) {
				paymentMethods.value = res.data.paymentOptions;
				console.log('支付方式列表:', paymentMethods.value);
				// 如果有支付方式，默认选择第一个
				if (paymentMethods.value.length > 0) {
					selectedPaymentMethod.value = paymentMethods.value[0].paymentMethodType;
				}
			}
		} catch (error) {
			console.error('获取支付方式失败:', error);
			// 如果获取失败，使用默认支付方式
			paymentMethods.value = [{
					paymentMethodType: 'ALIPAY',
					paymentMethodName: '支付宝'
				},
				{
					paymentMethodType: 'WECHATPAY',
					paymentMethodName: '微信支付'
				}
			];
		}
	}

	// 选择支付方式
	const selectPaymentMethod = (methodType) => {
		selectedPaymentMethod.value = methodType;
	}

	// 获取支付方式图标
	const getPaymentIcon = (methodType) => {
		const iconMap = {
			'ALIPAY': 'alipay',
			'WECHATPAY': 'wechat',
			'WECHAT': 'wechat'
		};
		return iconMap[methodType] || 'default';
	}

	// 处理支付
	const handlePayment = async () => {
		if (!selectedPaymentMethod.value) {
			uni.showToast({
				title: '请选择支付方式',
				icon: 'none'
			});
			return;
		}

		try {
			uni.showLoading({
				title: t('common.processing')
			})

			const osType = getOsType();
			const res = await createAntomPayment(orderInfo.value.orderNo, selectedPaymentMethod.value, osType)

			if (res && res.code === 200 && res.data) {
				const paymentUrl = res.data.h5Url;

				if (!paymentUrl) {
					throw new Error('未获取到支付链接');
				}

				uni.hideLoading();
				 // #ifdef H5
				uni.setStorageSync('pendingPaymentNo', orderId.value);
				// #endif

				// 跳转到支付页面
				uni.navigateTo({
					url: `/pages/webview/index?url=${encodeURIComponent(paymentUrl)}&title=支付`
				});

				// 开始轮询支付状态
				startPaymentStatusPolling();

			} else {
				throw new Error(res?.msg || t('payment.createPayOrderFailed'))
			}
		} catch (error) {
			console.error('支付失败:', error)
			uni.showToast({
				title: error.message || t('payment.paymentFailed'),
				icon: 'none'
			})
		} finally {
			uni.hideLoading()
		}
	}

	// 轮询支付状态
	let pollingTimer = null;
	const startPaymentStatusPolling = () => {
		// 清除之前的定时器
		if (pollingTimer) {
			clearInterval(pollingTimer);
		}

		let pollCount = 0;
		const maxPollCount = 60; // 最多轮询60次（5分钟）

		pollingTimer = setInterval(async () => {
			pollCount++;

			if (pollCount > maxPollCount) {
				clearInterval(pollingTimer);
				uni.showToast({
					title: '支付超时，请重新支付',
					icon: 'none'
				});
				return;
			}

			try {
				const osType = getOsType();
				const res = await getAntomPaymentStatus(orderInfo.value.orderNo, osType);
				if (res && res.code === 200 && res.data) {
					const paymentStatus = res.data.paymentStatus;

					if (paymentStatus === 'SUCCESS') {
						clearInterval(pollingTimer);

						// uni.showToast({
						//   title: t('payment.paymentSuccess'),
						//   icon: 'success'
						// });

						try {
							await updateUserBalance(orderId.value);
						} catch (error) {
							console.warn('更新用户余额失败:', error);
						}
						console.log(orderInfo);

						setTimeout(() => {
							uni.redirectTo({
								url: `/pages/order/success?orderId=${orderId.value}&deviceId=${orderInfo.value.deviceNo}`
							});
						}, 1500);
					} else if (paymentStatus === 'FAIL' || paymentStatus === 'CANCELLED') {
						clearInterval(pollingTimer);
						uni.showToast({
							title: '支付失败，请重新支付',
							icon: 'none'
						});
					}
				}
			} catch (error) {
				console.error('查询支付状态失败:', error);
			}
		}, 5000); // 每5秒查询一次
	}

	// 页面卸载时清除定时器
	onMounted(() => {
		return () => {
			if (pollingTimer) {
				clearInterval(pollingTimer);
			}
		};
	});

	// 格式化时间
	const formatTime = (date) => {
		const year = date.getFullYear()
		const month = (date.getMonth() + 1).toString().padStart(2, '0')
		const day = date.getDate().toString().padStart(2, '0')
		const hour = date.getHours().toString().padStart(2, '0')
		const minute = date.getMinutes().toString().padStart(2, '0')

		return `${year}-${month}-${day} ${hour}:${minute}`
	}

	onLoad((options) => {
		uni.setNavigationBarTitle({
			title: t('payment.orderPayment')
		})

		// 优先从 options 中获取 orderId
		if (options && options.orderId) {
			orderId.value = options.orderId

			if (options.totalAmount) {
				passedTotalAmount.value = options.totalAmount;
			}

			if (options.depositAmount) {
				passedDepositAmount.value = options.depositAmount;
			}

			if (options.feeConfig) {
				try {
					const feeConfigStr = decodeURIComponent(options.feeConfig)
					deviceInfo.value = {
						feeConfig: feeConfigStr
					}
				} catch (e) {
					console.error('解析URL中的feeConfig失败:', e)
				}
			}
			
			loadOrderInfo()
		}
		// #ifdef H5
		// 如果 options 中没有 orderId，尝试从缓存中获取（H5 环境）
		else {
			const cachedOrderId = uni.getStorageSync('pendingPaymentNo');
      console.log("订单编号："+cachedOrderId);
      
			if (cachedOrderId) {
				orderId.value = cachedOrderId;
			}
		}
		// #endif

		// 调用 loadOrderInfo，内部会再次检查 orderId 是否存在
		
	})
</script>

<style lang="scss" scoped>
	.payment-container {
		min-height: 100vh;
		background: #f7f8fa;
		padding: 30rpx;
		padding-bottom: 180rpx;
		box-sizing: border-box;

		.status-card {
			background: #fff;
			border-radius: 20rpx;
			padding: 40rpx 30rpx;
			margin-bottom: 20rpx;
			display: flex;
			flex-direction: column;
			align-items: center;
			box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);

			.status-icon-wrapper {
				margin-bottom: 20rpx;

				.status-icon {
					width: 120rpx;
					height: 120rpx;
					border-radius: 50%;
					display: flex;
					align-items: center;
					justify-content: center;

					.icon-text {
						font-size: 60rpx;
					}

					&.waiting {
						background: #FFF9C4;
					}

					&.success {
						background: #E8F5E9;
					}

					&.failed {
						background: #FFEBEE;
					}
				}
			}

			.status-text {
				font-size: 36rpx;
				font-weight: bold;
				color: #333;
				margin-bottom: 10rpx;
			}

			.status-desc {
				font-size: 28rpx;
				color: #999;
			}
		}

		.order-card,
		.price-card,
		.payment-methods {
			background: #fff;
			border-radius: 20rpx;
			padding: 30rpx;
			margin-bottom: 20rpx;
			box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);

			.card-header {
				margin-bottom: 24rpx;

				.card-title {
					font-size: 32rpx;
					font-weight: bold;
					color: #333;
				}
			}

			.info-item,
			.price-item {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 16rpx 0;
				border-bottom: 1rpx solid #f0f0f0;

				&:last-child {
					border-bottom: none;
				}

				.label {
					font-size: 28rpx;
					color: #999;
				}

				.value {
					font-size: 28rpx;
					color: #333;
					text-align: right;
				}
			}

			.price-divider {
				height: 1rpx;
				background: #f0f0f0;
				margin: 10rpx 0;
			}

			.price-item.total {
				margin-top: 10rpx;
				padding-top: 20rpx;
				border-top: none;

				.label {
					font-size: 28rpx;
					color: #999;
				}

				.value {
					font-size: 48rpx;
					font-weight: bold;
					color: #ff6b6b;
				}
			}
		}

		.payment-methods {
			.method-item {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 24rpx 20rpx;
				margin-bottom: 16rpx;
				background: #f7f8fa;
				border-radius: 12rpx;
				border: 2rpx solid transparent;

				&:last-child {
					margin-bottom: 0;
				}

				&.active {
					background: #E8F5E9;
					border-color: #07c160;
				}

				.method-info {
					display: flex;
					align-items: center;

					.method-icon {
						width: 48rpx;
						height: 48rpx;
						margin-right: 16rpx;
						border-radius: 8rpx;

						&.alipay {
							background: #1677FF;
						}

						&.wechat {
							background: #07C160;
						}

						&.default {
							background: #999;
						}
					}

					.method-name {
						font-size: 30rpx;
						color: #333;
						font-weight: 500;
					}
				}

				.method-radio {
					width: 40rpx;
					height: 40rpx;
					border: 2rpx solid #ddd;
					border-radius: 50%;
					position: relative;

					&.checked {
						border-color: #07c160;
						background: #07c160;

						&::after {
							content: '';
							position: absolute;
							top: 50%;
							left: 50%;
							transform: translate(-50%, -50%);
							width: 16rpx;
							height: 16rpx;
							background: #fff;
							border-radius: 50%;
						}
					}
				}

				&:active {
					opacity: 0.8;
				}
			}
		}

		.bottom-bar {
			position: fixed;
			left: 0;
			right: 0;
			bottom: 0;
			background: #fff;
			padding: 20rpx 30rpx;
			padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
			display: flex;
			align-items: center;
			justify-content: space-between;
			box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.04);
			z-index: 10;
			gap: 20rpx;

			.total-amount {
				display: flex;
				align-items: baseline;

				.label-text {
					font-size: 28rpx;
					color: #666;
				}

				.amount {
					font-size: 36rpx;
					font-weight: bold;
					color: #ff6b6b;
					margin-left: 8rpx;
				}
			}

			.pay-btn {
				height: 88rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				background: #07c160;
				color: #fff;
				font-size: 30rpx;
				font-weight: 600;
				padding: 0 60rpx;
				border-radius: 44rpx;
				border: none;

				&:active {
					opacity: 0.8;
				}
			}
		}
	}
</style>