<template>
	<view class="container">
		<view class="utop"></view>
		<uni-nav-bar :fixed="true" class="unibar" title="Coffunity"
		
		 left-icon="home" backgroundColor="white" :border="false"  height="60px" @clickLeft="onHome"/>
		
		
		
		 <view class="loading" :style="{height:(windowHeight-statusBarHeight-50-height)+'px'}" v-if="isloading">
			<image src="https://business.coffunity.cn/upload/loading4.gif" style="width:20px;height:20px"></image>
		</view>
		<block v-else>
			<!-- <view class="head-bg" :style="{background:setColor}"></view> -->
			<view class="head-block">
				<view class="page-title-block flex flex-nowarp  box-pack-between">
					<view class="flex-grow-1 flex-y-center">
						<!-- <block v-if="teen_index==2 && systemInfo.is_waimai==1">
							<i class="iconfont icon-dizhi icon-1" style="color:#999;margin-right:0 ;"></i>
							<view class="page-title text-nowarp" @click="getWechatAddress" data-index="1">
								{{address.address||'请选择地址'}}
							</view>
						</block> -->
						<!-- <block v-if="(teen_index==1 || teen_index==3) && (systemInfo.is_hall ==1 || systemInfo.is_ziti==1)"> -->
							<!-- <i class="iconfont icon-canyin icon-1" :style="{color:setColor}"></i> -->
							<navigator url="../../menber/shop" class="page-title text-nowarp store-title">
								{{storeInfo.title || ''}} <uni-icons type="right" size="3"></uni-icons> 
							</navigator>
						<!-- </block> -->
					</view>
					<view class="flex-grow-1 flex-y-center" style="justify-content: flex-end; align-items: center;">
						
						<view  @click="onMyOrder" style="margin-right:10px;font-size:12px;font-weight:bold;">我的订单</view>
					</view>

					<!--is_ziti 自提 is_waimai 外卖  is_hall 堂食 -->
				<!-- 	<view class="por flex-grow-0"
						v-if="(systemInfo.is_hall==1||systemInfo.is_ziti==1) && systemInfo.is_waimai==1">
						<view class="item-off flex">
							<view class="flex-grow-1 flex-center" @click="bindCheck" :data-index="item.teenIndex"
								v-for="(item,index) of teen" :key="index"
								:class="item.teenIndex==teen_index||item.teenIndexTwo==teen_index?'act':''"
								:style="[item.teenIndex==teen_index||item.teenIndexTwo==teen_index?{'background-color':setColor}:'']">
								{{item.name}}
							</view>
						</view>
					</view> -->
				</view>

				<!-- <view @click="showNotice" hover-class="nav-hover" class="notice-block flex flex-y-center arr-r">
					<view class="content text-nowarp">公告：{{systemInfo.announcement || ''}}</view>
				</view> -->
			</view>

			<view :class="['main-block','flex','flex-nowarp','flex-x-between']"
				>
				<scroll-view scroll-y class="left-bar" :scroll-into-view="menuScrollIntoView" scroll-with-animation>
					<view v-for="(item,index) in goodsList" :id="`menu-${item.id}`" :key="index"
						:class="['item',currentCateId == item.id?'active':'']" @click="handleMenuTap(index,item.id)">
						
						
						
						<view class="name" >{{item.title}}</view>
						<view class="num" v-if="item.num>0">{{item.num}}</view>
						<!-- <view class="rund" :style="[currentCateId == item.id?{'background-color':setColor}:'']"></view> -->
						
					</view>
				</scroll-view>

				<view class="right-bar">
					<!-- <view class="top flex flex-nowarp flex-x-between flex-y-center"> -->
						<!-- <view class="active-cat flex flex-nowarp flex-y-center text-nowarp">
							<text class="name">{{goodsList[catActive].title}}</text>
							<text class="desc text-nowarp"
								v-if="goodsList[catActive].desc">({{goodsList[catActive].desc}})</text>
						</view> -->
						<!-- <navigator :url="`/pages/search/search?store_id=${store_id}&table_id=${table_id}`"
							class="search-btn flex flex-x-center flex-y-center flex-nowarp">
							<image src="../../static/icon_4.png" mode="aspectFit" class="icon-4"></image>
							<view class="btn-name">搜索</view>
						</navigator> -->
					<!-- </view> -->

					<scroll-view scroll-y :scroll-into-view="cateGoods" class="content" @scroll="handleGoodsScroll">
						<view :id="`cate-${item.id}`" :class="['item','goods-cat-item',index == 0?'first':'']"
							v-for="(item,index) in goodsList" :key="index">
							<view class="cat-block flex flex-nowarp flex-y-center text-nowarp">
								<text class="name">{{item.title}}</text>
								<text class="desc text-nowarp" v-if="item.desc">({{item.desc}})</text>
							</view>
							<view class="goods-list">
								<view class="goods-item flex flex-y-center flex-nowarp"
									v-for="(item2,index2) in item.goods_list" :key="index2">
									<image :src="URL+item2.thumb" mode="aspectFill" class="img"
										@click="shopDetails(item2.id)" lazy-load="true"></image>
									<view class="goods-info flex flex-column flex-x-between">
										<view class="name">{{item2.name}}</view>
										<view class="price flex-y-bottom">
											<block v-if="item2.is_rebate==1">
												<view>￥{{item2.first_price}}</view>
												<view class="textDecoration">￥{{item2.price}}</view>
											</block>
											<block v-else>
												<view>￥{{item2.price}}</view>
											</block>
										</view>
										<view class="price" v-if="item2.is_rebate==1 && item2.rebate">
											<view class="rebate-border">
												{{item2.rebate}}
											</view>
										</view>
										<view class="flex flex-x-end flex-y-center">
											<view class="spec-btn"  
												v-if="item2.is_gg == 2" @click="showSpec(item2.id)">
												
												<!-- <view class="spec-num" v-if="item2.num>0">{{item2.num}}</view> -->
												<view class="circle" >选规格</view>
												<view class="spec-num-gg" v-if="item2.num !== 0">{{item2.num}}</view>
											</view>

											<view class="goods-num-block flex flex-x-end flex-y-center" v-else
												:style="{color:setColor}">
												<!-- 		<block v-if="systemInfo.set.is_pocket==1">
												     <view class="num-btn num-btn-2 iconfont icon-jia1 gdsf"
												     	@click="changeNumShopping(item.id,item2.id,2,'goods','',item2.price,item2.many_rebate,item2.is_rebate)">
												     </view>
												</block>
												 -->
												<block>
													<view class="num-btn num-btn-1 iconfont icon-jian1"
														@click="changeNum(item.id,item2.id,1,'goods','',item2.price,item2.many_rebate,item2.is_rebate)"
														v-if="item2.num>0"></view>

													<view class="num" v-if="item2.num>0">{{item2.num}}</view>

													<view class="num-btn num-btn-2 iconfont icon-jia1 gdsf"
														@click="changeNum(item.id,item2.id,2,'goods','',item2.price,item2.many_rebate,item2.is_rebate)">
													</view>
												</block>

											</view>
										</view>
										<view class="ft24 many_rebate" v-if="item2.many_rebate>0 && item2.is_rebate==1">
											{{item2.many_rebate}}{{item2.unit}}起购
										</view>
									</view>
								</view>
							</view>
						</view>
					</scroll-view>
				</view>
			</view>

			<shopping-car v-on:catActive="bindCatActive" :carNum="carNum" :isDistance="is_distance"
				:deliveryPrice="delivery_price" :carTotal="carTotal" :carGoods="carGoods" :userInfo="userInfo"
				:eat_people="choosepeoples" @choosebag="choosebag" :checked="pocket"/>

			<view class="mask flex flex-column flex-nowarp flex-x-center flex-y-center" v-show="maskPop">
				<!-- 详情弹窗 -->
				<!-- 公告弹窗 -->
				<view class="pop-block notice-pop" v-show="noticePop">
					<view class="title">门店公告</view>
					<scroll-view scroll-y="true" class="content-block">
						<view class="content">{{systemInfo.announcement || ''}}</view>
					</scroll-view>
					<view class="sub-btn" :style="{color:setColor}" @click="showNotice">我已知晓</view>
				</view>

				<!-- 规格弹窗 -->
				<block v-if="specPop">
					<view class="pop-block spec-pop">
						<view class="title">{{goodsDetail.name}}</view>
						<scroll-view scroll-y="true" class="content-block">
							<view class="content">
								<block v-for="(item,index) in goodsDetail.edit_value" :key="index">
									<view class="spec-cat-title">
										<text>{{item.spec_name}}</text>
										<text style="font-size:24rpx;color:#aaa">（仅单选）</text>
									</view>
									<view class="spec-list flex">
										<view v-for="(spec,specIndex) in item.spec" :key="specIndex"
											@click="chooseSpec(index,specIndex)"
											:class="['spec-item',spec.active?'active':'']"
											:style="[spec.active?{'background-color':setColor,'border-color':setColor}:'']">
											{{spec.name}}
											<block v-if="spec.price">￥{{spec.price}}</block>
										</view>
									</view>
								</block>

							</view>
						</scroll-view>

						<view class="btm-block flex flex-y-baseline flex-nowarp">
							<view class="flex flex-nowarp flex-y-baseline">
								<view class="price">￥{{goodsDetail.spec_price}}</view>
								<view class="unit">/{{goodsDetail.unit}}</view>
							</view>
							<view class="choose-spec-list text-3" v-if="goodsDetail.specName">
								({{goodsDetail.specName}})</view>
							<block>
								<view class="add-car-btn" :style="{'background-color':setColor}"
									v-if="goodsDetail.num == 0"
									@click="changeNum(goodsDetail.category_id,goodsDetail.id,2,'spec',goodsDetail.many_rebate,goodsDetail.is_rebate)">
									加入购物车</view>
								<view class="goods-num-block flex flex-x-end flex-y-center" v-else
									:style="{color:setColor}">
									<view class="num-btn num-btn-1 iconfont icon-jian1"
										@click="changeNum(goodsDetail.category_id,goodsDetail.id,1,'spec',goodsDetail.many_rebate,goodsDetail.is_rebate)">
									</view>
									<view class="num">{{goodsDetail.num}}</view>
									<view class="num-btn num-btn-2 iconfont icon-jia1"
										@click="changeNum(goodsDetail.category_id,goodsDetail.id,2,'spec',goodsDetail.many_rebate,goodsDetail.is_rebate)">
									</view>
								</view>
							</block>
						</view>
					</view>
					<image src="/static/icon_5.png" mode="aspectFit" class="spec-close-btn" @click="showSpec">
					</image>
				</block>
			</view>
		</block>

		<float-modal v-if="shopId" :shopId="shopId" @modalStatusBack="handleModalBack"></float-modal>
		<!-- 2021041200077000000019093688 -->
		<page-btm-bar :active="3" />

