<template>
	<view class="order-list-page">
		<!-- 顶部标签栏 -->
		<view class="order-tabs">
			<view v-for="(tab, index) in tabs" :key="index" class="tab-item" :class="{active: currentTab === tab.value}"
				@click="switchTab(tab.value)">
				<text>{{tab.name}}</text>
			</view>
		</view>

		<!-- 订单列表 -->
		<scroll-view scroll-y class="order-list-scroll" @scrolltolower="loadMore" @refresherrefresh="refresh"
			:refresher-enabled="true" :refresher-triggered="refreshing">
			<view class="order-list">
				<!-- 订单卡片 -->
				<view class="order-card" v-for="(order, index) in orderList" :key="index">
					<view class="order-header">
						<text>{{ tabs[order.status - 1].name }}</text>
						<view class="order-status">
							<text v-if="order.teacherId">指定伴宠师下单</text>
							<text v-else>系统下单</text>
						</view>
						<view class="order-amount">
							<text>金额：</text>
							<text class="amount-value">¥{{order.payAmount}}</text>
						</view>
					</view>

					<!-- 宠物信息 -->
					<view class="pet-info" v-for="(pet, petIndex) in order.petVOList" :key="petIndex">
						<view class="pet-avatar">
							<image :src="pet.photo || '/static/images/personal/pet.png'" mode="aspectFill"></image>
							<view class="pet-tag" v-if="pet.tag">
								<text>{{pet.tag}}</text>
							</view>
						</view>
						<view class="pet-details">
							<view class="pet-name-gender" style="display: flex; align-items: center;">
								<text class="pet-name">{{pet.name}}</text>
								<view class="pet-gender"
									style="margin-left: 10rpx; display: flex; align-items: center;">
									<image
										:src="pet.gender=='男生'?'/static/images/details/boy.svg':'/static/images/details/girl.svg'"
										style="width: 24rpx; height: 24rpx;" alt="sex"></image>
								</view>
							</view>
							<text class="pet-service">
							{{ pet.productNameText.join(',') }} | 共{{ pet.orderServiceText.length }}天 {{ pet.orderServiceText.join(',') }}</text>
						</view>
					</view>

					<!-- 订单信息 -->
					<view class="order-info">
						<text class="order-time">下单时间: {{order.createTime}}</text>
						<view class="companion-info">
							<text>伴宠师: {{order.companionName}}</text> <text>（点击查看伴宠师详情）</text>
						</view>
					</view>

					<!-- 订单操作 -->
					<view class="order-actions">
						<view class="action-btn details-btn" v-if="order.status == 0"
							@click="$refs.cancelOrderPopup.open(order)">
							<text>取消订单</text>
						</view>
						<view class="action-btn details-btn" @click="viewOrderDetails(order.orderId)">
							<text>查看详情</text>
						</view>
						<view class="action-btn pay-btn" v-if="order.status == 0" @click="goToPay(order.orderId)">
							<text>去付款</text>
						</view>
						<!-- <view class="action-btn pay-btn" v-if="order.status == 1 || order.status == 2" @click="modifyOrder(order)">
							<text>修改订单</text>
						</view> -->
						<view class="action-btn pay-btn" v-if="order.status == 4" @click="goToReview(order)">
							<text>去评价</text>
						</view>
						<view class="action-btn pay-btn" v-if="order.status == 3" @click="handleReorder(order)">
							<text>再来一单</text>
						</view>
					</view>
				</view>

				<!-- 加载更多 -->
				<view class="loading-more" v-if="orderList.length > 0 && hasMore">
					<text>加载中...</text>
				</view>

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

				<!-- 无订单提示 -->
				<view class="no-order" v-if="orderList.length === 0 && !loading">
					<image src="/static/images/personal/no-data.png" mode="aspectFit" class="no-data-image"></image>
					<text>暂无订单</text>
				</view>
			</view>
		</scroll-view>

		<!-- 取消订单弹窗 -->
		<cancel-order-popup ref="cancelOrderPopup" @cancel="handleCancelOrder"></cancel-order-popup>

		<!-- 客服组件 -->
		<Kefu></Kefu>

		<!-- 伴宠师选择弹窗 -->
		<companion-select-popup ref="companionSelectPopup" />
	</view>
</template>

