<template>
	<view class="order-detail-page">
		
		<!-- 订单内容区域 -->
		<view class="order-detail-content">
			<!-- 服务地址组件 -->
			<service-address :address="orderDetail.address"></service-address>
			
			<!-- 服务宠物组件 -->
			<service-pets :pets="orderDetail.pets"></service-pets>
			
			<!-- 服务项目及费用组件 -->
			<service-items :items="orderDetail.items" :totalAmount="orderDetail.totalAmount" 
				:discount="orderDetail.discount" :finalAmount="orderDetail.finalAmount"></service-items>
			
			<!-- 服务备注组件 -->
			<service-remarks :remarks="orderDetail.remarks"></service-remarks>
			
			<!-- 其他信息组件 -->
			<order-info :orderInfo="orderDetail.orderInfo"></order-info>
		</view>
		
		<!-- 底部按钮区域 -->
		<view class="order-detail-footer">
			<view class="footer-btn cancel-btn" v-if="orderDetail.status === '1'" @click="$refs.cancelOrderPopup.open()">
				<text>取消订单</text>
			</view>
			<view class="footer-btn pay-btn" v-if="orderDetail.status === '1'" @click="goToPay">
				<text>去付款</text>
			</view>
			<view class="footer-btn review-btn" v-if="orderDetail.status === 4" @click="goToReview">
				<text>评价订单</text>
			</view>
			<view class="footer-btn contact-btn">
				<text>联系客服</text>
			</view>
		</view>
		
		<!-- 取消订单弹窗 -->
		<cancel-order-popup 
        ref="cancelOrderPopup"
        @cancel="handleCancelOrder"
		></cancel-order-popup>
		
		<!-- 客服组件 -->
		<Kefu></Kefu>
	</view>
</template>

