<template>
	<view class="home-content">

		<NewUserCoupon v-if="isNewUser" @close="closeNewUserPopup" @getCoupon="handleGetCoupon"></NewUserCoupon>
		
        <view class="banner">
			<uni-swiper-dot class="uni-swiper-dot-box" field="content">
				<swiper class="swiper" indicator-dots indicator-color="rgba(255, 255, 255, 0.50)"
					indicator-active-color="#ffffff" autoplay interval="5000">
					<swiper-item v-for="(item,i) in bannerList" :key="i">
						<image :src="item&&item.dictValue" style="width: 100%;" mode="widthFix" />
					</swiper-item>
				</swiper>
			</uni-swiper-dot>
		</view>

		<view style="margin: -250px 20rpx 0 20rpx;">
			<image style="width: 710rpx; height: 176rpx;" slot='cover'
				src="https://catmdogf.oss-cn-shanghai.aliyuncs.com/CMDF/front/petServiceOrder/TopDetail.png" />
		</view>
		<view class="card-container">
			<uni-card :is-shadow="false" padding="40rpx 20rpx 40rpx 20rpx" margin="20rpx">
				<view class="normal-bolb-text">
					<view @click="getLocationInfo"
						style="display: flex; align-items: center; justify-content: space-between;">
						<text v-if="isCheckLocation"
							style="color: #333333 ;font-size: 32rpx;font-weight: 600; font-style: normal; width: 450rpx; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">{{locationName}}</text>
						<text v-else
							style="color: #C4C4C4 ;font-size: 32rpx;font-weight: 500; font-style: normal;">请选择宠物上门服务地址</text>
						<uni-icons type="location-filled" size="20" color="#FFB13F"></uni-icons>
					</view>
				</view>
				<view class="line" style="background-color: #EFEFEF;"></view>
				<view class="content-container">
					<view class="example-body hideOnPc">
						<view class="normal-bolb-text">
							<view @click="toggleCalendar('bottom')">
								<view v-if="isCheckTime"
									style="display: flex; align-items: center; justify-content: space-between;">
									<text
										style="color: #333333 ;font-size: 32rpx;font-weight: 600; font-style: normal; width: 450rpx; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">{{selectedDateShowText}}</text>
									<text
										style="color: #333333 ;font-size: 32rpx;font-weight: 600; font-style: normal;">共选择
										<text style="color: #FFB13F;">{{selectedDate.length}}</text>
										天</text>
								</view>
								<view v-else
									style="display: flex; align-items: center; justify-content: space-between;">
									<text
										style="color: #C4C4C4 ;font-size: 32rpx;font-weight: 500; font-style: normal;">请选择宠物上门服务时间</text>
									<uni-icons type="right" size="20" color="#FFB13F"></uni-icons>
								</view>
							</view>
						</view>
					</view>
					<view>
						<uni-popup ref="popup" background-color="#fff" @change="changePopup">
							<view class="popupBottom">
								<uni-calendar ref="calendar" class="uni-calendar--hook" :selected="selectedDate"
									:startDate="startDate" :endDate="endDate" :showMonth="false"
									@change="changeCalendar" @confirm="changeCalendar" @close="close" />
								<view style="display: flex; justify-content: center; align-items: center;">
									<image @click="closePopup" style="width: 670rpx; height: 80rpx;" slot='cover' src="https://catmdogf.oss-cn-shanghai.aliyuncs.com/CMDF/front/petServiceOrder/yesButton.png" />
								</view>
							</view>
						</uni-popup>
					</view>
				</view>
				<view class="line" style="background-color: #EFEFEF;"></view>
				<view>
					<view style="display: flex;">
						<view @click="getOrder(true)" style="margin-right: 20rpx;">
							<image style="width: 304rpx; height: 100rpx;" slot='cover'
								src="https://catmdogf.oss-cn-shanghai.aliyuncs.com/CMDF/front/petServiceOrder/OrderByCompanion.png" />
						</view>
						<view @click="getOrder(false)">
							<image style="width: 304rpx; height: 100rpx;"
								src="https://catmdogf.oss-cn-shanghai.aliyuncs.com/CMDF/front/petServiceOrder/OrderBySystem.png" />
						</view>
					</view>
				</view>
			</uni-card>
		</view>

		<view class="coupon-list">
			<uni-card :is-shadow="false" padding=0 margin="10px">
				<view class="coupon-title" slot="title">
					<view class="coupon-title-left">
						<view class="coupon-flag"></view>
						<view>领券中心</view>
					</view>
					<view class="coupon-title-right">
						<view @click="getAllCoupon">
							更多 <uni-icons type="right" size="14px" color="#AAAAAA"></uni-icons>
						</view>
					</view>
				</view>
				<view class="split-line"></view>
				<view class="coupon-content">
					<view v-for="(item,index) in couponData" style="padding:20rpx;" :key="index">
						<view style="border: 1px solid #FFBF60; border-radius: 8px;">
							<view class="card">
								<view class="card-left">{{switchType(item.stockType)}}</view>
								<view class="card-center">
									<view class="card-center-top"></view>
									<view class="card-center-bottom"></view>
								</view>
								<view class="card-right">
									<view class="card-content">
										<view class="card-info">{{item.stockName}}</view>
										<view class="card-type">可用于
											<text class="card-type-text">专业喂养</text>
											<text class="card-type-text">专业遛狗</text>
										</view>
										<view class="card-time">有效期至: {{item && item.availableEndTime ? item.availableEndTime.slice(0, 16) : ''}}</view>
									</view>
									<view>
										<view style="width: 132rpx;height: 52rpx;background-color: #FFAA48; display: flex;align-items: center;justify-content: center;border-radius: 56rpx;">
											<text @click="receiveCoupon(item.id)" style="font-size: 24rpx; font-weight: 500; color: #FFFFFF;">立即领取</text>
										</view>
									</view>
								</view>
							</view>
							<view class="card-bottom">
								<view class="card-bottom-text">
									优惠券不可兑换现金
								</view>
								<view class="card-bottom-text" @click="showRulePopup(item)">
									查看详细规则>
								</view>
							</view>
						</view>
					</view>
				</view>
			</uni-card>
		</view>

		<view class="companion-list">
			<uni-card :is-shadow="false" padding=0 margin="10px">
				<view class="companion-title" slot="title">
					<view class="companion-title-left">
						<view class="companion-flag"></view>
						<view>周边伴宠师</view>
					</view>
					<view class="companion-title-right" @click="getAllCompanion">
						<view>
							更多 <uni-icons type="right" size="14px" color="#AAA"></uni-icons>
						</view>
					</view>
				</view>
				<view class="split-line"></view>
				<view class="companion-content">
					<view class="companion-item">
						<view class="companion-info">
							<image class="companion-img" slot='cover'
								:src="defaultCompanion.staffImages && defaultCompanion.staffImages.length > 0 ? defaultCompanion.staffImages[0].url : defaultStaffIamge">
							</image>
							<view class="companion-info-1">
								<view class="companion-info-2">
									<view class="companion-info-title">
										<view class="companion-name">
											{{defaultCompanion.name}}
										</view>
										<view class="companion-sex">
											<image :src="defaultCompanion.gender == '1' ? 'https://catmdogf.oss-cn-shanghai.aliyuncs.com/CMDF/front/personal/pet/sex_m.png' : 'https://catmdogf.oss-cn-shanghai.aliyuncs.com/CMDF/front/personal/pet/sex_f.png'" alt="sex"
												style="width: 40rpx;height: 40rpx;" />
										</view>
									</view>
									<view class="companion-info-star">
										<text style="color: #FFB13F;">客户点赞数{{defaultCompanion.star}}</text>
										<uni-icons type="hand-up-filled" size="18" color="#FFB13F"></uni-icons>
									</view>
								</view>
								<view class="companion-info-3" style="width: 100%;">
									<view class="ellipsis">
										距离{{defaultCompanion.distance}}km
									</view>
								</view>
								<view class="companion-info-4" style="width: 100%;">
									<view class="ellipsis" style="max-width: 450rpx;">
										简介：{{defaultCompanion.shortDescription}}
									</view>
								</view>
							</view>
						</view>
					</view>
					<view>
						<view class="companion-item-bottom">
							<text class="companion-item-bottom-text">养宠{{defaultCompanion.year}}年 | 评价{{defaultCompanion.record}}条 | 服务小结{{defaultCompanion.serviceNum}}份</text>
						</view>
					</view>
				</view>
			</uni-card>
		</view>

		<view class="history-record">
			<uni-card :is-shadow="false" padding=0 margin="10px">
				<view class="history-record-title" slot="title">
					<view class="history-record-title-left">
						<view class="history-record-flag"></view>
						<view>历史记录</view>
					</view>
					<view class="history-record-title-right">
						<view @click="getAllRecord">
							查看服务记录和评价详情 <uni-icons type="right" size="14px" color="#AAAAAA"></uni-icons>
						</view>
					</view>
				</view>
				<view class="split-line"></view>
				<view class="history-record-content">
					<view class="history-record-content-image">
						<view class="history-record-content-image-1">
							<view class="history-record-content-image-1-text">
								<view class="history-record-content-image-1-text-1">{{historyRecord.dog}}只</view>
								<view class="history-record-content-image-1-text-2">至{{historyRecord.dogTime}}</view>
							</view>
						</view>
						<view class="history-record-content-image-2">
							<view class="history-record-content-image-2-text">
								<view class="history-record-content-image-2-text-1">{{historyRecord.cat}}只</view>
								<view class="history-record-content-image-2-text-2">至2{{historyRecord.catTime}}</view>
							</view>
						</view>
						<view class="history-record-content-image-3">
							<view class="history-record-content-image-3-text">
								<view class="history-record-content-image-3-text-1">{{historyRecord.num}}次</view>
								<view class="history-record-content-image-3-text-2">至{{historyRecord.numTime}}</view>
							</view>
						</view>
					</view>
					<view class="history-record-content-text">
						<text>*数据来源于布丁猫妈狗爸平台</text>
					</view>
				</view>
			</uni-card>
		</view>

		<view class="service-content">
			<image src="https://catmdogf.oss-cn-shanghai.aliyuncs.com/CMDF/front/second_stage/ysbz.png"
				style="width: 100%;" mode="widthFix" alt="service" />
		</view>

		<view class="card-container">
			<uni-card :is-shadow="false" padding="0px" margin="10px">
				<view class="title-img4"></view>
				<uni-row class="demo-uni-row">
					<uni-col :span="12" v-for="(item,index) in peopleList" :key="index">
						<uni-card :is-shadow="false" margin="5px" padding="0" spacing="0" :border="false"
							shadow="0px 0px 0px 0px rgba(0, 0, 0, 0.08)">
							<image class="people-img" slot='cover' style="width: 100%;"
								:src="item&&item.staffImages&&item.staffImages.length>0?item.staffImages[0].url:defaultStaffIamge">
							</image>
							<text class="people-year">{{item.serviceAge}}年从业经验</text>
							<text class="show-text-1">姓名：{{item.nickName}}</text>
							<text class="show-text-2">简介：{{item.shortDescription}}</text>
						</uni-card>
					</uni-col>

				</uni-row>
			</uni-card>
		</view>
		
		<view>
			<image style="height: 132rpx; width: 710rpx; margin: 0 20rpx 20rpx 20rpx;"
				slot='cover'
				src="https://catmdogf.oss-cn-shanghai.aliyuncs.com/CMDF/front/petServiceOrder/joinus.png" />
		</view>

		<Kefu></Kefu>
		<view class="coupon_wrap" v-if="envVersion == 'dev'">
			<view class="details-subscribe">
				<view @click="getCoupon" class="details-btn">点击领取到卡包</view>
			</view>
			<view v-if="showMask" @closeMask="closeMask">
				<view class="mask-coupon" @click="closeMask">
					<view class="wx-coupon">
						<view class="title">
							领取优惠券
							<i>*</i>
						</view>
						<view class="content">
							优惠券列表显示
						</view>
						<view class="" v-for="(item,index) in couponList" :key="index">
							<send-coupon @sendcoupon="getSendCoupon" @userconfirm="redirectuser" :sign="item.sign"
								:send_coupon_params="item.sendCouponParams"
								:send_coupon_merchant="item.send_coupon_merchant">
								<view class="text-button">{{item.wechatStock.stockName}}</view>
							</send-coupon>
						</view>

					</view>
				</view>
			</view>
		</view>

		<!-- 优惠券详细规则弹窗 -->
		<uni-popup ref="rulePopup" type="center">
			<view class="rule-popup">
				<view class="rule-popup-title">优惠券详细规则</view>
				<view class="rule-popup-content">
					<view class="rule-item">
						<view class="rule-label">名称：</view>
						<view class="rule-value">{{currentCoupon && currentCoupon.stockName || ''}}</view>
					</view>
					<view class="rule-item">
						<view class="rule-label">折扣：</view>
						<view class="rule-value">{{getDiscountText(currentCoupon)}}</view>
					</view>
					<view class="rule-item">
						<view class="rule-label">使用规则：</view>
						<view class="rule-value">可用于专业喂养和专业遛狗服务</view>
					</view>
					<view class="rule-item">
						<view class="rule-label">有效日期：</view>
						<view class="rule-value">{{currentCoupon && currentCoupon.availableEndTime ? currentCoupon.availableEndTime.slice(0, 16) : ''}}</view>
					</view>
					<view class="rule-item">
						<view class="rule-label">特别说明：</view>
						<view class="rule-value">单笔订单仅限使用1张优惠券；优惠券仅限用户本人使用，不可赠送、不可提现、不得找零。</view>
					</view>
				</view>
				<view class="rule-popup-close" @click="closeRulePopup">关闭</view>
			</view>
		</uni-popup>

	</view>
