<template>
	<view class="container">
		<!-- 内容区域 -->
		<view class="content">
			<!-- 顶部背景渐变 -->
			<view class="top-gradient-bg"></view>
			<!-- 订单状态 -->
			<view class="status-section" :class="statusClass">
				<image class="status-icon" :src="getStatusIcon()" mode="aspectFit"></image>
				<text class="status-text">{{ orderData.status }}</text>
				<text v-if="orderData.failureReason" class="failure-reason">{{ orderData.failureReason }}</text>
			</view>

			<!-- 收货地址 - 仅实物商品显示 -->
			<view
				v-if="orderData.productType === 'physical' && orderData.address && Object.keys(orderData.address).length > 0"
				class="address-section">
				<view class="address-left">
					<image class="location-icon" :src="$baseUrl + 'homepage/Q3Res/settlementCenter_addressIcon.png'"
						mode="aspectFit"></image>
					<view class="address-info">
						<text class="address-text">{{ getFullAddress() }}</text>
						<view class="recipient-info">
							<text class="recipient-name">{{ orderData.address.name || '' }}</text>
							<text class="recipient-phone">{{ orderData.address.mobile || orderData.phone || '' }}</text>
						</view>
					</view>
				</view>
				<!-- <view class="arrow-icon">
					<image :src="$baseUrl + 'homepage/Q3Res/rightArrowBtn.png'" mode="aspectFill"></image>
				</view> -->
			</view>

			<!-- 模块1: 商品信息和券码 -->
			<view class="module-product-info">
				<view class="product-detail">
					<view class="product-image">
						<!-- 优先使用后端返回的goodsImage -->
						<image v-if="orderData.goodsImage && orderData.goodsImage.length > 0"
							:src="orderData.goodsImage[0]" mode="aspectFill" class="product-img" />
						<!-- 使用goodsIcon作为备选图片源 -->
						<image v-else-if="orderData.goodsIcon" :src="orderData.goodsIcon" mode="aspectFill"
							class="product-img" />
						<!-- 其次使用二维码图片（针对虚拟商品） -->
						<image
							v-else-if="orderData.productType === 'virtual' && orderData.coupon && orderData.coupon.qrImage"
							:src="orderData.coupon.qrImage" mode="aspectFill" class="product-img" />
						<!-- 最后显示占位文本 -->
						<text v-else class="image-placeholder">{{ orderData.productType === 'virtual' ? '优惠券' : '商品'
						}}</text>
					</view>
					<view class="product-info">
						<text class="product-name">{{ orderData.productName }}</text>
						<text v-if="orderData.productType === 'physical' && orderData.skuDesc" class="product-spec">{{
							orderData.skuDesc }}</text>
						<view class="price-quantity-row">
							<text class="product-price">{{ orderData.price }}</text>
							<text class="product-quantity">x{{ orderData.quantity }}</text>
						</view>
					</view>
				</view>

				<!-- 券码和过期时间 - 异业卡券 -->
				<view v-if="orderData.productType === 'virtual'" class="coupon-section">
					<!-- 券码展示 - 异业卡券 -->
					<view
						v-if="orderData.virtualType === 'card' && orderData.coupon && orderData.coupon.cards && orderData.coupon.cards.length > 0 && orderData.coupon.cards[0].code"
						class="coupon-code-item">
						<!-- 当只有code没有pwd时显示券码，否则显示卡号 - label和value在同一行 -->
						<div class="coupon-field">
							<text class="coupon-label">{{ orderData.coupon.cards[0].pwd ? '卡号' : '券码' }}</text>
							<div class="coupon-code-content">
								<text class="coupon-code">{{ orderData.coupon.cards[0].code }}</text>
								<text class="copy-btn" @click="copyCouponCode(orderData.coupon.cards[0].code)">复制</text>
							</div>
						</div>

						<!-- 卡密展示 - 如果存在pwd字段，在独立行中显示 -->
						<div v-if="orderData.coupon.cards[0].pwd" class="coupon-field">
							<text class="coupon-label">卡密</text>
							<div class="coupon-code-content">
								<text class="coupon-code">{{ orderData.coupon.cards[0].pwd }}</text>
								<text class="copy-btn" @click="copyCouponCode(orderData.coupon.cards[0].pwd)">复制</text>
							</div>
						</div>
					</view>

					<!-- 过期时间 -->
					<div v-if="orderData.expireTime" class="coupon-field">
						<text class="coupon-label">{{ orderData.virtualType === 'coupon' ? '优惠券时间' : '过期时间' }}</text>
						<text class="expire-time">{{ orderData.expireTime }}</text>
					</div>
				</view>
			</view>

			<!-- 模块3: 使用说明 -->
			<view v-if="orderData.productType === 'virtual' && (orderData.usageInstructions || orderData.goodsContent)"
				class="module-instructions">
				<text class="section-title">{{ orderData.virtualType === 'card' ? '使用说明' : '商品说明' }}</text>
				<rich-text v-if="orderData.goodsContent" :nodes="orderData.goodsContent"
					class="instruction-content"></rich-text>
				<text v-else-if="orderData.usageInstructions" class="instruction-text">{{
					orderData.usageInstructions }}</text>
			</view>

			<!-- 模块3: 商品总价 -->
			<view class="module-payment">
				<!-- 支付汇总/积分信息 -->
				<!-- 优选券显示积分信息 -->
				<template v-if="orderData.productType === 'virtual' && orderData.virtualType === 'coupon'">
					<view class="payment-row">
						<text class="payment-label">商品积分</text>
						<text class="payment-value">{{ orderData.totalPrice }}</text>
					</view>
					<view class="payment-total">
						<text class="total-label">实付:</text>
						<text class="total-value">{{ orderData.actualPayment }}</text>
					</view>
				</template>
				<!-- 异业卡券和实物商品显示价格信息 -->
				<template v-else>
					<view class="payment-row">
						<text class="payment-label">商品总价</text>
						<text class="payment-value">{{ orderData.totalPrice }}</text>
					</view>
					<view v-if="orderData.productType === 'physical'" class="payment-row">
						<text class="payment-label">运费</text>
						<text class="payment-value">¥0.00</text>
					</view>
					<view class="payment-total">
						<text class="total-label">实付:</text>
						<text class="total-value">{{ orderData.actualPayment }}</text>
					</view>
				</template>
			</view>

			<!-- 模块4: 订单编号和下单时间 -->
			<view class="module-order-info">
				<view class="info-row">
					<text class="info-label">订单编号</text>
					<view class="info-right">
						<text class="info-value">{{ orderData.orderNumber }}</text>
						<text class="copy-btn" @click="copyOrderNumber">复制</text>
					</view>
				</view>
				<view class="info-row">
					<text class="info-label">下单时间</text>
					<text class="info-value">{{ orderData.orderTime }}</text>
				</view>
			</view>

			<!-- 物流信息 - 仅实物商品且已发货/已完成时显示 -->
			<view
				v-if="orderData.productType === 'physical' && (orderData.status === 'shipped' || orderData.status === 'completed' || orderData.status === '已发货' || orderData.status === '已完成') && orderData.logisticsList && orderData.logisticsList.length > 0"
				class="module-logistics">
				<view v-for="(logistics, index) in orderData.logisticsList" :key="index" class="logistics-content"
					@click="viewLogistics(index)">
					<!-- 显示包裹序号 -->
					<view v-if="orderData.logisticsList.length > 1" class="package-number">
						<text>包裹 {{ index + 1 }}</text>
					</view>
					<view class="logistics-row">
						<text class="logistics-label">物流公司</text>
						<text class="logistics-value">{{ logistics.company }}</text>
					</view>
					<view class="logistics-row">
						<text class="logistics-label">物流单号</text>
						<view class="logistics-right">
							<text class="logistics-value">{{ logistics.trackingNumber }}</text>
							<text class="copy-btn" @click.stop="copyTrackingNumber(logistics.trackingNumber)">复制</text>
						</view>
					</view>
					<view class="arrow-icon">
						<image class="arrow-image" :src="$baseUrl + 'homepage/Q3Res/rightArrowBtn.png'"
							mode="aspectFill"></image>
					</view>
				</view>
			</view>

			<!-- 操作按钮 - 实物订单退货按钮在右下角 -->
			<view v-if="showActionButton" class="action-container">
				<view v-if="orderData.productType === 'virtual' && orderData.virtualType === 'coupon'"
					class="action-btn btn-use" @click="handleAction">
					<image :src="$baseUrl + 'homepage/Q3Res/orderDetailToUseBtn.png'" mode="aspectFill"></image>
				</view>
				<button v-else class="action-btn" :class="{
					'btn-refund': orderData.productType === 'physical',
					'corner-btn': orderData.productType === 'physical'
				}" @click="handleAction">{{ actionButtonText }}</button>
			</view>

			<!-- 客服按钮 -->
			<view class="service-btn" @click="handleServiceClick">
				<image class="service-icon" :src="$baseUrl + 'homepage/Q3Res/settlementCenter_serviceBtn.png'"
					mode="aspectFit">
				</image>
			</view>
		</view>
	</view>


	<!-- 退货确认弹窗 -->
	<view class="modal-overlay" v-if="showRefundModal" @click="closeRefundModal">
		<view class="modal-content" @click.stop>
			<view class="modal-title">确认退货</view>
			<view class="modal-message">确定要申请退货吗？</view>
			<view class="modal-buttons">
				<view class="modal-btn cancel-btn" @click="closeRefundModal">
					<image :src="$baseUrl + 'homepage/Q3Res/buyCancelBtn.png'" mode="aspectFill"></image>
				</view>
				<view class="modal-btn confirm-btn" @click="confirmRefund">
					<image :src="$baseUrl + 'homepage/Q3Res/buyComfirmBtn.png'" mode="aspectFill"></image>
				</view>
			</view>
			<!-- <view class="modal-disclaimer">申请退货后将由客服进行审核处理</view> -->
		</view>
		<!-- 关闭按钮 -->
		<view class="modal-close-btn" @click="closeRefundModal">
			<image :src="$baseUrl + 'homepage/Q3Res/commonCloseBtn1.png'" mode="aspectFit"></image>
		</view>
	</view>
