<template>
	<view class="order-container">
		<!-- 状态切换 -->
		<view class="status-tabs">
			<view v-for="(tab, index) in orderStatusTabs" :key="index" class="tab-item"
				:class="{ active: currentTab === index }" @click="switchTab(index)">
				{{ tab.text }}
			</view>
		</view>

		<!-- 订单列表 -->
		<view class="order-list">
		<view class="empty-state" v-if="orderList.length === 0">
			<view class="empty-icon">
				<image src="/static/orderList.png" mode="aspectFill" class="empty-icon"></image>
			</view>
			<text class="empty-text">{{ $t('order.noOrderRecord') }}</text>
		</view>

			<OrderItemCard
				v-for="(order, index) in orderList"
				:key="index"
				:order="order"
				:orderStatusMap="orderStatusMap"
				@pay="handlePayment"
				@cancel="handleCancelOrder"
				@return-device="onReturnDevice"
				@details="navigateToDetails"
			/>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		onMounted,
		onUnmounted
	} from 'vue';
    import OrderItemCard from '../../components/OrderItemCard.vue';
	import {
		onLoad
	} from '@dcloudio/uni-app';
	import {
		getOrderList,
		queryById,
		getOrderByOrderNoScorePayStatus,
		cancelOrder
	} from '../../config/api/order.js';
	import {
		confirmPaymentAndRent
	} from '../../config/api/device.js';
	import {
		updateUserBalance
	} from '../../config/api/user.js';
	import {
		URL
	} from '../../config/url.js';
	import { useI18n } from '@/utils/i18n.js'
	
	const { t: $t } = useI18n()

	// 初始化状态
	const currentTab = ref(0);
	const orderList = ref([]);

	// 订单状态映射
	const orderStatusMap = reactive({
		'0': {
			get text() { return $t('order.waitingForPayment') },
			class: 'status-waiting'
		},
		'1': {
			get text() { return $t('order.inUse') },
			class: 'status-using'
		},
		'2': {
			get text() { return $t('order.finished') },
			class: 'status-finished'
		},
		'3': {
			get text() { return $t('order.cancelled') },
			class: 'status-cancelled'
		},
		'waiting_for_payment': {
			get text() { return $t('order.waitingForPayment') },
			class: 'status-waiting'
		},
		'in_used': {
			get text() { return $t('order.inUse') },
			class: 'status-using'
		},
		'used_done': {
			get text() { return $t('order.finished') },
			class: 'status-finished'
		},
		'order_cancelled': {
			get text() { return $t('order.cancelled') },
			class: 'status-cancelled'
		},
		'express_return': {
			get text() { return $t('express.title') },
			class: 'status-express-return'
		}
	});

	// 订单状态标签
	const orderStatusTabs = reactive([{
			get text() { return $t('common.all') },
			status: []
		},
		{
			get text() { return $t('order.waitingForPayment') },
			status: ['waiting_for_payment']
		},
		{
			get text() { return $t('order.inUse') },
			status: ['in_used']
		},
		{
			get text() { return $t('order.finished') },
			status: ['used_done']
		},
		{
			get text() { return $t('order.cancelled') },
			status: ['order_cancelled']
		}
	]);

	// 页面加载
	onLoad(async (options) => {
		// 如果有传入orderId参数，说明是从设备租借页面跳转过来的
		if (options && options.orderId) {
			try {
				// 获取特定订单信息
				const res = await queryById(options.orderId);
				if (res.code === 200 && res.data) {
					// 获取到的订单数据
					const orderData = res.data;

					// 使用实际的startTime字段，如果没有则尝试使用createTime
					const orderStartTime = orderData.startTime || orderData.createTime || '';

					// 格式化订单数据
					const formattedOrder = {
						orderNo: orderData.orderId,
						status: orderData.orderStatus,
						deviceId: orderData.deviceNo,
						payWay: orderData.payWay,
						startTime: orderStartTime,
						endTime: orderData.endTime || '',
						positionName: orderData.positionName || orderData.positionLocation || '',
						deviceName: orderData.deviceName || '',
						amount: orderData.payAmount || orderData.actualDeviceAmount || orderData.currentFee || orderData.residueAmount || '0.00'
					};

					// 将订单添加到列表开头
					orderList.value = [formattedOrder, ...orderList.value];

					// 根据订单状态切换到对应标签
					const tabIndex = orderStatusTabs.findIndex(tab =>
						tab.status.includes(orderData.orderStatus)
					);

					if (tabIndex !== -1) {
						switchTab(tabIndex);
					}
				}
			} catch (error) {
				console.error('获取订单详情失败:', error);
			}
		}

		// 获取订单列表
		await loadOrderList();
	});

	// 切换标签
	const switchTab = async (index) => {
		currentTab.value = index;
		// 根据状态获取订单列表
		const statusList = orderStatusTabs[index].status[0];
		await loadOrderList(statusList);
	};

	// 加载订单列表
	const loadOrderList = async (statusList) => {
		try {
			if(statusList!=undefined){
				statusList = {
					orderStatus:statusList
				}
			}
			const res = await getOrderList(statusList);
			if (res.code === 200 && res.data && res.data.records) {
				// 处理订单列表数据
				orderList.value = res.data.records.map(item => {
					// 使用实际的startTime字段，如果没有则尝试使用createTime
					const orderStartTime = item.startTime || item.createTime || '';

					return {
						orderNo: item.orderNo,
						orderId: item.orderId,
						orderStatus: item.orderStatus,
						deviceId: item.deviceNo,
						payWay: item.payWay,
						startTime: orderStartTime,
						endTime: item.endTime || '',
						positionName: item.positionName || item.positionLocation || '',
						deviceName: item.deviceName || '',
						amount: item.payAmount || item.actualDeviceAmount || item.currentFee || item.residueAmount || '0.00'
					};
				});
			}
		} catch (error) {
			console.error('获取订单列表失败:', error);
			uni.showToast({
				title: $t('order.getOrderListFailed'),
				icon: 'none'
			});
		}
	};

	// 处理订单完成事件
	const handleOrderCompleted = (orderData) => {
		console.log('订单列表页收到订单完成事件:', orderData)
		// 刷新订单列表，根据当前选中的标签刷新对应状态的订单
		const statusList = orderStatusTabs[currentTab.value].status[0]
		loadOrderList(statusList)
	}

	// 设置页面标题并监听订单完成事件
	onMounted(() => {
		uni.setNavigationBarTitle({
			title: $t('order.myOrders')
		})
		
		// 监听订单完成事件
		uni.$on('orderCompleted', handleOrderCompleted)
	})
	
	// 页面卸载时移除事件监听
	onUnmounted(() => {
		uni.$off('orderCompleted', handleOrderCompleted)
	})

	// 同步订单状态
	const getOrderStatus = async (order) => {
		try {
			const res = await getOrderByOrderNoScorePayStatus(order.orderNo);
			if (res.code === 200) {
				uni.showToast({
					title: $t('order.syncSuccess'),
					icon: 'success'
				});
				await loadOrderList(orderStatusTabs[currentTab.value].status);
			}
		} catch (error) {
			uni.showToast({
				title: $t('order.syncFailed'),
				icon: 'none'
			});
		}
	};

	// 跳转到订单详情页面（统一入口）
	const navigateToOrderDetail = (order) => {
		uni.navigateTo({
			url: `/pages/order/detail?orderId=${order.orderId || order.orderNo}&deviceId=${order.deviceId}`
		});
	};

	// 组件事件：归还设备（实际跳转到订单详情页）
	const onReturnDevice = (order) => {
		navigateToOrderDetail(order);
	};
	
	// 跳转到订单详情页
	const navigateToDetails = (order) => {
		navigateToOrderDetail(order);
	};
	
	// 立即支付
	const handlePayment = async (order) => {
		try {
			uni.showLoading({
				title: $t('common.processing')
			});
			
			// 调用后端创建微信支付订单接口
			const res = await uni.request({
				url: `${URL || 'http://127.0.0.1:8080'}/app/wx-payment/create/${order.orderNo}`,
				method: 'GET',
				header: {
					'Authorization': "Bearer " + uni.getStorageSync('token'),
					'Clientid': uni.getStorageSync('client_id')
				}
			});

			if (res.statusCode === 200 && res.data.code === 200) {
				const payParams = res.data.data;
				
				// 调用微信支付
				await uni.requestPayment({
					...payParams,
					success: async () => {
						uni.showToast({
							title: $t('payment.paymentSuccess'),
							icon: 'success'
						});
						
						// 更新用户余额
						try {
							await updateUserBalance(order.orderId || order.orderNo);
						} catch (error) {
							console.warn('更新用户余额失败:', error);
						}
						
						// 刷新订单列表
						await loadOrderList(orderStatusTabs[currentTab.value].status);
					},
					fail: (err) => {
						console.error('支付失败:', err);
						throw new Error($t('payment.paymentFailedRetry'));
					}
				});
			} else {
				throw new Error(res.data.msg || '创建支付订单失败');
			}
			
			uni.hideLoading();
		} catch (error) {
			uni.hideLoading();
			uni.showToast({
				title: error.message || $t('payment.paymentFailed'),
				icon: 'none'
			});
		}
	};
	
	// 取消订单
	const handleCancelOrder = async (order) => {
		try {
			uni.showModal({
				title: $t('order.confirmCancel'),
				content: $t('order.confirmCancelContent'),
				success: async (res) => {
					if (res.confirm) {
						uni.showLoading({
							title: $t('common.processing')
						});
						
						const result = await cancelOrder({
							orderId: order.orderNo
						});
						
						if (result) {
							uni.hideLoading();
							uni.showToast({
								title: $t('order.cancelSuccess'),
								icon: 'success'
							});
							
							// 刷新订单列表
							await loadOrderList();
						} else {
							throw new Error(result.msg || $t('order.cancelFailed'));
						}
					}
				}
			});
		} catch (error) {
			uni.hideLoading();
			uni.showToast({
				title: error.message || $t('order.cancelFailed'),
				icon: 'none'
			});
		}
	};
