<template>
	<view class="service-new container">
		<view class="service-new-address">
			<uni-card padding=0 :is-shadow="false">
				<view class="service-new-title" slot="title">
					<view class="service-new-title-left">
						<view class="service-new-flag"></view>
						<view>服务地址</view>
					</view>
				</view>
				<view class="split-line"></view>
				<view class="service-new-address-content">
					<view class="service-new-address-selected">
						<view class="personal-address-info">
							<view class="personal-address-text">
								{{currentAddress.province}} {{currentAddress.city}} {{currentAddress.detailAddress}}
							</view>
							<view class="personal-address-people">
								<view>
									{{currentAddress.name}}
								</view>
								<view style="border: solid #7D8196 1px; margin: 0 10px; height: 12px;"> </view>
								<view>
									{{currentAddress.phone}}
								</view>
							</view>
						</view>
					</view>
				</view>
			</uni-card>
		</view>
		<view class="service-new-pet">
			<uni-card padding=0 :is-shadow="false">
				<view class="service-new-title" slot="title">
					<view class="service-new-title-left">
						<view class="service-new-flag">
						</view>
						<view class="service-new-title-text">
							服务宠物
						</view>
					</view>
				</view>
				<view class="split-line"></view>
				<view class="service-new-pet-content">
					<view class="personal-pet-list">
						<view v-for="(item,index) in showPets" :key="index">
							<view class="personal-pet-list-item">
								<view class="personal-pet-info">
									<!-- 左侧头像 -->
									<view class="pet-avatar">
										<u-avatar :src="item.photo?item.photo:defaultPhoto" size="60"
											shape="circle"></u-avatar>
									</view>

									<!-- 中间内容 -->
									<view class="pet-info" style="flex: 1; margin: 0 20rpx; max-width: 50%;">
										<view class="pet-name-gender" style="display: flex; align-items: center;">
											<view>{{item.name}}</view>
											<view class="pet-gender"
												style="margin-left: 10rpx; display: flex;align-items: center;">
												<img :src="item.gender=='男生'?'../../static/images/details/boy.svg':'../../static/images/details/girl.svg'"
													alt="sex" style="width: 16px;height: 16px;" />
											</view>
										</view>
										<view class="pet-dates ellipsis">
											{{ item.pets.map(e=>e.serviceDate).join(';') }}
										</view>
									</view>

									<!-- 右侧天数统计 -->
									<view class="date-total" style="margin-left: auto;width: 140rpx;text-align: end;">
										共 {{item.pets.length}} 天
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</uni-card>
		</view>
		<view class="service-new-pet">
			<uni-card padding=0 :is-shadow="false">
				<view class="service-new-title" slot="title">
					<view class="service-new-title-left">
						<view class="service-new-flag">
						</view>
						<view class="service-new-title-text">
							服务信息及费用
						</view>
					</view>
				</view>
				<view class="split-line"></view>
				<view class="service-new-pet-content">
					<view class="personal-pet-list">

						<view v-for="item in dailyShowData" :key="item.date" class="service-new-address">
							<view class="service-summary">
								<view style="display: flex; align-items: center;">
									<view style="padding-right: 10rpx;color: #7D8196;">{{ getDateText(item.date) }}</view>
									<!-- <view style="padding-right: 10rpx;color: #7D8196;">{{ item.date }}</view> -->
									<view
										style="margin: 0 10rpx; width: 2px; height: 20rpx; background-color: #7D8196;">
									</view>
									<view style="color: #333333; margin-left: 10rpx;">{{baseProduct}}
										{{item.customServicesTotalCnt? ' + 定制服务' + item.customServicesTotalCnt + '项' : '' }}
									</view>
								</view>
								<view style="display: flex; align-items: center;">
									<view style="color: #333333;margin-right: 10rpx;">¥{{ item.totalCost }}</view>
									<view>
										<u-icon @click="toggleExpand( item.date )"
											:name="expandedIndexs.includes( item.date ) ? 'arrow-up' : 'arrow-down'"
											color="#FFBF60" size="14"></u-icon>
									</view>
								</view>
							</view>

							<view v-if="!expandedIndexs.includes(item.date)" class="split-line"></view>
							<view v-show="expandedIndexs.includes(item.date)" class="service-details">
								<!-- 基础服务 上门次数 额外费用  -->
								<view>基础服务</view>
								<view v-for="(priceItem, priceIndex) in item.priceDetails" :key="priceIndex"
									class="price-details-item">
									<view style="display: flex;" v-for="(item2, index) in priceItem.item" :key="index">
										<view v-if="item2.quantity" class="service-item">
											<view v-if="item2.itemName != item.name"
												class="price-details-item-price-total-item">- {{ item2.itemName }}
											</view>
											<view class="price-details-item-price-total-item">¥{{ parseFloat(item2.price) }} ×
												{{ item2.quantity }} {{ item2.unit }}</view>
										</view>
									</view>
								</view>
								<view v-if="item.customServicesTotalCnt>0" style="margin-top: 20rpx;">定制服务</view>
								<view v-for="(pet, petIndex) in item.pets" :key="petIndex">
									<view
										v-if="pet.customServices &&pet.customServices.filter(e=>e.quantity>0).length>0"
										style="display: flex; align-items: center; justify-content: flex-start; margin-top: 20rpx;">
										<view class="pet-avatar">
											<u-avatar :src="pet.photo?pet.photo:defaultPhoto" size="34"
												shape="circle"></u-avatar>
										</view>
										<view style="margin-left: 20rpx;">{{ pet.name}}</view>
									</view>
									<!-- 定制服务 -->
									<view v-for="(customItem, customIndex) in pet.customServices" :key="customIndex">
										<view v-if="customItem.quantity" class="service-item">
										<view>- {{ customItem.name }}</view>
										<view>¥{{ parseFloat(customItem.price).toFixed(2) }} × {{ customItem.quantity }} 次</view>
									</view>
									</view>
								</view>
							</view>
						</view>

						<view class="service-new-address">
							<view v-if="needPreFamiliarize.length>0" class="total-cost">
				<view>提前熟悉 </view>
				<view>¥{{ (price_config && price_config.preFamiliarize && price_config.preFamiliarize.price) || 40 }}</view>
			</view>
							<!-- 伴宠师价格已合并到基础服务价格中，不再单独显示 -->
							<view class="total-cost">
							<view>费用总计 </view>
							<view>¥{{ parseFloat(originalTotalPrice).toFixed(2) }}</view>
						</view>
							<view class="total-cost" @click="selectCoupon">
								<view>平台优惠</view>
								<view style="color: #FF530A;">
									{{ selectedCoupon ? selectedCoupon.stockName : '未使用优惠券' }}
									<uni-icons type="right" size="28rpx" color="#AAA"></uni-icons>
								</view>
							</view>
							<view class="total-cost" v-if="discountMemberText">
								<view>会员折扣</view>
								<view style="display: flex; align-items: center;">
								<view style="color: #999999;">{{ currentMember.itemType }}{{ discountMemberText }}折优惠</view>
								<view style="border: solid #7D8196 1px; margin: 0 10rpx; height: 12px;"> </view>
								<view style="color: #FF530A;">-¥{{ parseFloat(memberDiscount).toFixed(2) }}</view>
							</view>
							</view>
							<view class="total-cost" v-if="$globalData.newOrderData.moreOrderPrice && $globalData.newOrderData.moreOrderPrice > 0">
								<view>再来一单费用</view>
								<view style="color: #FF530A;">+¥{{ parseFloat($globalData.newOrderData.moreOrderPrice).toFixed(2) }}</view>
							</view>
							<view class="total-cost">
							<view>应付费用</view>
							<view style="font-weight: 500;font-size: 32rpx;">¥{{ parseFloat(finalPrice).toFixed(2) }}</view>
						</view>
						</view>

					</view>
				</view>
			</uni-card>
		</view>

		<view class="service-new-pet">
			<uni-card padding=0 :is-shadow="false">
				<view class="service-new-title" slot="title">
					<view class="service-new-title-left">
						<view class="service-new-flag">
						</view>
						<view class="service-new-title-text">
							服务细则
						</view>
					</view>
				</view>
				<view class="split-line"></view>
				<view class="service-new-details-content">
					<view style="margin: 30rpx 0;">
						<u-checkbox-group @change="changePreFamiliarize" :value="needPreFamiliarize"
							iconPlacement="right" placement="column">
							<u-checkbox activeColor="#FFBF60" label="是否提前熟悉" name="是否提前熟悉" shape="circle"></u-checkbox>
						</u-checkbox-group>
					</view>
					<view class="split-line"></view>
					<view class="service-new-details-desc">
						<view style="display: flex;">
							<text style="width: 20rpx;">*</text>
							<text style="flex: 1;">价格{{ (price_config && price_config.preFamiliarize && price_config.preFamiliarize.price) || 40 }}元/次</text>
						</view>
						<view style="display: flex; margin: 20rpx 0;">
							<text style="width: 20rpx;">*</text>
							<text style="flex: 1;">服务内容: 购买此服务后，伴宠师将在您离家前，按照约定日期提前上门沟通，熟悉喂养要求及宠物</text>
						</view>
						<view style="display: flex;">
							<text style="width: 20rpx;">*</text>
							<text style="flex: 1;">服务保障: 购买此服务后，平台支持在提前熟悉后，上门服务第一天前，无理由免费更换伴宠师1次</text>
						</view>
					</view>
				</view>
			</uni-card>
		</view>
		<view class="details-subscribe">
			<view class="details-radio" style="width: 100%;padding-bottom: 20rpx;">
				<view>
					<u-checkbox-group v-model="isAgree" size="16" labelSize="14" labelColor="#999999">
						<u-checkbox activeColor="#FFBF60" label="我同意" name="我同意" labelSize="14" size="14"
							shape="circle"></u-checkbox>
					</u-checkbox-group>
				</view>
				<text style="color: #FFBF60;font-size: 28rpx;" @click="checkAgreement">《猫妈狗爸用户服务协议和隐私协议》</text>
			</view>
			<view style="display: flex;justify-content: space-between; align-items: center;">
				<view style="height: 80rpx; display: flex; align-items: center;">
					<text style="color: #333333;">订单总价: </text>
					<text style="color: #FF530A; font-size: 40rpx;">¥{{ parseFloat(finalPrice).toFixed(2) }} <text
							style="font-size: 32rpx;"></text></text>
				</view>
				<view style="display: flex;">
					<u-button color="#FFF4E4" customStyle="width: 200rpx; color: #FFAA48; margin-right: 20rpx;"
						text="上一步" @click="goBack"></u-button>
					<u-button color="#FFBF60" customStyle="width: 200rpx; color: #FFF;" text="支付"
						@click="goNext"></u-button>
				</view>
			</view>
		</view>
		<view v-if="showCoupon" class="calendar-popup">
			<view class="calendar-mask"></view>
			<view class="calendar-content">
				<view class="price-details">
					<view class="price-details-header">
						<text
							style="text-align: center; width: 100%; font-size: 32rpx; font-weight: 500; color: #333333;">优惠券</text>
						<u-icon name="close" @click="togglePriceDetails"></u-icon>
					</view>
					<view class="split-line"></view>
					<scroll-view class="price-details-body" scroll-y v-if="showCouponList">
						<view v-for="(item,index) in couponList" style="padding-bottom:14px;" :key="index">
							<view class="coupon-card" :class="{ 
								'auto-selected': item.checked && item.checked.length > 0 && item.isAutoSelected,
								'manual-selected': item.checked && item.checked.length > 0 && !item.isAutoSelected
							}">
								<view class="card-left"><text
										style="font-size: 40rpx; margin-left: 5rpx;">{{ getCouponAmountOrDiscount(item) }}</text>
								</view>
								<view class="card-right">
									<view class="card-content">
										<view class="card-info">
											{{item.stockName}}
											<text v-if="item.checked && item.checked.length > 0 && item.isAutoSelected" style="color: #FF530A; font-size: 24rpx; margin-left: 10rpx;">(自动选择)</text>
											<text v-if="item.checked && item.checked.length > 0 && !item.isAutoSelected" style="color: #FF530A; font-size: 24rpx; margin-left: 10rpx;">(手动选择)</text>
										</view>
										<view class="card-time">有效期限: {{item.expireTime.slice(0, 10)}}截止</view>
									</view>
									<view style="width: 20%;">
										<u-checkbox-group :value="item.checked" @change="changeCoupon">
											<u-checkbox :disabled="item.transactionMinimum > originalTotalPrice"
												shape="circle" :name="item.id" activeColor="#ffbf60"></u-checkbox>
										</u-checkbox-group>
									</view>
								</view>
							</view>
						</view>
					</scroll-view>
				</view>
				<u-button color="#FFBF60" type="primary" @click="confirmCoupon">确定</u-button>
			</view>

		</view>
	</view>
