<template>
	<view class="container">
		<!-- 内容区域 -->
		<view class="content">
			<!-- 订单状态 -->
			<view class="status-section" :class="statusClass">
				<view class="status-icon" :class="statusIconClass">{{ statusIcon }}</view>
				<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>

			<!-- 商品详情 -->
			<view class="product-section">
				<view class="product-detail">
					<view class="product-image">
						<image v-if="orderData.goodsImage && orderData.goodsImage.length > 0"
							:src="orderData.goodsImage[0]" 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>
						<text v-if="orderData.productType === 'virtual' && orderData.expireTime"
							class="product-spec">过期时间 {{ orderData.expireTime }}</text>
						<text v-if="orderData.productType === 'virtual' && orderData.goodsContent"
							class="product-spec">使用说明 {{ orderData.goodsContent }}</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>

			<!-- 支付汇总 -->
			<view class="payment-section">
				<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>
			</view>

			<!-- 订单信息 -->
			<view class="order-info-section">
				<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 === '已发货' || orderData.status === '已完成')"
				class="logistics-section" @click="viewLogistics">
				<view class="logistics-row">
					<text class="logistics-label">物流公司</text>
					<text class="logistics-value">{{ orderData.logisticsCompany }}</text>
				</view>
				<view class="logistics-row">
					<text class="logistics-label">物流单号</text>
					<view class="logistics-right">
						<text class="logistics-value">{{ orderData.trackingNumber }}</text>
						<text class="copy-btn" @click.stop="copyTrackingNumber">复制</text>
					</view>
				</view>
				<text class="arrow-icon">{{ ">" }}</text>
			</view>
		</view>

		<!-- 底部操作按钮 -->
		<view v-if="showActionButton" class="bottom-action">
			<button class="action-btn" :class="actionBtnClass" @click="handleAction">{{ actionButtonText }}</button>
		</view>

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

<script>
import { getOrderDetail } from '@/api/user.js';

export default {
	data() {
		return {
			// 订单数据
			orderData: {
				productType: '', // 'physical' | 'virtual'
				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
		}
	},
	onLoad(options) {
		console.log('订单详情页面参数:', options);
		if (options.orderId) {
			this.loadOrderDetail(options.orderId);
		} else {
			uni.showToast({
				title: '订单ID不能为空',
				icon: 'none'
			});
			setTimeout(() => {
				uni.navigateBack();
			}, 1500);
		}
	},
	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') ||
				(this.orderData.productType === 'virtual' && this.orderData.statusCode === 'success');
		},

		// 操作按钮文本
		actionButtonText() {
			if (this.orderData.productType === 'physical' && this.orderData.statusCode === 'waiting_ship') {
				return '申请退货';
			}
			if (this.orderData.productType === 'virtual' && this.orderData.statusCode === 'success') {
				return '去使用';
			}
			return '';
		},

		// 操作按钮样式类
		actionBtnClass() {
			return this.orderData.productType === 'virtual' ? 'btn-use' : 'btn-refund';
		}
	},
	methods: {
		// 加载订单详情
		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;
			}
		},

		// 将API数据映射为订单数据
		mapApiDataToOrderData(apiData) {
			// 基础订单信息
			this.orderData.orderNo = apiData.orderNo || '';
			this.orderData.orderNumber = apiData.orderNo || '';
			this.orderData.createTime = apiData.createTime || '';
			this.orderData.orderTime = this.formatTime(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();
		},

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

			// 根据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') {
				this.orderData.price = '0积分';
				this.orderData.totalPrice = '0积分';
				this.orderData.actualPayment = '免费';
			} else {
				this.orderData.price = `${this.orderData.credits}${this.orderData.creditsTypeName}`;
				this.orderData.totalPrice = `${this.orderData.totalCredits}${this.orderData.creditsTypeName}`;
				this.orderData.actualPayment = `${this.orderData.totalCredits}${this.orderData.creditsTypeName}`;
			}

			// 设置物流信息（仅实物商品）
			if (this.orderData.productType === 'physical' && this.orderData.express && Object.keys(this.orderData.express).length > 0) {
				this.orderData.logisticsCompany = this.orderData.express.company || '';
				this.orderData.trackingNumber = this.orderData.express.trackingNumber || '';
			}

			// 设置有效期（非实物商品）
			if (this.orderData.productType === 'virtual' && this.orderData.coupon.expireTime) {
				this.orderData.expireTime = this.formatTime(this.orderData.coupon.expireTime);
			}
		},

		// 映射订单状态
		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: '已完成' };
		},

		// 格式化时间
		formatTime(timestamp) {
			if (!timestamp) return '';
			const date = new Date(timestamp);
			return date.toLocaleString('zh-CN', {
				year: 'numeric',
				month: '2-digit',
				day: '2-digit',
				hour: '2-digit',
				minute: '2-digit',
				second: '2-digit'
			}).replace(/\//g, '.');
		},

		// 获取完整地址
		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: 'success'
					});
				}
			});
		},

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

		// 查看物流详情
		viewLogistics() {
			uni.showToast({
				title: '查看物流详情',
				icon: 'none'
			});
		},

		// 处理操作按钮点击
		handleAction() {
			if (this.orderData.productType === 'physical' && this.orderData.statusCode === 'waiting_ship') {
				uni.showToast({
					title: '申请退货',
					icon: 'none'
				});
			}
			if (this.orderData.productType === 'virtual' && this.orderData.statusCode === 'success') {
				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 = '免费';
			}
		}
	}
}
</script>

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

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

