<template>
	<view class="order-modify-container">
		
		<view class="content">
			<!-- 加载状态 -->
			<view class="loading-container" v-if="loading">
				<view class="loading-circle"></view>
				<text class="loading-text">加载中...</text>
			</view>
			
			<view v-else>
				<view class="info-section modify-instruction-section">
					<view class="gradient-header">
						<view class="section-title">订单修改说明</view>
					</view>
					<view class="info-content">
						<view class="desc-item">
							<view class="desc-icon">🐾</view>
							<view class="desc-text">您可以对<text class="highlight">不涉及服务费用变动</text>的订单信息进行修改</view>
						</view>
						<view class="desc-item">
							<view class="desc-icon">🐾</view>
							<view class="desc-text">若需修改涉及金额变动的服务信息，如"增加或删除服务宠物/服务项目"，可点击下方按钮<text class="highlight">【修改服务】</text>来修改；或者，您也可"取消订单"后，"重新下单"</view>
						</view>
					</view>
				</view>
				
				<view class="info-section service-modify-section">
					<view class="section-header">
						<view class="accent-bar"></view>
						<view class="section-title">服务修改信息</view>
					</view>
					<view class="info-content">
						<view class="info-row editable">
							<text class="info-label">联系人</text>
							<input class="info-value-input" type="text" v-model="modifyInfo.contactName" placeholder="请输入联系人姓名" />
						</view>
						
						<view class="info-row editable">
							<text class="info-label">联系方式</text>
							<input class="info-value-input" type="text" v-model="modifyInfo.contactPhone" placeholder="请输入联系电话" />
						</view>
						
						<view class="info-row clickable">
							<text class="info-label">钥匙交接方式</text>
							<view class="info-value-container">
								<text class="info-value">{{modifyInfo.keyHandoverMethod || '存于快递柜'}}</text>
								<text class="arrow-right">></text>
							</view>
						</view>
					</view>
				</view>
				
			</view>
		</view>
		
		<!-- 底部按钮区域 -->
		<view class="order-modify-footer">
			<view class="footer-btn modify-service-btn" @click="modifyOrder">
				<view class="btn-icon">📝</view>
				<text class="btn-text">修改服务</text>
			</view>
			<view class="footer-btn confirm-modify-btn" @click="confirmModify">
				<text class="btn-text">确认修改</text>
			</view>
		</view>
		
		<!-- 客服组件 -->
		<Kefu></Kefu>
	</view>
</template>

<script>
import { getOrderDetail, updateBaseOrder } from '@/api/order/order.js';
import { mapState } from 'vuex';

import { getOpenIdKey } from '@/utils/auth'
import {
    getTeacherDetail,
} from "@/api/order/order"    
import positionMixin from '@/mixins/position';
	import {
		getAddressDetails,addAddress,updateAddress
	} from '@/api/system/address.js'