</template>
<script>
	import {
		getPersonalInfo,
		getCouponList,
		getCouponListForOrder
	} from "@/api/system/personal.js"
	import {
		getToken,
		getOpenIdKey
	} from '@/utils/auth'
	import {
		createOrderNew
	} from '@/api/system/user.js'
	import dayjs from '@/utils/lib/dayjs.min.js'
	export default {
		data() {
			return {
				isPaying: false,
				currentAddress: {},
				currentPetsByDay: [],
				showPets: [],
				expandedIndexs: [],
				isAgree: false,
				needPreFamiliarize: [],
				dailyShowData: [],
				originalTotalPrice: 0,
				totalPrice: 0, // 总费用
				discount: 0, // 平台优惠
				memberDiscount: 0, // 会员折扣
				finalPrice: 0, // 应付费用
				defaultPhoto: 'https://catmdogf.oss-cn-shanghai.aliyuncs.com/CMDF/front/personal/pet/catdog.png',
				currentMember: {},
				memberDiscountList: [{
						itemType: "新晋家长",
					},
					{
						itemType: "普卡会员",
					},
					{
						itemType: "银卡会员",
					},
					{
						itemType: "金卡会员",
					}
				],
				couponList: [],
				showCoupon: false,
				selectedCoupon: null,
				showCouponList: true,
				couponId: null,
				basePrice: 0,
				baseProduct: '',
				// 节假日价格配置
				holidayPrice: 75,
				normalPrice: 75,
				holidayDate: [],
                //折扣
                discountMemberText : '',
                companionLevelTitle : '',

                freePetConfig : {
                    cat: { freeCount: 1 },
                    smallDog: { freeCount: 0 },
                    mediumDog: { freeCount: 0 },
                    largeDog: { freeCount: 0 }
                },
			}
		},
		onLoad() {
			if (getToken() && getOpenIdKey()) {
				this.getPersonalInfo()
			}

			this.originalTotalPrice = this.$globalData.newOrderData.totalPrice
			if (this.originalTotalPrice) {
				this.basePrice = this.$globalData.mainSku[0].price
				this.baseProduct = this.$globalData.mainSku[0].name
				this.currentAddress = this.$globalData.newOrderData.currentAddress
				this.currentPetsByDay = this.$globalData.newOrderData.currentPetsByDay
				this.needPreFamiliarize = this.$globalData.newOrderData.needPreFamiliarize
			} else {
				// 返回首页
				uni.reLaunch({
					url: '/pages/index'
				});
			}
			this.initPriceConfig()
			this.getShowPets()
			this.groupPetsByDate()
			this.getCouponList()
			// this.totalPrice = this.$globalData.newOrderData.totalPrice

            this.companionLevelTitle = (this.$globalData.newOrderData.companionLevel && this.$globalData.newOrderData.companionLevel.paramValue) || ''
		},
		methods: {
            companionLevelPrice(){
            let companionLevel = this.$globalData.newOrderData.companionLevel
            if (!companionLevel || !companionLevel.paramValueText) {
                return 0
            }
            let paramValueText = isNaN(companionLevel.paramValueText) ? 0 : Number(companionLevel.paramValueText)
            let addPrice = this.isAddPrice()
            let memberRate = isNaN(this.$store.state.memberRate) ? 1 : Number(this.$store.state.memberRate)
            let price = paramValueText * addPrice

                return price * memberRate
            },
            //判断当前选中的地址是否加价
            isAddPrice(){
                let currentAddress = this.$globalData.newOrderData.currentAddress || {}

                let defaultPrice = 1

                try{
                    defaultPrice = this.price_config.cityConfig.priceRates.default
                }catch(e){
                    defaultPrice = 1
                }

                if(!this.price_config.cityConfig || !currentAddress.province || !currentAddress.city){
                    return defaultPrice
                }

                let addressList = this.price_config.cityConfig.priceRates || []

                for(let key in addressList){
                    if((currentAddress.province + currentAddress.city).includes(key)){
                        return addressList[key]
                    }
                }
                return defaultPrice
            },
			getDateText(date){
				return dayjs(date).format('MM-DD')
			},
			// 将currentPets转换为showPets
			getShowPets() {
				const showPets = []
				// 将 currentPetsByDay 通过petId分组
				const groupedPets = this.currentPetsByDay.reduce((acc, pet) => {
					pet.index = pet.petId + '-' + pet.serviceDate
					if (!acc[pet.petId]) {
						acc[pet.petId] = []; // 如果不存在，则初始化一个空数组
					}
					acc[pet.petId].push(pet); // 将当前宠物添加到对应的 petId 数组中
					return acc;
				}, {});
				console.log(groupedPets)
				// 循环将pets转换为showPets
				for (let petId in groupedPets) {
					const showPet = {
						petId: petId,
						name: groupedPets[petId][0].name,
						gender: groupedPets[petId][0].gender,
						petType: groupedPets[petId][0].petType,
						bodyType: groupedPets[petId][0].bodyType,
						photo: groupedPets[petId][0].photo,
						pets: groupedPets[petId]
					}
					showPets.push(showPet)
				}
				this.showPets = showPets
				console.log(this.showPets)
			},
			// 将宠物按天分组
			groupPetsByDate() {
				const dailyShowData = []
				const dailyPets = [];
				// 按日期分组宠物
				this.currentPetsByDay.forEach(pet => {
					const serviceDate = pet.serviceDate;
					if (!dailyPets[serviceDate]) {
						dailyPets[serviceDate] = [];
					}
					dailyPets[serviceDate].push(pet);
				});

				// 计算每日费用
				for (const date in dailyPets) {
					const pets = dailyPets[date];
					const priceDetails = []
					// 基础服务 - 根据是否为节假日设置价格
					const holidayPrice = isNaN(this.holidayPrice) ? 75 : Number(this.holidayPrice)
					const normalPrice = isNaN(this.normalPrice) ? 75 : Number(this.normalPrice)
					const baseServiceCost = Number(this.isHoliday(date) ? holidayPrice : normalPrice)

					const largeDogCount = pets.filter(pet => pet.petType === 'dog' && pet.bodyType.includes('大型')).length;
					let mediumDogCount = pets.filter(pet => pet.petType === 'dog' && pet.bodyType.includes('中型')).length;
					let smallDogCount = pets.filter(pet => pet.petType === 'dog' && pet.bodyType.includes('小型')).length;
					let catCount = pets.filter(pet => pet.petType === 'cat').length;


					const additionalCostItem = []
					let additionalCost = 0
					// 单天总宠物费用
					let totalPetCost = pets.reduce((acc, pet) => {
						return acc + this.calculatePetCost(pet);
					}, 0);


                    // 根据 freePetConfig 配置计算免费宠物数量
                    const freePetConfig = this.price_config.freePetConfig || this.freePetConfig
                    
                    // 计算收费的宠物数量（扣除免费数量）
                    const chargeableMediumDogCount = Math.max(0, mediumDogCount - freePetConfig.mediumDog.freeCount)
                    const chargeableSmallDogCount = Math.max(0, smallDogCount - freePetConfig.smallDog.freeCount)
                    const chargeableCatCount = Math.max(0, catCount - freePetConfig.cat.freeCount)
                    
                    // 计算额外宠物费用
                    if (chargeableMediumDogCount > 0) {
                        additionalCost += (this.calculatePetCost({
                            petType: 'dog',
                            bodyType: '中型',
                        }) * chargeableMediumDogCount)
                        additionalCostItem.push({
                            itemName: '中型犬',
                            price: this.calculatePetCost({
                                petType: 'dog',
                                bodyType: '中型',
                            }),
                            quantity: chargeableMediumDogCount,
                            unit: '只'
                        })
                    }
                    if (chargeableSmallDogCount > 0) {
                        additionalCost += (this.calculatePetCost({
                            petType: 'dog',
                            bodyType: '小型',
                        }) * chargeableSmallDogCount)
                        additionalCostItem.push({
                            itemName: '小型犬',
                            price: this.calculatePetCost({
                                petType: 'dog',
                                bodyType: '小型',
                            }),
                            quantity: chargeableSmallDogCount,
                            unit: '只'
                        })
                    }
                    if (chargeableCatCount > 0) {
                        additionalCost += (this.calculatePetCost({
                            petType: 'cat',
                        }) * chargeableCatCount)
                        additionalCostItem.push({
                            itemName: '猫猫',
                            price: this.calculatePetCost({
                                petType: 'cat',
                            }),
                            quantity: chargeableCatCount,
                            unit: '只'
                        })
                    }
					// 计算收费的大型犬数量（扣除免费数量）
					const chargeableLargeDogCount = Math.max(0, largeDogCount - freePetConfig.largeDog.freeCount)
					if (chargeableLargeDogCount > 0) {
						additionalCost += (this.calculatePetCost({
                            petType: 'dog',
                            bodyType: '大型',
                        }) * chargeableLargeDogCount)
						additionalCostItem.push({
							itemName: '大型犬',
							price: this.calculatePetCost({
                                petType: 'dog',
                                bodyType: '大型',
                            }),
							quantity: chargeableLargeDogCount,
							unit: '只'
						})
					}
					// 当日多次服务次数 - 基础价格乘以倍数
					let multServicesTotalCost = 0
					const maxFeedCount = Math.max(...pets.map(pet => pet.feedCount));
					const multiService = this.price_config.multiService || { two: { price: 1 }, three: { price: 1 } }
					if (maxFeedCount === 2) {
						multServicesTotalCost += baseServiceCost * (multiService.two.price || 1); // 基础价格 × 2次倍数
					} else if (maxFeedCount === 3) {
                        multServicesTotalCost += baseServiceCost * (multiService.three.price || 1); // 基础价格 × 3次倍数
					}
					priceDetails.push({
						name: '专业喂养',
						item: [{
							itemName: this.isHoliday(date) ? '节假日' : '非节假日',
							price: baseServiceCost,
							quantity: 1,
							unit: '天'
						}, ]
					})
					priceDetails.push({
						name: '上门次数',
						item: [{
								itemName: `1天2次 (${this.isHoliday(date) ? '节假日' : '非节假日'})`,
								price: baseServiceCost * (multiService.two.price || 1),
								quantity: maxFeedCount === 2 ? 1 : 0,
								unit: '天'
							},
							{
								itemName: `1天3次 (${this.isHoliday(date) ? '节假日' : '非节假日'})`,
								price: baseServiceCost * (multiService.three.price || 1),
								quantity: maxFeedCount === 3 ? 1 : 0,
								unit: '天'
							},
						]
					})

					if (additionalCostItem.length > 0) {
						priceDetails.push({
							name: '额外宠物费用',
							item: additionalCostItem
						})
					}

					// 所有宠物定制服务费用
					const customServiceCost = pets.reduce((acc, pet) => Number(acc) + Number(this.calculatePetCustomServiceCost(pet)), 0)
                    // console.log(baseServiceCost + additionalCost + multServicesTotalCost + customServiceCost);
                    console.log(baseServiceCost , additionalCost , multServicesTotalCost , customServiceCost);
                    
					if (isNaN(baseServiceCost)) {
						console.log('baseServiceCost is not a number', baseServiceCost);
					}
					if (isNaN(additionalCost)) {
						console.log('additionalCost is not a number', additionalCost);
					}
					if (isNaN(multServicesTotalCost)) {
						console.log('multServicesTotalCost is not a number', multServicesTotalCost);
					}
					if (isNaN(customServiceCost)) {
						console.log('customServiceCost is not a number', customServiceCost, pets);
						uni.showToast({
							title: '定制服务费用计算错误',
							icon: 'none'
						})
					}

					// 确保所有数值都是有效的数字，避免NaN
					const safeBaseServiceCost = isNaN(baseServiceCost) ? 0 : Number(baseServiceCost)
					const safeAdditionalCost = isNaN(additionalCost) ? 0 : Number(additionalCost)
					const safeMultServicesTotalCost = isNaN(multServicesTotalCost) ? 0 : Number(multServicesTotalCost)
					const safeCustomServiceCost = isNaN(customServiceCost) ? 0 : Number(customServiceCost)
					
					const totalCost = parseFloat(safeBaseServiceCost + safeAdditionalCost + safeMultServicesTotalCost + safeCustomServiceCost).toFixed(2)
					// 所有宠物定制服务总项数，每个类型的服务只算一次
					const acc = []
					pets.map(pet => {
						pet.customServices.forEach(service => {
							if (!acc.includes(service.skuId) && service.quantity > 0) {
								acc.push(service.skuId)
							}
						})
					})
					const customServicesTotalCnt = acc.length
					dailyShowData.push({
						date,
						pets,
						priceDetails,
						totalCost,
						customServicesTotalCnt
					})

				}
				// 将dailyShowData按日期排序
				this.dailyShowData = dailyShowData.sort((a, b) => new Date(a.date) - new Date(b.date))
				this.getShowTotalPrice()
			},
			calculatePetCost(pet) {
                let petExtra = this.price_config.petExtra || {}
                let petCost = 0;
                if (pet.petType === 'cat' && petExtra.cat) {
                    petCost += Number(petExtra.cat.price || 0); // 猫额外费用
                } else if (pet.petType === 'dog' && pet.bodyType.includes('小型') && petExtra.smallDog) {
                    petCost += Number(petExtra.smallDog.price || 0); // 小型犬额外费用
                } else if (pet.petType === 'dog' && pet.bodyType.includes('中型') && petExtra.mediumDog) {
                    petCost += Number(petExtra.mediumDog.price || 0); // 中型犬额外费用
                } else if (pet.petType === 'dog' && pet.bodyType.includes('大型') && petExtra.largeDog) {
                    petCost += Number(petExtra.largeDog.price || 0); // 大型犬额外费用
                }
                return petCost;
            },
			// 计算宠物定制服务费用
			calculatePetCustomServiceCost(pet) {
                console.log('pet.customServices',pet.customServices)
				// 确保customServices存在且为数组
				if (!pet.customServices || !Array.isArray(pet.customServices)) {
					return 0
				}
				const customServiceCost = pet.customServices.reduce((acc, item) => {
					if (isNaN(item.price) || isNaN(item.quantity)) {
						console.log('customServiceCost item price or quantity is not a number', item);
						throw new Error('customServiceCost item price or quantity is not a number')
					}
					const price = Number(item.price)
					const quantity = Number(item.quantity)
					return Number(acc) + price * quantity
				}, 0)
                console.log('customServiceCost',customServiceCost)
				return parseFloat(customServiceCost).toFixed(2)
			},
			// 展开或收起服务详情
			toggleExpand(index) {
				console.log(index)
				this.expandedIndexs = this.expandedIndexs.includes(index) ? this.expandedIndexs.filter(i => i !== index) :
					[...this.expandedIndexs, index];
				// this.expandedIndexs.push(index)
				console.log(this.expandedIndexs)
			},
			goBack() {
				let len = getCurrentPages().length;
				if (len >= 2) {
					uni.navigateBack();
				} else {
					uni.redirectTo({
						url: '/pages/newOrder/serviceNew2'
					});
				}
			},
			changeAgree() {
				this.isAgree = !this.isAgree
			},
			checkAgreement() {
				uni.navigateTo({
					url: '/pages/details/agreement'
				});
			},
			// 初始化价格配置
			initPriceConfig() {
                let priceConfig = this.$store.state.price_config
                console.log('价格配置:', priceConfig)
                
                // 将价格配置赋值给组件
                this.price_config = priceConfig || {}
                
                // 获取伴宠师等级价格和城市倍率，确保都是有效数字
                let companionPrice = isNaN(this.$globalData.newOrderData.companionLevelPrice) ? 0 : Number(this.$globalData.newOrderData.companionLevelPrice)
                let cityPriceRate = isNaN(this.$globalData.newOrderData.cityPriceRate) ? 1 : Number(this.$globalData.newOrderData.cityPriceRate)
                let memberRate = isNaN(this.$store.state.memberRate) ? 1 : Number(this.$store.state.memberRate)
                
                if(priceConfig.basePrice && priceConfig.basePrice.holiday){
                    const holidayBasePrice = isNaN(priceConfig.basePrice.holiday) ? 75 : Number(priceConfig.basePrice.holiday)
                    this.holidayPrice = Number((holidayBasePrice * memberRate * cityPriceRate) + companionPrice).toFixed(2)
                } else {
                    this.holidayPrice = 75
                }
                if(priceConfig.basePrice && priceConfig.basePrice.normal){
                    const normalBasePrice = isNaN(priceConfig.basePrice.normal) ? 75 : Number(priceConfig.basePrice.normal)
                    this.normalPrice = Number((normalBasePrice * memberRate * cityPriceRate) + companionPrice).toFixed(2)
                } else {
                    this.normalPrice = 75
                }
                if(priceConfig.holidays && Array.isArray(priceConfig.holidays) && priceConfig.holidays.length > 0){
                    this.holidayDate = priceConfig.holidays
                }else{
                    this.holidayDate = []
                }
                this.discountMemberText = (memberRate * 10)
            },
			// 判断是否为节假日
			isHoliday(date) {
				return this.holidayDate.includes(date)
			},
			// 节流
			throttle(func, delay) {
				let lastCall = 0;
				return function(...args) {
					const now = new Date().getTime();
					if (now - lastCall < delay) {
						return;
					}
					lastCall = now;
					func(...args);
				}
			},
			getPersonalInfo() {
				getPersonalInfo().then(res => {
					if (res && (res.id || res.id === 0)) {
						let userLevel = res.level
						this.currentMember = this.memberDiscountList.find(item => {
							if (item.itemType.includes(userLevel)) {
								return item
							}
						})
						this.getShowTotalPrice()
						// 重新计算最优惠的优惠券
						if (this.couponList.length > 0) {
							this.autoSelectBestCoupon()
						}
					}
				})
			},
			// 获取优惠券列表
			getCouponList() {
				getCouponListForOrder().then(res => {
					let rows = res.rows
					console.log(rows)
					this.couponList = rows.filter(item => item.couponState == "SENDED")
					this.couponList.forEach(item => {
						item.checked = []
						item.couponAmount = 20
						item.isAutoSelected = false
					})
					// 自动选择最优惠的优惠券
					this.autoSelectBestCoupon()
				})
			},
			selectCoupon() {
				this.showCoupon = true
			},
			changeCoupon(item) {
				this.showCouponList = false
				const selectedCouponId = item[0]
				const selectedCoupon = this.couponList.find(coupon => coupon.id === selectedCouponId)
				
				// 清空所有优惠券的选中状态和自动选择标记
				this.couponList.forEach(coupon => {
					coupon.checked = null
					coupon.isAutoSelected = false
				})
				
				// 如果选择了优惠券，检查是否有相同 couponState 的优惠券已被使用
				if (selectedCoupon) {
					// 检查是否有相同 couponState 的优惠券已被使用
					const hasSameStateUsed = this.couponList.some(coupon => 
						coupon.id !== selectedCouponId && 
						coupon.couponState === selectedCoupon.couponState && 
						coupon.checked && 
						coupon.checked.length > 0
					)
					
					if (hasSameStateUsed) {
						uni.showToast({
							title: '相同类型的优惠券不可重复使用',
							icon: 'none'
						})
						this.showCouponList = true
						return
					}
					
					// 设置选中状态，标记为用户手动选择
					selectedCoupon.checked = item
					selectedCoupon.isAutoSelected = false
				}
				
				this.showCouponList = true
			},
			confirmCoupon() {
				this.selectedCoupon = this.couponList.find(coupon => coupon.checked && coupon.checked.length > 0)
				if (!this.selectedCoupon) {
					this.couponId = null
					this.discount = 0
				} else {
					this.couponId = this.selectedCoupon?.id
					// 如果优惠券是折扣
					if (this.selectedCoupon?.stockType == "PDISCOUNT" && this.selectedCoupon?.discountPercent > 0) {
						//保留两位小数	
						this.discount = (this.originalTotalPrice * (1 - this.selectedCoupon.discountPercent / 100))
							.toFixed(2)
					} else {
						this.discount = this.selectedCoupon?.discountAmount
					}
				}
				this.getShowTotalPrice()
				this.showCoupon = false

			},
			togglePriceDetails() {
				this.showCoupon = !this.showCoupon
			},
			// 构造订单
			constructOrder() {
				const order = {
					openId: getOpenIdKey(),
					addressId: this.currentAddress.id,
					totalPrice: this.finalPrice,//应付费用
					needPreFamiliarize: this.needPreFamiliarize.length > 0,
					couponId: this.couponId,
					petOrderServices: this.getPetOrderServices(this.currentPetsByDay),
                    //费用明细
                    //dailyShowData : JSON.stringify(this.dailyShowData),
                    //优惠券优惠
                    couponDiscount: this.discount,
                    //会员折扣
                    memberDiscount: this.memberDiscount,
                    //费用总计
                    oldPrice : this.originalTotalPrice,
                    //提前熟悉的费用
                    preFamiliarizePrice: (this.price_config.preFamiliarize && this.price_config.preFamiliarize.price) || 40,

                    //伴宠师等级名称
                    companionLevelTitle : this.companionLevelTitle,
                    //伴宠师等级加价（已合并到基础价格中）
                    companionLevelPrice: 0,
				}
				
				if(this.buyInfo.teacher){
					order.teacherId = this.buyInfo.teacher.userId
				} 
                if(this.$globalData.newOrderData.companionLevel){
                    //打印
                    console.log(this.$globalData.newOrderData.companionLevel);
                    order.companionLevel = this.$globalData.newOrderData.companionLevel.paramValueNum
					// order.companionLevel = ['', 'junior', 'senior'].indexOf(this.$globalData.newOrderData.companionLevel)
				}
                
                if(this.$globalData.newOrderData.orderId){
                    order.orderId = this.$globalData.newOrderData.orderId
				}
				
				// 再来一单费用
				if(this.$globalData.newOrderData.moreOrderPrice){
					order.moreOrderPrice = this.$globalData.newOrderData.moreOrderPrice
				}
				
				console.log(order)
				return order
			},
			getSkuList(customServices, feedCount, price) {
                console.log('customServices', JSON.parse(JSON.stringify(customServices)));
				const skuList = customServices.filter(service => service.quantity > 0).map(service2 => {
					return {
						skuId: service2.skuId,
						quantity: service2.quantity,
						isMainProduct: service2.isMainProduct,
                        price: service2.price
					}
				})
				skuList.push({
					skuId: this.$globalData.mainSku[0].skuId,
					quantity: feedCount,
					isMainProduct: true,
                    price
				})
				return skuList
			},
			getPetOrderServices(currentPetsByDay) {
                console.log('currentPetsByDay', JSON.parse(JSON.stringify(currentPetsByDay)));
				const petOrderServices = currentPetsByDay.map(pet => {
                    let price = this.isHoliday(pet.serviceDate) ? this.holidayPrice : this.normalPrice
                    
					// 当日多次服务次数 - 基础价格乘以倍数
                    let feedCountPrice = 0;
                    const multiService = this.price_config.multiService || { two: { price: 1 }, three: { price: 1 } }
					if (pet.feedCount == 2) {
						feedCountPrice += price * (multiService.two.price || 1); // 基础价格 × 2次倍数
					} else if (pet.feedCount == 3) {
                        feedCountPrice += price * (multiService.three.price || 1); // 基础价格 × 3次倍数
					}
					return {
						petId: pet.petId,
						serviceDate: pet.serviceDate,
						feedCount: pet.feedCount,
						selectedTimeSlots: pet.selectedTimeSlots.join(','),
						skuList: this.getSkuList(pet.customServices, pet.feedCount, price),
                        feedCountPrice,//当日多次服务加价
					}
				})
				return petOrderServices
			},
			pay(params) {
				if (this.isPaying) {
					return;
				}
				this.isPaying = true
				uni.requestPayment({
					provider: 'wxpay',
					timeStamp: params.timeStamp,
					nonceStr: params.nonceStr,
					package: params.package_ || params.packageValue,
					signType: params.signType,
					paySign: params.paySign,
					success: (res) => {
						this.$modal.showToast('支付成功')
						this.$globalData.newOrderData = {
							currentAddress: {},
							currentPets: [],
							totalPrice: 0,
							needPreFamiliarize: []
						}
						uni.reLaunch({
							// url: '/pages_order/order/orderList'
							url: '/pages_order/order/payOrderSuccessful'
						});
					},
					fail: (err) => {
						this.loading = false
						console.log('支付失败', err)
						this.$modal.showToast('支付失败')
                        uni.reLaunch({
							url: '/pages_order/order/orderList'
						});
					},
					complete: () => {
						this.loading = false
						this.isPaying = false
					}
				})
			},
			changePreFamiliarize(name) {
				const preFamiliarizePrice = (this.price_config.preFamiliarize && this.price_config.preFamiliarize.price) || 40
				if (name && name.length > 0) {
					this.needPreFamiliarize = name
					this.originalTotalPrice = this.originalTotalPrice + preFamiliarizePrice
				} else {
					this.needPreFamiliarize = []
					this.originalTotalPrice = this.originalTotalPrice - preFamiliarizePrice
				}
				// 重新计算最优惠的优惠券
				this.autoSelectBestCoupon()
				this.getShowTotalPrice()
			},
			getShowTotalPrice() {
				// 会员折扣已经在上一个页面减去了，这里需要根据originalTotalPrice反推会员减去了多少
				// originalTotalPrice: 已经应用会员折扣后的价格
				// memberRate: 会员折扣率（如0.9表示9折）
				// 反推原价：originalTotalPrice / memberRate
				// 会员折扣金额：原价 - originalTotalPrice
				const originalPriceBeforeMemberDiscount = this.originalTotalPrice / this.$store.state.memberRate
				this.memberDiscount = (originalPriceBeforeMemberDiscount - this.originalTotalPrice).toFixed(2)

				// 获取再来一单费用
				const moreOrderPrice = this.$globalData.newOrderData.moreOrderPrice || 0

				// 计算最终支付价格
				// finalPrice: 最终支付价格 = 已应用会员折扣的价格 + 再来一单费用 - 优惠券优惠
				this.finalPrice = (this.originalTotalPrice + moreOrderPrice - this.discount).toFixed(2)
			},
			getCouponAmountOrDiscount(item) {
				if (item.stockType == "PDISCOUNT") {
					return item.discountPercent / 10 + '折'
				} else {
					return '¥' + item.discountAmount
				}
			},
			// 自动选择最优惠的优惠券
			autoSelectBestCoupon() {
				// 清空所有优惠券的选中状态和自动选择标记
				this.couponList.forEach(coupon => {
					coupon.checked = null
					coupon.isAutoSelected = false
				})
				
				// 过滤出可用的优惠券（满足最低消费要求）
				const availableCoupons = this.couponList.filter(coupon => 
					this.originalTotalPrice >= coupon.transactionMinimum
				)
				
				if (availableCoupons.length === 0) {
					this.selectedCoupon = null
					this.couponId = null
					this.discount = 0
					return
				}
				
				// 计算每个优惠券的实际优惠金额
				const couponsWithDiscount = availableCoupons.map(coupon => {
					let discountAmount = 0
					
					if (coupon.stockType === "PDISCOUNT" && coupon.discountPercent > 0) {
						// 折扣券：计算折扣后的优惠金额
						discountAmount = this.originalTotalPrice * (coupon.discountPercent / 100)
					} else {
						// 满减券：直接使用优惠金额
						discountAmount = coupon.discountAmount
					}
					
					return {
						...coupon,
						calculatedDiscount: discountAmount
					}
				})
				
				// 按优惠金额从高到低排序，选择最优惠的
				couponsWithDiscount.sort((a, b) => b.calculatedDiscount - a.calculatedDiscount)
				
				// 选择最优惠的优惠券
				const bestCoupon = couponsWithDiscount[0]
				
				// 在原始的 couponList 中找到对应的优惠券并设置选中状态
				const originalCoupon = this.couponList.find(coupon => coupon.id === bestCoupon.id)
				if (originalCoupon) {
					originalCoupon.checked = [originalCoupon.id]
					originalCoupon.isAutoSelected = true // 标记为自动选择
					this.selectedCoupon = originalCoupon
					this.couponId = originalCoupon.id
					
					// 计算优惠金额
					if (originalCoupon.stockType === "PDISCOUNT" && originalCoupon.discountPercent > 0) {
						this.discount = (this.originalTotalPrice * (1 - originalCoupon.discountPercent / 100)).toFixed(2)
					} else {
						this.discount = originalCoupon.discountAmount
					}
					
					console.log('自动选择最优惠优惠券:', originalCoupon.stockName, '优惠金额:', this.discount)
				}
				
				// 重新计算总价
				this.getShowTotalPrice()
			},
			goNext() {
				if (!this.isAgree) {
					uni.showToast({
						title: '请先同意用户协议',
						icon: 'none'
					})
					return
				}
				const order = this.constructOrder()
				createOrderNew(order).then(res => {
					if (res.code == 200) {
						this.pay(res.data)
					} else {
						this.$modal.showToast('创建订单失败，请重试');
						this.loading = false
					}
				})

			}
		}
	}