<!-- 		<uni-popup ref="popup" type="center">
			<view class="shopping">

				<form @submit="Shoppingbag">

					<view class="shopping_title flex-center">
						购物口袋
					</view>

					<view class="shopping_number flex-center">
						<input type="number" name="pocket" placeholder-class="shopping_placeholder"
							placeholder="口袋:1(单个数字)" />
					</view>

					<view class="flex-y-center shopping_btn">
						<view class="flex-grow-1 flex-center">
							取消
						</view>
						<view class="shopping_line">

						</view>
						<button form-type="submit" class="flex-grow-1 flex-center" style="font-size:32rpx">
							确定
						</button>
					</view>

				</form>
			</view>
		</uni-popup> -->


	</view>
</template>
<script>
	import {
		mapState,
		mapGetters,
		mapMutations
	} from 'vuex'
	const app = getApp();
	const _timer = "";
	let hideLoading = true;
	import mpHtml from '@/uni_modules/mp-html/components/mp-html/mp-html'
	import shoppingCar from '@/components/shoppingCar.vue';
	export default {
		components: {
			shoppingCar
		},
		data() {
			return {
				user_xcx_info: {}, // 记录普通用户信息
				maskPop: false, //弹窗一层判断
				getPhonePop: false, //获取手机号码弹窗
				detailPop: false, //详情弹窗
				noticePop: false, //通知弹窗
				specPop: false, //规格弹窗
				carGoodsPop: false, //购物车弹窗
				carGoods: [], //购物车商品
				carNum: 0, //购物车数量
				carTotal: 0, //购物车价格
				specActive: [0, 0], //选中规格
				goodsList: [], //商品列表
				goodsDetail: {}, //商品详情
				teen: [],
				delivery_price: '0.00', //配送费
				is_distance: 1, //是否超过距离
				loading: false,
				//加载页
				cateScrollTop: 0,
				sizeCalcState: false,
				currentCateId: null, //选中分类id
				currentCateDId: null, //选中分类id
				catActive: 0, //选中分类
				catActive_act: null,
				menuScrollIntoView: 'menu-0',
				cateGoods: "",
				isState: true,
				scrollEndTimer: null,
				statusBarHeight: 0,
				windowHeight: 650,
				safeAreaInsetsBottom: 0,
				height: 0,
				heightPx: 0,
				URL: getApp().globalData.URL,
				isloading: true,
				SocketOpen: false,
				number: 0,
				lockReconnect: false,
				limit: 0,
				choosepeoples: 0, //选择的人数
				new_goodsList: [],
				scrollTop: 0,
				shopId: '',
				shoppingObj: {},
				pocket: 1,
				is_checkeds:1,
				storeInfo:null,
			}
		},

		computed: {
			...mapState(['systemInfo', 'setColor', 'store_id', 'table_id', 'userInfo', 'teen_index', 'address',
				'descFood'
			]),
			dateRange() {
				const {
					store_id,
					userInfo
				} = this;
				return {
					store_id,
					userInfo
				}
			},
			dataTask() {
				const {
					store_id,
					table_id,
					systemInfo
				} = this;
				return {
					store_id,
					table_id,
					systemInfo
				}
			},
		},

		watch: {
			systemInfo(nVal) {
				if (!this.$store.state.is_Refresh) {
					return
				}
			},
			descFood(nVal) {
				this.teen = [{
						name: nVal.food1,
						teenIndex: 1,
						teenIndexTwo: 3,
					},
					{
						name: nVal.food2,
						teenIndex: 2,
					},
				]
			},

			setColor(nVal) {
				uni.setNavigationBarColor({
					frontColor: '#ffffff',
					backgroundColor: nVal,
				})
			},

			teen_index(val) {
				console.log('----teen_index')
				// console.log("切换数据更新")
				this.getIndexInfo();
			},

			dateRange(val) {
				console.log('----dateRange')
				if (val.store_id && val.userInfo.id) {
					this.getIndexInfo();
					this.setCopy();
					this.isovertime(); 
				}
			},
		

			is_creatOrder(val) {
				this.getCarList();
			},

			dataTask(val) {
				if (val.store_id && val.table_id && val.systemInfo) {
					if (val.systemInfo.shopid) {
						this.shopId = val.systemInfo.shopid;
					}
					if (val.systemInfo.is_qian_many == 1) {
						this.Socket();
					}
				}
			},

			address(val) {
				if (val.id) {
					this.getDeliveryPrice();
				}
			},
		},

		onLoad(options) {
			// this.teen_index == 2 ? this.getDeliveryPrice() : '';
			uni.setStorageSync("lastChoose", false) //默认没有选择就餐人数
			this.BarHeight();
			uni.hideTabBar();
			this.userInfo = uni.getStorageSync('userInfo');
			
			
			
			if (this.systemInfo) {
				this.shopId = this.systemInfo.shopid;
			}
		 
			if (this.store_id) {
				this.getIndexInfo()
				this.setCopy();
				this.teen = [{
						name: this.descFood.food1,
						teenIndex: 1,
						teenIndexTwo: 3,
					},
					{
						name: this.descFood.food2,
						teenIndex: 2,
					},
				];
			}else{
				uni.navigateTo({
					url:'/shop/index/index'
				})
			}
		},

		onHide() {
			clearInterval(this._timer)
		},

		onReady() {},

		onShow() {
			if (this.goodsList.length) {
				this.getCarList()
			}
			this.teen_index == 2 ? this.MyDefaultAddress() : '';
			// diy跳转分类
			let cate_id = this.$store.state.cate_id;
			if (cate_id && this.goodsList.length) {
				var obj = this.goodsList.find((v, i) => v.id == cate_id);
				var index = this.goodsList.findIndex(item => item.id === cate_id);
				if (obj.id) {
					this.$nextTick(() => {
						this.currentCateId = obj.id; //选中分类id
						this.currentCateDId = obj.id; //选中分类id
						this.catActive = index; //选中分类
						this.cateGoods = `cate-${obj.id}`
					})
				}
			}
			if (this.store_id && this.table_id && this.systemInfo) {
				if (this.systemInfo.is_qian_many == 1) {
					this.Socket();
				}
			}
			this.SocketClose();
			if (this.store_id && this.userInfo.id) {
				this.teen_index == 1 ? this.isovertime() : ''; //距离上一次是否超时 是否选择人数
			}
			
			
		},

		onPullDownRefresh() {
			if (this.store_id) {
				this.getIndexInfo()
			} else {
				uni.stopPullDownRefresh();
			}
		},

		onShareAppMessage(e) {
			return {}
		},

		onShareTimeline() {
			return {
				title: this.systemInfo.title,
				imageUrl: this.URL + this.systemInfo.thumb,
			}
		},

		methods: {
			...mapMutations(['SET_ADDRESS', 'SET_TEEN_INDEX']),
	
			onMyOrder(e){
				uni.navigateTo({
					url:"/pages/myOrderList/myOrderList"
				})
			},
			handleModalBack(res) {
				console.log(res, '-----123')
			},
			
			onHome(e){
				uni.switchTab({
					url:'/pages/home/home'
				})
			},

			choosebag(index) {
				this.pocket = index;
			},

			openVideo() {
				let goods = this.goodsDetail;
				if (goods.feedid && goods.finder) {
					wx.openChannelsActivity({
						finderUserName: goods.finder,
						feedId: goods.feedid,
						success: () => {
							console.log("打开成功")
						}
					})
				} else {
					wx.openChannelsUserProfile({
						finderUserName: goods.finder,
						success: () => {
							console.log("打开成功")
						}
					})
				}
			},

			closeSocket() {
				uni.closeSocket();
			},

			Socket() {
				if (this.systemInfo.is_qian_many == 1) {
					app.globalData.callback = (r) => {
						let res = JSON.parse(r.data); 
						if (res.type == 'clear_list') {
							if (this.goodsList.length > 0) {
								this.carGoods = []
								this.carNum = 0
								this.carTotal = 0
								this.maskPop = false
								this.carGoodsPop = false
								let goodsList = this.goodsList
								for (let i in goodsList) {
									goodsList[i].num = 0
									for (let j in goodsList[i].goods_list) {
										goodsList[i].goods_list[j].num = 0
									}
								}
								this.goodsList = goodsList
							}
						} else if (res.type == 'ping') {
							return
						} else if (res.type == 'init_list' || res.type == 'add_cart_list') {

							this.isloading = false
							if (res.list.length == 0) {
								this.maskPop = false
								this.carGoodsPop = false
							}

							this.computGoodsNum(res.list, res.total_price, this.number)

						}
					}
					setTimeout(() => {
						this.socktopentInit()
					}, 1000)
				}
			},

			// 初始化
			socktopentInit() {
				var datas = {
					group: this.table_id,
					type: 'init',
					store_id: this.store_id,
					table_id: this.table_id,
				}
				app.sendSocketMessage(JSON.stringify(datas)).then(res => {
					console.log('初始化！');
				})
			},

			// 重新链接
			SocketClose() {
				app.globalData.closeCallback = (r) => {
					console.log(r, "我已断开")
					if (this.systemInfo.is_qian_many == 1) {
						this.reconnect();
					}
				}
			},
			// 断开重新链接30次之后更新
			reconnect() {
				if (this.lockReconnect) return;
				this.lockReconnect = true;
				clearTimeout(this.timer)
				if (this.limit < 30) {
					this.timer = setTimeout(() => {
						app.initSocket();
						app.globalData.onSocketOpen = (r) => {
							this.socktopentInit()
						}
						this.lockReconnect = false;
					}, 5000);
					this.limit = this.limit + 1;
				}
			},

			// 获取高度
			BarHeight() {
				var _this = this;
				uni.getSystemInfo({
					success: function(e) {
						// console.log(e,"getSystemInfo")
						// #ifdef MP-WEIXIN
						var custom = uni.getMenuButtonBoundingClientRect();
						_this.height = custom.height + 3 * (custom.top - e.statusBarHeight);
						// #endif
						// 导航栏高度=状态栏高度+标题栏高度，标题栏高度=胶囊按钮高度+3*(胶囊按钮Top-状态栏高度)
						// #ifdef MP-ALIPAY
						var custom = e.titleBarHeight;
						// 48
						_this.height = custom;
						// #endif
						// console.log(e, "getSystemInfo")
						// 36
						_this.statusBarHeight = e.statusBarHeight;
						_this.windowHeight = e.windowHeight;

						// #ifdef MP-ALIPAY
						_this.heightPx = 350 / 750 * e.windowWidth;
						// #endif

						// #ifdef MP-WEIXIN
						_this.heightPx = 370 / 750 * e.windowWidth;
						// #endif  

						// #ifdef MP-WEIXIN
						_this.safeAreaInsetsBottom = e.screenHeight - e.safeArea.bottom;
						// #endif

						// #ifdef MP-ALIPAY
						let model = e.model,
							hg = 0;
						let iphoneArr = new Set(['iPhone X', 'iPhone 11', 'iPhone 11 Pro Max', 'iPhone XR',
							'iPhone 12', 'iPhone 13'
						]); //机型
						if (iphoneArr.has(model)) hg = 36;
						_this.safeAreaInsetsBottom = hg;
						// #endif
					}
				})
			},

			getShop(e) {
				uni.navigateTo({
					url: "../../shop/index/index"
				})
			},
			// 赋能
			setCopy() {
				if (getApp().globalData.isApp) {
					this.$http.request('xcx/funeng', {
						store_id: this.store_id,
					}, "", "", hideLoading).then(res => {
						getApp().globalData.isApp = false
						let way_power = res.data.way_power;
						if (!way_power) {
							return
						}
						let content = way_power.replace(/<br\s*\/?\s*>/ig, "\n");
						uni.setClipboardData({
							data: content,
							success: function(r) {
								console.log('success', r);
							}
						});
					})
				}
			},

			bindCatActive(e) {
				this.currentCateDId = e;
				this.currentCateId = e;
				this.cateGoods = `cate-${e}`
			},

			// 选择外卖地址
			bindCheck(e) {
				let index = e.currentTarget.dataset.index;
				index = index == 1 ? (this.systemInfo.is_hall == 1 ? index : this.systemInfo.is_ziti == 1 ? 3 : index) :
					index;
				this.SET_TEEN_INDEX(index);
				// 从默认地址获取配送费
				if (index == 2) {
					this.getDeliveryPrice();
				}
				//判断如果切换到点餐且没有选就调走
				if (this.teen_index == 1) {
					this.isovertime(); //距离上一次是否超时
				}
			},

			// 获取默认地址
			MyDefaultAddress() {
				if (this.address.id) {
					this.getDeliveryPrice();
				} else {
					this.$http.request('xcx/MyDefaultAddress', {
						user_id: this.userInfo.id,
					}, "", "", hideLoading).then(res => {
						this.SET_ADDRESS(res.data)
						// console.log("getDeliveryPrice")
						this.getDeliveryPrice();
					}).catch(err => {})
				}
			},

			// 获取配送费
			getDeliveryPrice() {
				this.$http.request('xcx/getDeliveryPrice', {
					lat: this.address.lat || '',
					lng: this.address.lng || '',
					store_id: this.store_id,
				}, "", "", hideLoading).then(res => { 
					let distance = Number(res.data.distance);
					if (distance) {
						if (!distance) {
							this.is_distance = 2;
							return
						}
						this.delivery_price = Number(res.data.delivery_price);
						if (!this.systemInfo.set.number || !distance) {
							this.is_distance = 1;
							return
						}
						// 如果大于商家距离is_distance = 2 提出超出距离
						if (distance > this.systemInfo.set.number) {
							this.is_distance = 2;
						} else {
							this.is_distance = 1;
						}
					} else {
						this.is_distance = 3;
					}
				}).catch(err => {})
			},

			// 选择外卖地址
			getWechatAddress: function(e) {
				uni.navigateTo({
					url: '../address/address?teen_index=1'
				})
			},

			//获取首页分类 商品列表
			getIndexInfo() {
				// console.log("门店数据更新")
				this.$http.request('xcx/system', {
					store_id: uni.getStorageSync('store_id'),
					table_id: uni.getStorageSync('table_id'),
				}).then(res => {
					this.sizeCalcState = false;
					let is_rebate = 2
					
					this.storeInfo=res.data;
					try {
						is_rebate = res.data.set.is_rebate
					} catch (err) {
						console.log(err)
					}
					
					console.log('res',res);
				 
					if (is_rebate == 1) {
						this.getCategoryList()
						return false
					} 
					this.$http.request('xcx/index', {
						store_id: this.store_id,
						state: Number(this.teen_index),
					}, "", "", hideLoading).then(res => {
						uni.stopPullDownRefresh();
						let list = res.data;
						this.goodsList = list;   
						
						// diy跳转分类
						let cate_id = this.$store.state.cate_id;
						if (cate_id) {
							var obj = list.find((v, i) => v.id == cate_id);
							var index = list.findIndex(item => item.id === cate_id);
							if (obj.id) {
								this.currentCateId = obj.id; //选中分类id
								this.currentCateDId = obj.id; //选中分类id
								this.catActive = index; //选中分类
								this.cateGoods = `cate-${obj.id}`
							}
						}else{
							if(list.length>0){
								var obj=list[0];
								this.currentCateId = obj.id; //选中分类id
								this.currentCateDId = obj.id; //选中分类id
								this.catActive = index; //选中分类
								this.cateGoods = `cate-${obj.id}`
							}
						}
						
						this.getCarList();
					}).catch(err => {
						uni.stopPullDownRefresh()
					})
				})
			},
			//获取购物车数据
			getCarList() {
				var url = 'xcx/cart_list',
					datas; 
					console.log(this.systemInfo);
				if (this.systemInfo.is_qian_many == 1) {
					return
				}
				
				datas = {
					user_id: this.userInfo.id,
					store_id: this.store_id,
				}
				if (this.userInfo.id && this.store_id) {
					this.$http.request(url, datas, "", "", hideLoading).then(res => {
						if(res.data.list<=0){
							this.pocket = 1
						}
						let arr = this.$utils.removal(res.data.list)
						this.new_list = res.data.new_list;
						this.computGoodsNum(arr, res.data.total_price, 0, res.data.new_list)
						this.isloading = false
						
						
					}).catch(err => {})
				}
			},

			//根据购物车列表计算购物车数据
			computGoodsNum(list, total_price, spec_num, new_list = []) {
				if (this.goodsList.length <= 0) {
					return
				}
				let num = 0
				//计算商品数量
				let goodsList = this.goodsList;
				for (let i in goodsList) {
					goodsList[i].num = 0
					for (let j in goodsList[i].goods_list) {
						goodsList[i].goods_list[j].num = 0
					}
				}
				for (let i in list) {
					num += list[i].num
					for (let j in goodsList) {
						if (list[i].category_id == goodsList[j].id) {
							for (let n in goodsList[j].goods_list) {
								if (list[i].goods_id == goodsList[j].goods_list[n].id) {
									goodsList[j].num += list[i].num
									goodsList[j].goods_list[n].num += list[i].num
									break
								}
							}
							break;
						}
					}
				}
				this.goodsList = goodsList
				this.carNum = num
				this.carGoods = new_list
				this.$store.commit('SET_CARGOODS', new_list) //监听购物车是否有变化
				this.carTotal = total_price
				if (this.detailPop || this.specPop) {
					this.goodsDetail.num = spec_num
				}
			},
			/**
			 * 改变商品数量
			 * @category_id:分类id
			 * @goods_id:商品id
			 * @type:1减少 2增加
			 * @data_from 购物车列表传 'car' 规格弹窗传 'spec' 无规格传 'goods' 否则不传
			 * @car_index 购物车下标 data_form = 'car'传
			 * @goods_price 商品价格 data_from = 'goods' 传
			 * @many_rebate 起购数量  is_rebate=1/2 是/否起购
			 * */

			changeNum(category_id, goods_id, type, data_from, car_index, goods_price, many_rebate = '', is_rebate = '',
				idx = '') {
				/* pocket 购物口袋
				  goodsList 数据列表
				  idx 如果是有从购物车加入 */
				let money = 0,
					pocket = this.pocket,
					carGoods,
					num = 0,
					spec = '',
					new_list = this.new_list,
					carItem = false;
				    carGoods = this.carGoods;
				pocket = idx === '' ? pocket : idx;
				if (type == 2) {
					for (let i of new_list) {
						if (i.pocket == pocket) {
							carGoods = i.list;
						}
					}
				}
				if (type == 1) {
					function getData(new_list,pocket,goods_id) {
	                    let as = false
						for (let i of new_list) {
							for(let j of i.list){	
								if (i.pocket == pocket && j.goods_id == goods_id) {
									  as = true
								}
							}
						}
						return as	
					}
					// 判断当前选中的购物口袋是否选中并且还有产品
					let isAllStudentType = getData(new_list,pocket,goods_id)
					if (isAllStudentType) {
						for (let i of new_list) {
						  if (i.pocket == pocket) {
						        carGoods = i.list;
						   }
						}
					} else {
						for (let i of new_list) {
							for (let j of i.list) {
								if (j.goods_id == goods_id) {
									pocket = i.pocket
									carGoods = i.list
								}
							}
						}
					}
				}
				if (data_from == 'car') {
					//购物车规格
					carItem = carGoods[car_index]
					spec = carItem.spec || ''
					money = carItem.price
				} else if (data_from == 'spec') {
					let specArr = []
					let specList = this.goodsDetail.edit_value
					for (let i in specList) {
						for (let j in specList[i].spec)
							if (specList[i].spec[j].active) {
								specArr.push(specList[i].spec_name + ':' + specList[i].spec[j].name)
								break
							}
					}
					if (specArr.length != specList.length) {
						uni.showToast({
							title: "请选择规格",
							icon: 'none'
						})
						return false
					} else {
						spec = specArr.join(',')
						money = this.goodsDetail.spec_price
						// 调用 showSpec 方法
						   this.showSpec(goods_id);
					}
				} else if (data_from == 'goods') {
					//无规格商品
					spec = ''
					money = goods_price
				}
				if (data_from != 'car') {
					for (let i in carGoods) {
						if (carGoods[i].goods_id == goods_id && carGoods[i].spec == spec) {
							carItem = carGoods[i]
							break
						}
					}
				}
				num = carItem ? carItem.num : 0
				if (type == 1) {
					if (num > 0) {
						// 起购
						if (many_rebate > 0 && is_rebate == 1) {
							if (many_rebate >= num) {
								num = num - many_rebate;
							} else {
								num--;
							}
						} else {
							num--
						}
					} else {
						return false
					}
				} else if (type == 2) {
					// 起购
					if (many_rebate > 0 && is_rebate == 1) {
						if (many_rebate <= num) {
							num++
						} else {
							num = num + many_rebate;
						}
					} else {
						num++
					}
				} else {
					return false
				}
				let datas = {
					user_id: this.userInfo.id,
					category_id: category_id, //分类id
					goods_id: goods_id, //是	string	商品id
					num: num <= 0 ? 0 : num, //是	string	购买数量
					table_id: this.table_id, //是	string	桌号
					spec: spec, //是	string	规格（json），有的传
					money: money,
					group: this.table_id,
					type: 'add_cart',
					store_id: this.store_id,
					pocket: pocket
				}
				if (this.systemInfo.is_qian_many == 1 && app.globalData.readyReset == 1) {
					app.sendSocketMessage(JSON.stringify(datas)).then(res => {
						this.number = num;
					})
				} else {
					this.$http.request('xcx/add_cart', datas, 'POST', false, true).then(res => {
						
						if (res.data.list.length == 0 && data_from == 'car') {
							this.pocket = 1 
							this.maskPop = false
							this.carGoodsPop = false
						}
						
						let arr = this.$utils.removal(res.data.list)
						this.new_list = res.data.new_list;
						
						this.computGoodsNum(arr, res.data.total_price, num, res.data.new_list)
						
						 
						  }).catch(err => {})
				}
			},


			//清空购物车
			clearCar() {
				// console.log("ggg")
				this.pocket = 1
				this.new_list = []
				this.carGoods = []
				this.$store.commit('SET_CARGOODS', []) //监听购物车是否有变化
				this.carNum = 0
				this.carTotal = 0
				this.maskPop = false
				this.carGoodsPop = false
				let goodsList = this.goodsList
				for (let i in goodsList) {
					goodsList[i].num = 0
					for (let j in goodsList[i].goods_list) {
						goodsList[i].goods_list[j].num = 0
					}
				}
				this.goodsList = goodsList
				// 多人点餐开启
				if (this.systemInfo.is_qian_many == 1 && app.globalData.readyReset == 1) {
					let datas = {
						group: this.table_id,
						type: "clear",
						store_id: this.store_id,
						table_id: this.table_id,
					}
					app.sendSocketMessage(JSON.stringify(datas)).then(res => {
						// console.log('发送成功！');
					})
				}
			},

			//拼接图片全路径
			getImgSrc(src) {
				if (src) {
					return this.$utils.getImgSrc(src)
				}
			},

			//新增跳转详情
			shopDetails(e) {
				uni.navigateTo({
					url: '/menber/goods_detail?id=' + e
				})
			},

			//显示商品详情弹窗
			showGoodsDetail(index, index2) {
				if (this.detailPop) {
					this.maskPop = false
					this.detailPop = false
					return false
				}
				this.goodsDetail = JSON.parse(JSON.stringify(this.goodsList[index].goods_list[index2]))
				this.goodsDetail.description = this.goodsList[index].goods_list[index2].description.replace(/\<img/gi,
					'<img style="max-width:100%;height:auto" ')
				this.goodsDetail.category_id = this.goodsList[index].id
				this.maskPop = true
				this.detailPop = true
			},

			//显示公告详情
			showNotice() {
				this.maskPop = !this.maskPop
				this.noticePop = !this.noticePop
			},

			//显示规格弹窗
			showSpec(goods_id) {
				if (this.specPop) {
					this.maskPop = false
					this.specPop = false
					return false
				}
				this.$http.request('xcx/goodinfo', {
					goods_id: goods_id
				}, "", "", hideLoading).then(res => {
					let info = res.data.goods
					let edit_value = info.edit_value
					for (let i in edit_value) {
						for (let j in edit_value[i].spec) {
							edit_value[i].spec[j] = {
								'name': edit_value[i].spec[j],
								active: false
							}
						}
					}
					info.edit_value = edit_value
					info.spec_price = info.price
					info.num = 0
					info.specName = ""
					this.goodsDetail = info
					this.maskPop = true
					this.specPop = true
					this.detailPop = false
				}).catch(err => {})
			},
			
			//选择规格
			chooseSpec(index, specIndex) {
				let spec = this.goodsDetail.edit_value[index].spec
				for (let i in spec) {
					if (i == specIndex) {
						spec[i].active = true
					} else {
						spec[i].active = false
					}
				}
				this.goodsDetail.edit_value[index].spec = spec
				this.goodsDetail.num = 0
				this.computSpecPrice()
			},
			
			//计算规格价格
			computSpecPrice() {
				let edit_value = this.goodsDetail.edit_value
				let specNameArr = [],
					carSpecArr = []
				for (let i in edit_value) {
					for (let j in edit_value[i].spec) {
						if (edit_value[i].spec[j].active) {
							specNameArr.push(edit_value[i].spec[j].name)
							carSpecArr.push(edit_value[i].spec_name + ':' + edit_value[i].spec[j].name)
							break
						}
					}
				}
				let specName = specNameArr.join(":")
				this.goodsDetail.specName = specNameArr.join(',')
				let spec = this.goodsDetail.spec
				for (let i in spec) {
					if (spec[i].spec == specName) {
						this.goodsDetail.spec_price = this.userInfo.is_vip == 1 ? spec[i].growth : spec[i].growth
						break
					}
				}
				let carGoods = this.carGoods
				carSpecArr = carSpecArr.join(",")
				for (let i in carGoods) {
					if (this.goodsDetail.id == carGoods[i].goods_id && carSpecArr == carGoods[i].spec) {
						this.goodsDetail.num = carGoods[i].num
						break
					}
				}
			},

			//选择分类
			handleMenuTap(index, id) {
				// console.log(index, id)
				if (!this.sizeCalcState) {
					this.calcSize()
				}
				this.catActive = index;
				this.catActive_act = index;
				this.currentCateId = id;
				this.currentCateDId = id;
				this.cateGoods = `cate-${id}`
			},

			// 商品滚动
			async handleGoodsScroll({
				detail
			}) {
				// console.log('商品滚动',detail)
				if (!this.sizeCalcState) {
					this.calcSize()
				}
				var {
					scrollTop
				} = await detail;

				if (this.scrollEndTimer) {
					clearTimeout(this.scrollEndTimer);
					this.scrollEndTimer = null;
				}
				this.scrollEndTimer = setTimeout(() => {
					let deltaY = this.scrollTop - scrollTop;
					this.scrollTop = scrollTop;
					// console.log(this.goodsList[this.catActive].top,scrollTop,deltaY,"scrollTop")
					// scrollfx<0 下滚动 ,下滚动同时分类的top 大于滚动条时候，说明滚动下面商品不够，退出自动切换分类。
					if (deltaY < 0 && this.goodsList[this.catActive].top >= scrollTop) {
						return
					}
					let tabs = this.goodsList.filter(item => item.top <= Math.floor(scrollTop + 10)).reverse();
					// console.log(tabs)
					if (tabs.length > 0) {
						this.currentCateId = tabs[0].id;
						this.currentCateDId = tabs[0].id;
						this.catActive = tabs[0].catActive;
						this.menuScrollIntoView = `menu-${tabs[0].id}`;
						this.catActive_act = null;
					}
				}, 300);
			},

			calcSize() {
				let h = 10;
				this.goodsList.forEach((item, index) => {
					let view = uni.createSelectorQuery().select(`#cate-${item.id}`)
					view.fields({
						size: true
					}, data => {
						item.top = Math.floor(h);
						h += data.height
						item.bottom = h
						item.catActive = index
					}).exec()
				})
				this.sizeCalcState = true
			},

			//是否超时
			isovertime() {
				let lastpageChoose = uni.getStorageSync("lastChoose"); //上个页面是否选择了
				let teenIndexs = this.teen_index; //等于1是点餐 2是外卖
				//选择的人数
				// console.log(this.choosepeoples, "this.choosepeoples")
				this.$http.request('xcx/eat_people_time', {
					store_id: this.store_id,
					user_id: this.userInfo.id,
				}).then(res => {
					if (res.code == "200") {
						//先判断是否开启
						// console.error(res.data)
						if (res.data.eat_open == 1 && this.teen_index == 1) {
							//首先判断是否开启选择人数就餐且是点餐的情况
							if (res.data.eat_open_time == 1) { //判断时间开关是否开启1开启 0关闭
								if (res.data.on_time == 1 && !lastpageChoose) { //on_time 1超过 2没超过
									uni.navigateTo({
										url: '../../menber/choose_people'
									})
								}
								if (res.data.on_time == 2) {
									console.log(this.choosepeoples, "this.choosepeoples")
									this.choosepeoples = 0;
								}
							} else { //关闭时间开关需重新选择
								if (!lastpageChoose) {
									uni.navigateTo({
										url: '../../menber/choose_people'
									})
								}
							}
						}
					}
				}).catch((res) => {
					uni.showToast({
						title: res.message,
						icon: 'none'
					})
				});
			},
			// 获取商品分类
			getCategoryList() {
				this.$http.request('yy/xcx_index', {
					store_id: this.store_id,
					state: Number(this.teen_index),
				}).then(res => {
					// console.log("商品分类", res)
					this.goodsList = res.data
					if (res.data.length > 0) {
						this.currentCateId = res.data[0].id
						this.getCategoryGoods(res.data[0].id, 0, res.data.length)
					}

				}).catch(err => {

				})
			},
			// 获取指定分类商品
			getCategoryGoods(category_id, index, len) {
				// console.log('获取指定分类商品', category_id)
				//如果已经请求过商品不再重复请求
				if (this.goodsList[index].goods_list) {
					return false
				}
				this.$http.request('yy/xcx_detail', {
					store_id: this.store_id,
					state: Number(this.teen_index),
					category_id,
				}).then(res => {
					// console.log("分类商品")
					uni.stopPullDownRefresh();
					this.goodsList[index].goods_list = res.data
					if (len - index > 1) {
						this.getCategoryGoods(this.goodsList[index + 1].id, index + 1, len)
					} else if (len - index == 1) {
						// console.log('123456')
						// diy跳转分类
						let cate_id = this.$store.state.cate_id;
						if (cate_id) {
							var obj = this.goodsList.find((v, i) => v.id == cate_id);
							var activeIndex = this.goodsList.findIndex(item => item.id === cate_id);
							if (obj.id) {
								this.currentCateId = obj.id; //选中分类id
								this.currentCateDId = obj.id; //选中分类id
								this.catActive = activeIndex; //选中分类
							}
						}
						this.getCarList();
					}

				}).catch(err => {
					uni.stopPullDownRefresh();
				})


			},
		}
	}
	// function removal(arr) {
	//         var newArr=[];
	//           arr.forEach(item => {
	//           var dataItem = item;
	//             if(newArr.length>0) {
	//                 var filterValue = newArr.filter(v => {
	//                   return v.goods_id == dataItem.goods_id
	//                 })
	//                 if(filterValue.length>0){
	//                     newArr.forEach(n => {
	//                       if( n.goods_id == filterValue[0].goods_id){
	//                           n.num = filterValue[0].num + dataItem.num
	//                       } 
	//                     })
	//                 }else{
	//                     newArr.push(dataItem)
	//                 }
	//             }else{
	//                 newArr.push(dataItem)
	//             }
	//         })
	//         return newArr
	// }
</script>

<style lang="scss">
	@import url("./index.css");
</style>
