<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;"
		@click="toProductDetail">
			<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">
					<CouponItem 
						v-for="(item,index) in couponData" 
						:key="index"
						:couponData="item"
						@show-rule="showRulePopup"
						@coupon-received="handleCouponReceived"
						@update-coupon="updateCouponData"
					/>
				</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"
                v-for="(item,index) in companionList" :key="index"
                v-if="index < 1">
					<view class="companion-item">
						<view class="companion-info">
							<image class="companion-img" slot='cover'
								:src="item.userImage">
							</image>
							<view class="companion-info-1">
								<view class="companion-info-2">
									<view class="companion-info-title">
										<view class="companion-name">
											{{ item.userName || '匿名' }}
										</view>
										<view class="companion-sex">
											<img :src="item.appletUsersTeacher.sex == 0?'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: 20px;height: 20px;" />
										</view>
									</view>
									<view class="companion-info-star">
										<text style="color: #FFB13F;">点赞数{{ item.appletUsersTeacher.thumbsUp || 0 }}</text>
										<uni-icons type="hand-up-filled" size="20" color="#FFB13F"></uni-icons>
									</view>
								</view>
								<view class="companion-info-3" style="width: 100%;">
									<view class="ellipsis" v-if="item.distanceText">
										距离{{ item.distanceText }}km
									</view>
									<view class="ellipsis" v-else>
										{{ '<' }}1km
									</view>
								</view>
								<view class="companion-info-4" style="width: 100%;">
									<view class="ellipsis" style="max-width: 225px;">
										简介：{{ item.appletUsersTeacher.userBrief || '暂无' }}
									</view>
								</view>
							</view>
						</view>
					</view>
					<view>
						<view class="companion-item-bottom">
							<text class="companion-item-bottom-text">养宠{{ item.experience || 0 }}年 | 评价{{ item.commentNum || 0 }}条 | 服务小结{{ item.serviceSummaryNum || 0 }}份</text>
						</view>
					</view>
				</view>

                <view class="no-data" v-if="companionList.length == 0">
                    <view class="no-data-text">
                        您周边没有伴宠师呢
                    </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" 
				v-if="historyRecordConfig && 
				historyRecordConfig.length > 0">
					<view class="history-record-content-image">
						<view class="history-record-content-image-1"
					v-for="(item, index) in historyRecordConfig"
					:key="index"
					:style="'background-image: url(' + item.image + '); background-size: cover;'">
							<view class="history-record-content-image-1-text">
								<view class="history-record-content-image-1-text-1">{{ item.count }}</view>
								<view class="history-record-content-image-1-text-2">{{ item.time }}</view>
							</view>
						</view>
					</view>
					<view class="history-record-content-text">
						<text>*数据来源于猫妈狗爸平台</text>
					</view>
				</view>
				
				<view class="history-record-content" v-else>
					<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'
				@click="toPetFront"
				src="https://catmdogf.oss-cn-shanghai.aliyuncs.com/CMDF/front/petServiceOrder/joinus.png" />
		</view>

		<Kefu></Kefu>
		<!-- <view class="coupon_wrap" v-if="envVersion.includes('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> -->

		<!-- 优惠券详细规则弹窗 -->
		<CouponRulePopup ref="rulePopup" :coupon="currentCoupon" />
		
		

	</view>
</template>