<script>
	import Kefu from '@/pages/common/kefu.vue'
	import {
		// getOrderList
	} from "@/api/system/user.js"
	import {
		getOrderList
	} from "@/api/order/order.js"
	import {
		getOpenIdKey
	} from '@/utils/auth'
	import CancelOrderPopup from '@/pages_order/components/order/CancelOrderPopup.vue'
	import CompanionSelectPopup from '@/pages_order/components/order/CompanionSelectPopup.vue'
	import { getOrderServiceText, getProductNameText } from '@/utils/serviceTime.js'
	export default {
		components: {
			Kefu,
			CancelOrderPopup,
			CompanionSelectPopup,
		},
		data() {
			return {
				tabs: [{
						name: '全部',
						value: -1
					},
					{
						name: '待付款',
						value: 0
					},
					{
						name: '已接单',
						value: 1
					},
					{
						name: '服务中',
						value: 2
					},
					{
						name: '已完成',
						value: 3
					}
				],
				currentTab: -1,
				orderList: [],
				page: 1,
				size: 10,
				hasMore: true,
				loading: false,
				refreshing: false,
				currentOrder: null,
				// 示例数据，实际应从API获取
				exampleData: [{
					id: '1',
					status: '0',
					statusText: '待付款',
					amount: '264',
					pets: [{
							name: '小咪',
							avatar: '/static/images/personal/pet.png',
							tag: '猫',
							gender: '女生',
							serviceTime: '专业喂养2天: 03-20,03-22'
						},
						{
							name: '小汪',
							avatar: '/static/images/personal/pet.png',
							tag: '狗',
							gender: '男生',
							serviceTime: '专业喂养2天: 03-20,03-22'
						}
					],
					orderTime: '2025-12-14 18:23:06',
					companionName: '张三',
					companionNote: '伴宠师名称暂不可见'
				}]
			};
		},
		methods: {
			// 切换标签
			switchTab(tabValue) {
				// if (this.currentTab === tabValue) return;
				this.currentTab = tabValue;
				this.orderList = [];
				this.page = 1;
				this.hasMore = true;
				this.getOrderList();
			},

			// 下拉刷新
			refresh() {
				this.refreshing = true;
				this.page = 1;
				this.orderList = [];
				this.hasMore = true;
				this.getOrderList().then(() => {
					this.refreshing = false;
				}).catch(() => {
					this.refreshing = false;
				});
			},

			handleCancelOrder() {
                this.refresh()
			},

			// 加载更多
			loadMore() {
				if (this.loading || !this.hasMore) return;
				this.page++;
				this.getOrderList();
			},

			// 查看订单详情
			viewOrderDetails(orderId) {
				uni.navigateTo({
					url: `/pages_order/order/orderDetail?id=${orderId}`
				});
			},

			// 去付款
			goToPay(orderId) {
				uni.navigateTo({
					url: `/pages/details/order?id=${orderId}`
				});
			},

			// 去评价
			goToReview({teacherId, orderId}) {
				uni.navigateTo({
					url: `/pages_order/order/orderReview?id=${teacherId}&orderId=${orderId}`
				});
			},

			// 获取订单列表
			getOrderList() {
				if (this.loading) return Promise.reject();
				this.loading = true;

				// 构建请求参数
				const params = {
					status: this.currentTab,
					openId: getOpenIdKey(),
					pageNumber: this.page,//pageNumber
					pageSize: this.size
				};
				

				// 实际API调用
				// return new Promise((resolve, reject) => {
				// 	// 模拟API调用，实际项目中应使用真实API
				// 	setTimeout(() => {
				// 		try {
				// 			// 模拟数据，实际应调用API
				// 			if (this.page === 1) {
				// 				this.orderList = [...this.exampleData];
				// 			} else if (this.page < 3) {
				// 				this.orderList = [...this.orderList, ...this.exampleData];
				// 			} else {
				// 				this.hasMore = false;
				// 			}
				// 			this.loading = false;
				// 			resolve();
				// 		} catch (err) {
				// 			this.loading = false;
				// 			reject(err);
				// 		}
				// 	}, 500);
				// });
				// 实际API调用应该是这样：
				return getOrderList(params).then(res => {
					if (res.content) {
						const newList = res.content || [];
						if (this.page === 1) {
							this.orderList = newList;
						} else {
							this.orderList = [...this.orderList, ...newList];
						}
						this.hasMore = newList.length === this.size;
						
						this.orderList.forEach(item => {
							
							item.petVOList.forEach(pet => {
								pet.orderServiceText = getOrderServiceText(pet.id, item.orderServiceList || []) || []
								pet.productNameText = getProductNameText(pet.id, item.orderItemList, item.orderServiceList || []) || []
							})
							
						})
						
					} else {
						this.hasMore = false;
					}
					this.loading = false;
					resolve();
				}).catch(err => {
					this.loading = false;
				});
			},

			// 处理再来一单
			handleReorder(order) {
				this.currentOrder = order;
				this.$refs.companionSelectPopup.open();
			},
			
			// 修改订单
			modifyOrder(order) {
                uni.navigateTo({
                    url: `/pages_order/order/orderModify?orderId=${order.orderId}`
                });
			},

		},
		onLoad() {
			// 页面加载时获取订单列表
			this.getOrderList();
		}
	}