export default {
	mixins: [positionMixin],
	components: {
	},
	data() {
		return {
			loading: false,
			orderId: null,
			modifyInfo: {
				contactName: '',
				contactPhone: '',
				paymentMethod: '',
				keyHandoverMethod: '',
			},
			showCancelOrderPopup: false,
			originalOrderData: null
		}
	},
    computed: {
        ...mapState(['teacherLevelList'])
    },
	onLoad(options) {
		if (options.orderId) {
			this.orderId = options.orderId;
			this.loadOrderData();
		} else {
			uni.showToast({
				title: '订单ID不存在',
				icon: 'none'
			});
			setTimeout(() => {
				uni.navigateBack();
			}, 1500);
		}
	},
	methods: {
		// 加载订单数据
		async loadOrderData() {
			if (!this.orderId) return;
			
			const params = {
				openId: getOpenIdKey(),
				orderId: this.orderId
			};
			
			this.loading = true;
			try {
				const res = await getOrderDetail(params);
                
				if (res) {
					const orderData = res;
					this.originalOrderData = orderData;
					
					// 初始化修改信息
					this.modifyInfo.contactName = orderData.receiverName || '';
					this.modifyInfo.contactPhone = orderData.receiverPhone || '';
					this.modifyInfo.paymentMethod = orderData.paymentMethod || '';
				} else {
					uni.showToast({
						title: res.msg || '获取订单信息失败',
						icon: 'none'
					});
				}
			} catch (error) {
				console.error('获取订单数据失败', error);
				uni.showToast({
					title: '网络异常，请稍后重试',
					icon: 'none'
				});
			} finally {
				this.loading = false;
			}
		},
		
		// 确认修改
		async confirmModify() {
			// 表单验证
			if (!this.modifyInfo.contactName.trim()) {
				return uni.showToast({
					title: '请输入联系人姓名',
					icon: 'none'
				});
			}
			
			if (!this.modifyInfo.contactPhone.trim()) {
				return uni.showToast({
					title: '请输入联系方式',
					icon: 'none'
				});
			}
			
			// 验证手机号
			const phoneReg = /^1[3-9]\d{9}$/;
			if (!phoneReg.test(this.modifyInfo.contactPhone)) {
				return uni.showToast({
					title: '请输入正确的手机号码',
					icon: 'none'
				});
			}
			
			// 检查是否有修改（如果有原始数据的话）
			let hasChanged = false;
			if (this.originalOrderData) {
				hasChanged = 
					this.modifyInfo.contactName !== this.originalOrderData.contactName ||
					this.modifyInfo.contactPhone !== this.originalOrderData.contactPhone ||
					this.modifyInfo.paymentMethod !== this.originalOrderData.paymentMethod;
			} else {
				// 如果没有原始数据，只要有输入内容就认为有修改
				hasChanged = 
					this.modifyInfo.contactName.trim() !== '' ||
					this.modifyInfo.contactPhone.trim() !== '';
			}
				
			if (!hasChanged) {
				return uni.showToast({
					title: '未检测到任何修改',
					icon: 'none'
				});
			}
			
			this.loading = true;
			try {
				const updateData = {
					id: this.orderId,
					contactName: this.modifyInfo.contactName,
					contactPhone: this.modifyInfo.contactPhone,
					paymentMethod: this.modifyInfo.paymentMethod,
				};
				
				const res = await updateBaseOrder(updateData);
				if (res && res.code === 200) {
					uni.showToast({
						title: '订单修改成功',
						icon: 'success'
					});
					
					setTimeout(() => {
						uni.navigateBack();
					}, 1500);
				} else {
					uni.showToast({
						title: res.msg || '订单修改失败',
						icon: 'none'
					});
				}
			} catch (error) {
				console.error('订单修改失败', error);
				uni.showToast({
					title: '网络异常，请稍后重试',
					icon: 'none'
				});
			} finally {
				this.loading = false;
			}
		},
		
		// 修改服务（跳转到下单流程）
        async modifyOrder() {

            this.$globalData.newOrderData.orderId = this.orderId;

            let order = this.originalOrderData

            // 验证地址是否存在
            if(order.addressId) {
                try {
                    const addressRes = await getAddressDetails(order.addressId);
                    if(addressRes && addressRes.id) {
                        // 地址存在，设置地址信息
                        this.$globalData.newOrderData.currentAddress = {
                            id: order.addressId,
                            name: order.receiverName,
                            phone: order.receiverPhone,
                            province: order.receiverProvince,
                            city: order.receiverCity,
                            district: order.receiverDistrict,
                            detailAddress: order.receiverDetailAddress,
                            latitude: order.latitude,
                            longitude: order.longitude,
                        }
                    } else {
                        // 地址不存在，不设置地址信息
                        console.log('地址不存在，addressId:', order.addressId);
                        this.$globalData.newOrderData.currentAddress = {};
                    }
                } catch (error) {
                    console.error('验证地址失败:', error);
                    // 验证失败时也不设置地址信息
                    this.$globalData.newOrderData.currentAddress = {};
                }
            } else {
                // 没有地址ID，不设置地址信息
                this.$globalData.newOrderData.currentAddress = {};
            }

            if(order.teacherId){
                getTeacherDetail({
                    userId : order.teacherId
                }).then(response => {
					if (response) {
						let companionInfo = response
                	    companionInfo.distanceText = this.calculateDistanceAddress(response.appletAddresseList)
                        this.buyInfo.teacher = companionInfo
					}
				})
            }

            if(order.companionLevel){
                this.$globalData.newOrderData.companionLevel = 
                this.teacherLevelList.find(item => item.paramValueNum == order.companionLevel);
            }

            // 处理提前熟悉相关数据
            if(order.needPreFamiliarize) {
                this.$globalData.newOrderData.needPreFamiliarize = ['是否提前熟悉']
            }

            // 组装宠物数据
            if(order.petVOList && order.petVOList.length > 0) {
                this.$globalData.newOrderData.currentPets = order.petVOList.map(pet => {
                    // 获取该宠物的服务日期
                    const petServices = order.orderServiceList.filter(service => service.petId === pet.id);
                    const selectedDate = petServices.map(service => ({
                        date: service.serviceDate,
                        info: "预定"
                    }));
                    
                    return {
                        ...pet,
                        checked: ['checked'], // 默认选中
                        selectedDate,
                    };
                });
            }

            uni.navigateTo({
                url: `/pages/newOrder/serviceNew`
            });
        },
		
	}
}
</script>

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

.header {
	background-color: #FFAA48;
	padding: 20rpx 30rpx;
	color: #FFFFFF;
	
	.title {
		font-size: 36rpx;
		font-weight: bold;
	}
}

.content {
	flex: 1;
	padding: 20rpx;
}

.loading-container {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	height: 300rpx;
	margin-top: 100rpx;
}

.loading-circle {
	width: 80rpx;
	height: 80rpx;
	border: 4rpx solid #FFAA48;
	border-top-color: transparent;
	border-radius: 50%;
	animation: spin 1s linear infinite;
	margin-bottom: 20rpx;
}

@keyframes spin {
	0% {
		transform: rotate(0deg);
	}
	100% {
		transform: rotate(360deg);
	}
}

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