</script>

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

		// 状态标签栏
		.status-tabs {
			display: flex;
			background: #fff;
			padding: 0 20rpx;
			position: sticky;
			top: 0;
			z-index: 10;
			box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

            .tab-item {
				flex: 1;
				height: 90rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 28rpx;
				color: #666;
				position: relative;

				&.active {
                    color: #07c160;
					font-weight: 500;

					&::after {
						content: '';
						position: absolute;
						bottom: 0;
						left: 50%;
						transform: translateX(-50%);
						width: 40rpx;
						height: 4rpx;
                        background: #07c160;
						border-radius: 2rpx;
					}
				}
			}
		}

		// 订单列表
		.order-list {
			padding: 20rpx;

			// 订单项
			.order-item {
				background: #fff;
				border-radius: 16rpx;
				margin-bottom: 20rpx;
				overflow: hidden;
				box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);

				// 订单头部
				.order-header {
					display: flex;
					justify-content: space-between;
					align-items: center;
					padding: 24rpx;
					border-bottom: 1rpx solid #f0f0f0;

					.order-id {
						font-size: 26rpx;
						color: #666;
					}

					.order-status {
						font-size: 26rpx;
						font-weight: 500;

						&.status-waiting {
							color: #FF9800;
						}

                        &.status-using {
                            color: #07c160;
						}

						&.status-finished {
							color: #4CAF50;
						}

						&.status-cancelled {
							color: #9E9E9E;
						}

						&.status-express-return {
							color: #FF9800;
						}
					}
				}

				// 订单内容
				.order-body {
					padding: 24rpx;

					.device-info {
						margin-bottom: 20rpx;
						display: flex;
						justify-content: space-between;
						align-items: flex-start;

						.device-left {
							flex: 1;
							margin-right: 20rpx;

							.device-name {
								font-size: 32rpx;
								font-weight: 500;
								color: #333;
								margin-bottom: 6rpx;
							}

							.device-id {
								font-size: 26rpx;
								color: #999;
								margin-bottom: 0;
							}
						}

						.device-right {

							// 支付分标识
							.payment-badge {
								display: inline-flex;
								align-items: center;
								padding: 6rpx 12rpx;
								border-radius: 8rpx;
								white-space: nowrap;

								&.wx-score {
									background: rgba(7, 193, 96, 0.08);

									.badge-icon {
										width: 32rpx;
										height: 26rpx;
										margin-right: 8rpx;
									}

									.badge-text {
										font-size: 22rpx;
										color: #07c160;
										display: flex;
										align-items: center;

										.divider {
											margin: 0 6rpx;
										}

										.highlight {
											font-weight: 500;
										}
									}
								}

								&.member {
									background: rgba(25, 118, 210, 0.08);

									.badge-text {
										font-size: 22rpx;
										color: #1976D2;
										font-weight: 500;
									}
								}

								&.deposit {
									background: #f5f5f5;

									.badge-text {
										font-size: 22rpx;
										color: #666;
										font-weight: 500;
									}
								}
							}
						}
					}

					.order-times {
						.time-row {
							display: flex;
							font-size: 26rpx;
							margin-bottom: 8rpx;

							.time-label {
								color: #999;
								width: 140rpx;
							}

							.time-value {
								color: #333;
								flex: 1;
							}
						}
					}
				}

				// 订单底部
				.order-footer {
					display: flex;
					justify-content: space-between;
					align-items: center;
					padding: 20rpx 24rpx;
					background: #fafafa;
					border-top: 1rpx solid #f0f0f0;

					.price {
						font-size: 34rpx;
						font-weight: 500;
						color: #ff6b6b;
					}

					.actions {
						display: flex;
						flex-wrap: wrap;
                        justify-content: flex-end;

						.action-item {
							font-size: 26rpx;
							padding: 10rpx 30rpx;
							border-radius: 30rpx;
							margin-left: 20rpx;
							display: flex;
							align-items: center;
							justify-content: center;
                            margin-bottom: 10rpx;

                            &.primary {
                                background: #07c160;
                                color: #fff;
                            }

							&.secondary {
								background: #f5f5f5;
								color: #666;
								border: 1rpx solid #e0e0e0;
							}

							&:active {
								opacity: 0.8;
							}
						}
					}
				}
			}

			// 空状态
			.empty-state {
				padding: 100rpx 0;
				text-align: center;

				.empty-icon {
					width: 180rpx;
					height: 180rpx;
					margin: 0 auto 30rpx;
					background: #f5f5f5;
					// border-radius: 50%;
				}

				.empty-text {
					font-size: 28rpx;
					color: #999;
				}
			}
		}
	}
</style>