<script>
import { bindCode } from '@/api/order/order.js'
	import {
		getStaffList,
		getProductList,
		getBannerList,
		getCouponList,
		getCouponListNoAuth,
		getOpenId,
	} from "@/api/system/user"
	import {
		setToken,
		getToken,
		getOpenIdKey,
		setOpenIdKey
	} from '@/utils/auth'
    // import { getTeacherListIndex } from '@/api/home'
	import {
		getTeacherList,
	} from "@/api/order/order"
	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 CouponItem from '@/components/CouponItem/index.vue';
	import CouponRulePopup from '@/components/CouponRulePopup/index.vue';
	import positionMixin from '@/mixins/position.js';
	import {getPhoneNumber} from "@/api/system/user.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",
				},
				historyRecordConfig : [],
				currentCoupon: null,
				companionList: [],
                isMember: false,
			}
		},
		components: {
			Kefu,
			uniPopup,
			NewUserCoupon,
			CouponItem,
			CouponRulePopup
		},
		// onLoad() {
		// 	this.getCalendarDate();
			
		// },
		methods: {
			closeNewUserPopup() {
				this.isNewUser = false;
			},
			handleGetCoupon() {
				if (getToken()) {
					
				} else {
					uni.navigateTo({
						url: '/pages/personalCenter/index'
					});
				}
			},
			getAllCoupon() {
				uni.navigateTo({
					url: '/pages_order/companionPetList/couponList'
				});
			},
			getAllCompanion() {
				if (!this.isCheckLocation) {
					uni.showToast({
						title: '请先选择地址',
						duration: 1500,
						icon: "none"
					})
				} else {
					uni.navigateTo({
						url: `/pages_order/companionPetList/companionPetList?info=` + encodeURIComponent(JSON
							.stringify(this.allInfo))
					});
				}
			},
			toProductDetail(){
				uni.switchTab({
					url: 'details/feed'
				})
			},
			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);
					}
				});
			},
            getLocation(){
                return new Promise((resolve, reject) => {
                    uni.getLocation({
                        type: 'gcj02',
                        success: (res) => {
                            resolve(res)
                        }
                    })
                })
			},
			async getCompanionList() {
				// 构建参数，使用当前位置坐标
				let data = {
					latitude: this.position.latitude,
					longitude: this.position.longitude,
				}

				// if(!data.latitude){
				// 	let res = await this.getLocation()
				// 	data.latitude = res.latitude
				// 	data.longitude = res.longitude
				// }

				getTeacherList({}).then(response => {
					if (response.code == 200) {
						this.companionList = response.rows
						this.calculateTeacherListDistance()
					}
					console.log(response);
				})
			},
			// 跳转伴宠师
			toPetFront(){
				uni.navigateToMiniProgram({
					appId: 'wx01f0f43759922fda',
					// path: '',
					envVersion: "release",
					success: res => {
						// 打开成功
						console.log("打开成功", res);
					},
					fail: err => {
						console.log(err);
					}
				})
			},
			calculateTeacherListDistance(){
				this.companionList.forEach(item => {
					item.distanceText = this.calculateDistanceAddress(item.appletAddresseList)
				})
				
				this.companionList.sort((a,b) => a.distanceText - b.distanceText)
			},
			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_order/companionPetList/companionPetList?info=` 
                            + encodeURIComponent(JSON
								.stringify(this.allInfo))
						});
					}
				} else {
                    this.initGlobalData()
                    this.$store.commit('setPosition', {})
                    this.buyInfo.teacher = null
					uni.navigateTo({
						url: '/pages/newOrder/serviceNew',
					});
				}
			},
			getCouponListAuth() {
				getCouponList().then(res => {
					if (res.code == 200) {

                        for (let index = 0; index < res.data.length; index++) {
                            const element = res.data[index];
                            if(element.sendType == 'newUser'){
                                this.couponData = [element]
                                this.isNewUser = true
                                this.$store.commit('setNewUserCoupon', element)
                                return
                            }
                        }

						this.couponData = [res.data[0]]
					} 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)
							if(uni.getStorageSync('inviteCode')){
								bindCode({
									openId : openId,
									code : uni.getStorageSync('inviteCode'),
								})
							}
						}
					}
				})
			},
			showRulePopup(coupon) {
				if (!coupon) {
					console.warn('尝试显示空优惠券详情');
					return;
				}
				this.currentCoupon = coupon;
				this.$refs.rulePopup.show();
			},
			
			// 处理优惠券领取成功事件
			handleCouponReceived(couponData) {
				console.log('首页优惠券领取成功:', couponData);
				// 可以在这里处理一些额外的逻辑，比如刷新优惠券列表等
			},
			
			// 更新优惠券数据
			updateCouponData(updatedCoupon) {
				// 找到对应的优惠券并更新数据
				const couponIndex = this.couponData.findIndex(item => item.id === updatedCoupon.id);
				if (couponIndex !== -1) {
					// 使用Vue.set或者$set来确保响应式更新
					this.$set(this.couponData, couponIndex, updatedCoupon);
				}
			}

		},


		onShow() {
			if (!getToken() || !getOpenIdKey()) {
				this.login()
			}else {
				this.getCouponListAuth()
			}
			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.$store.commit('getUserInfo')
			
			// 获取周边伴宠师数据
			this.getCompanionList();
		},
		
		onLoad: function({inviteCode}) {
			
			if(inviteCode){
				uni.setStorageSync('inviteCode', inviteCode)
			}
			
			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.$store.commit('setPosition', {
				address: "上海市浦东新区浦东南路150弄",
				longitude: 121.49857,
				latitude: 31.22514
			});
			
			
			uni.$on('initConfig', r => {
				
				let homejson = this.$store.state.configMap.home_config
				
				console.log('homejson', homejson);
				
				if(homejson && homejson.paramValueText){
					try{
						let home = JSON.parse(homejson.paramValueText)
						this.historyRecordConfig = home && home.historyRecords || []
					}catch(e){}
				}
			})
			
			this.getCalendarDate()
		}
	}
</script>

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

    .no-data{
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        .no-data-text{
            font-size: 24rpx;
            color: #999;
        }
    }

	.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 {
				// 优惠券内容样式已移至CouponItem组件
			}
		}

		.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%;
		}
	}


</style>