<template>
	<view class="service-new container">


		<view style="background-color: #FFF4E5; margin: 10px; padding: 10px; border-radius: 8rpx;">
			<view style="display: flex;">
                <image style="width: 40rpx; height: 40rpx;" slot='cover'
                    src="https://catmdogf.oss-cn-shanghai.aliyuncs.com/CMDF/front/petServiceOrder/OrderIcon.png">
				</image>
				<text style="color: #A94F20; font-size: 28rpx; font-weight: 500;">
					下单方式：
                    <text v-if="buyInfo.teacher">指定喂养员 - {{ buyInfo.teacher.userName }}</text>
					<text v-else>系统派单</text>
				</text>
			</view>
			<view style="margin-top: 10rpx;">
				<text v-if="buyInfo.teacher" style="color: #A94F20; font-size: 24rpx; font-weight: 400;">
					(若伴宠师1小时内无响应或拒绝接单则系统派单)
				</text>
			</view>
		</view>
        
		<view>
			<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-pet-content">
					<scroll-view scroll-x class="scroll-view">
						<view class="scroll-content">
							<view v-for="item in currentPets" :key="item.id" class="service-new-pet-item ellipsis"
                                :class="{ 'pet-selected': item.id === currentPetId, 'pet-unselect': item.id !== currentPetId }"
								@click="selectPet(item)">
								{{ item.name }}
							</view>
						</view>
					</scroll-view>
				</view>
			</uni-card>
		</view>
    <view>
			<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-pet-content">
					<scroll-view scroll-y class="scroll-view-vertical">
						<view v-for="(month, monthIndex) in sortedGroupedDates" :key="monthIndex" class="month-group">
							<view class="month-title">{{ month.monthLabel }}</view>
							<scroll-view scroll-x class="scroll-view-horizontal">
								<view class="dates-wrapper">
									<view v-for="(day, dayIndex) in month.dates" :key="dayIndex" class="calendar-day"
                                        :class="{ 'day-selected': isDateSelected(day) }" @click="selectDate(day)">
										<image :src="isDateSelected(day) ? 
											'https://catmdogf.oss-cn-shanghai.aliyuncs.com/CMDF/front/newOrder/updated.png' : 
                                            'https://catmdogf.oss-cn-shanghai.aliyuncs.com/CMDF/front/newOrder/update_un.png'" class="calendar-bg" />
                                        <view class="day-content">
                                            <text class="day-text"
                                                :class="{ 'day-highlighted': isCurrentSelected(day), 'day-normal': !isCurrentSelected(day) }">
                                                {{ day.date < 10 ? '0' + day.date : day.date }}
                                            </text>
                                            <text class="day-price" v-if="getDatePriceInfo(day.fullDate)"
                                                :class="{ 
                                                    'price-holiday': getDatePriceType(day.fullDate) === 'holiday',
                                                    'price-weekend': getDatePriceType(day.fullDate) === 'weekend',
                                                    'price-normal': getDatePriceType(day.fullDate) === 'normal'
                                                }">
                                                ¥{{ getDatePriceInfo(day.fullDate).memberDiscountPrice || getBasePriceByDate(day.fullDate) }}
                                            </text>
                                        </view>
									</view>
								</view>
							</scroll-view>
						</view>
					</scroll-view>
				</view>
			</uni-card>
		</view>
    <view>
			<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>期望时间 <span class="time-slot-time-tip">*请勾选您可以接受的上门时间段</span></view>
					</view>
				</view>
				<view class="split-line"></view>
				<view class="service-new-pet-content">
					<view class="time-slots">
						<view v-for="slot in timeSlots" :key="slot.id" class="time-slot-item"
							@click="selectTimeSlot(slot.id)">
							<image :src="slot.selected ? slot.activeIcon : slot.inactiveIcon" class="time-slot-icon" />
							<view class="time-slot-info">
								<text class="time-slot-time">{{ slot.time }}</text>
							</view>
						</view>
					</view>
				</view>
			</uni-card>
		</view>
    <view>
			<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 style="display: flex; justify-content: flex-end; align-items: center; ">
                        <view style="margin-right: 10rpx;color: #AAAAAA;">爱宠：{{ currentPetId && getCurrentPetName() }}
                            全日期保持一致</view>
                        <u-switch space="2" :value="isAllSame" activeColor="#f9ae3d" size="18" @change="isAllSameChange"
							inactiveColor="rgb(230, 230, 230)">
						</u-switch>
					</view>
				</view>
				<view class="split-line"></view>
				<view class="service-new-pet-content">
					<view class="service-item">
						<view class="service-item-header">
							<image src="https://catmdogf.oss-cn-shanghai.aliyuncs.com/CMDF/front/newOrder/service.png"
								class="service-icon"></image>
							<text class="service-title">基础服务</text>
						</view>
						<view class="service-list">
							<!-- <view style="border-radius: 8rpx" :style="{'background-color': needFeed.length > 0 ? '#FFFCF2' : '#F9F9F9', 'border': needFeed.length > 0 ? '1px solid #FFBF60' : 'none'}" >
								<view style="padding: 30rpx 0; margin: 0 20rpx; ">
									<u-checkbox-group
										v-model="needFeed"
										iconPlacement="right" 
										placement="column">
										<u-checkbox activeColor="#FFBF60" label="专业喂养" shape="circle"></u-checkbox>
									</u-checkbox-group>
								</view>
							</view> -->
							<view class="service-list" style="border-radius: 8rpx;margin-top: 28rpx;">
								<view class="service-row" style="background-color: #FFECCD">
									<view class="service-row-content"
                                        :style="{ 'border-bottom': feedCount > 1 ? '1rpx solid #ECBFA8' : 'none' }">
										<text class="service-name" style="color: #A94F20;">一天多次</text>
										<view class="service-price">
                                            <u-number-box slot="right-icon" :value="feedCount" @change="feedCountChange"
                                                step="1" :min="1" :max="3">
												<view slot="minus" class="minus">
													<u-icon name="minus-circle-fill" size="20" color="#FFBF60"></u-icon>
												</view>
												<text slot="input" style="width: 40rpx;text-align: center;"
                                                    class="input">{{ feedCount }}</text>
												<view slot="plus" class="plus">
													<u-icon name="plus-circle-fill" color="#FFBF60" size="20"></u-icon>
												</view>
											</u-number-box>
										</view>
									</view>
								</view>
								<view v-if="feedCount > 1" class="service-row" style="background-color: #FFECCD">
									<view class="service-row-content">
										<text class="service-name" style="color: #A94F20;">额外服务费</text>
										<view class="service-price" style="color:#A94F20">
                                            <text style="font-size: 32rpx;">
                                                ¥{{ calculateMemberDiscountPrice(feedCount > 2 ? priceConfig.multiService.three.price : priceConfig.multiService.two.price) }}
                                            </text>
										</view>
									</view>
								</view>
							</view>
						</view>
					</view>

					<view class="service-item">
						<view class="service-item-header">
							<image src="https://catmdogf.oss-cn-shanghai.aliyuncs.com/CMDF/front/newOrder/love.png"
								class="service-icon"></image>
							<text class="service-title">定制服务</text>
						</view>
						<view class="service-list" style="border-radius: 8rpx;">
							<view class="service-row" v-for="(item, index) in customServices" :key="item.skuId">
                                <view class="service-row-content"
                                    :style="{ 'border-bottom': index !== customServices.length - 1 ? '1rpx solid #EFEFEF' : 'none' }">
                                    <text class="service-name" style="">{{ item.name }}</text>
									<view class="service-price">
                                        <view class="price-container">
                                            <text style="font-size: 32rpx; color: #FFBF60; margin-right: 20rpx;">
                                                ¥{{ calculateMemberDiscountPrice(item.price) }}元/次
                                            </text>
                                        </view>
                                        <u-number-box slot="right-icon" :value="item.quantity" :name="item.name"
                                            @change="customServiceCountChange" step="1" :min="0" :max="10">
											<view slot="minus" class="minus">
												<u-icon name="minus-circle-fill" size="20" color="#FFBF60"></u-icon>
											</view>
                                            <text slot="input" style="width: 40rpx;text-align: center;"
                                                class="input">{{ item.quantity }}</text>
											<view slot="plus" class="plus">
												<u-icon name="plus-circle-fill" color="#FFBF60" size="20"></u-icon>
											</view>
										</u-number-box>
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</uni-card>
		</view>

		<view v-if="!showPriceDetails" class="details-subscribe">
			<view style="display: flex;justify-content: space-between;">
				<view style="height: 80rpx;">
					<view>
						<text style="color: #333333;">订单总价： </text>
                        <text style="text-decoration: line-through; color: #999; font-size: 28rpx; margin-right: 10rpx;">
                            ¥{{ totalPrice }}.00
                        </text>
                        <text style="color: #FF530A; font-size: 36rpx;">¥{{ calculateMemberDiscountPrice(totalPrice) }} <text
                                style="font-size: 28rpx;">.00</text></text>
					</view>
					<view style="display: flex; justify-content: flex-end;" @click="togglePriceDetails">
                        <text v-if="currentDayPrice" style="color:#FF530A; font-size: 24rpx;"> 当日价格¥{{ calculateMemberDiscountPrice(currentDayPrice) }}.00 |</text>
                        <text style="color:#FF530A; font-size: 24rpx;margin-left: 10rpx;">明细</text>
						<u-icon name="arrow-up" color="#FF530A" size="10"></u-icon>
					</view>
				</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="showPriceDetails" class="price-details-overlay">
			<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 style="text-align: center; width: 100%; font-size: 28rpx; color: #AAAAAA; margin: 20rpx 0;">
					实际支付金额以确认下单页为准</view>
				<view class="split-line"></view>
				<scroll-view class="price-details-body" scroll-y>
                    <view v-for="(item, idx) in priceDetails" :key="idx" class="price-detail-row" style="display:flex;justify-content:space-between;align-items:center;">
                        <view>
                            <view class="price-detail-title">{{ item.name }}</view>
                            <view class="price-detail-label" style="color:#999;font-size:24rpx;" v-if="item.formula">{{ item.formula }}</view>
                        </view>
                        <view class="price-detail-amount" :style="{color: item.amount < 0 ? '#FF530A' : '#333'}">{{ item.amount > 0 ? '+' : '' }}¥{{ item.amount.toFixed(2) }}</view>
                    </view>
                </scroll-view>
			</view>
			<view class="details-subscribe">
				<view style="display: flex; justify-content: space-between;">
					<view style="display: flex; flex-direction: column; align-items: flex-start;">
                        <text style="color: #FF530A; font-size: 36rpx;">订单总价: ¥{{ calculateMemberDiscountPrice(totalPrice).toFixed(2) }}</text>
                        <text style="color: #999; font-size: 24rpx; margin-top: 4rpx; white-space: normal; line-height: 1.4;">当日价格: ¥{{ calculateMemberDiscountPrice(currentDayPrice).toFixed(2) }} 明细</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>
	</view>
