<template>
	<view>

	</view>
</template>

<script>
	import {
		wxLogin,
	} from '../../../util/index'

	import {
		getMyIndexInfo
	} from "../../../config/user.js";
	import {
		queryHasOrder
	} from "../../../config/user.js";
	import {
		checkOrdersByStatus
	} from "../../../config/user.js";

	export default {
		data() {
			return {

			}
		},
		async onLoad(option) {
			console.log('bagCheck onLoad option:', option);
			try {
				uni.showLoading({
					title: '处理中...',
					mask: true
				});

				// 检查是否传入设备编号
				if (!option || !option.deviceNo) {
					throw new Error('未识别到设备编号');
				}

				const deviceNo = option.deviceNo;
				
				// 检查用户是否有进行中(in_used)或待支付(waiting_for_payment)的订单
				const statusesToCheck = ['in_used', 'waiting_for_payment'];
				const res = await checkOrdersByStatus(deviceNo, statusesToCheck);

				if (res.code === 200 && res.data && res.data.length > 0) {
					// 找到相关订单，取最新的一条
					const latestOrder = res.data[0]; // 假设返回结果按时间倒序

					if (latestOrder.orderStatus === 'in_used') {
						// 如果是使用中的订单，跳转到归还页面
						console.log('检测到使用中订单，跳转归还页:', latestOrder.orderId);
						uni.redirectTo({
							url: `/pages/device/return?orderId=${latestOrder.orderId}`
						});
					} else if (latestOrder.orderStatus === 'waiting_for_payment') {
						// 如果是待支付订单，跳转到支付页面，并传递必要信息
						console.log('检测到待支付订单，跳转支付页:', latestOrder.orderId);
						const packageTime = latestOrder.packageTime ? `${latestOrder.packageTime / 60}小时` : '默认套餐'; // 示例转换
						const packagePrice = latestOrder.packagePrice || '0.00';
						const depositAmount = latestOrder.depositAmount || '99.00';
						const totalAmount = (parseFloat(depositAmount) + parseFloat(packagePrice)).toFixed(2);
						
						uni.redirectTo({
							url: `/pages/order/payment?orderId=${latestOrder.orderId}&packageTime=${packageTime}&packagePrice=${packagePrice}&totalAmount=${totalAmount}&depositAmount=${depositAmount}`
						});
					} else {
						// 其他状态（理论上不应该到这里，除非statusesToCheck配置错误），默认到详情页
						console.log('检测到其他状态订单，跳转详情页:', latestOrder.orderId);
						uni.redirectTo({
							url: `/pages/device/detail?deviceNo=${deviceNo}`
						});
					}
				} else {
					// 没有找到相关状态的订单，跳转到设备详情页进行租借
					console.log('未检测到相关订单，跳转详情页');
					uni.redirectTo({
						url: `/pages/device/detail?deviceNo=${deviceNo}`
					});
				}
			} catch (error) {
				console.error('扫码检查订单失败:', error);
				uni.showToast({
					title: error.message || '处理失败，请稍后重试',
					icon: 'none',
					duration: 2000
				});
				// 错误时也尝试跳转到详情页，给用户一个操作入口
				setTimeout(() => {
				    if (option && option.deviceNo) {
					    uni.redirectTo({
					        url: `/pages/device/detail?deviceNo=${option.deviceNo}`
					    });
				    } else {
                        // 如果连deviceNo都没有，则返回首页
                        uni.switchTab({ url: '/pages/index/index' });
                    }
				}, 2000);
			} finally {
				uni.hideLoading();
			}
		},
		methods: {

		}
	}
</script>

<style>

</style>