.info-section {
	background-color: #FFFFFF;
	border-radius: 20rpx;
	margin-bottom: 20rpx;
	overflow: hidden;
}

.modify-instruction-section {
	background: linear-gradient(135deg, #FFF5E6 0%, #FFFFFF 100%);
	border: 1px solid #FFE4B3;
}

.gradient-header {
	//background: linear-gradient(135deg, #FFAA48 0%, #FFB366 100%);
	padding: 20rpx;
	border-radius: 20rpx 20rpx 0 0;
}

.modify-instruction-section .section-title {
	//color: #FFFFFF;
	border-bottom: none;
	padding: 0;
	font-size: 32rpx;
	font-weight: bold;
}

.service-modify-section {
	background-color: #FFFFFF;
}

.section-header {
	display: flex;
	align-items: center;
	padding: 20rpx;
	border-bottom: 1px solid #EEEEEE;
}

.accent-bar {
	width: 6rpx;
	height: 32rpx;
	background-color: #FFAA48;
	border-radius: 3rpx;
	margin-right: 15rpx;
}

.service-modify-section .section-title {
	color: #333333;
	border-bottom: none;
	padding: 0;
	font-size: 32rpx;
	font-weight: bold;
}

.info-row {
	display: flex;
	align-items: center;
	padding: 20rpx;
	border-bottom: 1px solid #F5F5F5;
	
	&:last-child {
		border-bottom: none;
	}
	
	&.clickable {
		cursor: pointer;
	}
}

.info-row .info-label {
	width: 180rpx;
	font-size: 28rpx;
	color: #666666;
	flex-shrink: 0;
}

.info-row .info-value {
	flex: 1;
	font-size: 28rpx;
	color: #333333;
	text-align: right;
}

.info-row.editable {
	.info-value-input {
		flex: 1;
		font-size: 28rpx;
		color: #333333;
		text-align: right;
		border: none;
		background: transparent;
		padding: 0;
		
		&::placeholder {
			color: #CCCCCC;
		}
		
		&:focus {
			outline: none;
		}
	}
}

.info-value-container {
	display: flex;
	align-items: center;
	justify-content: flex-end;
	flex: 1;
}

.arrow-right {
	font-size: 24rpx;
	color: #CCCCCC;
	margin-left: 10rpx;
}

.section-title {
	font-size: 32rpx;
	font-weight: bold;
	padding: 20rpx;
	border-bottom: 1px solid #EEEEEE;
}

.info-content {
	padding: 20rpx;
}

.desc-item {
	display: flex;
	align-items: flex-start;
	margin-bottom: 20rpx;
	
	&:last-child {
		margin-bottom: 0;
	}
}

.desc-icon {
	font-size: 24rpx;
	margin-right: 15rpx;
	margin-top: 4rpx;
	color: #FFAA48;
}

.desc-text {
	font-size: 28rpx;
	color: #666;
	line-height: 1.6;
	flex: 1;
}

.highlight {
	color: #FFAA48;
	font-weight: 500;
}

.info-item {
	display: flex;
	align-items: center;
	margin-bottom: 20rpx;
	
	&:last-child {
		margin-bottom: 0;
	}
	
	.info-label {
		width: 180rpx;
		font-size: 28rpx;
		color: #666;
	}
	
	.info-value {
		flex: 1;
		font-size: 28rpx;
		color: #333;
		padding: 10rpx;
		border: 1px solid #EEEEEE;
		border-radius: 8rpx;
	}
}

.payment-method {
	.payment-value {
		display: flex;
		align-items: center;
		
		input {
			flex: 1;
			border: none;
			padding: 0;
		}
		
		.arrow-right {
			font-size: 24rpx;
			color: #999;
			margin-left: 10rpx;
		}
	}
}

.reason-input {
	width: 100%;
	height: 200rpx;
	font-size: 28rpx;
	padding: 20rpx;
	box-sizing: border-box;
	border: 1px solid #EEEEEE;
	border-radius: 8rpx;
}

.order-modify-footer {
	padding: 30rpx 20rpx;
	background-color: #FFFFFF;
	border-top: 1px solid #EEEEEE;
	display: flex;
	justify-content: space-between;
	align-items: center;
	gap: 20rpx;
}

.footer-btn {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 20rpx;
	border-radius: 12rpx;
	text-align: center;
	transition: all 0.3s ease;
	
	&:active {
		transform: scale(0.95);
	}
}

.modify-service-btn {
	background-color: #FFFFFF;
	border-radius: 12rpx;
	padding: 20rpx 30rpx;
	min-width: 120rpx;
	
	.btn-icon {
		font-size: 32rpx;
		margin-bottom: 8rpx;
	}
	
	.btn-text {
		font-size: 24rpx;
		color: #333333;
		font-weight: 500;
	}
}

.confirm-modify-btn {
	background-color: #FFAA48;
	border: none;
	border-radius: 50rpx;
	padding: 20rpx 60rpx;
	flex: 1;
	
	.btn-text {
		font-size: 32rpx;
		color: #FFFFFF;
		font-weight: bold;
	}
}
</style>