<template>
	<!-- 拼团单一商家 -->
	<view class="page1" @touchmove="onPageTouchMove">
		<!-- 固定顶部导航栏（悬浮在背景图之上） -->
		<view class="nav-bar"
			:style="{'padding-top': menuButtonInfo.top +'px','background':lastScrollTop>217?'#fff':''}">
			<view class="back-btn" @tap="back">
				<uni-icons type="left" size="28"></uni-icons>
			</view>
			<view class="title-search">
				<uni-icons type="search" size="18" style="margin: 9rpx;"></uni-icons>
				<input type="text" placeholder="搜索" />
			</view>
		</view>
		<!-- 背景头图（随页面滚动） -->
		<view class="title"></view>
		<view class="content">
			<view class="pintuan">
				<view class="shop-top">
					<view class="shop-img">
						<img :src="shopItem.shopIcon" alt="">
						<img src="https://jewel-shop.oss-cn-beijing.aliyuncs.com/6c4ab92a43c842d8bb22035bce1f65cc.png"
							alt=""
							style="width:30rpx;height:30rpx;position: absolute;top: 0;left: 0;background-size: 100%;" />
					</view>
					<view class="shop-content" @tap="goDetail('shopDetail')">
						<view class="shop-name">
							{{shopItem.shopName}}
						</view>
						<view class="shop-content-center">
							<view class="shop-rate">
								<view class="shop-rate-num">{{shopItem.shopScore}}</view>
								<view>
									<uni-rate :disabled="true" size="20" disabledColor="rgba(255, 184, 84, 1)"
										:value="shopItem.shopScore" />
								</view>
							</view>
							<view class="shop-tag">
								<text
									style="padding: 4rpx 10rpx;background: rgba(223, 255, 176, 1);color: #777;border-radius: 6rpx;">
									{{shopItem.shopTypeTitle}}
								</text>
							</view>
						</view>
						<view class="shop-content-bottom">
							<view class="shop-deal" @tap.stop="goDetail('shopEvaluate')" style="color: #777;">
								店铺评价<uni-icons type="right" size="12"></uni-icons>
							</view>
							<view class="shop-deal1">
								销量 <text> {{shopItem.saleCount != null ? shopItem.saleCount : 0}}</text>
							</view>
						</view>
					</view>
				</view>
				<view class="shop-bottom">
					公告：{{shopItem.remark}}
				</view>
			</view>

			<view class="pintuan" style="padding: 0;margin-top:20rpx;display: flex;"  v-if="orderListWait.length > 0" @tap="openOrderWait('')">
				
				<swiper class="zaixian-swiper" vertical circular :autoplay="orderListWait.length > 0"
					:interval="onlineWorkerInterval" :duration="onlineWorkerDuration">
					<swiper-item v-for="(item,index) in orderListWait" :key="index">
						<view style="display: flex;">
							<view class="pintuan-left">
								<view class="pintuan-left-img">
									<img :src="item.productPicture" alt="">
								</view>
								<view class="pintuan-left-box">
									<view class="pintuan-left-name">
										{{item.productName}}
									</view>
									<view class="pintuan-left-price">
										拼团<text style="color: red;">￥{{item.groupPrice}}</text>
									</view>
								</view>
							</view>
							<view class="pintuan-right">
								<view class="pintuan-right-img">
									<img src="https://jewel-shop.oss-cn-beijing.aliyuncs.com/94f91382e76c4f289d53fbf858e8732b.png"
										alt="" />
									<view class="weipincheng">+</view>
								</view>
								<view class="pintuan-right-cha">
									差<text style="color: red;">{{item.targetMembers - item.currentMembers}}人</text>拼成
								</view>
							</view>
						</view>
					</swiper-item>
				</swiper>
			</view>
			<!-- 分类栏：移到goods-list外层，position:sticky才能生效 -->
			<view class="container" style="display: flex;height: 72%;margin-top: 20rpx;">
				<scroll-view scroll-y id="menuList" style="border-right: 1px solid #eee;font-weight: 700;font-size: 28rpx;height: 100%;width: 160rpx;">
					<view class="menu1" @tap="checkTab(index)" v-for="(item,index) in menuList" :key="index"
						:style="{'border-top-right-radius':item.checked?'20rpx':'','border-bottom-right-radius':item.checked?'20rpx':'','color':item.checked?'rgba(0, 35, 28, 1)':'#777','background':item.checked?'#fff':''}">
						<view style="width: 160rpx;">{{item.categoryName}}</view>
					</view>
				</scroll-view>
				<scroll-view class="goods-list" scroll-y :scroll-into-view="scrollIntoViewId" :scroll-top="goodsListScrollTop" @scroll="onGoodsListScroll" @scrolltoupper="onGoodsListScrollToTop" :scroll-with-animation="true">
					<view class="goods-member" :id="'category-' + item.categoryId" v-for="(item,index) in productItem" :key="index"
						@tap="goDetail('product',item)">
						<view @tap.stop="buyingye" v-if="item.status == 1"
							style="width: 100%;height:100%;position: absolute;top: 0;background: rgba(0, 0, 0, 0.1);z-index: 999;border-radius: 20rpx;">
						</view>
						<view class="goods-top">
							
							<view class="goods-img">
								<img :src="item.productPicture" alt="" style="border-radius: 20rpx;">
								<img src="https://jewel-shop.oss-cn-beijing.aliyuncs.com/6c4ab92a43c842d8bb22035bce1f65cc.png"
									alt=""
									style="width:30rpx;height:30rpx;position: absolute;top: 0;left: 0;background-size: 100%;" />
							</view>
							<view class="goods-content" @tap="goDetail('goodsDetail')">
								<view class="goods-name">
									{{item.productName}}
								</view>
								<view class="goods-content-center">
									<view class="goods-deal1">
										销量 <text> {{item.tailWarn}}</text>
									</view>
								</view>
								<view class="shop-tag1">
									<view class="goods-tag"  @tap.stop="openOrderWait(item)" v-if="item.orderListWait != undefined && item.orderListWait.length > 0">
										<view class="pintuan-right-img">
											<img src="https://jewel-shop.oss-cn-beijing.aliyuncs.com/94f91382e76c4f289d53fbf858e8732b.png"
												alt="" />
											<view class="weipincheng">+</view>
										</view>
										<view class="pintuan-right-cha">
											差<text style="color: red;">{{item.minGroupCount}}人</text>拼成
										</view>
									</view>
								</view>
							</view>
						</view>
						<view class="goods-bottom">
							
							<view v-if="item.productGroupBuyPrices != null && item.isMoreBuy != 1" class="goods-btn" style="margin-left: 6%;" :style="{'float':groupId != ''?'right':''}" @tap="openPopup('xiadan','pintuan',item)">
								拼团购买¥{{ getGroupPrice(item) }}
							</view>
							<view class="goods-btn" v-if="!groupId" @tap="openPopup('xiadan','dandu',item)"
								style="background: rgba(166, 255, 234, 0.3);border: 1px solid rgba(166, 255, 234, 0.5);height:68rpx;">
								直接购买¥{{item.attributeListPrice | sliceMsg}}
							</view>
						</view>
					</view>
					<uni-load-more :status="loadStatus" @change="onChange" />
					<view style="width: 100%;height: 160rpx;"></view>
				</scroll-view>
				
			</view>
		</view>
		<view style="width: 100%;height: 160rpx;"></view>
		<view class="bottom">
			<view class="bottom-left">
				<view style="position: relative;width: 60rpx;height: 80rpx;margin-top: 20rpx;"
					@tap="openPopup('car','','')">
					<img src="https://jewel-shop.oss-cn-beijing.aliyuncs.com/60db52398a65459e9541881c926986a4.png"
						alt="" />
					<view class="bottom-dot" v-if="cartTotalCount > 0">{{cartTotalCount}}</view>
				</view>
				<view class="bottom-price">￥{{cartTotalPrice}}</view>
			</view>
			<view class="bottom-right" @tap="submitCartCheckout">
				<img src="https://jewel-shop.oss-cn-beijing.aliyuncs.com/d93d893296ed46ea99cfd0e8e2835eaa.png" alt="" />
			</view>
		</view>


		<!-- 购物车弹窗 -->
		<uni-popup ref="carPopup" background-color="#fff">
			<view class="car-content">
				<view class="car-close" @tap="$refs.carPopup.close()">
					<uni-icons type="close" size="30" color="#fff"></uni-icons>
				</view>
				<view class="car-title">
					已加购商品（{{cartTotalCount}}）
				</view>

				<scroll-view scroll-y style="max-height: 400rpx;">
					<view class="goods-top" style="padding: 20rpx 0;" v-for="(cartItem, index) in cartItems"
						:key="index">
						<view class="goods-img" style="width: 168rpx;height: 168rpx;">
							<img :src="cartItem.item.productPicture" alt=""
								style="border-radius: 20rpx;width:100%;height:100%;">
						</view>
						<view class="goods-content" style="padding-left: 20rpx;">
							<view class="goods-name">
								{{cartItem.item.productName}}
							</view>
							<view class="goods-content-center">
								<view class="goods-deal1" v-if="cartItem.specs">
									<text style="color: #999; font-size: 20rpx;">
										已选规格:{{getSpecDisplayString(cartItem.specs)}}
									</text>
								</view>
							</view>
							<view class="goods-content-bottom" style="margin-top: 10rpx;">
								<view
									style="font-size: 28rpx;line-height: 54rpx;margin-right: 20rpx;flex: 1;color: red;">
									￥{{cartItem.price}}
								</view>
								<view class="goods-num">
									<view class="num-plus" style="background: #999;color: #fff;"
										@tap="adjustCart(cartItem.cartId, -1)">
										-
									</view>
									<view class="num">
										{{cartItem.quantity}}
									</view>
									<view class="num-plus" @tap="adjustCart(cartItem.cartId, 1)">
										+
									</view>
								</view>
							</view>
						</view>
					</view>
				</scroll-view>

				<view style="width: 100%;height: 160rpx;"></view>
				<view class="bottom" style="padding-bottom: 20rpx;">
					<view class="bottom-left">
						<view style="width: 60rpx;height: 80rpx;margin-top: 10rpx;" @tap="$refs.carPopup.close()">
							<img src="https://jewel-shop.oss-cn-beijing.aliyuncs.com/60db52398a65459e9541881c926986a4.png"
								alt="" />
						</view>
						<view class="bottom-price" style="line-height: 48rpx;">
							<view>￥{{cartTotalPrice}}</view>
						</view>
					</view>
					<view class="bottom-right" @tap="submitCartCheckout">
						<img src="https://jewel-shop.oss-cn-beijing.aliyuncs.com/d93d893296ed46ea99cfd0e8e2835eaa.png"
							alt="" />
					</view>
				</view>
			</view>
		</uni-popup>

		<!-- 警告弹出层 -->
		<uni-popup ref="warnPopup" background-color="#fff">
			<view class="warnImg">
				<img @tap="$refs.warnPopup.close()"
					src="https://jewel-shop.oss-cn-beijing.aliyuncs.com/4996043b3987401794b974d359429b8e.png"
					alt="购物车是空的" style="width:600rpx;height:740rpx;" />
			</view>
		</uni-popup>
		<!-- 拼团和选规格弹窗 -->
		<uni-popup ref="pintuanPopup" background-color="#fff">
			<view class="car-content">
				<view class="car-close" @tap="$refs.pintuanPopup.close()">
					<uni-icons type="close" size="30" color="#fff"></uni-icons>
				</view>
				<view class="goods-top">
					<view class="goods-img">
						<img :src="currentItem.productPicture" alt="" style="border-radius: 20rpx;">
						<img src="https://jewel-shop.oss-cn-beijing.aliyuncs.com/6c4ab92a43c842d8bb22035bce1f65cc.png"
							alt=""
							style="width:30rpx;height:30rpx;position: absolute;top: 0;left: 0;background-size: 100%;" />
					</view>
					<view class="goods-content">
						<view class="goods-name">
							{{currentItem.productName}}
						</view>
						<view class="goods-content-center">
							<view class="goods-deal1">
								月售 <text> 100+</text>
							</view>
						</view>
						<view class="goods-content-bottom">
							<view style="font-size: 28rpx;line-height: 54rpx;margin-right: 20rpx;">
								￥{{currentItem.attributeListPrice | sliceMsg}}
							</view>
						</view>
					</view>
				</view>
				<scroll-view scroll-y style="max-height: 50vh;">
					<view class="goods-spec" v-if="parsedSpecs.length > 0">
						<view class="spec1" v-for="(spec, sIndex) in parsedSpecs" :key="sIndex">
							<view class="spec11">
								选{{spec.name}}
							</view>
							<view class="spec22">
								<view :class="spec.selected === option ? 'spec-check' : 'spec222'"
									v-for="(option, oIndex) in spec.options" :key="oIndex"
									@tap="selectSpec(sIndex, option)">
									{{option}}
								</view>
							</view>
						</view>
					</view>
					<template
						v-if="(groupId == null || groupId == '') && isPintuan && currentItem.productGroupBuyPrices && currentItem.productGroupBuyPrices.length > 0">
						<view class="spec11">
							成团选择
						</view>
						<view class="goods-team">
							<view
								:class="selectedGroupRule && selectedGroupRule.groupCount === rule.groupCount ? 'team-check' : 'team1'"
								v-for="(rule, rIndex) in currentItem.productGroupBuyPrices" :key="rIndex"
								@tap="selectGroupRule(rule)">
								<view class="team11">
									￥{{parseFloat(rule.groupPrice).toFixed(2)}}
								</view>
								<view class="team11">
									{{rule.groupCount}}人团
								</view>
							</view>
						</view>
					</template>
					<view class="spec11"  v-if="moreBuyList.length > 0 && isPintuan" style="display: flex;">
						<view style="flex: 1;">
							搭配小食
						</view>
						<view style="padding-top: 10rpx;">
							<view class="goods-num">
								<view class="num-plus" style="background: #999;color: #fff;"
									@tap="changeValue('minus')">
									-
								</view>
								<view class="num">
									{{vModelValue}}
								</view>
								<view class="num-plus" @tap="changeValue('plus')">
									+
								</view>
							</view>
						</view>
						
					</view>
					<view class="goods-team"  v-if="moreBuyList.length > 0 && isPintuan">
						<view :class="spec.isChecked ? 'team-check' : 'team1'"
							v-for="(spec, sIndex) in moreBuyList" :key="sIndex"
							@tap="selectMoreBuy(spec,sIndex)">
							<view class="team11">
								￥{{spec.attributeListPrice | sliceMsg}} 
							</view>
							<view class="team11">
								{{spec.productName}}
							</view>
							<view class="jiaobiao" v-if="spec.isChecked && spec.quantity>0">
								{{spec.quantity ? spec.quantity : ''}}
							</view>
						</view>
					</view>
					<!-- 优惠券选择 -->
					<view v-if="isPintuan" style="display: flex;height: 80rpx;line-height: 80rpx;border-top: 1px solid #eee;font-size: 28rpx;font-weight: 700; align-items:center; margin-top: 20rpx;" @tap="openCouponPopup">
						<view style="flex: 1; color: #777;">
							优惠券
						</view>
						<view style="color: #ff5722;" v-if="selectedCoupon">
							-￥{{selectedCoupon.discountAmount.toFixed(2)}}
						</view>
						<view style="color: #0b9b73;" v-else-if="availableCoupons.length > 0">
							有 {{availableCoupons.length}} 张可用
						</view>
						<view style="color: #999;" v-else>
							无可用券
						</view>
						<uni-icons type="right" size="14" color="#999" style="margin-left:10rpx;"></uni-icons>
					</view>
					<view style="width: 100%;height: 160rpx;"></view>
				</scroll-view>
				<view class="bottom" style="padding-bottom: 40rpx;height: 160rpx;z-index: 10;">
					<view v-if="isPintuan" class="pintuan1">
						<template v-if="!groupId">
							<view class="pintuan2" style="border-bottom-left-radius: 100rpx;border-top-left-radius: 100rpx;"
								@tap.stop="submitPintuan(true)">
								面对面团
							</view>
							<view class="pintuan2"
								style="background: rgba(0, 35, 28, 1);border-bottom-right-radius: 100rpx;border-top-right-radius: 100rpx;color: rgba(166, 255, 234, 1);"
								@tap.stop="submitPintuan(false)">
								发起拼团￥{{selectedGroupRule && selectedGroupRule.groupPrice ? parseFloat(selectedGroupRule.groupPriceAndMore).toFixed(2) : '0.00'}}
							</view>
						</template>
						<template v-else>
							<view class="pintuan2"
								style="width: 100%; border-radius: 100rpx;"
								@tap.stop="submitPintuan(false)">
								参与拼团￥{{selectedGroupRule && selectedGroupRule.groupPriceAndMore ? parseFloat(selectedGroupRule.groupPriceAndMore).toFixed(2) : '0.00'}}
							</view>
						</template>
					</view>
					<view v-else class="pintuan0" @tap="submitAddToCart">
						加入购物车
					</view>
				</view>
			</view>
		</uni-popup>
		<!-- 拼团和选规格弹窗 -->
		<uni-popup ref="pintuanGroupPopup" background-color="#fff">
			<view class="car-content">
				<view class="car-close" @tap="$refs.pintuanGroupPopup.close()">
					<uni-icons type="close" size="30" color="#fff"></uni-icons>
				</view>
				<view class="goods-top" style="font-size: 28rpx;font-weight: 700;">
					快来加入拼团吧！可以选取任意拼团商品下单！
				</view>
				<scroll-view scroll-y style="max-height: 50vh;">
					<template>
						<!-- 占位假数据展示 -->
						<view class="">
							<view class="goods-center" v-for="(item, index) in orderListWait" :key="index">
								<view class="list-right">
									<view class="list-right-img">
										<img src="https://jewel-shop.oss-cn-beijing.aliyuncs.com/94f91382e76c4f289d53fbf858e8732b.png"
											alt="" />
										<view class="list-weipincheng">+</view>
									</view>
									<view class="list-right-cha">
										<view class="cha11">
											{{item.targetMembers}}人拼
										</view>
										<view style="line-height: 40rpx;padding-left: 10rpx;">
											差<text style="color: red;">{{item.targetMembers - item.currentMembers}}人</text>拼成
										</view>
									</view>
								</view>
								<view class="list-btn" @tap.stop="chooseOrderWait(item)">
									去拼单
								</view>
							</view>
						</view>
					</template>
					<view style="width: 100%;height: 160rpx;"></view>
				</scroll-view>
			</view>
		</uni-popup>

		<!-- 支付弹出层 -->
		<uni-popup ref="payPopup" background-color="#fff">
			<view class="pay-popup" style="height: 580rpx;background: #fff;border-radius: 40rpx 40rpx 0 0;padding-top: 40rpx;">
				<view class="content" style="height: 100%;margin-top:0">
					<view class="box1">
						<view style="height: 70rpx;line-height: 70rpx;text-align: center;">
							支付剩余时间 59:09
						</view>
						<view
							style="height: 90rpx;line-height: 90rpx;text-align: center;font-weight: 700;font-size: 30rpx;">
							￥<text
								style="font-size: 60rpx;">{{backendTotalAmount ? backendTotalAmount.toFixed(2) : '0.00'}}</text>
						</view>
						<view  style="height: 40rpx;text-align: center;color: #777;">
							
							<text v-if="groupId != '' && isFaceToFaceGroup">配送费(均摊) {{tuanzhangOrder.deliveryFee}} 元 </text>
							
							<text v-if="groupdeliveryType == 1"> 打包费 {{currentItem.lunchBox}} 元</text>
						</view>
						<view style="height: 40rpx;text-align: center;color: #ff5722;" v-if="selectedCoupon">
							优惠券抵扣 -￥{{selectedCoupon.discountAmount.toFixed(2)}}
						</view>
						<view style="height: 40rpx;text-align: center;color: red;">
							若拼团失败，将会为您自动退款
						</view>
					</view>
					<view class="box1" style="display: flex;padding: 40rpx;">
						<view style="flex: 1;">
							<view style="height: 42rpx;line-height: 42rpx;display: flex;">
								<img src="https://jewel-shop.oss-cn-beijing.aliyuncs.com/4c8e0cc311db4d38ab43e019673c4b8c.png"
									alt="" style="width: 42rpx;height: 42rpx;margin-right: 20rpx;" />
								<text style="font-size: 30rpx;font-weight: 700;">微信支付</text>
							</view>
							<view style="text-align: right;margin-left: 60rpx;color: #777;width: 146rpx;">
								使用微信支付
							</view>
						</view>
						<view style="width: 36rpx;padding-top: 20rpx;">
							<img src="https://jewel-shop.oss-cn-beijing.aliyuncs.com/02bff7edc4e04caaa1868955ff684f1f.png"
								alt="" style="width: 36rpx;height: 36rpx;" />
						</view>
					</view>
					<view class="btn" style="background: linear-gradient(90deg, rgba(227, 255, 150, 1), rgba(166, 255, 234, 1));width: 90%;height: 100rpx;border-radius: 100rpx;text-align: center;font-size: 28rpx;font-weight: 700;line-height: 100rpx;margin: 40rpx auto;" @tap="wxPayment">
						确认付款
					</view>
				</view>
			</view>
		</uni-popup>

		<!-- 参团成功提示弹出层 -->
		<uni-popup ref="joinSuccessPopup" background-color="#fff" @change="onJoinSuccessPopupChange">
			<view class="pintuan-popup" style="position: relative;height: 1200rpx;width: 100%;border-top-left-radius: 20rpx;border-top-right-radius: 20rpx;padding: 20rpx;">
				<img src="https://jewel-shop.oss-cn-beijing.aliyuncs.com/ecd00dab1c9c44198d765bc08bc1bd71.png" alt=""
					style="position: absolute;top: 0;right: 0;width: 240rpx;height: 180rpx;" @tap="$refs.joinSuccessPopup.close()">
				<view style="position: absolute;bottom: 0;width: 100%;height: 760rpx;">
					<view class="kaituan1">
						<view class="kaituan1-title" style="margin-top: 100rpx;text-align: center;font-size: 40rpx;font-weight: bold;">
							参团成功！
						</view>
						<view class="kaituan1-title1" style="text-align: center;margin-top: 20rpx;color: #777;">
							您已成功参与拼团
						</view>
					</view>
					<view class="kaituan2" style="display: flex;justify-content: center;margin-top: 60rpx;">
						<view class="kaituan22">
							<img src="https://jewel-shop.oss-cn-beijing.aliyuncs.com/801c569079da4540990c1cc634186fdd.png"
								alt=""
								style="width: 90rpx;height: 90rpx;border-radius: 90rpx;margin: 0 auto;display: block;" />
						</view>
					</view>
				</view>
			</view>
		</uni-popup>

		<!-- 优惠券选择弹出层 -->
		<uni-popup ref="couponPopup" type="bottom" background-color="#F5F8F5">
			<view style="width: 100%; height: 800rpx; display: flex; flex-direction: column;">
				<view style="height: 100rpx; line-height: 100rpx; text-align: center; font-size: 32rpx; font-weight: bold; border-bottom: 1px solid #eee; position: relative; background: #fff;">
					选择优惠券
					<uni-icons type="closeempty" size="24" @tap="$refs.couponPopup.close()" style="position: absolute; right: 30rpx; top: 0;"></uni-icons>
				</view>
				<scroll-view scroll-y style="flex: 1; padding: 20rpx; box-sizing: border-box;">
					<view v-for="(item, index) in availableCoupons" :key="index" @tap="selectCoupon(item)"
						style="background: #fff; border-radius: 12rpx; padding: 30rpx 20rpx; margin-bottom: 20rpx; display: flex; align-items: center; justify-content: space-between;">
						<view style="display: flex; align-items: center; flex: 1;">
							<view style="color: #ff5722; font-size: 40rpx; font-weight: bold; width: 140rpx;">
								<text style="font-size: 24rpx;">￥</text>{{item.discountAmount}}
							</view>
							<view style="flex: 1; display: flex; flex-direction: column; justify-content: center; margin-left: 20rpx;">
								<view style="font-size: 28rpx; font-weight: bold; color: #333; margin-bottom: 6rpx;">{{item.couponName}}</view>
								<view style="font-size: 22rpx; color: #999;" v-if="item.minAmount > 0">满{{item.minAmount}}可用</view>
								<view style="font-size: 22rpx; color: #999;" v-else>无门槛使用</view>
							</view>
						</view>
						<uni-icons v-if="selectedCoupon && selectedCoupon.id === item.id" type="checkmarkempty" size="20" color="#0b9b73"></uni-icons>
						<view v-else style="width: 40rpx; height: 40rpx; border-radius: 50%; border: 1px solid #ddd;"></view>
					</view>
					<view v-if="availableCoupons.length===0" style="text-align:center; padding-top: 100rpx; color: #999;">
						暂无可用优惠券
					</view>
					<view style="height:40rpx;"></view>
				</scroll-view>
				<view style="padding: 20rpx 40rpx; background: #fff;" v-if="availableCoupons.length>0">
					<view @tap="selectCoupon(null)" style="width: 100%; height: 80rpx; background: linear-gradient(90deg, #e3ff96, #a6ffea); font-size: 30rpx; font-weight: 700; line-height: 80rpx; text-align: center; border-radius: 100rpx;">
						不使用优惠券
					</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				loadStatus: 'more',
				type: '',
				shopId: '',
				shopItem: {
					shopIcon:'',
					shopName:'',
					shopScore:'',
					shopTypeTitle:'',
					saleCount:'',
					remark:'',
				},
				productId: '',
				productItem: [],
				tuanzhangOrder:{},
				cartItems: [],
				moreBuyData:[],
				vModelValue:0,
				currentItem: {},
				checkMoreBuyIndex:'',
				parsedSpecs: [],
				moreBuyList:[],
				selectedGroupRule: {},
				pageNum: 1,
				total: 1,
				chooseWaitType:false,
				// 导航栏高度（用于sticky top偏移）
				navBarHeight: 0,
				orderListWait:[],
				// 分类栏距离页面顶部的距离（用于上滑检测）
				menuListOffsetTop: 0,
				lastScrollTop: 0,
				// 防止切换分类之后onPageScroll闪回的标志
				isSwitching: false,
				containerOriginalTop: 0,
				scrollIntoViewId: '',
				goodsListScrollTop: 0,
				isAutoScrolling: false,
				pageScrollTop: 0,
				searchForm: {
					shopId: '',
					delFlag: 1,
					pageNum: 1,
					pageSize: '100',
					categoryId: ''
				},
				menuButtonInfo: {},
				groupdeliveryType:'',
				isPintuan: true,
				groupId: null,
				isFaceToFaceGroup: false,
				targetMembers: 2,
				backendTotalAmount: 0,
				currentOrderId: '',
				onlineWorkerInterval:2500,
				onlineWorkerDuration:500,
				menuList: [{
					categoryName: '猜你喜欢',
					id: '1',
					checked: true
				}],
				shopRecommend:[],
				availableCoupons: [],
				selectedCoupon: null
			}
		},
		components: {

		},
		computed: {
			cartTotalCount() {
				return this.cartItems.reduce((acc, curr) => acc + curr.quantity, 0);
			},
			cartTotalPrice() {
				return this.cartItems.reduce((acc, curr) => acc + (curr.quantity * curr.price), 0).toFixed(2);
			}
		},
		filters: {
			sliceMsg(val) {
				var name = ''
				if (typeof(val) == 'string') {
					let newObj = JSON.parse(val)
					for (let as in newObj) {
						name = newObj[as].specPrice
					}
				}
				return name;
			},
			slicePrice(val) {
				let begin = ''
				if (val != null) {
					begin = val[0].groupPrice
					for (let i = 0; i < val.length; i++) {
						if (val[i].groupPrice < begin) {
							begin = val[i].groupPrice
						}
					}
				}
				return begin;
			}
		},
		onLoad(option) {
			this.type = option.type;
			if (option.groupId) {
				this.groupId = option.groupId;
			}
			if (option.isFaceToFace) {
				this.isFaceToFaceGroup = option.isFaceToFace === '1' || option.isFaceToFace === 'true';
				if(this.isFaceToFaceGroup){
					this.tui.request("/mall/order/selectMallOrderByGroupId/"+this.groupId, "GET", {}, false, true).then((res) => {
						if (res.code == 200) {
							this.tuanzhangOrder = res.result;
						} else {
							that.tui.toast(res.message)
							return
						}
						uni.hideLoading()
					}).catch((res) => {})
				}
			}
			if (option.targetMembers) {
				this.targetMembers = parseInt(option.targetMembers);
			} else {
				this.targetMembers = 2; // Default fallback
			}
			if (this.type == 'shop') {
				try {
					this.shopItem = JSON.parse(decodeURIComponent(option.item));
				} catch(e) {
					this.shopItem = JSON.parse(option.item);
				}
				if(this.shopItem.products){
					this.shopRecommend = this.shopItem.products
					for(let i=0;i<this.shopRecommend.length;i++){
						this.shopRecommend[i].categoryId = '1'
						this.shopRecommend[i].isChecked = false
					}
				}
			} else {
				try {
					this.productItem = JSON.parse(decodeURIComponent(option.item));
				} catch(e) {
					this.productItem = JSON.parse(option.item);
				}
			}
			this.getCategory(this.shopItem.id);
			this.getProduct('');
		},
		onShow() {
			this.menuButtonInfo = uni.getMenuButtonBoundingClientRect();
			this.fetchCoupons();
			// 计算导航栏高度用于sticky offset：statusBarHeight + 40px内容区
			const info = uni.getSystemInfoSync();
			this.navBarHeight = info.statusBarHeight + 40;
		},
		onReady() {
			// 记录container相对页面的初始偏移量
			setTimeout(() => {
				const query = uni.createSelectorQuery().in(this);
				query.select('.container').boundingClientRect(rect => {
					if (rect) {
						this.containerOriginalTop = rect.top;
						this.menuListOffsetTop = rect.top;
					}
				}).exec();
			}, 500);
		},
		onPageScroll(e) {
			this.lastScrollTop = e.scrollTop;
			console.log(e.scrollTop)
			// 当页面滚动到container应该触顶的位置时，启用吸顶
			const stickyThreshold = this.containerOriginalTop - this.navBarHeight;
			
		},
		methods: {
			// 页面touchmove事件：吸顶后阻止页面整体滑动（让goods-list接管滚动）
			onPageTouchMove(e) {
				// 吸顶状态下不需要额外处理，scroll-view会自己处理
				console.log(e)
			},
			// goods-list滚动事件：检测分类切换 + 滚回顶部取消吸顶
			onGoodsListScroll(e) {
				if (this.isAutoScrolling) return;
				const scrollTop = e.detail.scrollTop;
				
				// 根据滚动位置自动选中对应分类
				this.detectCurrentCategory();
			},
			onGoodsListScrollToTop() {
				if (this.isAutoScrolling) return;
				
			},
			// 检测当前可见的分类
			detectCurrentCategory() {
				if (this.isSwitching) return;
				const query = uni.createSelectorQuery().in(this);
				// 获取goods-list中所有goods-member的位置
				query.selectAll('.goods-member').boundingClientRect();
				query.select('.goods-list').boundingClientRect();
				query.exec((res) => {
					if (!res || !res[0] || !res[1]) return;
					const items = res[0];
					const listRect = res[1];
					const listTop = listRect.top;
					let currentCategoryId = '';
					// 找到第一个顶部在goods-list可视区域内或刚过顶部的item
					for (let i = items.length - 1; i >= 0; i--) {
						if (items[i].top <= listTop + 10) {
							// 从productItem中获取categoryId
							if (this.productItem[i]) {
								currentCategoryId = this.productItem[i].categoryId;
							}
							break;
						}
					}
					if (currentCategoryId !== '' || currentCategoryId === '') {
						// 在menuList中找到匹配的菜单并选中
						let found = false;
						for (let i = 0; i < this.menuList.length; i++) {
							if (String(this.menuList[i].id) === String(currentCategoryId)) {
								if (!this.menuList[i].checked) {
									for (let j = 0; j < this.menuList.length; j++) {
										this.menuList[j].checked = (j === i);
									}
									this.$forceUpdate();
								}
								found = true;
								break;
							}
						}
						// 如果没找到匹配的分类（如categoryId为空），选中"猜你喜欢"
						if (!found && currentCategoryId === '') {
							for (let j = 0; j < this.menuList.length; j++) {
								this.menuList[j].checked = (j === 0);
							}
							this.$forceUpdate();
						}
					}
				});
			},
			getProduct(categoryId) {
				let that = this;
				this.loadStatus = 'loading';
				this.searchForm.shopId = this.shopItem.id;
				this.searchForm.categoryId = categoryId;
				that.tui.request("/app/product/getShareList", "POST", this.searchForm, false, false).then((res) => {
					that.loadStatus = 'nomore';
					if (res.code == 200) {
						if (that.searchForm.pageNum == 1) {
							that.productItem = res.result.records;
						} else {
							that.productItem = [...that.productItem, ...res.result.records];
						}
						for(let i = 0;i<that.productItem.length;i++){
							if(this.productItem[i].sellBeginTime !='' && this.productItem[i].sellEndTime != ''){
								let isEndTime = this.isWithinBusinessHours(this.productItem[i].sellBeginTime,this.productItem[i].sellEndTime)
								console.log(isEndTime)
								this.productItem[i].status = isEndTime ? 0 : 1
							}
							if(that.productItem[i].isMoreBuy == 1){
								//搭配的小料商品
								that.productItem[i].isChecked = false
								that.moreBuyList.push(that.productItem[i])
							}
						}
						console.log('好的',that.productItem)
						//获取当前店铺待成团列表
						that.getOrderWait();
						
						that.total = res.result.pages; // pages = 总页数
						that.pageNum = that.searchForm.pageNum;
						that.$forceUpdate();
					} else {
						that.tui.toast(res.message);
						return;
					}
					uni.hideLoading();
				}).catch((res) => {});
			},
			getCategory(id) {
				let that = this
				that.tui.request("/app/productCategory/list", "GET", {
					shopId: id
				}, false, true).then((res) => {
					if (res.code == 200) {
						if (res.result.length > 0) {
							for (let i = 0; i < res.result.length; i++) {
								res.result[i].checked = false
								that.menuList.push(res.result[i])
							}
						}
						that.$forceUpdate()
					} else {
						that.tui.toast(res.message)
						return
					}
					uni.hideLoading()
				}).catch((res) => {})
			},
			checkTab(index) {
				this.isSwitching = true;
				for (let i = 0; i < this.menuList.length; i++) {
					this.menuList[i].checked = (i === index);
				}

				const selectedCategory = this.menuList[index];
				// 如果是"猜你喜欢"（id为空），滚动到顶部
				if (!selectedCategory.id && selectedCategory.id !== 0) {
					this.goodsListScrollTop = 0;
					this.$nextTick(() => {
						this.goodsListScrollTop = 0;
					});
				} else {
					
					// 通过scroll-into-view滚动到对应分类的第一个商品
					const targetId = 'category-' + selectedCategory.id;
					// 先清空再设置，确保同一个id也能触发滚动
					this.scrollIntoViewId = '';
					this.$nextTick(() => {
						this.isAutoScrolling = true;
						this.scrollIntoViewId = targetId;
						// 延迟恢复滚动检测，避免自动滚动触发分类切换
						setTimeout(() => {
							this.isAutoScrolling = false;
							this.isSwitching = false;
						}, 500);
					});
					return;
				}
				setTimeout(() => { 
					this.isSwitching = false;
				}, 300);
				this.$forceUpdate();
			},
			openOrderWait(item){
				this.chooseWaitType = false
				if(item != ''){
					this.chooseWaitType = true
					this.orderListWait = item.orderListWait
					
					this.currentItem = item;
					// Parse specifications
					this.parsedSpecs = [];
					if (item.attributeList && item.attributeList !== '{}') {
						try {
							let attrs = typeof item.attributeList === 'string' ? JSON.parse(item.attributeList) : item
								.attributeList;
							for (let key in attrs) {
								if (attrs[key] && attrs[key].title && attrs[key].title.length > 0) {
									this.parsedSpecs.push({
										name: key,
										options: attrs[key].title,
										selected: attrs[key].title[0] // Default select first
									});
								}
							}
						} catch (e) {
							console.log(e);
						}
					}
					this.isPintuan = true;
					
					if (this.groupId) {
						// Determine best price match given targetMembers
						let prices = item.productGroupBuyPrices || [];
						let validPrices = prices.filter(p => p.groupCount <= this.targetMembers);
						if (validPrices.length > 0) {
							this.selectedGroupRule = validPrices.reduce((max, obj) => (obj.groupCount > max.groupCount ? obj : max));
							this.selectedGroupRule.groupPriceAndMore = this.selectedGroupRule.groupPrice
							if(this.selectedCoupon){
								this.selectedGroupRule.groupPriceAndMore -= parseFloat(this.selectedCoupon.discountAmount);
								if(this.selectedGroupRule.groupPriceAndMore <= 0){
									this.selectedGroupRule.groupPriceAndMore = 0.01
								}
							}
						} else if (prices.length > 0) {
							this.selectedGroupRule = prices.reduce((prev, curr) => (prev.groupCount < curr.groupCount ? prev : curr));
							this.selectedGroupRule.groupPriceAndMore = this.selectedGroupRule.groupPrice
							if(this.selectedCoupon){
								this.selectedGroupRule.groupPriceAndMore -= parseFloat(this.selectedCoupon.discountAmount);
								if(this.selectedGroupRule.groupPriceAndMore <= 0){
									this.selectedGroupRule.groupPriceAndMore = 0.01
								}
							}
						} else {
							this.selectedGroupRule = {};
						}
					} else {
						// Normal init
						if (item.productGroupBuyPrices && item.productGroupBuyPrices.length > 0) {
							this.selectedGroupRule = item.productGroupBuyPrices[0];
							this.selectedGroupRule.groupPriceAndMore = this.selectedGroupRule.groupPrice
							if(this.selectedCoupon){
								this.selectedGroupRule.groupPriceAndMore -= parseFloat(this.selectedCoupon.discountAmount);
								if(this.selectedGroupRule.groupPriceAndMore <= 0){
									this.selectedGroupRule.groupPriceAndMore = 0.01
								}
							}
						} else {
							this.selectedGroupRule = {};
						}
					}
					
					let moreBuyPrice = 0
					for(let i = 0;i<this.moreBuyList.length;i++){
						if(this.moreBuyList[i].quantity > 0){
							moreBuyPrice += Number((Number(this.moreBuyList[i].quantity) * Number(this.sliceMsg2(this.moreBuyList[i].attributeListPrice))).toFixed(2))
						}
					}
					this.selectedGroupRule.groupPriceAndMore = Number(this.selectedGroupRule.groupPrice) + moreBuyPrice
					if(this.selectedCoupon){
						this.selectedGroupRule.groupPriceAndMore -= parseFloat(this.selectedCoupon.discountAmount);
						if(this.selectedGroupRule.groupPriceAndMore <= 0){
							this.selectedGroupRule.groupPriceAndMore = 0.01
						}
					}
				}
				this.$refs.pintuanGroupPopup.open('bottom')
			},
			getOrderWait(){
				let that = this
				
				this.tui.request("/mall/order/getMallOrderGroupByShopId", "POST", {
					shopId:this.shopItem.id,
					status:0,
					isFace:0,
				}, false, false).then((res) => {
					that.loadStatus = 'nomore';
					if (res.code == 200) {
						that.orderListWait = res.result;
						for(let i = 0;i<that.productItem.length;i++){
							that.productItem[i].orderListWait = []
							if(that.orderListWait !=null){
								that.productItem[i].minGroupCount = that.orderListWait[0].targetMembers - that.orderListWait[0].currentMembers
								for(let y = 0;y<that.orderListWait.length;y++){
									if(that.productItem[i].id == that.orderListWait[y].productId){
										if(that.productItem[i].minGroupCount > (that.orderListWait[y].targetMembers - that.orderListWait[y].currentMembers)){
											that.productItem[i].minGroupCount = that.orderListWait[y].targetMembers - that.orderListWait[y].currentMembers
										}
										that.productItem[i].orderListWait.push(that.orderListWait[y])
									}
								}
							}
						}
						
						that.$forceUpdate();
					} else {
						that.tui.toast(res.message);
						return;
					}
					uni.hideLoading();
				}).catch((res) => {});
			},
			chooseOrderWait(item){
				this.$refs.pintuanGroupPopup.close();
				this.groupId = item.id;
				this.targetMembers = parseInt(item.targetMembers);
				this.selectedCoupon = null;
				if(this.chooseWaitType){
					this.fetchCoupons();
					this.$refs.pintuanPopup.open('bottom');
				}
			},
			openPopup(type, index, item) {
				if (type == 'car') {
					this.$refs.carPopup.open('bottom')
				} else if (type == 'xiadan') {
					this.currentItem = item;
					// Parse specifications
					this.parsedSpecs = [];
					if (item.attributeList && item.attributeList !== '{}') {
						try {
							let attrs = typeof item.attributeList === 'string' ? JSON.parse(item.attributeList) : item
								.attributeList;
							for (let key in attrs) {
								if (attrs[key] && attrs[key].title && attrs[key].title.length > 0) {
									this.parsedSpecs.push({
										name: key,
										options: attrs[key].title,
										selected: attrs[key].title[0] // Default select first
									});
								}
							}
						} catch (e) {
							console.log(e);
						}
					}

					if (index == 'pintuan') {
						this.isPintuan = true;
						this.selectedCoupon = null;
						
						if (this.groupId) {
							// Determine best price match given targetMembers
							let prices = item.productGroupBuyPrices || [];
							let validPrices = prices.filter(p => p.groupCount <= this.targetMembers);
							if (validPrices.length > 0) {
								this.selectedGroupRule = validPrices.reduce((max, obj) => (obj.groupCount > max.groupCount ? obj : max));
								this.selectedGroupRule.groupPriceAndMore = this.selectedGroupRule.groupPrice
								if(this.selectedCoupon){
									this.selectedGroupRule.groupPriceAndMore -= parseFloat(this.selectedCoupon.discountAmount);
									if(this.selectedGroupRule.groupPriceAndMore <= 0){
										this.selectedGroupRule.groupPriceAndMore = 0.01
									}
								}
							} else if (prices.length > 0) {
								this.selectedGroupRule = prices.reduce((prev, curr) => (prev.groupCount < curr.groupCount ? prev : curr));
								this.selectedGroupRule.groupPriceAndMore = this.selectedGroupRule.groupPrice
								if(this.selectedCoupon){
									this.selectedGroupRule.groupPriceAndMore -= parseFloat(this.selectedCoupon.discountAmount);
									if(this.selectedGroupRule.groupPriceAndMore <= 0){
										this.selectedGroupRule.groupPriceAndMore = 0.01
									}
								}
							} else {
								this.selectedGroupRule = {};
							}
							
							if (this.isFaceToFaceGroup) {
								if (this.parsedSpecs.length === 0) {
									// No specs needed, jump straight to direct pay
									this.submitFTFJoinPay({});
									return;
								}
							}
						} else {
							// Normal init
							if (item.productGroupBuyPrices && item.productGroupBuyPrices.length > 0) {
								this.selectedGroupRule = item.productGroupBuyPrices[0];
								this.selectedGroupRule.groupPriceAndMore = this.selectedGroupRule.groupPrice
								if(this.selectedCoupon){
									this.selectedGroupRule.groupPriceAndMore -= parseFloat(this.selectedCoupon.discountAmount);
									if(this.selectedGroupRule.groupPriceAndMore <= 0){
										this.selectedGroupRule.groupPriceAndMore = 0.01
									}
								}
							} else {
								this.selectedGroupRule = {};
							}
						}
						
						let moreBuyPrice = 0
						for(let i = 0;i<this.moreBuyList.length;i++){
							if(this.moreBuyList[i].quantity > 0){
								moreBuyPrice += Number((Number(this.moreBuyList[i].quantity) * Number(this.sliceMsg2(this.moreBuyList[i].attributeListPrice))).toFixed(2))
							}
						}
						this.selectedGroupRule.groupPriceAndMore = Number(this.selectedGroupRule.groupPrice) + moreBuyPrice
						
						this.fetchCoupons();
						this.$refs.pintuanPopup.open('bottom');
					} else {
						this.isPintuan = false;
						// If solo buy and NO specs, add immediately to cart
						if (this.parsedSpecs.length === 0) {
							this.addToCart(item, null);
							uni.showToast({
								title: '已加入购物车',
								icon: 'none'
							});
						} else {
							// Open popup to select specs
							this.$refs.pintuanPopup.open('bottom');
						}
					}
				}
			},
			selectSpec(sIndex, option) {
				this.parsedSpecs[sIndex].selected = option;
				this.$forceUpdate();
			},
			selectGroupRule(rule) {
				this.selectedGroupRule = rule;
				this.selectedGroupRule.groupPriceAndMore = this.selectedGroupRule.groupPrice
				if(this.selectedCoupon){
					this.selectedGroupRule.groupPriceAndMore -= parseFloat(this.selectedCoupon.discountAmount);
					if(this.selectedGroupRule.groupPriceAndMore <= 0){
						this.selectedGroupRule.groupPriceAndMore = 0.01
					}
				}
			},
			submitAddToCart() {
				let specChoices = {};
				for (let spec of this.parsedSpecs) {
					specChoices[spec.name] = spec.selected;
				}
				this.addToCart(this.currentItem, specChoices);
				uni.showToast({
					title: '已加入购物车',
					icon: 'none'
				});
				this.$refs.pintuanPopup.close();
			},
			submitPintuan(isFaceToFace) {
				let specChoices = {};
				for (let spec of this.parsedSpecs) {
					specChoices[spec.name] = spec.selected;
				}
				let packageFee = parseFloat(this.currentItem.lunchBox || 0);

				this.currentItem.moreBuyData = []
				for(let i = 0;i<this.moreBuyData.length;i++){
					if(this.moreBuyData[i].quantity != undefined && this.moreBuyData[i].quantity > 0){
						this.currentItem.moreBuyData.push(this.moreBuyData[i])
					}
				}
				if (this.groupId && this.isFaceToFaceGroup) {
					// Direct face-to-face pay path
					this.submitFTFJoinPay(specChoices);
					return
				}

				// Pack data for checkout
				
				let goData = {
					item: this.currentItem,
					groupRule: this.selectedGroupRule,
					specs: specChoices,
					orderType: 2, // 2 indicates Group Buy
					groupId: this.groupId,
					isFaceToFace: this.groupId ? this.isFaceToFaceGroup : (isFaceToFace || false)
				};
				uni.navigateTo({
					url: '/package1/buyFood/buyFood?item=' + encodeURIComponent(JSON.stringify(goData)) +
						'&shopItem=' + encodeURIComponent(JSON.stringify(this.shopItem)) + '&packageFee=' +
						packageFee
				});
				this.$refs.pintuanPopup.close();
			},
			submitFTFJoinPay(specChoices) {
				let items = [{
					productId: this.currentItem.id,
					specs: JSON.stringify(specChoices || {}),
					price: parseFloat(this.selectedGroupRule && this.selectedGroupRule.groupPrice ? this.selectedGroupRule.groupPrice : 0),
					quantity: 1
				}];
				if(this.currentItem.moreBuyData){
					for(let a = 0;a<this.currentItem.moreBuyData.length;a++){
						items.push({
							productId: this.currentItem.moreBuyData[a].id,
							specs: '',
							price: parseFloat(this.sliceMsg2(this.currentItem.moreBuyData[a].attributeListPrice)).toFixed(2),
							quantity: this.currentItem.moreBuyData[a].quantity
						});
					}
				}

				let packageFee = parseFloat(this.currentItem.lunchBox || 0);

				let payload = {
					userId: uni.getStorageSync('id') || 'test-user123',
					shopId: this.shopItem.id,
					deliveryType: this.tuanzhangOrder.deliveryType, 
					packageFee: this.tuanzhangOrder.deliveryType == 1 ? packageFee : 0,
					remark: '',
					items: items,
					receiverName: '',
					receiverPhone: '',
					receiverAddress: '',
					shopName: this.shopItem.shopName,
					shopPhone: this.shopItem.shopPhone || '',
					shopAddress: this.shopItem.shopAddress || '',
					groupId: this.groupId,
					userCouponId: this.selectedCoupon ? this.selectedCoupon.id : null
				};
				payload.regionId = JSON.parse(uni.getStorageSync('area')).id
				uni.showLoading({ title: '创建订单中...' });
				this.tui.request("/mall/order/create", "POST", payload, false, false).then(res => {
					uni.hideLoading();
					if (res.success && res.result) {
						this.currentOrderId = res.result.id;
						this.groupdeliveryType = res.result.deliveryType;
						this.backendTotalAmount = res.result.totalAmount;
						this.$refs.payPopup.open('bottom');
						if (this.$refs.pintuanPopup) this.$refs.pintuanPopup.close();
					} else {
						uni.showToast({ title: res.message || '下单失败', icon: 'none' });
					}
				}).catch(err => {
					uni.hideLoading();
				});
			},
			addToCart(item, specs) {
				let specStr = specs ? JSON.stringify(specs) : '';
				let cartId = item.id + '_' + specStr;
				let existingItem = this.cartItems.find(c => c.cartId === cartId);
				if (existingItem) {
					existingItem.quantity++;
				} else {
					let priceToUse = 0;
					if (item.attributeListPrice) {
						try {
							let pObj = typeof item.attributeListPrice === 'string' ? JSON.parse(item.attributeListPrice) :
								item.attributeListPrice;
							if (Array.isArray(pObj) && pObj.length > 0) {
								priceToUse = parseFloat(pObj[0].specPrice);
							} else {
								for (let k in pObj) {
									priceToUse = parseFloat(pObj[k].specPrice);
									break;
								}
							}
						} catch (e) {}
					}
					this.cartItems.push({
						cartId: cartId,
						item: item,
						specs: specs,
						quantity: 1,
						price: priceToUse.toFixed(2)
					});
				}
			},
			//判断是否在营业时间内
			isWithinBusinessHours(begin, end) {
				// 获取当前时间的时和分
				const now = new Date();
				const currentMinutes = now.getHours() * 60 + now.getMinutes();
			
				// 解析开始和结束时间（格式 "HH:MM"）
				const parseTime = (timeStr) => {
					const [hours, minutes] = timeStr.split(':').map(Number);
					return hours * 60 + minutes;
				};
			
				const startMinutes = parseTime(begin);
				const endMinutes = parseTime(end);
				console.log(currentMinutes +','+startMinutes +','+endMinutes)
			
				// 判断是否在区间内（包含端点）
				return currentMinutes >= startMinutes && currentMinutes <= endMinutes;
			},
			adjustCart(cartId, delta) {
				let index = this.cartItems.findIndex(c => c.cartId === cartId);
				if (index !== -1) {
					let newQty = this.cartItems[index].quantity + delta;
					if (newQty <= 0) {
						this.cartItems.splice(index, 1);
					} else {
						this.cartItems[index].quantity = newQty;
					}
				}
			},
			getSpecDisplayString(specs) {
				if (!specs) return '';
				let arr = [];
				for (let k in specs) {
					arr.push(specs[k]);
				}
				return arr.join(',');
			},
			submitCartCheckout() {
				if (this.cartItems.length === 0) {
					this.$refs.warnPopup.open()
					return;
				}

				let totalPackageFee = 0;
				for (let cartItem of this.cartItems) {
					totalPackageFee += parseFloat(cartItem.item.lunchBox || 0) * cartItem.quantity;
				}
				// 类似普通订单结算逻辑
				uni.navigateTo({
					url: '/package1/buyFood/buyFood?cart=' + encodeURIComponent(JSON.stringify(this.cartItems)) +
						'&shopItem=' + encodeURIComponent(JSON.stringify(this.shopItem)) + '&packageFee=' +
						totalPackageFee
				});
			},
			goDetail(type) {
				if (type == 'goodsDetail') {
					uni.navigateTo({
						url: '/package1/goods/goodsDetail'
					})
				} else if (type == 'shopDetail') {
					uni.navigateTo({
						url: '/package1/group/groupBuyDetail?item=' + JSON.stringify(this.shopItem)
					})
				} else if (type == 'shopEvaluate') {
					uni.navigateTo({
						url: '/package1/group/shopEvaluate?item=' + JSON.stringify(this.shopItem)
					})
				}
			},
			buyingye() {
				uni.showToast({
					title: '商品不在售卖时间！',
					icon: 'none'
				});
			},
			getGroupPrice(item) {
				if (!this.groupId) {
					return this.$options.filters.slicePrice(item.productGroupBuyPrices);
				}
				let target = this.targetMembers;
				let prices = item.productGroupBuyPrices || [];
				if (prices.length === 0) return '0.00';
				let validPrices = prices.filter(p => p.groupCount <= target);
				if (validPrices.length === 0) {
					let minRule = prices.reduce((prev, curr) => (prev.groupCount < curr.groupCount ? prev : curr));
					return parseFloat(minRule.groupPrice).toFixed(2);
				}
				let bestRule = validPrices.reduce((max, obj) => (obj.groupCount > max.groupCount ? obj : max));
				return parseFloat(bestRule.groupPrice).toFixed(2);
			},
			selectMoreBuy(item,index){
				this.checkMoreBuyIndex = item.id
				this.moreBuyList[index].isChecked = !this.moreBuyList[index].isChecked;
				let isHas = false
				let index1 = ''
				for(let i = 0;i<this.moreBuyList.length;i++){
					if(this.moreBuyList[i].id != item.id && this.moreBuyList[index].isChecked){
						this.moreBuyList[i].isChecked = false
					}
				}
				for(let i = 0;i<this.moreBuyData.length;i++){
					if(this.moreBuyData[i].id == this.moreBuyList[index].id){
						isHas = true
						index1 = i
						this.vModelValue = this.moreBuyData[i].quantity ? this.moreBuyData[i].quantity : 0
						this.moreBuyList[index].quantity = this.moreBuyData[i].quantity ? this.moreBuyData[i].quantity : 0
					}
				}
				if(!isHas){
					this.vModelValue = 0
				}
				
				if(this.moreBuyList[index].isChecked && !isHas){
					item.quantity = 0
					this.moreBuyData.push(item)
				}
				if(!this.moreBuyList[index].isChecked && isHas){
					this.moreBuyData.splice(index1,1)
					this.moreBuyList[index].quantity = 0
				}
				
				let moreBuyPrice = 0
				for(let i = 0;i<this.moreBuyData.length;i++){
					if(this.moreBuyData[i].quantity > 0){
						moreBuyPrice += Number((Number(this.moreBuyData[i].quantity) * Number(this.sliceMsg2(this.moreBuyData[i].attributeListPrice))).toFixed(2))
					}
				}
				this.selectedGroupRule.groupPriceAndMore = Number(this.selectedGroupRule.groupPrice) + moreBuyPrice
				if(this.selectedCoupon){
					this.selectedGroupRule.groupPriceAndMore -= parseFloat(this.selectedCoupon.discountAmount);
					if(this.selectedGroupRule.groupPriceAndMore <= 0){
						this.selectedGroupRule.groupPriceAndMore = 0.01
					}
				}
			},
			sliceMsg2(val) {
				var name = ''
				if (typeof(val) == 'string') {
					let newObj = JSON.parse(val)
					for (let as in newObj) {
						name = newObj[as].specPrice
					}
				}
				return name;
			},
			changeValue(type) {
				if(type == 'plus'){
					this.vModelValue += 1
				}else{
					this.vModelValue = this.vModelValue > 0 ?this.vModelValue -= 1:0
				}
				let moreBuyPrice = 0
				for(let i = 0;i<this.moreBuyList.length;i++){
					if(this.moreBuyList[i].id == this.checkMoreBuyIndex){
						this.moreBuyList[i].quantity = this.vModelValue
					}
					if(this.moreBuyList[i].quantity > 0){
						moreBuyPrice += Number((Number(this.moreBuyList[i].quantity) * Number(this.sliceMsg2(this.moreBuyList[i].attributeListPrice))).toFixed(2))
					}
				}
				this.selectedGroupRule.groupPriceAndMore = Number(this.selectedGroupRule.groupPrice) + moreBuyPrice
				if(this.selectedCoupon){
					this.selectedGroupRule.groupPriceAndMore -= parseFloat(this.selectedCoupon.discountAmount);
					if(this.selectedGroupRule.groupPriceAndMore <= 0){
						this.selectedGroupRule.groupPriceAndMore = 0.01
					}
				}
				for(let i = 0;i<this.moreBuyData.length;i++){
					if(this.moreBuyData[i].id == this.checkMoreBuyIndex){
						this.moreBuyData[i].quantity = this.vModelValue
					}
				}
				this.$forceUpdate()
			},
			wxPayment() {
				let that = this;
				if (!this.currentOrderId || !this.backendTotalAmount) return;

				let amountInCents = Math.round(this.backendTotalAmount * 100);

				this.tui.request("/api/wechat/pay/unified-order", "POST", {
					openid: uni.getStorageSync('miniProgramOpenid') || 'test-openid',
					amount: amountInCents,
					description: '商城订单',
					outTradeNo: this.currentOrderId
				}, false, false).then((res) => {
					if (res.code == 200) {
						uni.requestPayment({
							provider: 'wxpay',
							timeStamp: res.timeStamp,
							nonceStr: res.nonceStr,
							package: res.package,
							signType: res.signType,
							paySign: res.paySign,
							success: function(res2) {
							/* uni.showToast({ title: '支付成功', icon: 'success' });
								that.tui.request("/api/wechat/pay/paySuccess", "POST", {
									outTradeNo: that.currentOrderId
								}, false, false).then((res3) => {
									if(res3.code == 200){
										uni.redirectTo({
											url: '/package1/order/orderConfirm?id=' + that.currentOrderId + '&groupId=' + that.groupId + '&amount=' + this.backendTotalAmount 
										});
									}else{
										that.tui.toast("订单创建失败，请联系客服处理");
									}
								}) */
								uni.redirectTo({
									url: '/package1/order/orderConfirm?id=' + that.currentOrderId + '&groupId=' + that.groupId + '&amount=' + that.backendTotalAmount 
								});
							},
							fail: function(err) {
								that.tui.toast("支付失败或取消");
							}
						});
					} else {
						// 模拟支付成功
						if (res.code == 404 || res.code == 500 || res.code == 400 || !res.code) {
							that.tui.request(
								`/hiver/order/payMallOrderSuccess?orderId=${that.currentOrderId}&workerId=`,
								"POST", {}, false, false).then(res2 => {
								that.$refs.payPopup.close();
								uni.showToast({ title: '支付成功(模拟)', icon: 'none' });
								setTimeout(() => { that.$refs.joinSuccessPopup.open('bottom'); }, 1500);
							});
						} else {
							that.tui.toast(res.message);
						}
					}
				})
			},
			onJoinSuccessPopupChange(e) {
				if (!e.show) {
					uni.redirectTo({
						url: '/package1/order/pendGroup?groupId=' + this.groupId
					});
				}
			},
			fetchCoupons() {
				let userId = uni.getStorageSync('id');
				if (!userId) return;
				let amount = this.selectedGroupRule && this.selectedGroupRule.groupPriceAndMore ? this.selectedGroupRule.groupPriceAndMore : 0;
				this.tui.request('/mall/coupon/available', 'GET', {
					userId: userId,
					applyScene: 1,
					regionId:JSON.parse(uni.getStorageSync('area')).id,
					amount: amount,
					merchantId: this.shopItem.id || '0'
				}, false, true).then((res) => {
					if (res.code == 200 && res.result) {
						this.availableCoupons = res.result;
						if (this.selectedCoupon) {
							let stillValid = this.availableCoupons.find(c => c.id === this.selectedCoupon.id);
							if (!stillValid) this.selectedCoupon = null;
						}
					}
				});
			},
			selectCoupon(item) {
				this.selectedCoupon = item;
				this.selectedGroupRule.groupPriceAndMore -= parseFloat(this.selectedCoupon.discountAmount);
				if(this.selectedGroupRule.groupPriceAndMore <= 0){
					this.selectedGroupRule.groupPriceAndMore = 0.01
				}
				this.$refs.couponPopup.close();
			},
			openCouponPopup() {
				this.fetchCoupons();
				this.$refs.couponPopup.open('bottom');
			},
			back() {
				uni.navigateBack()
			}
		}

	}