</script>

<style lang="scss" scoped>
	.order-list-page {
		background-color: #f5f5f5;
		min-height: 100vh;
		display: flex;
		flex-direction: column;
	}

	.order-tabs {
		display: flex;
		justify-content: space-around;
		align-items: center;
		height: 88rpx;
		background-color: #FFBF60;
		color: #FFFFFF;

		.tab-item {
			padding: 0 20rpx;
			height: 100%;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 28rpx;
			position: relative;

			&.active {
				font-weight: bold;

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

	.order-list-scroll {
		flex: 1;
		width: 100%;
	}

	.order-list {
		padding: 20rpx;
		padding-bottom: 40rpx;
	}

	.order-card {
		background-color: #FFFFFF;
		border-radius: 20rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	.order-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		background-color: #FFF4E5;
		padding: 30rpx;
		padding-bottom: 20rpx;

		.order-status {
			color: #A94F20;
			padding: 6rpx 16rpx;
			border-radius: 20rpx;
			font-size: 24rpx;
			background-color: #FFE0BF;
			margin-right: auto;
			margin-left: 20rpx;
		}

		.order-amount {
			font-size: 28rpx;
			color: #333;

			.amount-value {
				color: #FF5252;
				font-weight: bold;
			}
		}
	}

	.pet-info {
		display: flex;
		align-items: center;
		padding: 30rpx;
		padding-bottom: 20rpx;
		padding-top: 20rpx;

		.pet-avatar {
			position: relative;
			width: 80rpx;
			height: 80rpx;
			margin-right: 20rpx;

			image {
				width: 100%;
				height: 100%;
				border-radius: 50%;
			}

			.pet-tag {
				position: absolute;
				right: -10rpx;
				bottom: -10rpx;
				background-color: #FFAA48;
				color: #FFFFFF;
				font-size: 20rpx;
				padding: 4rpx 8rpx;
				border-radius: 10rpx;
				line-height: 1;
			}
		}

		.pet-details {
			display: flex;
			flex-direction: column;

			.pet-name {
				font-size: 28rpx;
				color: #333;
				font-weight: bold;
			}

			.pet-service {
				font-size: 24rpx;
				color: #666;
				margin-top: 4rpx;
				overflow:hidden; //超出的文本隐藏
				text-overflow:ellipsis; //溢出用省略号显示
				white-space:nowrap; //溢出不换行
			}
		}
	}

	.order-info {
		padding: 30rpx;
		padding-bottom: 20rpx;
		padding-top: 20rpx;

		.order-time {
			font-size: 24rpx;
			color: #999;
			display: block;
			margin-bottom: 10rpx;
		}

		.companion-info {
			font-size: 24rpx;
			color: #999;
			background-color: #F0F9FF;
			padding: 16rpx;
			border-radius: 10rpx;
		}
	}

	.order-actions {
		padding: 30rpx;
		padding-top: 20rpx;
		display: flex;
		justify-content: flex-end;
		align-items: center;

		.action-btn {
			padding: 16rpx 30rpx;
			border-radius: 30rpx;
			font-size: 26rpx;
			margin-left: 20rpx;
		}

		.details-btn {
			background-color: #FFFFFF;
			color: #666;
			border: 1px solid #DDDDDD;
		}

		.pay-btn {
			background-color: #FFAA48;
			color: #FFFFFF;
		}
	}

	.loading-more,
	.no-more {
		text-align: center;
		padding: 20rpx 0;
		color: #999;
		font-size: 24rpx;
	}

	.no-order {
		text-align: center;
		padding: 100rpx 0;
		color: #999;
		font-size: 28rpx;
		display: flex;
		flex-direction: column;
		align-items: center;

		.no-data-image {
			width: 200rpx;
			height: 200rpx;
			margin-bottom: 20rpx;
		}
	}
</style>