<template>
	<view class="order-list-container">
		<!-- 页面标题 -->
		<view class="page-header">
			<text class="page-title">仅展示星妈会全积分兑换记录</text>
			<view class="view-preferred" @tap="viewPreferredOrders">
				<text class="preferred-text">查看优选订单</text>
				<text class="arrow">{{ ">" }}</text>
			</view>
		</view>

		<!-- 订单列表 -->
		<view class="order-list">
			<view v-for="(order, index) in orderList" :key="order.orderId" class="order-card">
				<!-- 订单头部 -->
				<view class="order-header">
					<text class="order-number">订单号 {{ order.orderId }}</text>
					<!-- :class="getStatusClass(order.status)" -->
					<text class="order-status">{{ getStatusText(order.status)
					}}</text>
				</view>

				<!-- 商品信息 -->
				<view class="product-info">
					<view class="product-image">
						<image :src="order.productImage || $baseUrl + 'placeholder/product.png'" mode="aspectFill"
							class="product-img" />
					</view>
					<view class="product-details">
						<view class="product-name-row">
							<text class="product-name">{{ order.productName }}</text>
							<text class="product-points">{{ order.points }}{{ order.creditsTypeName }}</text>
						</view>
						<!-- <text class="product-description">{{ order.description }}</text> -->

						<!-- 卡券有效期 -->
						<text v-if="order.productType === 'coupon' && order.validUntil" class="validity-period">
							有效期 {{ order.validUntil }}前使用
						</text>

						<text class="exchange-time">兑换时间 {{ order.exchangeTime }}</text>
					</view>
				</view>

				<!-- 操作区域 -->
				<view class="action-area">
					<!-- 待付款倒计时 -->
					<view v-if="order.status === 'pending_payment'" class="countdown-container">
						<text class="countdown-text">付款倒计时 {{ order.countdown }}</text>
						<view class="pay-btn" @tap="goToPay(order)">
							<text class="btn-text">去付款</text>
						</view>
					</view>

					<!-- 待使用状态 -->
					<view v-else-if="order.status === 'pending_use'" class="action-btn" @tap="useCoupon(order)">
						<text class="btn-text">去使用</text>
					</view>

					<!-- 待领取状态 -->
					<view v-else-if="order.status === 'pending_take'" class="action-btn" @tap="takeReward(order)">
						<text class="btn-text">去领取</text>
					</view>

					<!-- 其他状态的操作按钮 -->
					<view v-else class="action-btn" @tap="viewOrderDetail(order)">
						<text class="btn-text">查看详情</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 加载状态 -->
		<view v-if="loading" class="loading-container">
			<text class="loading-text">加载中...</text>
		</view>

		<!-- 没有更多数据 -->
		<view v-if="!hasMore && orderList.length > 0" class="no-more-container">
			<text class="no-more-text">没有更多数据了</text>
		</view>

		<!-- 空状态 -->
		<view v-if="orderList.length === 0" class="empty-state">
			<text class="empty-text">暂无兑换记录</text>
		</view>
	</view>
</template>

<script>
import { getExchangeList } from '@/api/user.js';
import { jump, JumpType } from '../../utils';
import md from '../../md';