</template>

<script>
	import {
			getProductList,
			getOpenId
		} from "@/api/system/user"
import { setToken, setOpenIdKey } from '@/utils/auth'
import PriceCalculator from '@/utils/priceCalculator.js'
	export default {
		data() {
			return {
            // 从后台获取，不再硬编码
            basePrice: 0,
            baseProduct: '专业喂养',
				currentPets: [],
				currentPetId: '',
				currentMonthDay: {},
				selectedDates: [],
				groupedDates: [],
				timeSlots: [
					{
						id: 'MORNING',
						name: '早上',
						time: '08:00-12:00',
						selected: false,
						activeIcon: 'https://catmdogf.oss-cn-shanghai.aliyuncs.com/CMDF/front/newOrder/morning.png',
						inactiveIcon: 'https://catmdogf.oss-cn-shanghai.aliyuncs.com/CMDF/front/newOrder/morning_un.png'
					},
					{
						id: 'AFTERNOON',
						name: '午后',
						time: '12:00-18:00',
						selected: false,
						activeIcon: 'https://catmdogf.oss-cn-shanghai.aliyuncs.com/CMDF/front/newOrder/noon.png',
						inactiveIcon: 'https://catmdogf.oss-cn-shanghai.aliyuncs.com/CMDF/front/newOrder/noon_un.png'
					},
					{
						id: 'EVENING',
						name: '晚间',
						time: '18:00-22:00',
						selected: false,
						activeIcon: 'https://catmdogf.oss-cn-shanghai.aliyuncs.com/CMDF/front/newOrder/night.png',
						inactiveIcon: 'https://catmdogf.oss-cn-shanghai.aliyuncs.com/CMDF/front/newOrder/night_un.png'
					}
				],
            feedCount: 1,
				// customServices原始值
            customServicesStr: '',
            customServices: [],
            showPriceDetails: false,
				priceDetails: [],
				totalPrice: 0,
				isAllSame: false,
				newOrderData: [],
            // 提前熟悉费用 - 从后台获取
				needPreFamiliarizeCost: 0,
				// 基础服务总费用
				baseServiceTotalCost: 0,
				// 额外宠物总费用
				additionalTotalCost: 0,
				// 多次服务总费用
				multServicesTotalCost: 0,
				// 定制服务总费用
				customServicesTotalCost: 0,
				// 一天两次日期
				oneDayTwoTimesDates: [],
				// 一天三次日期
				oneDayThreeTimesDates: [],
				// 宠物类型次数统计
				petTypeCounts: [],
				// 定制服务单项总次数统计
            customServiceItemCount: [],
				// 当日价格
            currentDayPrice: 0,
            // 购买信息 - 包含指定喂养员信息
            buyInfo: {
                teacher: null
            },
            // 价格计算器
            priceCalculator: null,
            // 价格配置 - 从后台获取
            priceConfig: {
                // 基础价格配置
                basePrice: {
                    normal: 75,        // 普通价格
                    holiday: 85,       // 节假日价格
                    weekend: 80        // 周末价格
                },
                // 会员折扣配置
                memberDiscount: {
                    'new': 0.95,      // 新晋家长9.5折
                    'regular': 0.9,   // 普卡会员9折  
                    'silver': 0.88,   // 银卡会员8.8折
                    'gold': 0.85      // 金卡会员8.5折
                },
                // 提前熟悉费用配置
                preFamiliarize: {
                    price: 40,        // 基础价格
                    holidayRate: 1.2  // 节假日倍率
                },
                // 多次服务费用配置
                multiService: {
                    two: {
                        price: 45,     // 一天两次基础费用
                        holidayRate: 1.1 // 节假日倍率
                    },
                    three: {
                        price: 130,    // 一天三次基础费用
                        holidayRate: 1.1 // 节假日倍率
                    }
                },
                // 宠物额外费用配置
                petExtra: {
                    largeDog: {
                        price: 40,     // 大型犬基础费用
                        holidayRate: 1.1
                    },
                    mediumDog: {
                        price: 30,     // 中型犬基础费用
                        holidayRate: 1.1
                    },
                    smallDog: {
                        price: 15,     // 小型犬基础费用
                        holidayRate: 1.1
                    },
                    cat: {
                        price: 10,     // 猫基础费用
                        holidayRate: 1.1
                    }
                },
                // 套餐免费额度配置
                freeQuota: {
                    threshold: 30,        // 免费阈值金额
                    rules: [
                        {
                            type: 'cat',
                            count: 3,
                            freeAmount: 30,
                            description: '3只及以上猫免费30元'
                        },
                        {
                            type: 'smallDog', 
                            count: 2,
                            freeAmount: 30,
                            description: '2只及以上小型犬免费30元'
                        },
                        {
                            type: 'mediumDog',
                            count: 1, 
                            freeAmount: 30,
                            description: '1只及以上中型犬免费30元'
                        },
                        {
                            type: 'mixed',
                            count: 0,
                            freeAmount: 25,
                            description: '混合类型免费25元(1猫1小型犬)'
                        }
                    ]
                },
                // 节假日配置 - 后台配置的节假日列表
                holidays: [
                    // 示例数据，实际从后台获取
                    '2024-07-15', '2024-07-16', '2024-07-17',
                    '2024-10-01', '2024-10-02', '2024-10-03'
                ],
                // 周末配置
                weekends: [0, 6], // 0=周日, 6=周六
                // 定制服务配置
                customServices: {
                    // 从后台getProductList接口获取
                    priceConfig: {},
                    holidayRate: 1.1  // 节假日倍率
                },
                // 城市差异化配置
                cityConfig: {
                    currentCity: 'default',
                    priceRates: {
                        'beijing': 1.2,
                        'shanghai': 1.15,
                        'guangzhou': 1.1,
                        'shenzhen': 1.15,
                        'default': 1.0
                    }
                }
            }
        }

    },
    onLoad: function (option) {
		},
		mounted() {
			this.currentPets = this.$globalData.newOrderData.currentPets;
        if (this.currentPets.length < 1) {
				uni.reLaunch({
					url: '/pages/index'
				});
				return
			}
        
                // 从全局数据获取基础服务价格
        if (this.$globalData.mainSku && this.$globalData.mainSku[0]) {
				this.basePrice = this.$globalData.mainSku[0].price
				this.baseProduct = this.$globalData.mainSku[0].name
			}

        // 初始化购买信息
        this.buyInfo = this.$globalData.buyInfo || { teacher: null }
        
        // 初始化价格计算器
        this.priceCalculator = new PriceCalculator(this.priceConfig)
			
			this.getProductList()
        this.loadPriceConfig() // 加载价格配置
		},
		watch: {
			currentPetId: {
				immediate: true,
				handler(newId) {
					if (newId) {
						this.updateGroupedDates()
					}
				}
			}
		},
		methods: {
        initNewOrderData() {
            const needPreFamiliarize = this.$globalData.newOrderData.needPreFamiliarize.length > 0
            const pets = []
				// 初始化当前宠物全日期保持一致
            this.currentPets = this.currentPets.map(pet => {
					pet.isAllSame = false
					return pet
				})	
				
            this.currentPets.map(pet => {
					// 单个宠物服务日期列表
					const serviceDateList = pet.selectedDate.map(item => item.date)
					serviceDateList.forEach(date => {
						pets.push({
							petId: pet.id,
							serviceDate: date,
							name: pet.name,
							gender: pet.gender,
							petType: pet.petType,
                        bodyType: pet.bodyType,
							photo: pet.photo,
							feedCount: 1,
							selectedTimeSlots: [],
							customServices: [],
							//额外费用
							additionalCost: 0
						})
					})
				})
				this.newOrderData = {
					needPreFamiliarize: needPreFamiliarize, // 是否需要提前熟悉 40元/次 参与计算
					pets: pets
				}
				// 默认选择第一个宠物	
				this.selectPet(this.currentPets[0] || {})
				this.calculateTotalPrice()
			},
			// 选择宠物
			selectPet(pet) {
				this.currentPetId = pet.id
				// 默认选择当前宠物的最小日期
            if (pet.selectedDate && pet.selectedDate.length > 1) {
					const minDate = pet.selectedDate.reduce((min, date) => {
						const currentDate = new Date(date.date);
						const minDate = new Date(min.date);
						return currentDate < minDate ? date : min;
					}, pet.selectedDate[0]);
					// 当前选择日期
					this.currentMonthDay = {
						petId: this.currentPetId,
						date: new Date(minDate.date).getDate(),
						fullDate: minDate.date
					}
				} else {
					this.currentMonthDay = {
						petId: this.currentPetId,
						date: new Date(pet.selectedDate[0].date).getDate(),
						fullDate: pet.selectedDate[0].date
					}
				}
				this.getCurrentPetIsAllSame()
				this.selectDate(this.currentMonthDay)
			},
			selectDate(day) {
				// 当前选择日期
				this.currentMonthDay = day
            const selectedDay = this.selectedDates && this.selectedDates.find(item => item.fullDate === day.fullDate && item
					.currentPetId === day.petId)
				if (!selectedDay) {
					this.selectedDates.push(day)
				}
				// 还原当前选择日期是否已选择期望时间
            const pets = this.newOrderData && this.newOrderData.pets
				const selectedPet = pets.find(pet => pet.petId === this.currentPetId && pet.serviceDate === this
					.currentMonthDay.fullDate);
				const selectedTimeSlots = selectedPet ? selectedPet.selectedTimeSlots : [];
            if (selectedTimeSlots.length > 0) {
                this.timeSlots.forEach(slot => {
                    if (selectedTimeSlots.includes(slot.id)) {
							slot.selected = true
						} else {
							slot.selected = false
						}
					})
				} else {
					this.timeSlots.forEach(slot => {
						slot.selected = false
					})
				}
				// 还原当前选择日期喂食次数
				this.feedCount = selectedPet ? selectedPet.feedCount : 1
				// 还原当前选择日期是否已选择定制服务
				this.customServices = selectedPet.customServices.length > 0 ? selectedPet.customServices : JSON.parse(this.customServicesStr)
				this.getCurrentDayPrice(this.currentMonthDay.fullDate)
			},

			isDateSelected(day) {
				const selectedDay = this.selectedDates.find(item => item.fullDate === day.fullDate && this.currentPetId ===
					item.petId)
				if (selectedDay) {
					return true
				}
				return false
			},
        isCurrentSelected(day) {
				return this.currentMonthDay.fullDate === day.fullDate && this.currentPetId === day.petId
			},
			updateGroupedDates() {
				const currentPet = this.currentPets.find(pet => pet.id === this.currentPetId)
				if (!currentPet) return

				// 按月份分组日期
				const grouped = currentPet.selectedDate.reduce((acc, dateObj) => {
					const date = new Date(dateObj.date)
					const monthKey = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`
					const monthLabel = `${date.getFullYear()}年${date.getMonth() + 1}月`

					if (!acc[monthKey]) {
						acc[monthKey] = {
							monthLabel,
							dates: []
						}
					}

					acc[monthKey].dates.push({
						petId: currentPet.id,
						date: date.getDate(),
						fullDate: dateObj.date
					})

					return acc
				}, {})

				// 转换为数组并排序
				this.groupedDates = Object.values(grouped).sort((a, b) => {
					return a.monthLabel.localeCompare(b.monthLabel)
				})
			},
			selectTimeSlot(slotId) {
				const slot = this.timeSlots.find(slot => slot.id === slotId)
				if (slot) {
					slot.selected = !slot.selected
				}
				// 将期望时间添加到当前宠物
				const selectedTimeSlots = this.timeSlots.filter(slot => slot.selected)
            if (this.isAllSame) {
					// 如果保持一致，则更新该宠物所有期望时间
                this.newOrderData.pets.forEach(pet => {
                    pet.selectedTimeSlots = selectedTimeSlots.map(item => item.id)
					})
            } else {
					const currentPetIndex = this.newOrderData.pets.findIndex(pet => pet.petId === this.currentPetId 
						&& pet.serviceDate === this.currentMonthDay.fullDate)
					if (currentPetIndex !== -1) {
						this.newOrderData.pets[currentPetIndex].selectedTimeSlots = selectedTimeSlots.map(item => item.id)
					}
				}
			},
        feedCountChange(e) {
				this.feedCount = e.value
            if (this.isAllSame) {
					// 如果保持一致，则更新该宠物的喂食次数
                this.newOrderData.pets.forEach(pet => {
                    if (pet.petId === this.currentPetId) {
                        pet.feedCount = this.feedCount
						}
					})
				} else {
					const pets = this.newOrderData.pets
					const currentPetIndex = pets.findIndex(pet => pet.petId === this.currentPetId && pet.serviceDate ===
						this.currentMonthDay.fullDate)
					if (currentPetIndex !== -1) {
						this.newOrderData.pets[currentPetIndex].feedCount = this.feedCount
					}
				}
				this.calculateTotalPrice()

			},
			customServiceCountChange(val) {
				console.log(val)
            this.customServices.forEach(item => {
                if (item.name === val.name) {
						item.quantity = val.value
					}
				})
            if (this.isAllSame) {
					// 如果保持一致，则更新当前宠物的定制服务次数
                this.newOrderData.pets.forEach(pet => {
                    if (pet.petId === this.currentPetId) {
                        pet.customServices = JSON.parse(JSON.stringify(this.customServices))
						}
					})
				} else {
					const pets = this.newOrderData.pets
					const currentPetIndex = pets.findIndex(pet => pet.petId === this.currentPetId && pet.serviceDate ===
						this.currentMonthDay.fullDate)
					if (currentPetIndex !== -1) {
						this.newOrderData.pets[currentPetIndex].customServices = JSON.parse(JSON.stringify(this
							.customServices))
					}
				}
				this.calculateTotalPrice()
			},
			togglePriceDetails() {
				this.showPriceDetails = !this.showPriceDetails; // 切换价格明细的显示状态
				if (this.showPriceDetails) {
					this.priceDetailDate()
				}
			},
			calculateTotalPrice() {
            if (!this.priceCalculator) {
                console.warn('价格计算器未初始化');
                return;
            }
            
            // 获取用户地址（从全局数据或当前地址）
            const userAddress = this.$globalData.newOrderData.currentAddress?.detailAddress || '';
            
            // 使用价格计算器计算订单总价
            const orderResult = this.priceCalculator.calculateOrderTotal(
                this.newOrderData,
                userAddress,
                this.getCurrentMemberLevel()
            );

            // 更新各项费用
            this.needPreFamiliarizeCost = orderResult.preFamiliarizeCost;
            this.baseServiceTotalCost = orderResult.dailyPrices.reduce((acc, daily) => acc + daily.baseServiceCost, 0);
            this.additionalTotalCost = orderResult.dailyPrices.reduce((acc, daily) => acc + daily.petExtraCost, 0);
            this.multServicesTotalCost = orderResult.dailyPrices.reduce((acc, daily) => acc + daily.multiServiceCost, 0);
            this.customServicesTotalCost = orderResult.dailyPrices.reduce((acc, daily) => acc + daily.customServiceCost, 0);

            // 更新总价
            this.totalPrice = orderResult.totalWithDiscount;

            // 更新当日价格
            this.getCurrentDayPrice(this.currentMonthDay.fullDate);
        },

        // 加载价格配置方法
        async loadPriceConfig() {
            try {
                // 从后台获取价格配置 - 暂时跳过，使用默认配置
                console.log('使用默认价格配置');
                this.priceCalculator = new PriceCalculator(this.priceConfig);
                
                // 如果需要从后台获取配置，可以取消注释以下代码
                /*
                const response = await new Promise((resolve, reject) => {
                    uni.request({
                        url: '/api/system/appletConfig/list',
                        method: 'GET',
                        data: { paramCode: 'price_config' },
                        success: (res) => resolve(res),
                        fail: (err) => reject(err)
                    });
                });
                
                if (response.data && response.data.rows && response.data.rows.length > 0) {
                    const config = response.data.rows[0];
                    if (config.paramValueText) {
                        this.priceConfig = JSON.parse(config.paramValueText);
                        this.priceCalculator = new PriceCalculator(this.priceConfig);
                    }
                }
                */
            } catch (error) {
                console.error('获取价格配置失败:', error);
                // 使用默认配置
                this.priceCalculator = new PriceCalculator(this.priceConfig);
            }
        },
        
        // 获取当前用户会员等级
        getCurrentMemberLevel() {
            const userLevel = (this.$globalData.userInfo && this.$globalData.userInfo.level) || 'new';
            const levelMapping = {
                '新晋家长': 'new',
                '普卡会员': 'regular', 
                '银卡会员': 'silver',
                '金卡会员': 'gold'
            };
            return levelMapping[userLevel] || 'new';
        },

        // 获取基础服务价格（根据日期类型）
        getBasePriceByDate(dateString) {
            if (!this.priceCalculator) return this.priceConfig.basePrice.normal;
            return this.priceCalculator.getBasePriceByDate(dateString);
        },

        // 计算会员折扣后的价格
        calculateMemberDiscountPrice(originalPrice, memberLevel = null) {
            if (!this.priceCalculator) return originalPrice;
            const level = memberLevel || this.getCurrentMemberLevel();
            return this.priceCalculator.calculateMemberDiscount(originalPrice, level);
        },

        // 获取指定日期的完整价格信息（用于日期选择界面显示）
        getDatePriceInfo(dateString, pets = null) {
            if (!this.priceCalculator) return null;
            
            const currentDayPets = pets || this.newOrderData.pets.filter(pet => pet.serviceDate === dateString);
            if (currentDayPets.length === 0) return null;

            const dailyPrice = this.priceCalculator.calculateDailyPrice(
                currentDayPets, 
                dateString, 
                Math.max(...currentDayPets.map(pet => pet.feedCount)),
                currentDayPets.reduce((acc, pet) => acc.concat(pet.customServices || []), [])
            );

            return {
                dateString,
                priceType: dailyPrice.priceType,
                basePrice: dailyPrice.baseServiceCost,
                petExtraCost: dailyPrice.petExtraCost,
                multiServiceCost: dailyPrice.multiServiceCost,
                customServiceCost: dailyPrice.customServiceCost,
                totalOriginalPrice: dailyPrice.totalOriginalPrice,
                memberDiscountPrice: this.calculateMemberDiscountPrice(dailyPrice.totalOriginalPrice),
                discount: dailyPrice.totalOriginalPrice - this.calculateMemberDiscountPrice(dailyPrice.totalOriginalPrice),
                memberLevel: this.getCurrentMemberLevel()
            };
        },

        // 获取日期价格类型（用于CSS类名）
        getDatePriceType(dateString) {
            if (!this.priceCalculator) return 'normal';
            return this.priceCalculator.getDatePriceType(dateString);
        },

        // 修改：从后台数据计算宠物费用
			calculatePetCost(pet) {
            if (!this.priceCalculator) return 0;
            return this.priceCalculator.getPetExtraCost(pet, pet.serviceDate);
			},

			goNext() {
				this.calculateTotalPrice(); // 计算总价
				this.showPriceDetails = false;
				this.$globalData.newOrderData.currentPetsByDay = this.newOrderData.pets
				this.$globalData.newOrderData.totalPrice = this.totalPrice
				uni.navigateTo({
					url: '/pages/newOrder/confirmOrder'
				});
			},
			goBack() {
				this.showPriceDetails = false

				let len = getCurrentPages().length;
				this.loading = false
				if (len >= 2) {
					uni.navigateBack();
				} else {
					uni.redirectTo({
						url: '/pages/newOrder/serviceNew'
					});
				}
			},
			// 价格明细数据
			priceDetailDate() {
    const userAddress = this.$globalData.newOrderData.currentAddress?.detailAddress || '';
    const memberLevel = this.getCurrentMemberLevel();
    this.priceDetails = this.priceCalculator.getFullPriceBreakdown(this.newOrderData, userAddress, memberLevel);
    this.priceDetailsTotal = this.priceDetails.length > 0 ? this.priceDetails[this.priceDetails.length - 1].amount : 0;
    this.calculateTotalPrice();
},

			showName(item) {
				return item.item.some(item2 => item2.quantity > 0)
			},
			isAllSameChange(e) {
				if (e) {
					this.isAllSame = true
					this.setCurrentPetIsAllSame()
					// 当前宠物全日期保持一致
                this.newOrderData.pets.forEach(pet => {
                    if (pet.petId === this.currentPetId) {
							pet.selectedTimeSlots = this.timeSlots.filter(slot => slot.selected).map(item => item.id)
							pet.feedCount = this.feedCount
							pet.customServices = this.customServices
						}
					})
					this.calculateTotalPrice()
				} else {
					this.isAllSame = false
					this.setCurrentPetIsAllSame()
				}

			},
			getProductList() {
				getProductList({
					"publishStatus": 1,
					"categoryId": 78,
					"needSku": true
				}).then(response => {
					if (response && response.content && response.content.length > 0) {
                    this.customServices = response.content.map(item => {
							const skus = item.skus
                        if (skus && skus.length > 0) {
								let productSku = {
									"skuId": skus[0].id,
                                "price": skus[0].price,
                                "name": item.name,
									"quantity": 0,
                                "isMainProduct": false
								}
								return productSku
							}
						})
						this.customServicesStr = JSON.stringify(this.customServices)
						// 初始化新订单数据
						this.initNewOrderData()
						
                } else {
						uni.showToast('获取主产品失败，请联系管理员')
					}
					
					console.log(response);
				})
			},
			login() {
				uni.login({
					provider: 'weixin',
					success: (loginRes) => {
						this.getOpenId(loginRes.code)
					},
                fail: function (error) {
						// 授权失败处理
						uni.showToast('授权失败，请授权后再试')
					}
				});
			},
			getOpenId(code) {
				getOpenId(code).then(res => {
					if (res.code == 200 && res.data) {
						let resData = JSON.parse(res.data)
						let token = resData.token;
						let openId = resData.openId;
						setOpenIdKey(openId)
                    if (token) {
							setToken(token)
						}
					}
				})
			},
                // 当日价格计算
        getCurrentDayPrice(currentDay) {
            if (!this.priceCalculator) {
                this.currentDayPrice = 0;
                return;
            }
            
            const currentDayPets = this.newOrderData.pets.filter(pet => pet.serviceDate === currentDay);
            if (currentDayPets.length === 0) {
                this.currentDayPrice = 0;
                return;
            }

            // 使用价格计算器计算当日价格
            const dailyPrice = this.priceCalculator.calculateDailyPrice(
                currentDayPets,
                currentDay,
                Math.max(...currentDayPets.map(pet => pet.feedCount)),
                currentDayPets.reduce((acc, pet) => acc.concat(pet.customServices || []), [])
            );

            // 获取用户地址
            const userAddress = this.$globalData.newOrderData.currentAddress?.detailAddress || '';
            const cityRate = this.priceCalculator.getCityPriceRate(userAddress);
            
            // 应用城市倍率和会员折扣
            const totalWithCityRate = this.priceCalculator.roundToTwoDecimals(dailyPrice.totalOriginalPrice * cityRate);
            const totalWithDiscount = this.calculateMemberDiscountPrice(totalWithCityRate);
            
            this.currentDayPrice = totalWithDiscount;
			},
			calculatePetCustomServiceCost(pet) {
				const customServiceCost = pet.customServices.reduce((acc, item) => acc + item.price * item.quantity, 0)
				return customServiceCost
			},
        getCurrentPetName() {
            const currentPet = this.currentPets.find(pet => pet.id === this.currentPetId)
				return currentPet.name
			},
        setCurrentPetIsAllSame() {
            const currentPet = this.currentPets.find(pet => pet.id === this.currentPetId)
            currentPet.isAllSame = this.isAllSame
        },
        getCurrentPetIsAllSame() {
            const currentPet = this.currentPets.find(pet => pet.id === this.currentPetId)
				this.isAllSame = currentPet.isAllSame
			},
        getMemberLevelText() {
            const level = this.getCurrentMemberLevel();
            const levels = {
                'new': '新晋家长',
                'regular': '普卡会员',
                'silver': '银卡会员',
                'gold': '金卡会员'
            };
            return levels[level] || '未知会员';
        },
        getMemberDiscountRate() {
            const level = this.getCurrentMemberLevel();
            const discountRates = {
                'new': 0.95,
                'regular': 0.9,
                'silver': 0.88,
                'gold': 0.85
            };
            return discountRates[level] || 1; // 默认1，表示无折扣
        }
		},
		computed: {
			sortedGroupedDates() {
				return this.groupedDates.sort((a, b) => {
					const dateA = new Date(a.monthLabel.replace('年', '-').replace('月', '-01'))
					const dateB = new Date(b.monthLabel.replace('年', '-').replace('月', '-01'))
					return dateA - dateB
				})
			}
		}

	}
</script>


<style scoped lang="less">
	.container {
		position: relative;
		height: 100%;
		padding-bottom: 160rpx;

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

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

	.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-pet-content {
			padding: 20rpx 0;
		}

		.service-new-pet-item {
			height: 96rpx;
			width: 184rpx;
			border-radius: 8rpx;
			padding: 0 20rpx;
			margin-right: 40rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 28rpx;
			flex-shrink: 0;
		}

		.scroll-content {
			display: inline-flex;
		}

		.scroll-view {
			width: 100%;
			white-space: nowrap;
		}

		.pet-selected {
			background: #FFBF60;
			color: #FFFFFF;
		}

		.pet-unselect {
			background: #F5F5F7;
			color: #7D8196;
		}

	}

	.calendar-wrapper {
		display: flex;
		gap: 20rpx;
		padding: 20rpx;
	}

	.scroll-view {
		width: 100%;
		white-space: nowrap;
	}

	.calendar-day {
		position: relative;
		width: 80rpx;
		height: 80rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		cursor: pointer;
		margin-right: 20rpx;
		flex-shrink: 0;
	}

	.calendar-bg {
		position: absolute;
		width: 88rpx;
		height: 78rpx;
		z-index: 1;
	}

.day-content {
		position: relative;
		z-index: 2;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;
}

.day-text {
    margin-bottom: 2rpx;
}

	.day-highlighted {
    font-size: 32rpx;
    font-weight: bold;
    color: #FFBF60;
	}

	.day-normal {
		color: #3E3A39;
    font-size: 28rpx;
}

.day-price {
    font-size: 24rpx;
    font-weight: 500;
    line-height: 1;
}

.price-normal {
    color: #666;
}

.price-weekend {
    color: #FF8C00;
}

.price-holiday {
    color: #FF4500;
    font-weight: bold;
	}
	

	.month-group {
		margin-bottom: 30rpx;

		.month-title {
			font-size: 32rpx;
			color: #666;
			margin-bottom: 20rpx;
		}

		.dates-wrapper {
			display: inline-flex;
		}
	}

	.scroll-view-vertical {
		height: 100%;
	}

	.scroll-view-horizontal {
		width: 100%;
		white-space: nowrap;
	}

	.time-slots {
		display: flex;
		justify-content: space-around;
	}

	.time-slot-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		width: 200rpx;
		cursor: pointer;
	}

	.time-slot-icon {
		width: 160rpx;
		height: 160rpx;
		margin-bottom: 10rpx;
	}

	.time-slot-info {
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.time-slot-name {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 8rpx;
	}

	.time-slot-time {
		font-size: 24rpx;
		color: #666;
	}

	.time-slot-time-tip {
		background-color: #FFECCD;
		color: #A94F20;
		margin-left: 10rpx;
		padding: 5rpx 10rpx;
		font-size: 20rpx;
	}

	.service-item {
		margin-bottom: 20rpx;
		/* 每个服务项之间的间距 */
	}

	.service-item-header {
		display: flex;
		align-items: center;
		margin-bottom: 10rpx;
		/* 标题与服务列表之间的间距 */
	}

	.service-icon {
		width: 40rpx;
		/* 图标大小 */
		height: 40rpx;
		/* 图标大小 */
		margin-right: 10rpx;
		/* 图标与标题之间的间距 */
	}

    .service-title {
    font-size: 28rpx;
    /* 服务标题字体大小 */
    font-weight: bold;
    /* 服务标题加粗 */
    }

	.service-row {
		display: flex;
		align-items: center;
		/* 垂直居中对齐 */
		flex-wrap: wrap;
		background-color: #F9F9F9;
	}

	.service-row-content {
		display: flex;
		justify-content: space-between;
		/* 每行的上下内边距 */
		width: 100%;
		padding: 32rpx 0rpx;
		margin: 0 20rpx;
	}

	.service-name {
		width: 50%;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
		font-size: 28rpx;
		color: #333;
		/* 服务名称颜色 */
	}

	.service-price {
		display: flex;
		align-items: center;
		/* 垂直居中对齐 */
	}

	.service-count {
		display: flex;
		align-items: center;
		/* 垂直居中对齐 */
		margin-left: 10rpx;
		/* 价格数量之间的间距 */
	}

	.price-details {
		position: fixed;
		/* 固定位置 */
		bottom: 160rpx;
		/* 根据需要调整位置 */
		left: 0;
		right: 0;
		background: #FFF;
		/* 背景颜色 */
		padding: 10px 10px 0 10px;
		/* 内边距 */
		border-radius: 8rpx 8rpx 0 0;
		/* 圆角 */
		z-index: 1000;
		/* 确保在其他元素之上 */
		min-height: 600rpx;
		/* 固定高度 */
		overflow: hidden;
		/* 隐藏超出部分 */
	}

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

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

	.price-details-overlay {
		position: fixed;
		/* 固定位置 */
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.5);
		/* 半透明背景 */
		z-index: 999;
		/* 确保在其他元素之上 */
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.price-details-item {
		display: flex;
		justify-content: space-between;
		margin-bottom: 20rpx;

    .price-details-item-title {
        font-size: 28rpx;
        color: #333333;
        margin-bottom: 10rpx;
    }

		.price-details-item-price-total {
			display: flex;
        width: 100%;
        justify-content: space-between;
        align-items: center;
			flex-wrap: wrap;
		}

    .price-details-row {
        display: flex;
        justify-content: space-between;
        align-items: center;
        width: 100%;
        margin-bottom: 10rpx;
    }

    .price-details-left {
        display: flex;
        align-items: center;
    }

    .price-details-date {
        font-size: 28rpx;
			color: #999999;
        margin-right: 20rpx;
    }

    .price-details-name {
			font-size: 28rpx;
        color: #333333;
			margin-right: 20rpx;
		}

    .price-details-desc {
        font-size: 28rpx;
        color: #999999;
    }

    .price-details-amount {
        font-size: 28rpx;
        color: #333333;
        font-weight: bold;
    }

    .price-discount {
        color: #FF530A;
    }

    .price-details-total-label {
        font-size: 32rpx;
        color: #333333;
        font-weight: 500;
    }

    .price-details-total-amount {
        font-size: 32rpx;
        color: #333333;
        font-weight: 500;
    }
}
</style>