</script>
<style scoped lang="scss">
	.container {
		position: relative;
		height: 100%;
		padding-bottom: 200rpx;

		.details-subscribe {
			background-color: #FFFFFF;
			padding: 10px;
			width: 100%;
			height: 200rpx;
			position: fixed;
			bottom: 0;
			z-index: 100;

			.details-btn {
				width: 100%;
				border-radius: 6px;
				background: #FFB13F;
				font-size: 16px;
				color: #FFFFFF;
			}

			.details-radio {
				display: flex;
				align-items: center;
				justify-content: center;
			}
		}
	}

	.service-new {
		.service-new-flag {
			width: 8rpx;
			height: 32rpx;
			background: #FFBF60;
			border-radius: 30rpx 30rpx 30rpx 30rpx;
			margin-right: 10rpx;
		}

		.split-line {
			width: 100%;
			height: 1rpx;
			background: #EFEFEF;
		}

		.service-new-title {
			display: flex;
			font-weight: 500;
			font-size: 28rpx;
			color: #333333;
			line-height: 33rpx;
			margin: 42rpx 0 30rpx;
			justify-content: space-between;

			.service-new-title-left {
				display: flex;
				align-items: center;
			}
		}

		.service-new-details-desc {
			font-weight: 400;
			font-size: 24rpx;
			color: #A94F20;
			line-height: 28rpx;
			text-align: left;
			padding: 26rpx 0;
		}

		.personal-address-info {
			display: flex;
			align-items: center;
			justify-content: flex-start;
			flex-wrap: wrap;
			margin: 32rpx 0;
			width: 80%;

			.personal-address-text {
				color: #333;
				font-size: 28rpx;
				font-weight: bold;
				width: 100%;
			}

			.personal-address-people {
				color: #7D8196;
				font-size: 28rpx;
				font-weight: 400;
				display: flex;
				justify-content: flex-start;
				align-items: center;
			}
		}

		.service-new-address-selected {
			display: flex;
			justify-content: space-between;
			align-items: center;
		}
	}

	.personal-pet-list {
		margin-top: 20rpx;

		.personal-pet-list-item {
			margin-bottom: 20rpx;
			background-color: #F9F9F9;
			height: 172rpx;
			border-radius: 8rpx;

			.personal-pet-info {
				height: 100%;
				display: flex;
				align-items: center;
				padding: 0 20rpx;
			}
		}
	}

	.service-new-address {
		.service-summary {
			height: 90rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 15rpx;
			cursor: pointer;
			transition: background-color 0.3s;
		}

		.service-details {
			padding: 10rpx 15rpx;
			background-color: #F9F9F9;
			margin-bottom: 10rpx;

			.pet-info {
				display: flex;
				justify-content: space-between;
				margin: 5rpx 0;
				font-size: 24rpx;
				color: #333;
			}

			.service-item {
				display: flex;
				justify-content: space-between;
				width: 100%;
				color: #999999;
				font-size: 28rpx;
			}
		}

		.total-cost {
			padding: 10rpx 15rpx;
			font-size: 28rpx;
			color: #333;
			display: flex;
			justify-content: space-between;
		}

	}

	.calendar-popup {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		z-index: 999;

		.calendar-content {
			background: #F5F5F7;
			border-radius: 16rpx 16rpx 0 0;
			padding: 0 20rpx 40rpx;
		}
	}

	.calendar-mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.5);
		/* 半透明黑色 */
		z-index: 998;
		/* 确保在内容下方 */
		pointer-events: none;
		/* 使遮罩层不阻止点击事件 */
	}

	.calendar-content {
		position: relative;
		/* 确保内容在遮罩层之上 */
		z-index: 999;
		/* 确保内容在遮罩层之上 */
	}

	.price-details {
		background: #F5F5F7;
		/* 背景颜色 */
		padding: 10px 10px 0 10px;
		/* 内边距 */
		z-index: 1000;
		/* 确保在其他元素之上 */
		min-height: 600rpx;
		/* 固定高度 */
		overflow: hidden;
		/* 隐藏超出部分 */
	}

	.price-details-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding-bottom: 20rpx;
	}

	.price-details-body {
		margin-top: 20rpx;
		max-height: 450rpx;
		/* 留出头部空间 */
		overflow-y: auto;
		/* 允许上下滚动 */
	}

	.coupon-card {
		display: flex;
		align-items: center;
		width: 100%;
		padding: 10px 0;
		background: #fff;
		border-radius: 8px;
		-webkit-mask-image: radial-gradient(circle at 88px 4px, transparent 4px, #d8d8d8 4.5px), radial-gradient(closest-side circle at 50%, #d8d8d8 99%, transparent 100%);
		-webkit-mask-size: 100%, 2px 4px;
		-webkit-mask-repeat: repeat, repeat-y;
		-webkit-mask-position: 0 -4px, 87px;
		-webkit-mask-composite: source-out;
		mask-composite: subtract;
		// background: linear-gradient(45deg, orange, red);
		
		// &.auto-selected {
		// 	border: 2px solid #FF530A;
		// 	background: linear-gradient(135deg, #fff 0%, #FFF4E4 100%);
		// }
		
		// &.manual-selected {
		// 	border: 2px solid #4CAF50;
		// 	background: linear-gradient(135deg, #fff 0%, #E8F5E8 100%);
		// }
	}

	.card-left {
		width: 88px;
		text-align: center;
		font-size: 28rpx;
		color: #FF530A;

	}

	.card-right {
		padding: 0px 12px;
		display: flex;
		flex: 1;
		/* flex-direction: column; */
		justify-content: space-between;
		align-items: center;
		height: 60px;

		s .card-content {
			width: 80%;
		}

		.card-icon {
			position: relative;
			right: -10px;
			top: -10px;
		}
	}

	.card-info {
		margin: 0;
		font-size: 14px;
		line-height: 20px;
		color: #333333;
	}

	.card-time {
		font-size: 12px;
		line-height: 16px;
		font-weight: normal;
		color: #aaaaaa;
		margin-top: 4px;
	}
</style>