/* 订单状态 */
.status-section {
	padding: 40rpx 30rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.status-section.status-waiting {
	background-color: #f0e6d2;
}

.status-section.status-shipped {
	background-color: #f0e6d2;
}

.status-section.status-completed {
	background-color: #f0e6d2;
}

.status-section.status-success {
	background-color: #f0e6d2;
}

.status-section.status-failed {
	background-color: #ffe6e6;
}

.status-icon {
	width: 60rpx;
	height: 60rpx;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	margin-right: 20rpx;
	font-size: 32rpx;
	font-weight: bold;
}

.status-icon.icon-waiting {
	background-color: #d3a458;
	color: #fff;
}

.status-icon.icon-shipped {
	background-color: #d3a458;
	color: #fff;
}

.status-icon.icon-completed {
	background-color: #d3a458;
	color: #fff;
}

.status-icon.icon-success {
	background-color: #4CAF50;
	color: #fff;
}

.status-icon.icon-failed {
	background-color: #f44336;
	color: #fff;
}

.status-text {
	font-size: 32rpx;
	font-weight: bold;
}

.status-section.status-waiting .status-text,
.status-section.status-shipped .status-text,
.status-section.status-completed .status-text {
	color: #d3a458;
}

.status-section.status-success .status-text {
	color: #4CAF50;
}

.status-section.status-failed .status-text {
	color: #f44336;
}

.failure-reason {
	font-size: 24rpx;
	color: #f44336;
	text-align: center;
}

/* 收货地址 */
.address-section {
	background-color: #fff;
	padding: 30rpx;
	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: 28rpx;
	color: #333;
	line-height: 40rpx;
	margin-bottom: 10rpx;
	display: block;
}

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

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

/* 商品详情 */
.product-section {
	background-color: #fff;
	padding: 30rpx;
	margin-bottom: 20rpx;
	border-radius: 20rpx;
}

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

.product-image {
	width: 120rpx;
	height: 120rpx;
	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: 24rpx;
	color: #999;
	margin-bottom: 12rpx;
	display: block;
}

.price-quantity-row {
	display: flex;
	align-items: center;
}

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

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

/* 支付汇总 */
.payment-section {
	background-color: #fff;
	padding: 30rpx;
	margin-bottom: 20rpx;
	border-radius: 20rpx;
}

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

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

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

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

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

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

/* 订单信息 */
.order-info-section {
	background-color: #fff;
	padding: 30rpx;
	margin-bottom: 20rpx;
	border-radius: 20rpx;
}

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

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

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

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

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

.copy-btn {
	font-size: 24rpx;
	color: #999;
	padding: 8rpx 16rpx;
	border: 1rpx solid #ddd;
	border-radius: 20rpx;
	background-color: #f5f5f5;
}

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

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

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

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

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

.logistics-value {
	font-size: 28rpx;
	color: #666;
}

.arrow-icon {
	font-size: 32rpx;
	color: #999;
	position: absolute;
	right: 30rpx;
	top: 50%;
	transform: translateY(-50%);
}

/* 底部操作按钮 */
.bottom-action {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	background-color: #fff;
	padding: 20rpx 30rpx;
	box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
	z-index: 100;
}

.action-btn {
	width: 100%;
	height: 88rpx;
	border-radius: 44rpx;
	font-size: 32rpx;
	font-weight: bold;
}

.action-btn.btn-refund {
	background-color: #fff;
	color: #333;
	border: 1rpx solid #ddd;
}

.action-btn.btn-use {
	background-color: #d3a458;
	color: #fff;
}

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

.service-icon {
	width: 100%;
	height: 100%;
}
</style>