</script>

<style lang="scss">
	page {
		width: 100%;
		height: 100%;
		font-size: 24rpx;
		background: #F5F8F5;
		color: #00231C;
	}

	.page1 {
		width: 100%;
		height: 100%;
		font-size: 24rpx;
		position: relative;
	}

	/* 顶部背景图随页面滚动（不固定） */
	.title {
		background: url('https://jewel-shop.oss-cn-beijing.aliyuncs.com/8bc15960c2dc40268e295d6dd23aecce.png') no-repeat;
		width: 100%;
		height: 340rpx;
		background-size: 100% 100%;
	}

	/* 固定在顶部的导航栏，覆盖在背景图上 */
	.nav-bar {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		display: flex;
		align-items: center;
		z-index: 100;
		padding: 16rpx 24rpx;
		box-sizing: border-box;
	}

	.title-search {
		display: flex;
		flex: 1;
		background: rgba(255, 255, 255, 0.9);
		height: 54rpx;
		margin-left: 20rpx;
		border-radius: 54rpx;

		input {
			height: 54rpx;
			line-height: 54rpx;
		}
	}

	.back-btn {
		display: flex;
		align-items: center;
		justify-content: center;
		width: 60rpx;
		height: 60rpx;
		border-radius: 50%;
	}

	/* content 上移，叠在背景图下方，减少头部空白 */
	.content {
		margin-top: -150rpx;
		position: relative;
		z-index: 1;
		height: auto;
	}

	.shop-img {
		width: 160rpx;
		height: 160rpx;
		position: relative;

		img {
			width: 100%;
			background-size: 100%;
			height: 100%;
			border-radius: 20rpx;
		}
	}

	.shop-top {
		display: flex;
	}

	.shop-content {
		flex: 1;
		padding-left: 20rpx;

	}

	.shop-name {
		font-size: 32rpx;
		font-weight: 900;
	}

	.shop-content-center {
		display: flex;
		margin: 20rpx 0;
	}

	.shop-rate {
		background: rgba(249, 212, 157, 0.34);
		height: 40rpx;
		display: flex;
		border-radius: 20rpx;
		padding: 0 10rpx 0 0;
	}

	.shop-rate-num {
		width: 50rpx;
		height: 100%;
		text-align: center;
		background: linear-gradient(90deg, rgba(255, 77, 0, 1), rgba(255, 184, 84, 1));
		color: #fff;
		line-height: 40rpx;
		font-size: 22rpx;
		border-bottom-left-radius: 20rpx;
		border-top-left-radius: 20rpx;
		border-bottom-right-radius: 10rpx;
		border-top-right-radius: 10rpx;
		font-weight: 700;
	}

	.shop-tag {
		flex: 1;
		line-height: 40rpx;
		text-align: right;
	}

	.shop-tag1 {
		flex: 1;
		line-height: 40rpx;
		text-align: left;
	}

	.shop-content-bottom {
		display: flex;
	}

	.shop-deal {
		flex: 1;
	}

	.shop-bottom {
		margin-top: 20rpx;
		line-height: 40rpx;
		font-weight: 700;
	}

	.pintuan {
		background: #fff;
		padding: 20rpx;
		width: 95%;
		margin: 0 auto;
		border-radius: 20rpx;
	}

	.pintuan-left {
		display: flex;
		padding: 20rpx;
		flex: 1;
	}

	.pintuan-left-img {
		width: 90rpx;
		height: 90rpx;

		img {
			width: 100%;
			height: 100%;
			background-size: 100%;
			border-radius: 20rpx;
		}
	}

	.pintuan-left-box {
		flex: 1;
		padding-left: 20rpx;
	}

	.pintuan-right {
		display: flex;
		margin-top: 50rpx;
		width: 30%;
	}

	.pintuan-right-img {
		height: 40rpx;
		display: flex;

		img {
			width: 40rpx;
			height: 40rpx;
			z-index: 98;
			background-size: 100%;
		}
	}

	.pintuan-left-name {
		font-weight: 700;
		margin-bottom: 20rpx;
	}

	.pintuan-left-price {
		display: inline;
		padding: 10rpx;
		background: rgba(255, 57, 57, 0.1);
		border-radius: 10rpx;
	}

	.weipincheng {
		width: 40rpx;
		height: 40rpx;
		background: rgba(166, 255, 234, 1);
		border-radius: 40rpx;
		text-align: center;
		font-size: 28rpx;
		font-weight: 700;
		margin-left: -6rpx;
		z-index: 97;
	}

	.pintuan-right-cha {
		line-height: 40rpx;
		padding-left: 10rpx;
	}

	.goods-member {
		padding-bottom: 20rpx;
		margin: 0 0 20rpx;
		background: #fff;
		position: relative;
	}

	.goods-list {
		flex: 1;
		height: 100%;
		border-radius: 20rpx;
	}

	.container-sticky {
		position: fixed;
		left: 0;
		width: 100%;
		z-index: 50;
		height: calc(100vh - 160rpx);
		background: #F5F8F5;
		padding: 0 2.5%;
		box-sizing: border-box;
	}

	.goods-top {
		padding: 20rpx;
		display: flex;
	}

	.goods-content {
		flex: 1;
		padding-left: 20rpx;
	}

	.goods-name {
		font-size: 32rpx;
		font-weight: 900;
	}

	.goods-content-center {
		display: flex;
		margin: 16rpx 0;
	}

	.goods-rate {
		background: rgba(249, 212, 157, 0.34);
		height: 40rpx;
		display: flex;
		border-radius: 20rpx;
	}

	.goods-rate-num {
		width: 50rpx;
		height: 100%;
		text-align: center;
		background: linear-gradient(90deg, rgba(255, 77, 0, 1), rgba(255, 184, 84, 1));
		color: #fff;
		line-height: 40rpx;
		font-size: 22rpx;
		border-bottom-left-radius: 20rpx;
		border-top-left-radius: 20rpx;
		border-bottom-right-radius: 10rpx;
		border-top-right-radius: 10rpx;
	}

	.goods-deal1 {
		width: 60%;
	}

	.goods-tag {
		display: flex;
		margin: 0;
		width: 100%;
	}

	.goods-content-bottom {
		display: flex;
	}

	.goods-deal {
		flex: 1;
	}

	.goods-img {
		width: 160rpx;
		height: 160rpx;
		position: relative;

		img {
			width: 100%;
			background-size: 100%;
			height: 100%;
		}
	}

	.goods-bottom {
		width: 95%;
		margin: 0 auto;
		height: 70rpx;
		line-height: 70rpx;
	}

	.goods-btn {
		background: linear-gradient(90deg, rgba(227, 255, 150, 1), rgba(166, 255, 234, 1));
		width: 47%;
		text-align: center;
		font-size: 28rpx;
		font-weight: 700;
		border-radius: 20rpx;
		float:right;
	}

	.bottom {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		display: flex;
		background: #fff;
		z-index: 98;
		box-shadow: 0 -10rpx 10rpx rgba(0, 0, 0, 0.3);
	}

	.bottom-left {
		flex: 1;
		display: flex;
		padding: 20rpx;

		img {
			width: 60rpx;
			height: 80rpx;
			background-size: 100%;
		}
	}

	.bottom-price {
		margin-left: 40rpx;
		font-size: 40rpx;
		color: red;
		font-weight: 700;
		line-height: 110rpx;
	}

	.bottom-right {
		padding-top: 20rpx;
		flex: 1;

		img {
			width: 360rpx;
			height: 100rpx;
			background-size: 100%;
		}
	}

	.bottom-dot {
		position: absolute;
		top: 0;
		right: -20rpx;
		background: red;
		color: #fff;
		width: 32rpx;
		height: 32rpx;
		border-radius: 32rpx;
		text-align: center;
		line-height: 32rpx;
	}

	.car-content {
		position: relative;
		height: auto;
		max-height: 1200rpx;
		width: 100%;
		border-top-left-radius: 20rpx;
		border-top-right-radius: 20rpx;
		padding: 20rpx;
		overflow: scroll;
	}

	.car-close {
		width: 60rpx;
		height: 60rpx;
		position: absolute;
		top: -80rpx;
		right: 20rpx;
	}

	.car-title {
		height: 96rpx;
		line-height: 60rpx;
		margin: 0 auto;
		font-size: 28rpx;
		font-weight: 700;
	}

	.num-plus {
		width: 56rpx;
		height: 56rpx;
		font-size: 36rpx;
		text-align: center;
		font-weight: 700;
		line-height: 48rpx;
		border-radius: 10rpx;

		background: rgba(0, 35, 28, 1);
		color: rgba(166, 255, 234, 1);

	}

	.num {
		width: 80rpx;
		height: 56rpx;
		text-align: center;
		line-height: 56rpx;
		font-size: 28rpx;
	}

	.goods-num {
		display: flex;
		height: 56rpx;
		flex: 1;
		margin-left: 40rpx;
	}

	.pintuan0 {
		width: 90%;
		height: 100rpx;
		border-radius: 100rpx;
		background: linear-gradient(90deg, rgba(227, 255, 150, 1), rgba(166, 255, 234, 1));
		text-align: center;
		font-size: 26rpx;
		font-weight: 700;
		line-height: 100rpx;
		margin: auto;
	}

	.pintuan1 {
		width: 90%;
		height: 100rpx;
		line-height: 100rpx;
		display: flex;
		text-align: center;
		margin: auto;
		font-size: 26rpx;
		font-weight: 700;
	}

	.pintuan2 {
		flex: 1;
		background: linear-gradient(90deg, rgba(227, 255, 150, 1), rgba(166, 255, 234, 1));
	}

	.spec11 {
		height: 96rpx;
		line-height: 96rpx;
		font-size: 28rpx;
		font-weight: 700;
	}

	.spec222 {
		display: inline-block;
		padding: 0 20rpx;
		background: #eee;
		color: #777;
		height: 72rpx;
		line-height: 72rpx;
		text-align: center;
		border-radius: 20rpx;
		margin-right: 20rpx;
	}

	.spec-check {
		display: inline-block;
		padding: 0 20rpx;
		background: rgba(166, 255, 234, 1);
		height: 72rpx;
		line-height: 72rpx;
		text-align: center;
		border-radius: 20rpx;
		margin-right: 20rpx;
	}

	.team1 {
		width: 154rpx;
		height: 126rpx;
		background: #eee;
		border-radius: 20rpx;
		font-size: 26rpx;
		text-align: center;
		line-height: 40rpx;
		float: left;
		margin-right: 40rpx;
		font-weight: 700;
	}

	.team-check {
		width: 154rpx;
		height: 126rpx;
		background: rgba(166, 255, 234, 1);
		border-radius: 20rpx;
		font-size: 26rpx;
		text-align: center;
		line-height: 40rpx;
		float: left;
		margin-right: 40rpx;
		position: relative;
	}
	.zaixian-swiper{
		flex: 1;
		height: 126rpx;
	}
	.zaixian-item{
		height: 126rpx;
		line-height: 126rpx;
		font-size: 24rpx;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.team11 {
		height: 35rpx;
		margin-top: 18rpx;
	}

	.goods-team {
		width: 100%;
		min-height: 130rpx;
	}

	.list-right {
		display: flex;
		width: 100%;
		padding: 30rpx 0 30rpx 30rpx;
		flex: 1;
	}
	.jiaobiao{
		position: absolute;
		top: -16rpx;
		right: -12rpx;
		width: 40rpx;
		height: 40rpx;
		border-radius: 40rpx;
		background: red;
		color: #fff;
		text-align: center;
		line-height: 40rpx;
		font-size: 20rpx;
	}
	.list-right-img {
		height: 80rpx;
		display: flex;

		img {
			width: 80rpx;
			height: 80rpx;
			z-index: 98;
			background-size: 100%;
		}
	}

	.list-weipincheng {
		width: 80rpx;
		height: 80rpx;
		background: #a6ffea;
		border-radius: 80rpx;
		text-align: center;
		font-size: 28rpx;
		font-weight: 700;
		margin-left: -6rpx;
		z-index: 97;
		line-height: 80rpx;
	}

	.goods-center {
		width: 100%;
		margin: 0 auto 20rpx;
		background: #f5f8f5;
		height: 140rpx;
		border-radius: 20rpx;
		overflow: hidden;
		display: flex;
	}

	.list-right-cha {
		margin-left: 20rpx;
	}

	.list-right-price {
		flex: 1;
		text-align: right;
		line-height: 80rpx;
		color: red;
		font-size: 28rpx;
		font-weight: 700;
	}

	.list-btn {
		background: linear-gradient(90deg, #e3ff96, #a6ffea);
		width: 130rpx;
		text-align: center;
		font-size: 28rpx;
		font-weight: 600;
		border-radius: 60rpx;
		height: 60rpx;
		line-height: 60rpx;
		margin: 40rpx;
	}

	.cha11 {
		font-size: 22rpx;
		background: rgba(255, 57, 57, 0.2);
		color: red;
		display: inline-block;
		padding: 6rpx;
		border-radius: 10rpx;
		margin-bottom: 10rpx;
	}

	.checked-img {
		width: 180rpx;
		height: 20rpx;
		position: absolute;
		bottom: 0;
		left: 0;
	}

	.menu1 {
		width: 160rpx;
		height: 90rpx;
		position: relative;
		text-align: center;
		line-height: 90rpx;
	}
</style>