export default {
	data() {
		return {
			orderList: [],
			nextId: null,
			loading: false,
			hasMore: true
		}
	},
	onLoad() {
		this.loadExchangeList();
	},
	onReachBottom() {
		if (this.hasMore && !this.loading) {
			this.loadMoreData();
		}
	},
	methods: {
		// 初始化曝光埋点
		initExposure() {
			// 遍历订单列表，为显示"查看详情"按钮的订单添加曝光埋点
			this.orderList.forEach((order) => {
				// 只有当订单状态不是 pending_payment、pending_use、pending_take 时才显示"查看详情"按钮
				if (order.status !== 'pending_payment' &&
					order.status !== 'pending_use' &&
					order.status !== 'pending_take') {
					md.sensorComponentLogTake({
						xcxComponentExposure: "true",
						pageName: "我的订单页",
						componentName: "我的订单",
						componentContent: "查看详情"
					});
				}
			});
		},

		// 加载兑换记录列表
		async loadExchangeList(isRefresh = false) {
			if (this.loading) return;

			this.loading = true;

			try {
				const params = {};
				if (isRefresh) {
					// 刷新时重置分页
					this.nextId = null;
					this.hasMore = true;
				} else if (this.nextId) {
					// 加载更多时传递nextId
					params.nextId = this.nextId;
				}

				const response = await getExchangeList(params);

				if (response.ok) {
					const newList = this.mapApiDataToOrderList(response.data.list || []);

					if (isRefresh) {
						this.orderList = newList;
					} else {
						this.orderList = [...this.orderList, ...newList];
					}

					// 更新nextId，判断是否还有更多数据
					this.nextId = response.data.nextId || null;
					this.hasMore = !!this.nextId;

					// 数据加载完成后，添加曝光埋点
					this.$nextTick(() => {
						this.initExposure();
					});
				} else {
					// API调用失败
					console.warn('API调用失败:', response.msg);
					this.orderList = [];
				}
			} catch (error) {
				console.error('加载兑换记录失败:', error);
				this.orderList = [];
			} finally {
				this.loading = false;
			}
		},

		// 加载更多数据
		loadMoreData() {
			this.loadExchangeList(false);
		},

		// 刷新数据
		refreshData() {
			this.loadExchangeList(true);
		},

		// 将API数据映射为订单列表格式
		mapApiDataToOrderList(apiList) {
			return apiList.map(item => ({
				orderId: item.orderNo || '',
				status: this.mapFlowStateToStatus(item.flowState),
				productType: this.mapBizTypeToProductType(item.bizType),
				productName: item.bizDesc || '',
				description: item.bizDesc || '',
				points: item.credits || 0,
				creditsTypeName: item.creditsTypeName || '积分',
				exchangeTime: item.createTime,
				productImage: item.bizIcon || '',
				countdown: this.calculateCountdown(item.expireTime),
				validUntil: item.expireTime ? item.expireTime : null
			}));
		},

		// 映射订单状态
		mapFlowStateToStatus(flowState) {
			const statusMap = {
				// 处理中状态
				'0': 'processing',           // 处理中
				'11': 'processing',          // 扣积分成功
				'12': 'pending_payment',     // 扣积分失败 - 待付款
				'25': 'processing',          // 商品兑换处理中

				// 支付相关状态
				'20': 'pending_payment',     // 待支付
				'21': 'processing',          // 支付成功
				'22': 'payment_failed',      // 支付失败
				'23': 'audit_waiting',       // 待审核

				// 物流相关状态
				'30': 'pending_shipment',    // 待发货
				'31': 'shipped',             // 已发货
				'32': 'completed',          // 已确认收货

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

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

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

				// 订单结束状态
				'97': 'failed',              // 订单失败
				'98': 'cancelled',           // 订单已取消
				'99': 'completed'            // 订单完成
			};
			return statusMap[flowState.toString()] || 'completed';
		},

		// 映射业务类型到商品类型
		mapBizTypeToProductType(bizType) {
			// 根据业务类型判断是实物还是卡券
			return bizType === 'coupon' ? 'coupon' : 'physical';
		},

		// 格式化时间
		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, '.');
		},

		// 计算倒计时
		calculateCountdown(expireTime) {
			if (!expireTime) return '';
			const now = new Date().getTime();
			const expire = new Date(expireTime).getTime();
			const diff = expire - now;

			if (diff <= 0) return '00:00:00';

			const hours = Math.floor(diff / (1000 * 60 * 60));
			const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
			const seconds = Math.floor((diff % (1000 * 60)) / 1000);

			return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
		},

		// 获取状态文本
		getStatusText(status) {
			const statusMap = {
				// 处理中状态
				'processing': '处理中',
				'audit_waiting': '待审核',

				// 支付相关状态
				'pending_payment': '待付款',
				'payment_failed': '支付失败',

				// 物流相关状态
				'pending_shipment': '待发货',
				'shipped': '已发货',
				'completed': '已完成',

				// 使用相关状态
				'pending_use': '待使用',
				'used': '已使用',

				// 活动相关状态
				'pending_take': '待领取',
				'taken': '已领取',

				// 售后相关状态
				'refund_processing': '售后处理中',
				'refund_success': '售后完成',

				// 订单结束状态
				'failed': '交易失败',
				'cancelled': '已取消'
			};
			return statusMap[status] || '未知状态';
		},

		// 获取状态样式类
		getStatusClass(status) {
			return `status-${status}`;
		},

		// 查看优选订单
		viewPreferredOrders() {
			const url = `subPackages/orderCollect/order/index`;
			const type = JumpType.MINI;
			const extra = {
				appId: 'wx4205ec55b793245e',	//星妈优选小程序
				extraData: {},
				envVersion: 'release',
				embedded: true,
			};

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

		// 去付款
		goToPay(order) {
			uni.navigateTo({
				url: `/v3/payResultPage/payResultPage?orderId=${order.orderId}&type=payment`
			});
		},

		// 查看订单详情
		viewOrderDetail(order) {
			// 添加点击埋点
			md.sensorComponentLogTake({
				xcxComponentClick: "true",
				pageName: "我的订单页",
				componentName: "我的订单",
				componentContent: "查看详情"
			});

			uni.navigateTo({
				url: `/v3/orderDetail/orderDetail?orderId=${order.orderId}`
			});
		},

		// 使用优惠券
		useCoupon(order) {
			// 跳转到优惠券使用页面
			uni.navigateTo({
				url: `/v3/couponUse/couponUse?orderId=${order.orderId}`
			});
		},

		// 领取奖励
		takeReward(order) {
			// 跳转到奖励领取页面
			uni.navigateTo({
				url: `/v3/rewardTake/rewardTake?orderId=${order.orderId}`
			});
		}
	}
}
</script>