<script>
	import Kefu from '@/pages/common/kefu.vue'
	import ServiceAddress from '@/pages_order/components/order/ServiceAddress.vue'
	import ServicePets from '@/pages_order/components/order/ServicePets.vue'
	import ServiceItems from '@/pages_order/components/order/ServiceItems.vue'
	import ServiceRemarks from '@/pages_order/components/order/ServiceRemarks.vue'
	import OrderInfo from '@/pages_order/components/order/OrderInfo.vue'
	import CancelOrderPopup from '@/pages_order/components/order/CancelOrderPopup.vue'
	import { getOrderList } from "@/api/system/user.js"
	import { getOpenIdKey } from '@/utils/auth'
	import { getOrderDetail } from '@/api/order/order.js'
	import { getOrderServiceText, getProductNameText } from '@/utils/serviceTime.js'
	
	// 服务时间段映射
	const timeSlotMap = {
		'MORNING': '上午',
		'AFTERNOON': '下午',
		'EVENING': '晚上'
	}
	
	export default {
		components: {
			Kefu,
			ServiceAddress,
			ServicePets,
			ServiceItems,
			ServiceRemarks,
			OrderInfo,
			CancelOrderPopup
		},
		data() {
			return {
				orderId: null,
				orderDetail: {},
			};
		},
		onLoad(options) {
			if (options.id) {
				this.orderId = options.id;
				this.getOrderDetail();
			}
		},
		methods: {
			// 获取订单详情
			getOrderDetail() {
				const params = {
					openId: getOpenIdKey(),
					orderId: this.orderId
				};
				
				getOrderDetail(params).then(res => {
					if (res) {
						// 处理接口返回的数据
						const data = res;
						
						data.petVOList.forEach(pet => {
							pet.orderServiceText = getOrderServiceText(pet.id, data.orderServiceList) // 日期
							pet.productNameText = getProductNameText(pet.id, data.orderItemList, data.orderServiceList) // 服务
						})
						
						// 构建符合组件渲染需要的数据结构
						this.orderDetail = {
							// 地址信息
							address: {
								address: data.receiverProvince + data.receiverCity + data.receiverDistrict + data.receiverDetailAddress,
								contact: data.receiverName + ' ' + data.receiverPhone
							},
							
							// 宠物信息
							pets: data.petVOList ? data.petVOList.map(pet => {
								return {
									id: pet.id,
									name: pet.name,
									avatar: pet.photo,
									gender: pet.gender,
									serviceDays: pet.orderServiceText ? pet.orderServiceText.length : 0,
									serviceDates: pet.orderServiceText || [],
									services: pet.productNameText || []
								};
							}) : [],
							
							// 服务项目列表
							items: data.orderItemList.map((item, index) => {
								// 解析商品附加数据
								let spData = {};
								try {
									spData = JSON.parse(item.spData || '{}');
								} catch (e) {
									console.error('解析商品附加数据失败', e);
								}
								
								return {
									id: index + 1,
									name: item.productName,
									price: item.salePrice,
									quantity: item.quantity,
									customServices: []
								};
							}),
							
							// 费用信息
							totalAmount: data.totalAmount,
							discount: data.totalAmount - data.payAmount,
							finalAmount: data.payAmount,
							
							// 订单状态
							status: data.status.toString(),
							
							// 备注信息
							remarks: {
								keyHandoverMethod: '存于快递柜',
								isAdvanceFamiliar: true,
								priceInfo: `价格${data.payAmount}元`,
								serviceContent: '服务内容: 伴宠师将按照约定时间上门照顾宠物',
								serviceCondition: '服务保障: 购买此服务后，平台将安排伴宠师与您确认服务细节',
								notes: data.note || ''
							},
							
							// 其他信息
							orderInfo: {
								orderNumber: data.orderSn,
								orderTime: data.createTime,
								paymentTime: data.paymentTime
							}
						};
						
						// 如果有服务信息，处理服务日期和时间段
						if (data.orderServiceList && data.orderServiceList.length > 0) {
							// 处理服务日期和时间段
							const serviceDate = data.orderServiceList[0].serviceDate;
							const serviceTime = data.orderServiceList[0].expectServiceTime;
							
							// 更新服务项目描述
							if (this.orderDetail.items.length > 0) {
								this.orderDetail.items[0].serviceDate = serviceDate;
								this.orderDetail.items[0].serviceTime = timeSlotMap[serviceTime] || serviceTime;
							}
						}
					}
				}).catch(err => {
					console.error('获取订单详情失败', err);
				});
			},
			
			// 去付款
			goToPay() {
				uni.navigateTo({
					url: `/pages/details/order?id=${this.orderId}`
				});
			},
			
			// 去评价
			goToReview() {
				uni.navigateTo({
					url: `/pages_order/order/orderReview?id=${this.orderId}`
				});
			},
			
			// 处理取消订单
			handleCancelOrder() {
				// 待实现取消订单逻辑
			}
		}
	}
</script>

<style lang="scss" scoped>
	.order-detail-page {
		background-color: #f5f5f5;
		min-height: 100vh;
		display: flex;
		flex-direction: column;
	}
	
	.order-detail-content {
		flex: 1;
		padding: 20rpx;
	}
	
	.order-detail-footer {
		display: flex;
		justify-content: flex-end;
		align-items: center;
		padding: 20rpx 30rpx;
		background-color: #FFFFFF;
		border-top: 1px solid #EEEEEE;
		
		.footer-btn {
			padding: 16rpx 30rpx;
			border-radius: 30rpx;
			font-size: 26rpx;
			margin-left: 20rpx;
		}
		
		.cancel-btn {
			background-color: #FFFFFF;
			color: #666;
			border: 1px solid #DDDDDD;
		}
		
		.pay-btn {
			background-color: #FFAA48;
			color: #FFFFFF;
		}
		
		.review-btn {
			background-color: #FFAA48;
			color: #FFFFFF;
		}
		
		.contact-btn {
			background-color: #FFFFFF;
			color: #666;
			border: 1px solid #DDDDDD;
		}
	}
</style>