</template>

<script>
	import {
		getStaffList,
		getProductList,
		getBannerList,
		getCouponList,
		getCouponListNoAuth,
		getOpenId,
		receiveCoupon,
	} from "@/api/system/user"
	import {
		setToken,
		getToken,
		getOpenIdKey,
		setOpenIdKey
	} from '@/utils/auth'
    import { getTeacherListIndex } from '@/api/home'
	import Kefu from './common/kefu.vue'
	import uniPopup from '@/uni_modules/uni-popup/components/uni-popup/uni-popup.vue';
	import NewUserCoupon from './components/NewUserCoupon.vue';
	import positionMixin from '@/mixins/position.js';
	
	export default {
		mixins: [positionMixin],
		data() {
			return {
				current: 0,
				swiperDotIndex: 0,
				defaultSkuImage: 'https://catmdogf.oss-cn-shanghai.aliyuncs.com/CMDF/front/banner/%E5%96%82%E5%85%BB.png',
				defaultStaffIamge: 'https://catmdogf.oss-cn-shanghai.aliyuncs.com/CMDF/front/banner/gold_people.png',
				defaultLink: '/pages/details/feed',
				skuData: [],
				peopleList: [],
				cover: 'https://qiniu-web-assets.dcloud.net.cn/unidoc/zh/shuijiao.jpg',
				bannerList: [],
				couponList: [],
				showMask: false,
				envVersion: 'develop',
				isNewUser: false,
				selectedDate: [],
				startDate: '',
				endDate: '',
				isCheckTime: false,
				selectedDateShowText: '',
				isCheckLocation: false,
				locationName: '',
				locationLatitude: '',
				locationLongitude: '',
				locationAddress: '',
				allInfo: {
					isCheckLocation: false,
					locationName: '',
					locationLatitude: '',
					locationLongitude: '',
					locationAddress: '',
					selectedDate: [],
					isCheckTime: false,
					selectedDateShowText: '',
				},
				defaultCompanion: {
					name: '宠小二',
					gender: 0,
					star: 560,
					distance: 1.5,
					shortDescription: '有一只三岁蓝猫叫憨憨，热爱小宠物，心地善良，喜欢动物',
					staffImages: [{
						url: "https://catmdogf.oss-cn-shanghai.aliyuncs.com/2024/01/2634af25c5bf294f39b795ecc9d3c4eefa微信图片_20240126125100.png"
					}],
					year: 4,
					record: 11,
					serviceNum: 13,
				},
				couponData: [],
				historyRecord: {
					dog: "47131",
					dogTime: "2024.12.12",
					cat: "47131",
					catTime: "2024.12.12",
					num: "47131",
					numTime: "2024.12.12",
				},
				currentCoupon: null,
			}
		},
		components: {
			Kefu,
			uniPopup,
			NewUserCoupon
		},
		mounted() {
			this.getCalendarDate();
			this.checkNewUser();
		},
		methods: {
			checkNewUser() {
				const isFirstVisit = !uni.getStorageSync('hasVisited');
				if (isFirstVisit) {
					this.isNewUser = true;
					uni.setStorageSync('hasVisited', true);
				}
			},
			closeNewUserPopup() {
				this.isNewUser = false;
			},
			handleGetCoupon() {
				if (getToken()) {
					this.getCoupon();
				} else {
					uni.navigateTo({
						url: '/pages/personalCenter/index'
					});
				}
			},
			getAllCoupon() {
				uni.navigateTo({
					url: '/pages/companionPetList/couponList'
				});
			},
			getAllCompanion() {
				if (!this.isCheckLocation) {
					uni.showToast({
						title: '请先选择地址',
						duration: 1500,
						icon: "none"
					})
				} else {
					uni.navigateTo({
						url: `/pages/companionPetList/companionPetList?info=` + encodeURIComponent(JSON
							.stringify(this.allInfo))
					});
				}
			},
			getAllRecord () {
				
			},
			toggleCalendar(type) {
				this.type = type
				uni.hideTabBar()
				this.$refs.popup.open(type)
			},
			closePopup() {
				this.$refs.popup.close()
				setTimeout(() => {
					uni.showTabBar()
				}, 300)
			},
			changePopup(e) {
				console.log('当前模式：' + e.type + ',状态：' + e.show);
				if (e.show) {
					uni.hideTabBar()
				} else {
					setTimeout(() => {
						uni.showTabBar()
					}, 300)
				}
			},
			close() {
				console.log('弹窗关闭');
			},
			confirm(e) {
				console.log('confirm 返回:', e)
			},
			changeCalendar(e) {
				console.log('change 返回:', e)
				this.selectedDateShowText = ''
				const selectedValue = this.selectedDate.find(item => item.date === e.fulldate)
				console.log('const selectedValue', selectedValue)
				if (selectedValue) {
					this.selectedDate = this.selectedDate.filter(item => item.date !== e.fulldate);
					this.allInfo.selectedDate = this.selectedDate;
				} else {
					this.selectedDate.push({
						date: e.fulldate,
						info: 'time'
					})
					this.allInfo.selectedDate = this.selectedDate
					console.log('this.selectedDate', this.selectedDate)
				}
				console.log("this.selectedDate.length", this.selectedDate.length)
				console.log("this.selectedDate", this.selectedDate)
				if (this.selectedDate.length > 0) {
					this.isCheckTime = true
					this.allInfo.isCheckTime = this.isCheckTime
					if (this.selectedDate.length == 1) {
						this.selectedDateShowText = this.selectedDate[0].date + ''
						this.selectedDateShowText = this.selectedDateShowText.replace(/-/g, "/");
						this.allInfo.selectedDateShowText = this.selectedDateShowText
					} else if (this.selectedDate.length == 2) {
						this.selectedDateShowText = this.selectedDate[0].date + "," + this.selectedDate[1].date
						this.selectedDateShowText = this.selectedDateShowText.replace(/-/g, "/");
						this.allInfo.selectedDateShowText = this.selectedDateShowText
					} else if (this.selectedDate.length > 2) {
						this.selectedDateShowText = this.selectedDate[0].date + '...' + this.selectedDate[this.selectedDate
							.length - 1].date
						this.selectedDateShowText = this.selectedDateShowText.replace(/-/g, "/");
						this.allInfo.selectedDateShowText = this.selectedDateShowText
					}
				} else {
					this.isCheckTime = false
					this.allInfo.isCheckTime = this.isCheckTime
				}
			},
			getCalendarDate() {
				let tomorrow = new Date()
				tomorrow.setDate(tomorrow.getDate() + 2);
				this.startDate = this.formatDate(tomorrow);
				let threeMonthsLater = new Date();
				threeMonthsLater.setMonth(threeMonthsLater.getMonth() + 3);
				this.endDate = this.formatDate(threeMonthsLater);
			},
			formatDate(date) {
				let year = date.getFullYear();
				let month = (date.getMonth() + 1).toString().padStart(2, '0');
				let day = date.getDate().toString().padStart(2, '0');
				return year + '-' + month + '-' + day;
			},
			getLocationInfo() {
				wx.chooseLocation({
					type: 'gcj02',
					success: (res) => {
						this.isCheckLocation = true
						this.locationName = res.address
						this.locationLongitude = res.longitude
						this.locationLatitude = res.latitude
						this.locationAddress = res.address
						console.log('选择的位置：', res);
						this.allInfo.isCheckLocation = true
						this.allInfo.locationName = res.address
						this.allInfo.locationLongitude = res.longitude
						this.allInfo.locationLatitude = res.latitude
						this.allInfo.locationAddress = res.address
						
						// 保存位置信息到Vuex
						this.$store.commit('setPosition', {
							address: res.address,
							longitude: res.longitude,
							latitude: res.latitude
						});
						
						// 获取周边伴宠师
						this.getCompanionList();
					},
					fail: (err) => {
						console.error('选择位置失败：', err);
					}
				});
			},
			getLocationFirst() {
				wx.chooseLocation({
					type: 'gcj02',
					success: (res) => {
						this.isCheckLocation = true
						this.locationName = res.address
						this.locationLongitude = res.longitude
						this.locationLatitude = res.latitude
						this.locationAddress = res.address
						this.allInfo.isCheckLocation = true
						this.allInfo.locationName = res.address
						this.allInfo.locationLongitude = res.longitude
						this.allInfo.locationLatitude = res.latitude
						this.allInfo.locationAddress = res.address
						
						// 保存位置信息到Vuex
						this.$store.commit('setPosition', {
							address: res.address,
							longitude: res.longitude,
							latitude: res.latitude
						});
						
						// 获取周边伴宠师
						this.getCompanionList();
					},
					fail: (err) => {
						console.error('选择位置失败：', err);
					}
				});
			},
			getCompanionList() {
				// 构建参数，使用当前位置坐标
				let data = {
					address: this.locationAddress || "上海市浦东新区浦东南路150弄",
					latitude: this.locationLatitude || 31.22514,
					longitude: this.locationLongitude || 121.49857,
					petTypes: ["1", "2"],
					staffName: ""
				}
				console.log('获取周边伴宠师参数:', data);
				
				// 保存当前位置到Vuex，让position mixin能使用
				this.$store.commit('setPosition', {
					address: this.locationAddress,
					longitude: this.locationLongitude,
					latitude: this.locationLatitude
				});
				
				getTeacherListIndex(data).then(response => {
					if (response.code == 200 && response.rows && response.rows.length > 0) {
						const nearbyTeacher = response.rows[0];
						console.log('伴宠师原始数据:', nearbyTeacher);
						
						// 如果伴宠师有地址信息，使用mixin的calculateDistanceAddress计算距离
						let distance = 0;
						if (nearbyTeacher.addressList && nearbyTeacher.addressList.length > 0) {
							distance = this.calculateDistanceAddress(nearbyTeacher.addressList);
						} else if (nearbyTeacher.latitude && nearbyTeacher.longitude) {
							// 如果没有地址列表但有经纬度信息，则构造地址对象
							const addressList = [{
								latitude: nearbyTeacher.latitude,
								longitude: nearbyTeacher.longitude
							}];
							distance = this.calculateDistanceAddress(addressList);
						}
						
						// 处理用户图片
						let userImageUrl = "";
						if (typeof nearbyTeacher.userImage === 'string') {
							userImageUrl = nearbyTeacher.userImage;
						} else if (nearbyTeacher.userImage && Array.isArray(nearbyTeacher.userImage) && nearbyTeacher.userImage.length > 0) {
							userImageUrl = nearbyTeacher.userImage[0].url || "";
						}
						
						// 构建伴宠师信息对象
						this.defaultCompanion = {
							name: nearbyTeacher.userName || '宠小二',
							gender: nearbyTeacher.gender || '1', // 性别，1-男，2-女
							star: nearbyTeacher.likeNum || 0,
							distance: distance.toFixed(1),
							shortDescription: nearbyTeacher.shortDescription || '专业伴宠师，用心照顾每一位小宠物',
							staffImages: [{
								url: userImageUrl || "https://catmdogf.oss-cn-shanghai.aliyuncs.com/CMDF/front/personal/pet/catdog.png"
							}],
							year: nearbyTeacher.serviceAge || 1, // 服务年限
							record: nearbyTeacher.commentNum || 0, // 评价数
							serviceNum: nearbyTeacher.serviceSummaryNum || 0 // 服务小结数
						}
						
						console.log('周边伴宠师信息:', this.defaultCompanion);
					} else {
						console.log('没有找到周边伴宠师或返回数据有误');
					}
				}).catch(err => {
					console.error('获取周边伴宠师失败:', err);
				})
			},
			getOrder(value) {
				if (value) {
					if (!this.isCheckLocation) {
						uni.showToast({
							title: '请先选择地址',
							duration: 1500,
							icon: "none"
						})
					} else {

                        this.$store.commit('setPosition', {
                            address: this.locationAddress,
                            longitude: this.locationLongitude,
                            latitude: this.locationLatitude,
                            date: this.selectedDateShowText
                        })

						uni.navigateTo({
							url: `/pages/companionPetList/companionPetList?info=` 
                            + encodeURIComponent(JSON
								.stringify(this.allInfo))
						});
					}
				} else {
                    this.$store.commit('setPosition', {})
                    this.buyInfo.teacher = null
					uni.navigateTo({
						url: '/pages/newOrder/serviceNew',
					});
				}
			},
			getCoupon() {
				// getCouponList().then(res => {
				// 	if (res.code == 200) {
				// 		this.couponList = res.rows
				// 		this.showMask = true
				// 	} else {
				// 		this.$modal.showToast('获取优惠券失败')
				// 	}

				// })

			},
			getCouponListAuth() {
				getCouponList().then(res => {
					if (res.code == 200) {
						this.couponData.push(res.data[0])
						console.log("this.couponData", this.couponData)
					} else {
						this.$modal.showToast('获取优惠券失败')
					}
				})
			},
			switchType(type) {
				if (type == 'PNORMAL') {
					return '满减券'
				}
				if (type == 'PDISCOUNT') {
					return '折扣券'
				}
				if (type == 'PTRAIL') {
					return '体验券'
				}
				return '优惠券'
			},
			receiveCoupon(id) {
				let data = {
					stockId: id
				}
				receiveCoupon(data).then(res => {
					console.log("this.receiveCoupon", res)
					if (res.code == 200) {
						this.$modal.showToast('优惠券领取成功')
					} else {
						this.$modal.showToast('领取优惠券失败')
					}
				})
			},
			getCouponListNoAuth() {
				// console.log('进入 getCouponListNoAuth：');
				// getCouponListNoAuth().then(res => {
				// 	if (res.code == 200) {
				// 		if (res.rows && Array.isArray(res.rows)) {
				// 			this.couponData = res.rows.filter(item => item !== null);
				// 			console.log("优惠券数据加载成功：", this.couponData);
				// 		} else if (res.data && Array.isArray(res.data)) {
				// 			this.couponData = res.data.filter(item => item !== null);
				// 			console.log("优惠券数据加载成功：", this.couponData);
				// 		} else {
				// 			console.log("获取优惠券数据格式异常:", res);
				// 		}
				// 	} else {
				// 		this.$modal.showToast('获取优惠券失败')
				// 	}
				// }).catch(err => {
				// 	console.error("获取优惠券列表出错:", err);
				// })
			},
			closeMask() {
				this.showMask = false
			},
			getSendCoupon(res) {
				let that = this
				console.log('res', res)
				if (res.detail.errcode == 'OK') {
					console.log(222)
					if (res.detail.send_coupon_result[0].code == 'SUCCESS') {
						that.showMask = false
						uni.showToast({
							title: '领取成功',
							icon: 'success',
							duration: 2000,
						})
					} else {
						uni.showModal({
							title: '领取失败',
							content: res.detail.send_coupon_result[0].message,
							showCancel: false,
							success: function(res) {
								that.showMask = false
							}
						})
					}
				} else {
					uni.showToast({
						title: '领取失败',
						icon: 'none'
					})
					that.showMask = false
				}
			},
			redirectuser() {},
			getBanner() {
				getBannerList().then(res => {
					if (res.code == 200) {
						this.bannerList = res.data
					} else {
						this.$modal.showToast('获取Banner失败')
					}
				})
			},
			changeSwiper(e) {
				this.current = e.detail.current
			},
			getPeopleList() {
				getStaffList().then(response => {

					if (response.code == 200) {
						this.peopleList = response.rows
					}

					console.log(response);
				})
			},
			getProductList() {
				getProductList({
					"publishStatus": 1,
					"categoryId": 76
				}).then(response => {
					if (response && response.content && response.content.length > 0) {
						this.skuData = response.content;
					}
					console.log(response);
				})
			},
			goDetails(item) {
				if (item) {
					uni.navigateTo({
						url: `/pages/details/detail?id=${item.id}`
					});
				} else {
					this.$modal.showToast('数据有误，请联系管理员')
				}

			},

			init() {
				this.$globalData.itemPrice = []
				this.$globalData.submitData = {
					"phone": "",
					"wechatId": "",
					"note": "",
					"totalPrice": "",
					"address": {
						"province": "",
						"city": "",
						"district": "",
						"detailAddress": ""
					},
					"skuList": [],
					"service": {
						"serviceFrequency": "once_a_day",
						"serviceDate": [],
						"serviceTimeFirst": "",
						"serviceTimeSecond": "",
						"pet": []
					}
				}
			},
			login() {
				uni.login({
					provider: 'weixin',
					success: (loginRes) => {
						console.log("login", 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)
						}
					}
				})
			},
			showRulePopup(coupon) {
				if (!coupon) {
					console.warn('尝试显示空优惠券详情');
					return;
				}
				this.currentCoupon = coupon;
				this.$refs.rulePopup.open();
			},
			closeRulePopup() {
				this.$refs.rulePopup.close();
			},
			getDiscountText(coupon) {
				if (!coupon || !coupon.stockType) return '';

				if (coupon.stockType === 'PNORMAL') {
					return '满100可减10元';
				} else if (coupon.stockType === 'PDISCOUNT') {
					return '打8折';
				} else if (coupon.stockType === 'PTRAIL') {
					return '免费体验一次';
				}
				return '';
			},
		},


		onShow() {
			if (!getToken() || !getOpenIdKey()) {
				this.login()
			}
			if(this.$globalData.mainSku.length < 1 || !this.$globalData.mainSku[0].price){
				// 获取主产品
				this.getProductList()
			}
			this.currentAddress = this.$globalData.newOrderData.currentAddress
			if(this.currentAddress&&this.currentAddress.name){
				this.isAddressSelected=true
			}
			this.currentPets = this.$globalData.newOrderData.currentPets
			if(this.currentPets&&this.currentPets.length>0){
				this.isPetSelected=true
			}
			this.needPreFamiliarize = this.$globalData.newOrderData.needPreFamiliarize
			// 初始化伴宠师等级
			if(this.$globalData.newOrderData.companionLevel) {
				this.companionLevel = this.$globalData.newOrderData.companionLevel
			}
			
			// 获取周边伴宠师数据
			this.getCompanionList();
		},
		
		onLoad: function() {
			this.init()
			this.getPeopleList()
			this.getProductList()
			this.getBanner()
			const accountInfo = wx.getAccountInfoSync();
			this.envVersion = accountInfo.miniProgram.envVersion;
			if (!getToken() || !getOpenIdKey()) {
				this.login()
			} else {
			}
            this.getCouponListAuth()
			
			// 获取优惠券列表（无需登录）
			this.getCouponListNoAuth()
			
			// 设置默认位置，这样即使用户不选择位置也能显示一些伴宠师
			this.$store.commit('setPosition', {
				address: "上海市浦东新区浦东南路150弄",
				longitude: 121.49857,
				latitude: 31.22514
			});
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #F5F5F7 !important;
	}

	.home-content {
		position: relative;


		.swiper {
			height: calc(100vw * 1098/1125);
		}

		.banner {
			height: calc(100vw * 1098/1125 + 250px);
			background-image: linear-gradient(180deg, #FFBF60 0%, #FFBF60 90%, #F5F5F7 99.41%);
		}

		.uni-card {
			border-radius: 16rpx;
		}

		.float-button {
			position: fixed;
			bottom: 150px;
			right: 10px;
			width: 50px;
			height: 50px;
			.kf-btn {
				background-color: rgba(255, 255, 255, 1);
				height: 52px;
				width: 52px;
				border-radius: 50%;
				display: flex;
				align-items: center;
			}
		}

		.coupon-list {
			width: 100%;

			.coupon-title {
				display: flex;
				line-height: 33rpx;
				margin: 42rpx 0 30rpx;
				justify-content: space-between;

				.coupon-title-left {
					display: flex;
					align-items: center;
					font-weight: 900;
					font-size: 30rpx;
					color: #333333;

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

				.coupon-title-right {
					color: #7D8196;
					font-size: 24rpx;
					font-style: normal;
					font-weight: 500;
					line-height: 28rpx;
				}
			}

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

			.coupon-content {
				.card {
					display: flex;
					align-items: center;
					width: 100%;
					padding: 10px 0;
					border-radius: 8px 8px 0 0;
				}

				.card-bottom {
					display: flex;
					background-color: #FFF1E0;
					height: 50rpx;
					align-items: center;
					justify-content: space-between;
					padding: 0 20rpx 0 20rpx;
					border-radius: 0 0 8px 8px;

					.card-bottom-text {
						color: #AAAAAA;
						font-size: 24rpx;
						font-weight: 400;
					}
				}

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

				.card-center {
					display: flex;
					flex-direction: column;

					.card-center-top {
						width: 40rpx;
						height: 20rpx;
						border-radius: 0 0 20rpx 20rpx;
						background-color: #fff;
						line-height: 20rpx;
						border-bottom: 1px solid #FDA714;
						border-left: 1px solid #FDA714;
						border-right: 1px solid #FDA714;
						margin-top: -22rpx;
						margin-bottom: 20rpx;
						margin-left: -19rpx;
					}

					.card-center-bottom {
						border-right: 1px dashed #AAAAAA;
						width: 1px;
						height: 120rpx;
					}
				}

				.card-right {
					padding: 0 16rpx 0 0;
					display: flex;
					flex: 1;
					justify-content: space-between;
					align-items: center;
					height: 60px;

					.card-content {
						width: 77%;
					}

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

		.companion-list {
			width: 100%;

			.companion-title {
				display: flex;
				line-height: 33rpx;
				margin: 42rpx 0 30rpx;
				justify-content: space-between;

				.companion-title-left {
					display: flex;
					align-items: center;
					font-weight: 900;
					font-size: 30rpx;
					color: #333333;

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

				.companion-title-right {
					color: #7D8196;
					font-size: 24rpx;
					font-style: normal;
					font-weight: 500;
					line-height: 28rpx;
				}
			}

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

			.companion-content {
				.companion-item {
					padding: 10px 0px 0px 0;

					.companion-info {
						display: flex;
						align-items: center;
						justify-content: flex-start;

						.companion-img {
							width: 168rpx;
							height: 168rpx;
							border: #FEA714 5rpx solid;
							border-radius: 20rpx;
						}

						.companion-info-1 {
							margin-left: 10px;
							width: 80%;

							.companion-info-2 {
								display: flex;
								flex-wrap: wrap;

								.companion-info-title {
									display: flex;
									flex-wrap: wrap;
									width: 60%;
								}

								.companion-name {
									color: #333;
									font-size: 32rpx;
									margin-right: 10rpx;
									font-weight: 900;
									font-style: normal;
								}

								.companion-info-star {
									color: #FFAA48;
									font-size: 24rpx;
									font-weight: 400;
									line-height: 28rpx;
									display: flex;
									align-items: center;
								}
							}

							.companion-info-3 {
								display: flex;
								align-items: baseline;
								font-size: 28rpx;
								line-height: 32rpx;
								margin-top: 5px;
								color: #FFAA48;
								font-weight: 900;
							}

							.companion-info-4 {
								display: flex;
								align-items: baseline;
								font-size: 24rpx;
								margin-top: 10px;
								color: #7D8196;
								font-weight: 400;
								line-height: 32rpx;
							}

						}

					}
				}

				.companion-item-bottom {
					height: 60rpx;
					background-color: #FFF4E5;
					margin: 20rpx 0 20rpx 0;
					display: flex;
					align-items: center;
					justify-content: center;
					border-radius: 8rpx;

					.companion-item-bottom-text {
						color: #A94F20;
						margin: 14rpx;
						font-size: 24rpx;
						font-weight: 400;
					}
				}
			}
		}

		.history-record {
			width: 100%;

			.history-record-title {
				display: flex;
				line-height: 33rpx;
				margin: 42rpx 0 30rpx;
				justify-content: space-between;

				.history-record-title-left {
					display: flex;
					align-items: center;
					font-weight: 900;
					font-size: 30rpx;
					color: #333333;

					.history-record-flag {
						width: 8rpx;
						height: 33rpx;
						background: #FFBF60;
						border-radius: 30rpx 30rpx 30rpx 30rpx;
						margin-right: 10rpx;
					}
				}

				.history-record-title-right {
					color: #7D8196;
					font-size: 24rpx;
					font-style: normal;
					font-weight: 500;
					line-height: 28rpx;
				}
			}

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

			.history-record-content {
				padding: 20rpx 0 20rpx 0;

				.history-record-content-image {
					display: flex;
					flex-wrap: nowrap;
					margin-bottom: 10rpx;

					.history-record-content-image-1 {
						background-image: url("https://catmdogf.oss-cn-shanghai.aliyuncs.com/CMDF/front/petServiceOrder/catNum.png");
						background-size: cover;
						width: 208rpx;
						height: 260rpx;
						margin-right: 20rpx;

						.history-record-content-image-1-text {
							.history-record-content-image-1-text-1 {
								width: 100%;
								display: flex;
								justify-content: center;
								height: 156rpx;
								align-items: flex-end;
								color: #FF8D00;
								font-size: 32rpx;
								font-weight: 900;
							}

							.history-record-content-image-1-text-2 {
								width: 100%;
								display: flex;
								justify-content: center;
								height: 90rpx;
								align-items: flex-end;
								color: #AAAAAA;
								font-size: 24rpx;
								font-weight: 400;
							}
						}
						
					}
					
					.history-record-content-image-2 {
						background-image: url("https://catmdogf.oss-cn-shanghai.aliyuncs.com/CMDF/front/petServiceOrder/dogNum.png");
						background-size: cover;
						width: 208rpx;
						height: 260rpx;
						margin-right: 20rpx;
					
						.history-record-content-image-2-text {
							.history-record-content-image-2-text-1 {
								width: 100%;
								display: flex;
								justify-content: center;
								height: 156rpx;
								align-items: flex-end;
								color: #FF8D00;
								font-size: 32rpx;
								font-weight: 900;
							}
					
							.history-record-content-image-2-text-2 {
								width: 100%;
								display: flex;
								justify-content: center;
								height: 90rpx;
								align-items: flex-end;
								color: #AAAAAA;
								font-size: 24rpx;
								font-weight: 400;
							}
						}
						
					}
					
					.history-record-content-image-3 {
						background-image: url("https://catmdogf.oss-cn-shanghai.aliyuncs.com/CMDF/front/petServiceOrder/goodNum.png");
						background-size: cover;
						width: 208rpx;
						height: 260rpx;
					
						.history-record-content-image-3-text {
							.history-record-content-image-3-text-1 {
								width: 100%;
								display: flex;
								justify-content: center;
								height: 156rpx;
								align-items: flex-end;
								color: #FF8D00;
								font-size: 32rpx;
								font-weight: 900;
							}
					
							.history-record-content-image-3-text-2 {
								width: 100%;
								display: flex;
								justify-content: center;
								height: 90rpx;
								align-items: flex-end;
								color: #AAAAAA;
								font-size: 24rpx;
								font-weight: 400;
							}
						}
						
					}
				}

				.history-record-content-text {
					font-size: 24rpx;
					font-weight: 400;
					color: #A94F20;
				}
			}
		}
	}

	page {
		display: flex;
		flex-direction: column;
		box-sizing: border-box;
		background-color: #fff;
		min-height: 100%;
		height: auto;
	}

	.text {
		text-align: center;
		font-size: 26rpx;
		margin-top: 10rpx;
	}


	.popupBottom {
		height: 950rpx;
		overflow: hidden;
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		padding: 10rpx 20rpx;
		border-radius: 20rpx 20rpx 0 0;
		background-color: #fff;

		.bottom-btn {
			width: 100%;
			border-radius: 120rpx;
			background: #FFB13F;
			font-size: 32rpx;
			color: #FFFFFF;
		}
	}

	.line {
		height: 1px;
		width: 100%;
		margin: 16px 0;
	}

	.swiper-item {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		color: #fff;
		height: 500rpx;
		line-height: 300rpx;
	}

	.card-container {
		margin: 0;
		padding: 0;
	}

	.title-img1 {
		height: 30px;
		width: 104px;
		background-repeat: no-repeat;
		background-position: left;
		background-size: 104px 30px;
		background-image: url('/static/images/pages/cwfw.png');
	}

	.service-content-img {
		padding: 5px;
		margin-top: 5px;
		border-radius: 8px;
	}



	#myVideo {
		width: 100%;
		border-radius: 5px;
	}

	.service-content {
		width: 100%;
		padding: 0 10px;
	}

	.title-img4 {
		height: 30px;
		width: 202px;
		background-repeat: no-repeat;
		background-position: center;
		background-size: 202px 30px;
		background-image: url('/static/images/pages/jppcs.png');
		margin: 10px 0;
	}

	.demo-uni-row {
		margin: 0;
		padding: 0;
	}

	.people-img {
		width: 190px;
		height: 163px;
		border: #FFBF60 1px solid;
		border-radius: 5px;
	}

	.people-year {
		display: flex;
		width: 68px;
		padding: 1px 4px;
		justify-content: space-between;
		align-items: center;
		border-radius: 0px 10px 10px 0px;
		background: linear-gradient(90deg, #FDA714 0%, #FD8B04 99.41%);
		color: #FFF;
		font-family: PingFang SC;
		font-size: 10px;
		font-style: normal;
		line-height: 14px;
		position: absolute;
		top: 15px;
		left: 0;
	}

	.service-people {
		display: flex;
	}

	.service-people-text {
		display: flex;
		align-items: center;
		line-height: 24px;
	}

	.service-people-text::before {
		content: "";
		background-color: black;
		border-radius: 50%;
		display: inline-block;
		height: 5px;
		width: 5px;
		margin-right: 5px;
	}

	.show-text-1 {
		display: block;
		color: var(--Color-, #222229);
		font-family: PingFang SC;
		font-size: 14px;
		font-style: normal;
		font-weight: 600;
		line-height: 24px;
	}

	.show-text-2 {
		display: block;
		color: var(--Color-, #222229);
		font-family: PingFang SC;
		font-size: 12px;
		font-style: normal;
		line-height: 18px;
	}

	.image-wrapper {
		position: relative;
	}

	.text-wrapper {
		position: absolute;
		bottom: 83px;
		left: 10px;
		color: #fff;
		font-size: 10px;
		font-weight: blod;
		font-family: PingFang SC;
	}

	.coupone_wrap {
		margin-top: 200px;
	}

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

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

	.text-button {
		height: 100rpx;
		border-radius: 0px 0px 6rpx 0;
		background: rgba(255, 208, 0, 1);
		font-weight: 500;
		font-size: 36rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.couponItem {
		width: 100%;
		padding: 0 30rpx;
		margin-top: 24rpx;
		-webkit-overflow-scrolling: touch;
	}

	.couponItem:last-child {
		margin-bottom: 24rpx;
	}

	.mask-coupon {
		background: rgba(0, 0, 0, .5);
		width: 100vw;
		height: 100vh;
		position: fixed;
		left: 0;
		top: 0;
		padding-bottom: 120rpx;

		.wx-coupon {
			background: #F2F2F2;
			min-height: 300px;
			position: fixed;
			bottom: 0;
			left: 0;
			width: 100%;
		}

		.title {
			font-size: 24px;
			display: flex;
			align-items: center;
			justify-content: center;
			padding: 20rpx 0 10rpx;
		}

		.content {
			height: 80%;
			overflow-y: auto;
		}

		.text-button {
			height: 100rpx;
			border-radius: 0px 0px 6rpx 0;
			background: rgba(255, 208, 0, 1);
			font-weight: 500;
			font-size: 36rpx;
			display: flex;
			align-items: center;
			justify-content: center;
		}
	}


	@media screen and (min-width: 500px) {
		.uni-swiper-dot-box {
			width: 400px;
			margin: 0 auto;
			margin-top: 8px;
		}

		.image {
			width: 100%;
		}
	}

	/* 优惠券规则弹窗样式 */
	.rule-popup {
		width: 600rpx;
		background-color: #FFFFFF;
		border-radius: 16rpx;
		overflow: hidden;
	}

	.rule-popup-title {
		height: 100rpx;
		line-height: 100rpx;
		text-align: center;
		font-size: 32rpx;
		font-weight: 600;
		color: #FFFFFF;
		background-color: #FFAA48;
	}

	.rule-popup-content {
		padding: 30rpx;
	}

	.rule-item {
		display: flex;
		margin-bottom: 20rpx;
	}

	.rule-label {
		width: 140rpx;
		font-size: 28rpx;
		color: #666666;
		flex-shrink: 0;
	}

	.rule-value {
		flex: 1;
		font-size: 28rpx;
		color: #333333;
		line-height: 40rpx;
	}

	.rule-popup-close {
		height: 90rpx;
		line-height: 90rpx;
		text-align: center;
		font-size: 30rpx;
		color: #FFAA48;
		border-top: 1px solid #EEEEEE;
	}
</style>