</template>




<script>
import { getOrderDetail } from '@/api/user.js';
import { useHomeStore } from '@/stores/home';
import { jump, JumpType } from '@/utils/index';
import { fetchOrderCancel } from '../../api/goods';

export default {
	data() {
		return {
			// 订单数据
			orderData: {
				logisticsList: [],
				productType: '', // 'physical' | 'virtual'
				virtualType: '', // 'coupon' | 'card' - 区分优选券和异业卡券
				status: '', // 实物: '等待商家发货' | '已发货' | '已完成' | 虚拟: '交易成功' | '交易关闭'
				statusCode: 'completed', // 'waiting_ship' | 'shipped' | 'completed' | 'success' | 'failed'
				failureReason: '', // 失败原因
				productName: '',
				price: '',
				quantity: 1,
				totalPrice: '',
				actualPayment: '',
				orderNumber: '',
				orderTime: '',
				logisticsCompany: '',
				trackingNumber: '',
				expireTime: '',
				usageInstructions: '',
				// 新增字段
				orderNo: '',
				credits: '',
				creditsDiscount: 0,
				totalCredits: '',
				addCredits: '',
				creditsType: '',
				creditsTypeName: '',
				payPrice: '',
				totalPayPrice: '',
				priceMarket: '',
				buyNum: 1,
				payChannel: [],
				bizDesc: '',
				remark: '',
				skuDesc: '',
				createTime: '',
				flowState: 0,
				useState: 0,
				appGoodsId: 0,
				goodsType: '',
				goodsName: '',
				goodsDesc: '',
				goodsContent: '',
				goodsIcon: '',
				goodsImage: [],
				selfSell: false,
				coupon: {},
				address: {},
				phone: '',
				express: {},
				refundVO: {},
				stores: [],
				checkRule: {},
				failRule: {},
				errMsg: '',
				virtualConfig: {}
			},
			isLoading: true,
			showRefundModal: false
		}
	},
	// onLoad是生命周期钩子，应该直接放在组件对象下
	onLoad(options) {
		console.log('订单详情页面参数:', options);
		if (options.orderId) {
			this.loadOrderDetail(options.orderId);
		} else {
			uni.showToast({
				title: '订单ID不能为空',
				icon: 'none'
			});
			setTimeout(() => {
				uni.navigateBack();
			}, 1500);
		}
	},
	// computed属性应该和methods同级
	computed: {
		// 状态样式类
		statusClass() {
			const statusMap = {
				'waiting_ship': 'status-waiting',
				'shipped': 'status-shipped',
				'completed': 'status-completed',
				'success': 'status-success',
				'failed': 'status-failed'
			};
			return statusMap[this.orderData.statusCode] || 'status-completed';
		},

		// 状态图标样式类
		statusIconClass() {
			const iconMap = {
				'waiting_ship': 'icon-waiting',
				'shipped': 'icon-shipped',
				'completed': 'icon-completed',
				'success': 'icon-success',
				'failed': 'icon-failed'
			};
			return iconMap[this.orderData.statusCode] || 'icon-completed';
		},

		// 状态图标
		statusIcon() {
			const iconMap = {
				'waiting_ship': '①',
				'shipped': '🚚',
				'completed': '✓',
				'success': '✓',
				'failed': '!'
			};
			return iconMap[this.orderData.statusCode] || '✓';
		},

		// 是否显示操作按钮
		showActionButton() {
			return (this.orderData.productType === 'physical' && this.orderData.statusCode === 'waiting_ship') ||
				// 优选券（coupon）显示"去使用"按钮，交易失败不显示
				(this.orderData.productType === 'virtual' && this.orderData.virtualType === 'coupon' &&
					this.orderData.statusCode !== 'failed' && this.orderData.statusCode !== 'cancelled');
		},

		// 操作按钮文本
		actionButtonText() {
			if (this.orderData.productType === 'physical' && this.orderData.statusCode === 'waiting_ship') {
				return '申请退货';
			}
			// 优选券（coupon）显示"去使用"按钮，交易失败不显示
			if (this.orderData.productType === 'virtual' && this.orderData.virtualType === 'coupon' &&
				this.orderData.statusCode !== 'failed' && this.orderData.statusCode !== 'cancelled') {
				return '去使用';
			}
			return '';
		},

		// 操作按钮样式类
		actionBtnClass() {
			return this.orderData.productType === 'virtual' ? 'btn-use' : 'btn-refund';
		}
	},
	methods: {
		// 获取状态图标
		getStatusIcon() {
			const iconMap = {
				'waiting_ship': this.$baseUrl + 'homepage/Q3Res/icon_order_wait.png',
				'shipped': this.$baseUrl + 'homepage/Q3Res/icon_order_sendGoods.png',
				'completed': this.$baseUrl + 'homepage/Q3Res/icon_order_compelete.png',
				'success': this.$baseUrl + 'homepage/Q3Res/icon_order_compelete.png',
				'failed': this.$baseUrl + 'homepage/Q3Res/icon_order_warn.png'
			};
			return iconMap[this.orderData.statusCode] || (this.$baseUrl + 'homepage/Q3Res/icon_order_compelete.png');
		},

		// 加载订单详情
		async loadOrderDetail(orderId) {
			this.isLoading = true;
			try {
				const response = await getOrderDetail({ orderNo: orderId });
				console.log('订单详情接口返回:', response);

				if (response.ok && response.data) {
					this.mapApiDataToOrderData(response.data);
				} else {
					uni.showToast({
						title: response.msg || '获取订单详情失败',
						icon: 'none'
					});
				}
			} catch (error) {
				console.error('获取订单详情失败:', error);
				uni.showToast({
					title: '网络错误，请重试',
					icon: 'none'
				});
			} finally {
				this.isLoading = false;
			}
		},


		// 页面跳转
		navigateToCoupon: () => {
			const url = 'subPackages/shopMainProcess/coupons/couponList';
			const type = JumpType.MINI;
			const extra = {
				appId: 'wx4205ec55b793245e',	//星妈优选小程序
				extraData: {},
				envVersion: 'release',
				embedded: true,
			};

			jump({
				type: type,
				url: url,
				extra: extra
			});
		},

		// 将API数据映射为订单数据
		mapApiDataToOrderData(apiData) {
			// 基础订单信息
			// 订单编号从API获取，确保唯一性
			this.orderData.orderNo = apiData.orderNo || '';
			this.orderData.orderNumber = apiData.orderNo || this.generateOrderNumber(); // 订单编号随机生成且不可重复
			this.orderData.createTime = apiData.createTime || '';
			// 下单时间取用户支付成功时间，如果没有则使用创建时间
			this.orderData.orderTime = apiData.paymentSuccessTime || apiData.createTime;
			this.orderData.flowState = apiData.flowState || 0;
			this.orderData.useState = apiData.useState || 0;
			this.orderData.remark = apiData.remark || '';
			this.orderData.skuDesc = apiData.skuDesc || '';
			this.orderData.errMsg = apiData.errMsg || '';

			// 商品信息
			this.orderData.appGoodsId = apiData.appGoodsId || 0;
			this.orderData.goodsType = apiData.goodsType || '';
			this.orderData.goodsName = apiData.goodsName || '';
			this.orderData.productName = apiData.goodsName || '';
			this.orderData.goodsDesc = apiData.goodsDesc || '';
			this.orderData.goodsContent = apiData.goodsContent || '';
			this.orderData.goodsIcon = apiData.goodsIcon || '';
			this.orderData.goodsImage = apiData.goodsImage || [];
			this.orderData.selfSell = apiData.selfSell || false;

			// 积分和价格信息
			this.orderData.credits = apiData.credits || '';
			this.orderData.creditsDiscount = apiData.creditsDiscount || 0;
			this.orderData.totalCredits = apiData.totalCredits || '';
			this.orderData.addCredits = apiData.addCredits || '';
			this.orderData.creditsType = apiData.creditsType || '';
			this.orderData.creditsTypeName = apiData.creditsTypeName || '积分';
			this.orderData.payPrice = apiData.payPrice || '';
			this.orderData.totalPayPrice = apiData.totalPayPrice || '';
			this.orderData.priceMarket = apiData.priceMarket || '';
			this.orderData.price = apiData.price || '';
			this.orderData.buyNum = apiData.buyNum || 1;
			this.orderData.quantity = apiData.buyNum || 1;

			// 支付渠道
			this.orderData.payChannel = apiData.payChannel || [];

			// 业务描述
			this.orderData.bizDesc = apiData.bizDesc || '';

			// 用户信息
			this.orderData.phone = apiData.phone || '';

			// 复杂对象
			this.orderData.coupon = apiData.coupon || {};
			this.orderData.address = apiData.address || {};
			this.orderData.express = apiData.express || {};
			this.orderData.refundVO = apiData.refundVO || {};
			this.orderData.stores = apiData.stores || [];
			this.orderData.checkRule = apiData.checkRule || {};
			this.orderData.failRule = apiData.failRule || {};
			this.orderData.virtualConfig = apiData.virtualConfig || {};

			// 根据商品类型和状态设置显示信息
			this.setProductTypeAndStatus(apiData);
		},

		// 设置商品类型和状态
		setProductTypeAndStatus(apiData = null) {
			// 根据goodsType判断商品类型
			// Object("实物") - 实物商品，需要展示物流状态
			// Card("卡密"), Charge("直冲"), Link("链接"), Virtual("虚拟") - 非实物商品，不需要展示物流状态
			this.orderData.productType = this.orderData.goodsType === 'Object' ? 'physical' : 'virtual';

			// 区分优选券和异业卡券（根据type字段，异业卡券是card，其它非实物是优选券）
			// 如果没有type字段，根据goodsType判断
			const typeField = apiData ? (apiData.type || apiData.goodsType || '') : (this.orderData.goodsType || '');
			this.orderData.virtualType = typeField.toLowerCase() === 'card' ? 'card' : 'coupon';

			// 根据flowState映射状态
			const statusMapping = this.mapFlowStateToStatus(this.orderData.flowState);
			this.orderData.statusCode = statusMapping.code;
			this.orderData.status = statusMapping.text;
			this.orderData.failureReason = this.orderData.errMsg || '';

			// 非实物商品状态处理
			if (this.orderData.productType === 'virtual') {
				// 异业卡券（card）逻辑：只显示交易成功或交易关闭，没有失败状态
				if (this.orderData.virtualType === 'card') {
					if (statusMapping.code === 'failed' || statusMapping.code === 'cancelled') {
						this.orderData.status = '交易关闭';
					} else {
						this.orderData.status = '交易成功';
					}
					// 异业卡券不显示失败原因
					this.orderData.failureReason = '';
				}
				// 优选券（coupon）逻辑：按实际状态展示
				else {
					if (statusMapping.code === 'failed' || statusMapping.code === 'cancelled') {
						this.orderData.status = '交易失败';
						this.orderData.failureReason = '优惠券发放失败';
					} else {
						this.orderData.status = '交易成功';
						this.orderData.failureReason = '优惠券发放成功';
					}
				}
			}

			// 设置价格显示
			// 统一处理价格显示，优先使用credits字段，显示用户实际支付的积分额
			const creditsValue = this.orderData.credits || '0';
			const creditsType = this.orderData.creditsTypeName || '积分';

			this.orderData.price = `${creditsValue}${creditsType}`;
			this.orderData.totalPrice = `${creditsValue}${creditsType}`;
			// 显示用户实际支付积分额
			this.orderData.actualPayment = `${creditsValue}${creditsType}`;

			// 设置物流信息（仅实物商品）
			if (this.orderData.productType === 'physical') {
				// 处理多物流信息
				if (this.orderData.express && Object.keys(this.orderData.express).length > 0) {
					// 检查是否有多个物流信息
					if (this.orderData.express.logisticsList && Array.isArray(this.orderData.express.logisticsList) && this.orderData.express.logisticsList.length > 0) {
						// 有多物流列表
						this.orderData.logisticsList = this.orderData.express.logisticsList.map(item => ({
							company: item.company || '',
							trackingNumber: item.trackingNumber || item.order_no || ''
						}));
					} else if (this.orderData.express.trackingNumber || this.orderData.express.order_no) {
						// 只有单个物流信息
						this.orderData.logisticsList = [{
							company: this.orderData.express.company || '',
							trackingNumber: this.orderData.express.trackingNumber || this.orderData.express.order_no || ''
						}];
					} else {
						// 兼容旧数据格式或逗号分隔的物流信息
						const companies = (this.orderData.logisticsCompany || '').split(',');
						const trackingNumbers = (this.orderData.express.trackingNumber || this.orderData.express.order_no || this.orderData.trackingNumber || '').split(',');

						this.orderData.logisticsList = [];
						for (let i = 0; i < Math.max(companies.length, trackingNumbers.length); i++) {
							this.orderData.logisticsList.push({
								company: companies[i] || companies[0] || '',
								trackingNumber: trackingNumbers[i] || ''
							});
						}
					}
				} else {
					this.orderData.logisticsList = [];
				}
			}

			// 设置有效期和使用说明（非实物商品）
			if (this.orderData.productType === 'virtual') {
				this.orderData.expireTime = this.orderData.coupon.date;

				// 设置使用说明
				if (apiData && apiData.usageInstructions) {
					this.orderData.usageInstructions = apiData.usageInstructions;
				}
			}
		},

		// 映射订单状态
		mapFlowStateToStatus(flowState) {
			const statusMap = {
				// 处理中状态
				0: { code: 'processing', text: '处理中' },
				11: { code: 'processing', text: '处理中' },
				12: { code: 'pending_payment', text: '待付款' },
				25: { code: 'processing', text: '处理中' },

				// 支付相关状态
				20: { code: 'pending_payment', text: '待付款' },
				21: { code: 'processing', text: '处理中' },
				22: { code: 'payment_failed', text: '支付失败' },
				23: { code: 'audit_waiting', text: '待审核' },

				// 物流相关状态
				30: { code: 'waiting_ship', text: '待发货' },
				31: { code: 'shipped', text: '已发货' },
				32: { code: 'completed', text: '已完成' },

				// 使用相关状态
				40: { code: 'pending_use', text: '待使用' },
				41: { code: 'used', text: '已使用' },

				// 活动相关状态
				13: { code: 'pending_take', text: '待领取' },
				14: { code: 'taken', text: '已领取' },

				// 售后相关状态
				95: { code: 'refund_processing', text: '售后处理中' },
				96: { code: 'refund_success', text: '售后完成' },

				// 订单结束状态
				97: { code: 'failed', text: '交易失败' },
				98: { code: 'cancelled', text: '已取消' },
				99: { code: 'completed', text: '已完成' }
			};
			return statusMap[flowState] || { code: 'completed', text: '已完成' };
		},



		// 获取完整地址
		getFullAddress() {
			if (!this.orderData.address || Object.keys(this.orderData.address).length === 0) {
				return '';
			}

			const address = this.orderData.address;
			const parts = [];

			if (address.province) parts.push(address.province);
			if (address.city) parts.push(address.city);
			if (address.area) parts.push(address.area);
			if (address.town) parts.push(address.town);
			if (address.detail) parts.push(address.detail);
			if (address.floorNo) parts.push(address.floorNo);

			return parts.join('');
		},

		// 复制订单编号
		copyOrderNumber() {
			uni.setClipboardData({
				data: this.orderData.orderNumber,
				success: () => {
					uni.showToast({
						title: '订单编号已复制',
						icon: 'none'
					});
				}
			});
		},

		// 生成订单编号（作为备用方案，当API未返回时使用）
		generateOrderNumber() {
			// 生成16位随机订单号：时间戳+6位随机数
			const timestamp = Date.now();
			const random = Math.floor(Math.random() * 1000000).toString().padStart(6, '0');
			return timestamp + random;
		},

		// 复制物流单号
		copyTrackingNumber(trackingNumber) {
			uni.setClipboardData({
				data: trackingNumber,
				success: () => {
					uni.showToast({
						title: '物流单号已复制',
						icon: 'none'
					});
				}
			});
		},

		// 复制券码
		copyCouponCode(code) {
			uni.setClipboardData({
				data: code,
				success: () => {
					uni.showToast({
						title: '券码已复制',
						icon: 'none'
					});
				}
			});
		},

		// 查看物流详情
		viewLogistics(index) {
			const logistics = this.orderData.logisticsList[index];
			// 跳转到物流页面并传递订单ID和物流信息
			uni.navigateTo({
				url: `/v3/logisticsPage/logisticsPage?orderId=${this.orderData.orderNo || this.orderData.orderNumber}&company=${encodeURIComponent(logistics.company)}&trackingNumber=${encodeURIComponent(logistics.trackingNumber)}`
			});
		},

		// 处理操作按钮点击
		async handleAction() {
			if (this.orderData.productType === 'physical' && this.orderData.statusCode === 'waiting_ship') {
				// 显示自定义确认弹窗
				this.showRefundModal = true;
			}
			// 优选券（coupon）的"去使用"按钮点击跳转
			if (this.orderData.productType === 'virtual' && this.orderData.virtualType === 'coupon' &&
				this.orderData.statusCode !== 'failed' && this.orderData.statusCode !== 'cancelled') {
				// 点击跳转优惠券页面（星妈优选券包）
				this.navigateToCoupon()
			}
		},

		// 关闭退货确认弹窗
		closeRefundModal() {
			this.showRefundModal = false;
		},

		// 确认退货
		async confirmRefund() {
			try {
				// 调用退货接口
				const response = await fetchOrderCancel({
					order_no: this.orderData.orderNo || this.orderData.orderNumber
				});
				console.log('退货接口响应:', response, this.orderData.orderNo, this.orderData.orderNumber, this.orderData);

				if (response.ok && response.data) {
					uni.showToast({
						title: '申请退货成功',
						icon: 'none'
					});
					// 刷新订单状态
					this.loadOrderDetail(this.orderData.orderNo || this.orderData.orderNumber);
					// 关闭弹窗
					this.closeRefundModal();
				} else {
					uni.showToast({
						title: response.msg || '申请退货失败',
						icon: 'none'
					});
				}
			} catch (error) {
				console.error('申请退货失败:', error);
				uni.showToast({
					title: '网络错误，请重试',
					icon: 'none'
				});
			}
		},

		// 设置订单状态 - 供外部调用
		setOrderStatus(productType, statusCode, statusText, failureReason = '') {
			this.orderData.productType = productType;
			this.orderData.statusCode = statusCode;
			this.orderData.status = statusText;
			this.orderData.failureReason = failureReason;

			// 根据商品类型调整数据
			if (productType === 'virtual') {
				this.orderData.price = '¥0.00';
				this.orderData.totalPrice = '0积分';
				this.orderData.actualPayment = '免费';
			}
		},

		// 复制订单编号
		copyOrderNumber() {
			uni.setClipboardData({
				data: this.orderData.orderNumber,
				success: () => {
					uni.showToast({
						title: '订单编号已复制',
						icon: 'none'
					});
				}
			});
		},

		// 处理客服按钮点击
		handleServiceClick() {
			console.log('客服点击');
			const homeStore = useHomeStore();
			const {
				memberId,
				mobile,
				openId,
				unionId
			} = homeStore.homeInfo;
			const customerUrl =
				`https://intelcc-user.icsoc.net/?channelKey=45839e0505554f8c8aea3c7b6259b049&init=1&crmld=${memberId}&mobile=${mobile}&openId=${openId}&unionId=${unionId}`;
			jump({
				type: JumpType.H5,
				url: customerUrl
			});
		}
	}
}
</script>