<style scoped>
.order-list-container {
	background-color: #f5f5f5;
	min-height: 100vh;
	padding: 20rpx;
}

/* 页面标题 */
.page-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 30rpx;
	padding: 0 20rpx;
}

.page-title {
	font-size: 28rpx;
	color: #999999;
}

.view-preferred {
	display: flex;
	align-items: center;
}

.preferred-text {
	font-size: 28rpx;
	color: #999999;
	margin-right: 8rpx;
}

.arrow {
	font-size: 28rpx;
	color: #999999;
}

/* 订单列表 */
.order-list {
	display: flex;
	flex-direction: column;
	gap: 20rpx;
}

/* 订单卡片 */
.order-card {
	background-color: #ffffff;
	border-radius: 16rpx;
	border: 1rpx solid #EFEFEF;
	padding: 30rpx;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

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

.order-number {
	font-size: 28rpx;
	color: #b9b9b9;
	font-weight: 500;
}

.order-status {
	font-size: 28rpx;
	color: #b9b9b9;
	font-weight: 500;
}

/* 处理中状态 */
.status-processing {
	color: #D3A458;
}

.status-audit_waiting {
	color: #D3A458;
}

/* 支付相关状态 */
.status-pending_payment {
	color: #D3A458;
}

.status-payment_failed {
	color: #E34D59;
}

/* 物流相关状态 */
.status-pending_shipment {
	color: #b9b9b9;
}

.status-shipped {
	color: #b9b9b9;
}

.status-completed {
	color: #333333;
}

/* 使用相关状态 */
.status-pending_use {
	color: #D3A458;
}

.status-used {
	color: #333333;
}

/* 活动相关状态 */
.status-pending_take {
	color: #D3A458;
}

.status-taken {
	color: #333333;
}

/* 售后相关状态 */
.status-refund_processing {
	color: #D3A458;
}

.status-refund_success {
	color: #333333;
}

/* 订单结束状态 */
.status-failed {
	color: #E34D59;
}

.status-cancelled {
	color: #b9b9b9;
}

/* 商品信息 */
.product-info {
	display: flex;
	margin-bottom: 30rpx;
}

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

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

.product-details {
	flex: 1;
	display: flex;
	flex-direction: column;
	justify-content: space-between;
}

.product-name-row {
	display: flex;
	justify-content: space-between;
	align-items: flex-start;
	margin-bottom: 10rpx;
}

.product-name {
	width: 350rpx;
	font-size: 30rpx;
	color: #333333;
	font-weight: 600;
	flex: 1;
	margin-right: 20rpx;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.product-points {
	font-size: 28rpx;
	color: #D3A458;
	font-weight: 500;
}

.product-description {
	font-size: 26rpx;
	color: #666666;
	margin-bottom: 8rpx;
	line-height: 1.4;
}

.validity-period {
	font-size: 24rpx;
	color: #999999;
	margin-bottom: 8rpx;
}

.exchange-time {
	font-size: 24rpx;
	color: #999999;
}

/* 操作区域 */
.action-area {
	display: flex;
	justify-content: flex-end;
}

.countdown-container {
	display: flex;
	align-items: center;
	gap: 20rpx;
}

.countdown-text {
	font-size: 26rpx;
	color: #D3A458;
	font-weight: 500;
}

.pay-btn,
.action-btn {
	background-color: #D3A458;
	border-radius: 50rpx;
	width: 132rpx;
	height: 52rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.btn-text {
	font-size: 24rpx;
	color: #ffffff;
	font-weight: 500;
}

/* 加载状态 */
.loading-container {
	display: flex;
	justify-content: center;
	align-items: center;
	padding: 40rpx 0;
}

.loading-text {
	font-size: 28rpx;
	color: #999999;
}

/* 没有更多数据 */
.no-more-container {
	display: flex;
	justify-content: center;
	align-items: center;
	padding: 40rpx 0;
}

.no-more-text {
	font-size: 26rpx;
	color: #cccccc;
}

/* 空状态 */
.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 100rpx 0;
}

.empty-image {
	width: 200rpx;
	height: 200rpx;
	margin-bottom: 30rpx;
}

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