<style scoped>
.container {
	width: 100%;
	min-height: 100vh;
	background-color: #f5f5f5;
	box-sizing: border-box;
	overflow: hidden;
}

/* 内容区域 */
.content {
	padding: 0 20rpx;
	box-sizing: border-box;
}

/* 顶部背景渐变 */
.top-gradient-bg {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 240rpx;
	background: linear-gradient(180deg, #ECC990 0%, rgba(211, 164, 88, 0) 100%);
}

/* 订单状态 */
.status-section {
	padding: 20rpx 60rpx;
	display: flex;
	align-items: center;
	position: relative;
	margin: 0 -20rpx;
	width: calc(100% + 40rpx);
	overflow: hidden;
}

.status-icon {
	width: 34rpx;
	height: 34rpx;
	margin-right: 20rpx;
	flex-shrink: 0;
}

.status-text {
	font-size: 28rpx;
	font-weight: bold;
	color: #fff;
	flex-shrink: 0;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

/* 覆盖所有状态下的文本颜色为白色 */
.status-section.status-waiting .status-text,
.status-section.status-shipped .status-text,
.status-section.status-completed .status-text,
.status-section.status-success .status-text,
.status-section.status-failed .status-text {
	color: #fff;
}

.failure-reason {
	font-size: 24rpx;
	color: #fff;
	margin-left: 20rpx;
	flex-shrink: 0;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

/* 收货地址 */
.address-section {
	z-index: 1;
	position: relative;
	background-color: #fff;
	padding: 30rpx 20rpx;
	margin-bottom: 20rpx;
	display: flex;
	align-items: center;
	border-radius: 20rpx;
}

.address-left {
	display: flex;
	align-items: flex-start;
	flex: 1;
}

.location-icon {
	width: 32rpx;
	height: 32rpx;
	margin-right: 20rpx;
	margin-top: 5rpx;
}

.address-info {
	flex: 1;
}

.address-text {
	font-size: 30rpx;
	color: #333;
	line-height: 44rpx;
	margin-bottom: 12rpx;
	display: block;
}

.recipient-info {
	display: flex;
	gap: 20rpx;
}

.recipient-name,
.recipient-phone {
	font-size: 28rpx;
	color: #666;
}



/* 商品详情 - 现在是模块2的一部分 */
.product-section {
	/* 已迁移到module-product-info */
}

.product-detail {
	display: flex;
	align-items: center;
}

.product-image {
	width: 180rpx;
	height: 180rpx;
	background-color: #f0e6d2;
	border-radius: 10rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	margin-right: 20rpx;
}

.image-placeholder {
	font-size: 20rpx;
	color: #8b7355;
	text-align: center;
}

.product-img {
	width: 100%;
	height: 100%;
	border-radius: 10rpx;
}

.product-info {
	flex: 1;
}

.product-name {
	font-size: 28rpx;
	color: #333;
	line-height: 1.4;
	margin-bottom: 12rpx;
	display: block;
	font-weight: 500;
}

.product-spec {
	font-size: 26rpx;
	color: #999;
	margin-bottom: 12rpx;
	display: block;
}

.product-content {
	margin-bottom: 12rpx;
}

.content-text {
	font-size: 26rpx;
	color: #666;
	line-height: 1.5;
	max-height: 200rpx;
	overflow-y: auto;
}

.price-quantity-row {
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.product-price {
	font-size: 32rpx;
	color: #d3a458;
	font-weight: bold;
}

.product-quantity {
	font-size: 24rpx;
	color: #999;
}

/* 支付汇总 - 现在是模块4的一部分 */
.payment-section {
	/* 已迁移到module-order-summary */
}

.payment-row {
	display: flex;
	align-items: center;
	justify-content: space-between;
	margin-bottom: 20rpx;
}

.payment-label {
	font-size: 28rpx;
	color: var(--B700, #1C1C1C);
	font-weight: bold;
}

.payment-value {
	font-size: 28rpx;
	color: #A8A8A8;
}

.payment-total {
	display: flex;
	align-items: center;
	justify-content: flex-end;
	border-top: 1rpx solid #e6e6e6;
	padding-top: 20rpx;
}

.total-label {
	font-size: 30rpx;
	color: #333;
	margin-right: 10rpx;
	font-weight: bold;
}

.total-value {
	font-size: 34rpx;
	color: #d3a458;
	font-weight: bold;
}

/* 订单信息 - 现在是模块4的一部分 */
.order-info-section {
	/* 已迁移到module-order-summary */
}

.info-row {
	display: flex;
	align-items: center;
	justify-content: space-between;
	margin-bottom: 30rpx;
}

.info-row:last-child {
	margin-bottom: 0;
}

.info-label {
	font-size: 28rpx;
	color: #333;
	font-weight: bold;
}

.info-right {
	display: flex;
	align-items: center;
	gap: 20rpx;
}

.info-value {
	font-size: 28rpx;
	color: #A8A8A8;
}

/* 已统一到上方的.copy-btn样式 */

/* 物流信息 */
.address-section {
	background-color: #fff;
	padding: 30rpx 20rpx;
	margin-bottom: 20rpx;
	display: flex;
	align-items: center;
	justify-content: space-between;
	position: relative;
	border-radius: 20rpx;
}

.module-logistics {
	background-color: #fff;
	border-radius: 20rpx;
	margin-bottom: 20rpx;
	padding: 20rpx;
}

.logistics-content {
	position: relative;
	padding: 10rpx 0;
}

.logistics-content:not(:last-child) {
	border-bottom: 1rpx solid #f0f0f0;
	margin-bottom: 20rpx;
}

.package-number {
	background-color: #f5f5f5;
	padding: 8rpx 20rpx;
	border-radius: 20rpx;
	margin-bottom: 16rpx;
	display: inline-block;
}

.package-number text {
	font-size: 24rpx;
	color: #666;
}

.logistics-row {
	display: flex;
	align-items: center;
	justify-content: space-between;
	margin-bottom: 20rpx;
	/* 限制最大宽度，为右箭头留出空间 */
	max-width: calc(100% - 60rpx);
}

.logistics-row:last-child {
	margin-bottom: 0;
}

.logistics-label {
	font-size: 30rpx;
	color: #333;
	/* 固定标签宽度，确保对齐 */
	width: 140rpx;
	font-weight: bold;
}

.logistics-right {
	display: flex;
	align-items: center;
	gap: 20rpx;
	/* 内容区域不换行 */
	flex-shrink: 0;
}

.logistics-value {
	font-size: 30rpx;
	color: #666;
	/* 限制值的最大宽度，防止过长 */
	max-width: 400rpx;
	/* 文本超出时省略 */
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
}

.arrow-icon {
	position: absolute;
	right: 10rpx;
	top: 50%;
	transform: translateY(-50%);
	/* 确保箭头在最上层 */
	z-index: 1;


}

.arrow-icon image {
	width: 14rpx;
	height: 23rpx;
}

/* 操作按钮容器 */
.action-container {
	/* 虚拟商品按钮保持在底部固定位置 */
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	height: 180rpx;
	background-color: #fff;
	padding: 0rpx 30rpx;
	box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
	z-index: 100;
	/* 虚拟商品按钮居中显示，实物商品按钮推到右侧 */
	display: flex;
	justify-content: center;
}



/* 实物商品按钮容器特殊样式 */
.action-container:has(.btn-refund) {
	justify-content: flex-end;
}

.action-btn {
	/* 虚拟商品按钮保持全宽 */
	width: 100%;
	height: 88rpx;
	border-radius: 44rpx;
	font-size: 30rpx;
	font-weight: 500;
	text-align: center;
}

/* 实物商品申请退货按钮样式 - 右下角 */
.action-btn.corner-btn {
	width: 248rpx;
	height: 74rpx;
	border-radius: 50rpx;
	background-color: #fff;
	color: #000;
	border: 1rpx solid #000;
	/* 调整位置，使其在右下角 */
	position: fixed;
	right: 26rpx;
	box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
	/* 确保按钮显示在客服按钮上方 */
	z-index: 101;
	margin-top: 30rpx;
}

/* 去使用图片按钮样式 */
.action-btn.btn-use {
	background-color: transparent;
	/* 虚拟商品按钮保持在容器中 */
	position: static;
	box-shadow: none;
	/* 确保图片充满按钮 */
	overflow: hidden;
	/* 调整按钮尺寸为484*90 */
	width: 484rpx;
	height: 90rpx;
	border-radius: 45rpx;
}

/* 去使用按钮内的图片样式 */
.action-btn.btn-use image {
	width: 100%;
	height: 100%;
	border-radius: 45rpx;
}

/* 券码和过期时间样式 - 现在是模块1的一部分 */
.coupon-section {
	margin-top: 30rpx;
	/* padding-top: 30rpx; */
	/* border-top: 1rpx solid #f0f0f0; */
}

.coupon-code-item {
	margin-bottom: 20rpx;
}



.coupon-field {
	margin-bottom: 25rpx;
	width: 100%;
	padding: 0rpx;
	/* background-color: #f5f5f5; */
	border-radius: 10rpx;
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.coupon-label {
	font-size: 28rpx;
	color: #333;
	text-align: left;
	white-space: nowrap;
	font-weight: 600;
	margin-right: 20rpx;
}

.coupon-code-content {
	flex: 1;
	display: flex;
	align-items: center;
	justify-content: flex-end;
	gap: 12rpx;
}

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

.coupon-code {
	font-size: 28rpx;
	color: #A8A8A8;
	letter-spacing: 2rpx;
}

.expire-time {
	flex: 1;
	font-size: 28rpx;
	color: #A8A8A8;
	text-align: right;
}

/* 复制按钮样式 - 统一调整为与图2一致 */
.copy-btn {
	font-size: 20rpx;
	white-space: nowrap;
	color: #A8A8A8;
	text-align: center;
	font-style: normal;
	font-weight: 500;
	line-height: 32rpx;
	border-radius: 24rpx;
	border: 1px solid #A8A8A8;
	width: 74rpx;
	height: 32rpx;
	flex-shrink: 0;
	background: #FFF;
	/* 120% */
}

/* 模块样式 */
.module-product-info,
.module-instructions,
.module-payment,
.module-order-info,
.module-logistics {
	z-index: 1;
	position: relative;
	background-color: #fff;
	padding: 30rpx 20rpx;
	margin-bottom: 20rpx;
	border-radius: 20rpx;
}

/* 券码和过期时间样式 - 已在上方定义 */

/* 使用说明样式 - 现在是模块3 */
.usage-instructions {
	/* 已迁移到module-instructions */
}

.section-title {
	font-size: 28rpx;
	color: #333;
	font-weight: bold;
	margin-bottom: 24rpx;
	display: block;
}

.instruction-content,
.instruction-text {
	font-size: 28rpx;
	color: #A8A8A8;
	line-height: 44rpx;
}

.instruction-content img {
	max-width: 100% !important;
	height: auto !important;
}

/* 客服按钮 */
.service-btn {
	position: fixed;
	bottom: 200rpx;
	right: 30rpx;
	width: 96rpx;
	height: 96rpx;
	background-color: #d3a458;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	z-index: 100;
}

.service-icon {
	width: 100%;
	height: 100%;
}

/* 弹窗样式 */
.modal-overlay {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: rgba(0, 0, 0, 0.5);
	display: flex;
	align-items: center;
	justify-content: center;
	z-index: 9999;
	flex-direction: column;
}

.modal-content {
	width: 546rpx;
	height: 418rpx;
	flex-shrink: 0;
	border-radius: 38rpx;
	background: linear-gradient(180deg, #FFE9C5 0%, #FFF 52.87%);
}

.modal-title {
	color: #D3A458;
	text-align: center;
	font-size: 40rpx;
	font-style: normal;
	font-weight: 600;
	line-height: normal;
	margin-top: 62rpx;
}

.modal-message {
	color: var(--B900, #000);
	text-align: center;
	font-size: 28rpx;
	font-style: normal;
	font-weight: 400;
	line-height: normal;
	margin-top: 22rpx;
}

.modal-buttons {
	display: flex;
	gap: 20rpx;
	margin-top: 70rpx;
	justify-content: center;
}

.modal-btn {
	width: 220rpx !important;
	height: 78rpx !important;
	position: relative;
}

.modal-btn image {
	width: 220rpx !important;
	height: 78rpx !important;
}

.cancel-btn {
	border: none;
}

.confirm-btn {
	border: none;
	margin-left: 20rpx;
}

.modal-disclaimer {
	font-size: 24rpx;
	color: #999;
	text-align: center;
	line-height: 1.4;
	margin-top: 40rpx;
}

.modal-close-btn {
	width: 56rpx;
	height: 56rpx;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	margin-top: 80rpx;
}
</style>
