<template>
	<view class="u-wrap u-font-14 bg-gray">
		<template v-if="data.loading||data.noLogin">
			<my-skeleton @skeletonClick="skeletonClick"></my-skeleton>
		</template>
		<template v-else>
			<view class="fixed top bg-fff u-flex u-flex-row">
				<template v-if="true">

					<view class="u-flex-1   u-flex u-flex-row" style="overflow-x: scroll;">
						<scroll-view v-if="!isSearch" scroll-x scroll-with-animation :scroll-left="tabsEle.scrollLeft"
							class="u-tab-view content-scroll u-flex-row u-flex-1" style="white-space: nowrap;">
							<view class="u-flex u-flex-row">
								<view v-for="(item,index) in layoutData.category.list" :key="index" class="u-tab-item"
									:class="[layoutData.category.sel == index ? 'u-tab-item-active' : '','u-tab-item'+index]"
									@tap.stop="changeCategorySel(index)">
									<text class="u-line-1 u-font-14">{{item.name}}</text>
								</view>
							</view>
						</scroll-view>
					</view>
					<view class="search-box u-flex u-col-center color-666">
						<view class="u-flex u-col-center" @click="chooseTable">
							<view class="u-flex  u-col-center">
								<image src="/pagesCreateOrder/static/images/icon-table.svg" mode=""
									style="width: 20px;height: 20px;"></image>
							</view>
							<view class="u-m-r-12  font-14 no-wrap">
								<view class="u-flex" v-if="data.table.name">
									<text class="font-bold u-m-r-4 no-wrap">
										{{data.table.name}}
									</text>
									<view class="u-flex" @click.stop="resetTable">
										<up-icon name="close-circle" color="rgb(250,173,40)" bold=""
											:size="14"></up-icon>
									</view>
								</view>

								<text class="no-wrap" v-else>选择桌台</text>
							</view>
						</view>

						<view class="u-flex u-col-center" @click="toOrder">
							<view class="u-flex ">
								<up-icon name="order" size="24"></up-icon>
							</view>
							<view class="u-m-r-12">已点订单</view>
						</view>

						<view class="u-flex u-col-center" @click="changePop('search',true)">
							<view class="u-flex ">
								<up-icon name="search" size="24"></up-icon>
							</view>
							<view class="">搜索</view>
						</view>
						<view class="u-flex u-col-center u-m-l-10" @click="loginShow">
							<view class="u-flex ">
								<up-icon name="account" size="24"></up-icon>
							</view>
							<view class="">登录</view>
						</view>
					</view>
				</template>

				<!-- <view class="search-box u-flex u-col-center color-666">
					<view class="u-flex u-col-center" @click="chooseTable">
						<view class="u-flex  u-col-center">
							<image src="/pagesCreateOrder/static/images/icon-table.svg" mode=""
								style="width: 20px;height: 20px;"></image>
						</view>
						<view class="u-m-r-12  font-14">
							<view class="u-flex" v-if="data.table.name">
								<text class="font-bold u-m-r-4">
									{{data.table.name}}
								</text>
								<view class="u-flex" @click.stop="resetTable">
									<up-icon name="close-circle" color="rgb(250,173,40)" bold="" :size="14"></up-icon>
								</view>
							</view>

							<text v-else>选择桌台</text>
						</view>
					</view>

					<view class="u-flex u-col-center" @click="toOrder">
						<view class="u-flex ">
							<up-icon name="order" size="24"></up-icon>
						</view>
						<view class="u-m-r-12">已点订单</view>
					</view>

					<view class="u-flex u-col-center" @click="changePop('search',true)">
						<view class="u-flex ">
							<up-icon name="search" size="24"></up-icon>
						</view>
						<view class="">搜索</view>
					</view>
					<view class="u-flex u-col-center u-m-l-10" @click="loginShow">
						<view class="u-flex ">
							<up-icon name="account" size="24"></up-icon>
						</view>
						<view class="">登录</view>
					</view>
				</view> -->
			</view>
			<template v-if="!isSearch">

				<swiper :current="layoutData.current" :indicator-dots="false" :autoplay="false" :interval="3000"
					@transition="animationStart" @animationfinish="animationfinish" :duration="300"
					style="width: 100vw;height: 100vh;">
					<swiper-item v-for="(item,index) in layoutData.list" :key="index">
						<view class="bg-gray swiper-item-box h-100 u-flex u-flex-col" :style="computedSwiperItemStyle">
							<view :style="zhanweiStyle"></view>
							<template v-if="item.productList.length>0">
								<view class="item-container  u-flex-1" :class="['layout-'+item.padLayoutCode]">
									<view :class="['div'+(goodsIndex+1)]"
										v-for="(goodsItem, goodsIndex) in item.productList" :key="goodsIndex">
										<cart-goods-item @chooseGuige="chooseGuige($event,goodsIndex)" :layout="layout.sel"
											@showDetail="showDetail(goodsItem)" :windowWidth="sysInfo.windowWidth"
											:windowHeight="sysInfo.windowHeight"
											@add="goodsUpdate($event,goodsIndex,true)"
											@reduce="goodsUpdate($event,goodsIndex,false)" :index="index"
											:data="goodsItem"></cart-goods-item>

									</view>
								</view>
							</template>
							<template v-else>
								<view class="u-p-30">
									<my-img-empty tips="该分类下暂无商品"></my-img-empty>
								</view>

							</template>

						</view>
					</swiper-item>

				</swiper>

			</template>
			<template v-else>
				<swiper :indicator-dots="false" :autoplay="false" :interval="3000" :duration="300"
					style="width: 100vw;height: 100vh;">
					<template v-if="searchResult.length>0">
						<swiper-item v-for="(item,index) in searchResult" :key="index">
							<view class="bg-fff swiper-item-box h-100 u-flex u-flex-col"
								:style="computedSwiperItemStyle">
								<view :style="zhanweiStyle"></view>
								<view class="item-container  u-flex-1" :class="['layout-'+item.padLayoutCode]">
									<view :class="['div'+(goodsIndex+1)]"
										v-for="(goodsItem, goodsIndex) in item.productList" :key="goodsIndex">

										<cart-goods-item @chooseGuige="chooseGuige($event,goodsIndex)" :layout="layout.sel"
											@showDetail="showDetail(goodsItem)" :windowWidth="sysInfo.windowWidth"
											:windowHeight="sysInfo.windowHeight"
											@add="goodsUpdate($event,goodsIndex,true)"
											@reduce="goodsUpdate($event,goodsIndex,false)" :index="index"
											:data="goodsItem"></cart-goods-item>

									</view>
								</view>

							</view>
						</swiper-item>
					</template>

					<swiper-item v-else>
						<view class="bg-fff swiper-item-box h-100 u-flex u-flex-col"
							:style="computedSwiperItemStyle">
							<view :style="zhanweiStyle"></view>
							<my-img-empty v-if="!searchResult.length" tips="未搜索到相关商品"></my-img-empty>
						
						</view>
					</swiper-item>

				</swiper>
			</template>
			<view class="u-fixed position-all" style="z-index: 999;" v-if="!canXiadan" @click="xiadanClick"></view>


			<view class="bottom w-full" v-if="instance">
				<my-car @updateSafeBottom="updateSafeBottom" :instance="instance" @updateCart="getCart"
					:sysInfo="sysInfo" :isCreateOrderToDetail="isCreateOrderToDetail" @updateNumber="carsNumberChange"
					:user="data.vipUser" :masterId="data.masterId" :table="data.table" :data="cars"
					@clear="onClearCart"></my-car>
			</view>
		</template>



		<!-- 搜索 -->
		<pop-search @search="search" v-model:show="popup.search"></pop-search>
		<!-- 商品详情 -->
		<pop-goods-detail v-model:show="popup.goodsDetail" :goods="popup.data"></pop-goods-detail>
		<!-- 选择规格 -->
		<guige-model @update-sku="updateSkuSel" @confirm="guigeConfirm" ref="chooseGuigeModel" :goodsData="selGoods"
			:title="guigeModelData.title" :sku-map="guigeModelData.chooseGoods.skuMap"
			:skus="guigeModelData.chooseGoods.skus"></guige-model>
		<!-- 添加附加费 -->
		<my-surcharge @confirm="surchargeConfirm" ref="surcharge" title="添加附加费"></my-surcharge>
		<!-- 登录弹窗 -->
		<my-login v-model="modal.login" @loginSuccess="loginSuccess"></my-login>

	</view>
	<up-modal title="提示" content="该台桌购物车里有商品，是否清除该台桌里的商品?" :show="modal.clear" showCancelButton closeOnClickOverlay
		@confirm="confirmModelConfirm" @cancel="confirmModelConfirm('cancel')" @close="setModalShow('clear',false)"
		width="300px"> </up-modal>
</template>
<script setup>
	import _ from 'lodash';
	import * as Api from '@/http/yskApi/Instead.js'
	import * as padApi from '@/http/yskApi/pad.js'
	import {
		$table,
		$choseTable,
		$returnTableDetail
	} from '@/http/yskApi/table.js'
	import {
		$tbShopCategory
	} from '@/http/yskApi/goods.js'
	import util from './util.js';
	import color from '@/commons/color.js';
	import guigeModel from './components/guige'
	import cartGoodsItem from './components/cart-goods-item.vue'
	import mySurcharge from './components/surcharge'
	import mySkeleton from './components/skeleton'
	import popSearch from './components/pop-search.vue'
	import popGoodsDetail from './components/pop-goods-detail.vue'
	import {
		$getProductDetail,

	} from '@/http/yskApi/goods.js'
	import {
		onLoad,
		onReady,
		onShow,
		onPageScroll,
		onPullDownRefresh
	} from '@dcloudio/uni-app';
	import {
		onBeforeUnmount,
		computed,
		reactive,
		ref,
		nextTick,
		getCurrentInstance,
		watch,
		onMounted
	} from 'vue';
	import myCar from './components/car'
	import go from '@/commons/utils/go.js';
	import infoBox from '@/commons/utils/infoBox.js';
	import {
		getNowCart
	} from '@/pagesCreateOrder/util.js'
	import {
		$returnUseType,
		returnSelCategotyGoods,
		returnLayoutPage,
		returnPrveId,
		returnNextId
	} from './util.js'
	import {
		$productCategory,
		$layoutpage
	} from '@/http/yskApi/pad.js'
	import {
		tbShopInfo
	} from '@/http/yskApi/user.js'
	import {
		hasPermission
	} from '@/commons/utils/hasPermission.js'
	import {
		customNavHeight
	} from '@/commons/$data.js'
	import {
		getElRect
	} from '@/commons/utils/safe-bottom.js'



	function toOrder() {
		go.to('PAGES_ORDER_INDEX')
	}

	const popup = reactive({
		search: false,
		goodsDetail: false,
		data: {}
	})

	function showDetail(goods) {
		console.log(goods);
		changePop('goodsDetail', true, goods)
	}

	function changePop(key, show = true, data) {
		popup[key] = show
		console.log(data);
		popup.data = data
		if (!show) {
			data[key] = ''
			popup.data = {}
		}
	}

	const zhanweiStyle = reactive({
		style: ''
	})
	let safeBottom = ref(20)

	function updateSafeBottom(e) {
		// safeBottom.value = e.height + 16
	}
	const computedSwiperItemStyle = computed(() => {
		return {
			'padding-bottom': safeBottom.value + 'px'
		}
	})

	function tabsChange(e) {
		data.current = e.index
	}
	const modal = reactive({
		login: false,
		key: '',
		clear: false,
		data: ''
	})
	let canXiadan = ref(false)
	async function xiadanClick() {
		try {
			canXiadan.value = await hasPermission('允许下单')
		} catch (e) {
			modal.login = true
			//TODO handle the exception
		}
	}

	function loginShow() {
		modal.login = true
	}

	function loginSuccess() {
		data.noLogin = false
		modal.login = false
		init()
	}

	function skeletonClick() {
		// modal.login = true
		go.to('PAGES_LOGIN')
	}
	let instance = ref();
	instance.value = getCurrentInstance()
	//临时菜
	const lingshi = reactive({
		show: false
	})
	//附加费
	const extraFee = reactive({
		show: false
	})


	const cars = reactive([])
	const layout = reactive({
		listMap: {
			default: {
				size: 4
			},
			bigOne: {
				size: 1
			}
		},
		sel: 'default'
	})
	const data = reactive({
		loading: true,
		noLogin: true,
		scrollTop: 0, //tab标题的滚动条位置
		oldScrollTop: 0,
		current: 0, // 预设当前项的值
		menuHeight: 0, // 左边菜单的高度
		menuItemHeight: 0, // 左边菜单item的高度
		itemId: '', // 栏目右边scroll-view用于滚动的id
		tabbar: [],
		allGoods: [],
		selCategotyGoods: [],
		menuItemPos: [],
		arr: [],
		scrollRightTop: 0, // 右边栏目scroll-view的滚动条高度
		timer: null, // 定时器
		topZhanwei: 136 + 24,
		// 选择用户
		vipUser: {
			id: "",
		},
		//餐桌号
		masterId: "",
		table: {
			tableId: ""
		},

	})

	// 获取账号信息
	let $shop = ref({})
	async function getTbShopInfo() {
		const res = await tbShopInfo()
		$shop.value = res
		const useType = data.table.status == 'using' ? data.table.useType : $returnUseType(res)
		uni.setStorageSync('useType', useType)
		console.log(res);
		return res
	}


	function scanCode() {
		// 只允许通过相机扫码
		console.log('scanCode');
		uni.scanCode({
			onlyFromCamera: true,
			success: function(res) {
				console.log('条码类型：' + res.scanType);
				console.log('条码内容：' + res.result);
			}
		});
	}


	function setTabBar(category, goods, cars) {
		const goodsCategoryMap = goods.reduce((prve, cur) => {
			if (!prve.hasOwnProperty(cur.categoryId)) {
				prve[cur.categoryId] = []
			}
			prve[cur.categoryId].push(cur)
			return prve
		}, {})
		const chooseGoodsNumberMap = cars.reduce((prve, cur) => {
			if (!prve.hasOwnProperty(cur.productId)) {
				prve[cur.productId] = 0
			}
			prve[cur.productId] += cur.number
			return prve
		}, {})
		let tabbar = category.map(v => {
			const foods = goodsCategoryMap[v.id] || []
			return {
				...v,
				foods: foods.map((fgoods, index) => {
					return {
						...fgoods,
						chooseNumber: chooseGoodsNumberMap[fgoods.id],
						price: fgoods.lowPrice,
						isDan: fgoods.typeEnum !== 'sku'
					}
				})
			}
		})
		// tabbar.push({
		// 	name: '附加费',
		// 	foods: [{
		// 			name: "餐位费",
		// 			price:$shop.value.tableFee,
		// 			chooseNumber: 0,
		// 			isSeatFee:true,
		// 			isDan: true
		// 		}
		// 	]
		// })
		tabbar = tabbar.filter(v => {
			return v.foods.length
		})
		data.tabbar = tabbar
		data.allGoods = tabbar.reduce((prve, cur) => {
			prve.push(cur.foods)
			return prve
		}, [])
	}

	//request类
	//获取分类
	function getCategory(par = {
		page: 0,
		size: 300
	}) {
		return $tbShopCategory(par)
	}
	//获取商品列表
	function getGoods(par = {
		page: 0,
		size: 300
	}) {
		return Api.getGoodsLists(par)
	}
	//获取购物车数据
	async function getCart(par = {
		page: 0,
		size: 300,
		masterId: data.masterId,
		tableId: data.table.tableId
	}) {
		const res = await Api.getCart(par)
		const cartArr = getNowCart(res.records)
		cars.length = cartArr.length
		for (let i in cartArr) {
			cars[i] = cartArr[i]
		}
		return res
	}
	//获取取餐码
	async function getMasterId() {
		const res = await Api.$getMasterId({
			tableId: data.table.tableId
		})
		data.masterId = res.masterId
		return res

	}
	//清空购物车
	function clearCart() {
		return Api.$clearCart({
			masterId: data.masterId,
			tableId: data.table.tableId
		})
	}
	//加入购物车
	function addCart(par) {
		// if (!data.table.tableId) {
		// 	return infoBox.showToast('请先选择桌台！')
		// }
		const submitPar = {
			masterId: data.masterId,
			tableId: data.table.tableId,
			isPack: false,
			num: 1,
			productId: '',
			skuId: '',
			vipUserId: data.vipUser.id
		}
		Object.assign(submitPar, par)
		return Api.addCart(submitPar)
	}
	//更新购物车
	function updateCartGoods(par) {
		const submitPar = {
			cartId: '',
			masterId: data.masterId,
			tableId: data.table.tableId,
			isPack: false,
			num: 1,
			productId: '',
			skuId: '',
			vipUserId: data.vipUser.id
		}
		Object.assign(submitPar, par)
		return Api.$updateCart(submitPar)
	}
	//删除购物车某商品
	function removeCartGoods(par) {
		const submitPar = {
			cartId: '',
			masterId: data.masterId,
			tableId: data.table.tableId,
		}
		Object.assign(submitPar, par)
		return Api.$removeCart(submitPar)
	}
	//更新选择用户
	function setUser(par) {
		const submitPar = {
			masterId: data.masterId,
			tableId: data.table.tableId,
			vipUserId: data.vipUser.id ? data.vipUser.id : '',
			type: data.vipUser.id ? 0 : 1 //0 设置 1 取消
		}
		Object.assign(submitPar, par)
		return Api.$setUser(submitPar)
	}


	//点击清空购物车
	async function onClearCart() {
		await clearCart()
		cars.length = 0
		for (let i in layoutData.list) {
			for (let k in layoutData.list[i].productList) {
				layoutData.list[i].productList[k].chooseNumber = 0
			}
		}
	}

	//获取桌台信息
	async function getTableInfo() {
		if (data.table.tableId) {
			const res = await $table.get({
				qrcode: data.table.tableId
			})
			console.log(res);
			if (res && res.content[0]) {
				data.table = {
					...res.content[0],
					...data.table
				}
			}
		}
	}
	let $originGoods = []
	let $category = []
	const layoutData = reactive({
		category: {
			// list: uni.getStorageSync('category')||[] ,
			list: [],
			sel: 0,
			selData: {
				page: 0,
				totalElements: 0
			}
		},
		current: 0,
		nowData: {},
		// list: uni.getStorageSync('layoutDataList')||[] ,
		list: [],
		prvePage: {
			padLayoutCode: '',
			productList: []
		},
		currentPage: {
			padLayoutCode: '',
			productList: []
		},
		nextPage: {
			padLayoutCode: '',
			productList: []
		},
		query: {
			page: 1,
			size: 10,
			productCategoryId: '',
			padLayoutId: ''
		}
	})
	let isTapChangeCategorySel = false
	let isScrollChangeCategorySel = false

	function changeCategorySel(index) {
		layoutData.category.sel = index
		setTabsCurrentPosition()
		isTapChangeCategorySel = true
	}

	function setTabsCurrentPosition(position = 'center') {
		const index = layoutData.category.sel
		tabsEle.scrollLeft = tabsEle.tabsItems[index].left - tabsEle.scrollWidth / 2 + tabsEle.tabsItems[index].width / 2;
	}

	async function getGoodsData(max = 6, isGetPrve = false) {
		const fuhao = !isGetPrve ? 1 : -1
		for (let i = 0; i < max; i++) {
			if (layoutData.current + i >= layoutData.list.length - 1) {
				break
			} else {
				const pageData = layoutData.list[layoutData.current + i * fuhao]
				if (pageData && pageData.id && !pageData.hasAjax) {
					try {
						const res2 = await $productCategory(pageData.id)
						layoutData.list[layoutData.current + i * fuhao] = {
							...res2,
							productList: res2.productList.map(v => {
								const findGoodsInCar = cars.find(cars => cars.productId == v.id)
								if (findGoodsInCar) {
									return {
										...v,
										chooseNumber: findGoodsInCar.number
									}
								} else {
									return v
								}

							}),
							hasAjax: true
						}

					} catch (e) {
						layoutData.list[layoutData.current + i * fuhao].hasAjax = false;
						//TODO handle the exception
					}

				}
			}
		}
		// uni.setStorageSync('layoutDataList',layoutData.list)
	}
	async function getLayoutGoodsInit(max = 6, isGetPrve = false) {
		await getGoodsData(max, isGetPrve)
		if (isGetPrve) {
			await getGoodsData(max, isGetPrve)
		}
	}

	function animationStart(e) {
		isScrollChangeCategorySel = true
	}
	async function animationfinish(e) {
		if (isScrollChangeCategorySel) {
			layoutData.current = e.detail.current
			const categoryId = layoutData.list[layoutData.current].productCategoryId
			const index = layoutData.category.list.findIndex(v => v.id == categoryId)
			isScrollChangeCategorySel = true
			layoutData.category.sel = index
			await getLayoutGoodsInit()
		}
		isScrollChangeCategorySel = false
		isTapChangeCategorySel = false
	}
	// 获取标题区域宽度，和每个子元素节点的宽度以及元素距离左边栏的距离
	async function init() {
		try {
			if (layoutData.list.length) {
				data.loading = false
				data.noLogin = false
			}
			if (option.type == 'add') {
				data.masterId = option.masterId
			} else {
				await getMasterId()
			}
			const shopInfo = await tbShopInfo()
			$shop.value = shopInfo
			data.noLogin = false
			xiadanClick()
			const useType = data.table.status == 'using' ? data.table.useType : $returnUseType(shopInfo)
			uni.setStorageSync('useType', useType)
			await getTableInfo()
			const categoryRes = await getCategory()
			// const category = categoryRes.content.reduce((prve, cur) => {
			// 	prve.push({
			// 		...cur,
			// 		childrenList: null
			// 	});
			// 	return [...prve, ...cur.childrenList];
			// }, []);
			const category = categoryRes.content
			let arr = []
			for (let i = 0; i < category.length; i++) {
				const res = await $layoutpage({
					page: 1,
					size: 999,
					productCategoryId: category[i].id,
					padLayoutId: ''
				})
				res.content = res.content.map(v => {
					return {
						...v,
						hasAjax: false
					}
				})
				const content = res.content.length > 0 ? res.content : [{
					productCategoryId: category[i].id,
					padLayoutCode: "single",
					productList: []
				}];
				category[i].startIndex = arr.length
				arr.push(...content)
				category[i].endIndex = arr.length + content.length - 2
			}
			// uni.setStorageSync('category',category)
			layoutData.category.list = category
			layoutData.list = arr
			data.loading = false
			nextTick(() => {
				categoryEleInit()
			})
			getLayoutGoodsInit(2)
			getCart()

		} catch (e) {
			console.log('------err-------');
			console.log(e);
			data.noLogin = true
			// modal.login = true
			//TODO handle the exception
		}
	}

	const tabsEle = reactive({
		scrollWidth: 0,
		tabsItems: [],
		scrollLeft: 0
	})

	function categoryEleInit() {
		getElRect('content-scroll', instance.value, {
			rect: true
		}).then(res => {
			tabsEle.scrollWidth = res.width
		})
		for (let i in layoutData.category.list) {
			getElRect('u-tab-item' + i, instance.value, {
				rect: true
			}).then(res => {
				tabsEle.tabsItems[i] = {
					width: res.width,
					left: res.left
				}
			})
		}
	}
	// 监听选择用户事件



	const surcharge = ref(null)

	function surchargeConfirm(e) {
		data.tabbar[data.tabbar.length - 1].foods.unshift({
			...e,
			chooseNumber: 0
		})
	}

	function surchargeShow() {
		surcharge.value.open()
	}


	let searchValue = ref('')
	let isSearch = ref(false)
	let searchResult = ref([])

	function chunkArray(array, chunkSize) {
		let result = [];
		for (let i = 0; i < array.length; i += chunkSize) {
			result.push(array.slice(i, i + chunkSize));
		}
		return result;
	}

	function formatSearchGoods(arr) {
		const len = arr.length;
		const layoutArr = {
			"1": 'single',
			"2": 'double',
			"3": 'L1-R2',
			"4": '4-gird',
			"6": '6-grid',
		}
		const result = chunkArray(arr, 6)
		console.log(result);
		return result.map(v => {
			return {
				productList: v,
				padLayoutCode: v.length <= 4 ? layoutArr[v.length] : '6-grid'
			}
		})
	}

	function returnSearchGoods() {
		const newval = searchValue.value
		let arr = []
		let goods = []
		for (let i in layoutData.list) {
			const goodsArr = layoutData.list[i].productList || []
			for (let k in goodsArr) {
				goods.push({
					...goodsArr[k],
					index: i,
					goodsIndex: k
				})
			}
		}
		console.log(goods);
		if (newval == "") {
			arr = formatSearchGoods(goods);
		} else {
			const filterArr = goods.filter((v) =>
				v.name.includes(newval.trim())
			);
			console.log(filterArr);
			arr = formatSearchGoods(filterArr)
		}
		return arr
	}

	function search(e) {
		console.log(e);
		searchValue.value = e
		console.log(searchResult.value);
		if (searchValue.value === '') {
			isSearch.value = false
			return
		}
		isSearch.value = true
		searchResult.value = returnSearchGoods()
	}

	function clearSearch() {
		isSearch.value = false
	}

	function chooseUser() {
		go.to('PAGES_CHOOSE_USER')
	}

	function chooseTable() {
		go.to('PAGES_CHOOSE_TABLE', {
			...data.table
		})
	}


	async function confirmModelConfirm(isCancel = false) {
		if (modal.key == 'clear') {
			try {
				await $choseTable({
					masterId: data.masterId,
					tableId: modal.data.tableId,
					isClear: !isCancel ? true : false,
				});
			} catch (e) {
				console.log(e)
				//TODO handle the exception
			}
			data.table = modal.data;
			setModalShow('clear', false, '')
		}
	}

	function resetTable() {
		data.table = {
			tableId: ""
		}
	}

	function setModalShow(key = 'show', show = true, data) {
		modal.key = key
		modal[key] = show
		modal.data = data
	}

	function watchChooseTable() {
		uni.$off('choose-table')
		uni.$on('choose-table', async (item) => {
			if (data.table.tableId || cars.length <= 0) {
				data.table = item
				return;
			}
			if (item.status != "idle") {
				return infoBox.showToast('该台桌已在使用中')
			}
			const res = await $returnTableDetail({
				tableId: item.tableId,
			});
			if (res.cartCount > 0) {
				setModalShow('clear', true, item)
			} else {
				await $choseTable({
					masterId: data.masterId,
					tableId: item.tableId,
					isClear: false
				});
				data.table = item
			}
		})
	}

	function toLinshi() {
		go.to('PAGES_ADD_TEMP_CUISINE')
	}

	const chooseGuigeModel = ref(null)
	const guigeModelData = reactive({
		title: '',
		chooseGoods: {
			skuMap: {},
			item: '',
			skus: []
		}
	})


	// 返回当前选中商品skuList
	function returnSelGoodsSkuList(skuList, specSnap) {
		const specSnapArr = specSnap ? specSnap.split(",") : [];
		const result = skuList.map((v, index) => {
			const values = v.value.split(",");
			return {
				...v,
				valueArr: values,
				sel: specSnap ? specSnapArr[index] : "",
				values: values.map((name) => {
					return {
						name,
						disabled: false
					};
				}),
			};
		});
		return result
	}
	//返回当前选中商品skuMap
	function returnSelGoodsSkuMap(specList) {
		const skuMap = {}
		for (let i in specList) {
			skuMap[specList[i].specSnap] = specList[i];
		}
		return skuMap
	}

	//多规格商品弹窗时，找到默认可以下单的规格商品
	function findGoods(skuList = [], goodsListMap = {}, specList) {
		const skuMapNumber = skuList.reduce((prve, cur) => {
			for (let i in cur.valueArr) {
				prve[cur.valueArr[i]] = i;
			}
			return prve;
		}, {});
		const canBudyGoods = specList
			.filter((v) => util.isCanBuy(v))
			.sort((a, b) => {
				const aNumber = a.specSnap.split(",").reduce((prve, cur) => {
					return prve + skuMapNumber[cur];
				}, 0);
				const bNumber = b.specSnap.split(",").reduce((prve, cur) => {
					return prve + skuMapNumber[cur];
				}, 0);
				return aNumber - bNumber;
			});
		return canBudyGoods[0];
	}

	//设置商品默认选中,规格禁止以及选中
	function setSkugoodsDefaultInit(goods, skuList, skuMap, specList) {
		guigeModelData.chooseGoods.item = goods
		guigeModelData.chooseGoods.skus = skuList
		guigeModelData.chooseGoods.skuMap = skuMap
		const skuGoods = findGoods(skuList, skuMap, specList);
		console.log(skuList, skuMap);
		console.log(skuGoods);
		if (skuGoods) {
			// this.skuGoods.data = skuGoods;
			// this.skuGoods.number = skuGoods.suit || 1;
			skuGoods.specSnap.split(",").map((v, index) => {
				guigeModelData.chooseGoods.skus[index].sel = v;
			});
		}
		console.log(guigeModelData.chooseGoods.skus);
		setTagDisabled();
	}

	//更新选中规格
	function updateSkuSel(skusIndex, skdName) {
		const skuList = guigeModelData.chooseGoods.skus
		const skuMap = guigeModelData.chooseGoods.skuMap
		guigeModelData.chooseGoods.skus[skusIndex].sel = skdName
		const specSnap = guigeModelData.chooseGoods.skus.reduce((prve, cur) => {
			prve.push(cur.sel)
			return prve
		}, []).join()
		setTagDisabled();
		// const canChooseGoods = skuList.every((v) => v.sel);
		// if (canChooseGoods) {
		// 	const skuGoods =skuMap[specSnap];
		// 	guigeModelData.chooseGoods.item = skuGoods
		// }
	}
	//设置规格按钮的禁止状态
	function setTagDisabled() {
		const skuList = guigeModelData.chooseGoods.skus
		const skuMap = guigeModelData.chooseGoods.skuMap
		const selArr = skuList.reduce((prve, cur) => {
			if (cur.sel) {
				prve.push(cur.sel);
			} else {}
			return prve;
		}, []);

		console.log(selArr);
		let selArrAllGroup = util.generateCombinations(selArr, selArr.length - 1);
		console.log(selArrAllGroup);
		const matchArr = [];
		for (let key in skuMap) {
			const goods = skuMap[key];
			const keyArr = key.split(",");
			for (let spe of selArrAllGroup) {
				if (util.arrayContainsAll(keyArr, spe)) {
					matchArr.push(goods);
					break;
				}
			}
		}
		//全部规格都已下架
		if (!matchArr.length) {
			for (let k in skuList) {
				for (let i in skuList[k].values) {
					skuList[k].values[i].disabled = true
				}
			}
			return;
		}
		const includeSkuMap = matchArr.reduce((prve, cur) => {
			const speArr = cur.specSnap.split(",");
			for (let i of speArr) {
				if (!prve.hasOwnProperty("i")) {
					prve[i] = matchArr
						.filter((v) => v.specSnap.match(i))
						.every((v) => {
							return !util.isCanBuy(v)
						});
				}
			}
			return prve;
		}, {});
		for (let i in includeSkuMap) {
			for (let k in skuList) {
				const index = skuList[k].valueArr.findIndex((val) => val === i);
				if (index !== -1) {
					skuList[k].values[index].disabled = includeSkuMap[i]
				}
			}
		}
	}


	let selGoods = ref({})

	function chooseGuige(foodsindex, index) {
		const $goods = layoutData.list[foodsindex].productList[index]
		console.log($goods);
		selGoods.value = $goods
		guigeModelData.title = $goods.name
		const specList = $goods.specList;
		const tagSnap = JSON.parse($goods.skuResult.tagSnap)
		const skuMap = returnSelGoodsSkuMap(specList)
		const skuList = returnSelGoodsSkuList(tagSnap)
		setSkugoodsDefaultInit($goods, skuList, skuMap, specList)
		chooseGuigeModel.value.open()
	}

	async function guigeConfirm(sku, num) {
		const goods = guigeModelData.chooseGoods.item
		const skuId = sku.id
		const productId = goods.id
		const res = findGoodsInCar(goods, skuId)
		if (res) {
			//更新
			const {
				index
			} = res
			const carGoods = cars[index]
			const cartId = carGoods.id
			const newNumber = carGoods.number * 1 + num
			const {
				number
			} = await updateCartGoods({
				num: newNumber,
				cartId,
				productId,
				skuId
			})
			carGoods.number = number
		} else {
			//添加
			const cartGoods = await addCart({
				num,
				productId,
				skuId
			})
			infoBox.showToast('添加成功')
			cars.push({
				...cartGoods,
				specSnap: sku.specSnap
			})
		}
	}

	const $cacheGoods = {}

	//购物车商品数量改变
	async function carsNumberChange(e) {
		const {
			num,
			index,
			goods
		} = e
		const {
			productId,
			categoryId,
			skuId
		} = goods
		const cartId = goods.id
		const findCategory = layoutData.category.list.find(v => v.id == categoryId)
		console.log(findCategory);
		console.log(layoutData.list);
		let findGoods = []
		for (let j = findCategory.startIndex; j < findCategory.endIndex; j++) {
			const goodsArr = layoutData.list[j].productList || []
			console.log(goodsArr);
			for (let k = 0; k < goodsArr.length; k++) {
				const $goods = goodsArr[k]
				console.log($goods);
				if ($goods.id == productId) {
					findGoods.push($goods)
				}
			}
		}
		if (findGoods.length <= 0) {
			//有缓存读缓存无缓存请求接口
			if ($cacheGoods[productId]) {
				findGoods[0] = $cacheGoods[productId]
			} else {
				const goodsres = await $getProductDetail(productId)
				findGoods[0] = {
					...goodsres,
					specList: goodsres.skuList
				}
				$cacheGoods[productId] = findGoods[0]
			}
		}
		const $sku = findGoods[0].specList.find(v => v.id == skuId)
		if (num === 0 || num < $sku.suit) {
			//移除
			await removeCartGoods({
				cartId
			})
			cars.splice(index, 1)
			for (let n in findGoods) {
				findGoods[n].chooseNumber = 0;
			}
			return
		}
		await updateCartGoods({
			num,
			cartId,
			productId,
			skuId
		})
		cars[index].number = num
		for (let n in findGoods) {
			findGoods[n].chooseNumber = num;
		}
	}

	// 找到该规格商品在购物车中是否存在并返回index值以及对应的数据
	function findGoodsInCar($goods, skuId) {
		const productId = $goods.id
		const goodsInCarIndex = cars.findIndex((carsGoods) => {
			return carsGoods.skuId == skuId && carsGoods.productId == productId;
		});
		const carGoods = cars[goodsInCarIndex]
		return carGoods ? {
			index: goodsInCarIndex,
			carGoods
		} : false
	}


	function searchGoodsUpdate(goodsItem, goodsIndex, isAdd) {
		goodsUpdate(goodsItem.goodsIndex, goodsItem.index, isAdd, goodsIndex)
	}

	function setSearchGoods(index, chooseNumber) {
		if (index !== undefined) {
			console.log(searchResult.value[index]);
			searchResult.value[index].chooseNumber = chooseNumber
		}
	}
	async function goodsUpdate(foodsindex, index, isAdd, searchGoodsIndex) {
		console.log(foodsindex, index, isAdd, searchGoodsIndex);
		const $goods = layoutData.list[foodsindex].productList[index]
		console.log($goods);
		console.log($goods.typeEnum);
		if ($goods.typeEnum != 'sku') {
			//单规格
			const goodsInCarIndex = cars.findIndex((carsGoods) => {
				return carsGoods.skuId == $goods.specList[0].id && carsGoods.productId == $goods.id;
			});
			const productId = $goods.id
			const skuId = $goods.specList[0].id
			const suit = $goods.specList[0].suit || 1
			if (goodsInCarIndex !== -1) {
				//更新
				const carGoods = cars[goodsInCarIndex]
				const cartId = carGoods.id
				const step = isAdd ? 1 : -1
				const num = carGoods.number * 1 + step
				if (num === 0 || num < suit) {
					//移除
					cars.splice(goodsInCarIndex, 1)
					$goods.chooseNumber = 0
					setSearchGoods(searchGoodsIndex, 0)
					return await removeCartGoods({
						cartId
					})
				}
				const {
					number
				} = await updateCartGoods({
					num,
					cartId,
					productId,
					skuId
				})
				carGoods.number = number
				$goods.chooseNumber = number
				setSearchGoods(searchGoodsIndex, number)
			} else {
				//增加
				const num = suit
				const cartGoods = await addCart({
					num,
					productId,
					skuId
				})
				infoBox.showToast('添加成功')
				$goods.chooseNumber = num
				cars.push(cartGoods)
			}
			return
		}

	}

	let isTabClickOver = true
	// 点击左边的栏目切换
	async function swichMenu(index) {
		data.current = index
	}

	function watchChooseuser() {
		uni.$off('choose-user')
		uni.$on('choose-user', (user) => {
			console.log(user);
			data.vipUser = user ? user : {
				id: ''
			}
			setUser()
		})
	}
	watch(() => data.table.tableId, (newval, oldval) => {
		onSelTable()
	})
	watch(() => layoutData.category.sel, (newval, oldval) => {
		setTabsCurrentPosition()
		if (!isScrollChangeCategorySel) {
			layoutData.current = layoutData.category.list[newval].startIndex
			getLayoutGoodsInit(6, true)
		}

	})
	async function getLayoutGoods(isAdd) {

	}
	async function onSelTable() {
		const {
			masterId
		} = await getMasterId()
		data.masterId = masterId
		const cartRes = await getCart()
		cars.length = 0
		const cartArr = getNowCart(cartRes.records)
		for (let i in cartArr) {
			cars.push(cartArr[i])
		}
		setTabBar($category, $originGoods, cars)
	}
	onBeforeUnmount(() => {})

	function watchUpdate() {
		uni.$off('update:createOrderIndex')
		uni.$off('get:table')
		uni.$on('update:createOrderIndex', () => {
			// data.table = {
			// 	tableId: ""
			// }
			cars.length = 0
			console.log('update:createOrderIndex');
			init()
		})
		uni.$on('get:table', () => {
			console.log('get:table');
			if (data.table.tableId) {
				$table.get({
					qrcode: data.table.tableId
				}).then(res => {
					if (res.content[0] && res.content[0].status != 'idle') {
						data.table = {
							tableId: ''
						}
					}
				})
			}
		})
	}
	onShow(() => {
		// watchChooseuser()
		watchChooseTable()
		watchUpdate()
	})
	let isCreateOrderToDetail = ref(false)
	let option = {
		type: ''
	}

	let sysInfo = ref({
		windowWidth: 0,
		windowHeight: 0
	})
	onLoad((opt) => {
		sysInfo.value = uni.getSystemInfoSync()
		uni.hideTabBar()
		option = opt
		Object.assign(data.table, opt)
		if (opt.useType) {
			uni.setStorageSync('useType', opt.useType)
		}
		if (JSON.stringify(opt) == '{}') {
			isCreateOrderToDetail.value = true
		}
		// if (!opt.tableId) {
		// 	infoBox.showErrorToast('暂不支持不选择桌台下载，请从桌台点餐')
		// 	return setTimeout(() => {
		// 		go.back()
		// 	}, 1500)
		// }
		init()
	})
</script>

<style lang="scss" scoped>
	.choose-user {
		background: #F9F9F9;
		padding: 22rpx 28rpx;
	}

	.top {
		position: fixed;
		background-color: #fff;
		top: 0;
		left: 0;
		right: 0;
		z-index: 100;
		min-height: 40px;
		padding-top: calc(var(--status-bar-height));
		padding-bottom: 6px;
	}

	.top {
		.search-box {
			// position: absolute;
			// right: 0;
			// top: 0;
			// bottom: 0;
			padding-right: 30rpx;
			background-color: #fff;
			white-space: nowrap;
		}
	}

	.swiper-item-box {
		height: 100%;
		box-sizing: border-box;
		padding-bottom: 20px;
		padding-left: 20px;
		padding-right: 20px;
		padding-top: calc(var(--status-bar-height) + 40px + 16px);
	}

	.search {
		padding-right: 28rpx;
	}

	.icon-saoma {
		margin-left: 20rpx;
		width: 34rpx;
		height: 32rpx;
	}

	$u-tips-color: $my-main-color;
	$u-primary: $my-main-color;
	$u-main-color: $my-main-color;

	.u-wrap {
		display: flex;
		flex-direction: column;
	}

	.headeimg {
		width: 60rpx;
		height: 60rpx;
		display: flex;
		background-color: #eee;
		border-radius: 12rpx;
		overflow: hidden;

		.img {
			width: 60rpx;
			height: 60rpx;
		}
	}

	.u-menu-wrap {
		flex: 1;
		display: flex;
		overflow: hidden;
	}

	.u-search-inner {
		// background-color: rgb(234, 234, 234);
		background-color: #fff;
		border-radius: 100rpx;
		display: flex;
		align-items: center;
		padding: 10rpx 16rpx;
	}

	.u-search-text {
		font-size: 26rpx;
		color: $u-tips-color;
		margin-left: 10rpx;
	}

	.u-tab-view {
		width: 100%;
		background-color: #fff;
	}

	.u-tab-item {
		padding: 10px 16px;
		box-sizing: border-box;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 14px;
		color: #444;
		font-weight: 400;
		line-height: 1;
	}

	.u-tab-item-active {
		position: relative;
		color: $my-main-color;
		font-size: 16px;
		background: #fff;
	}

	.u-tab-item-active::before {
		content: "";
		display: block;
		position: absolute;
		border-bottom: 2px solid $my-main-color;
		left: 4px;
		right: 4px;
		bottom: 0;
	}


	.addCai {
		width: 250rpx;
		height: 272rpx;
		border-radius: 8rpx 8rpx 8rpx 8rpx;
		box-sizing: border-box;
		border: 4rpx solid #90BDF6;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
	}

	.lingshi {
		width: 250rpx;
		height: 136px;
		background: #FFFFFF;
		border-radius: 8rpx 8rpx 8rpx 8rpx;
		border: 4rpx solid #90BDF6;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
	}

	::v-deep .uni-searchbar {
		padding-top: 12px !important;
		padding-bottom: 16px !important;
	}

	.right-box {
		width: 572rpx;
		// background-color: rgb(250, 250, 250);
		background-color: rgb(255, 255, 255);
	}

	.page-view {
		// padding: 24rpx 28rpx 24rpx 24rpx;
	}

	.class-item {
		margin-bottom: 30rpx;
		background-color: #fff;
		border-radius: 8rpx;
	}

	.class-item:last-child {
		min-height: 50vh;
	}

	.item-title {
		font-size: 26rpx;
		font-weight: bold;

		&.active {
			color: $my-main-color;
		}
	}

	.item-menu-name {
		font-weight: normal;
		font-size: 24rpx;
		color: $u-main-color;
	}

	.item-container {
		// display: flex;
		// flex-direction: row;
		// justify-content: center;
		// align-items: center;
		// flex-wrap: wrap;
		width: 100%;

		&.layout-single {
			width: 100%;
			height: 100%;

			.div1 {
				width: 100%;
				height: 100%;
			}
		}

		&.layout-double {
			display: grid;
			grid-template-columns: repeat(2, 1fr);
			grid-template-rows: 1fr;
			grid-column-gap: 20px;
			grid-row-gap: 20px;

			.div1 {
				grid-area: 1 / 1 / 2 / 2;
			}

			.div2 {
				grid-area: 1 / 2 / 2 / 3;
			}
		}

		&.layout-L1-R2 {
			display: grid;
			grid-template-columns: repeat(2, 1fr);
			grid-template-rows: repeat(2, 1fr);
			grid-column-gap: 10px;
			grid-row-gap: 10px;

			.div1 {
				grid-area: 1 / 1 / 3 / 2;
			}

			.div2 {
				grid-area: 1 / 2 / 2 / 3;
			}

			.div3 {
				grid-area: 2 / 2 / 3 / 3;
			}
		}

		&.layout-4-gird {
			display: grid;
			grid-template-columns: repeat(2, 1fr);
			grid-template-rows: repeat(2, 1fr);
			grid-column-gap: 20px;
			grid-row-gap: 20px;

			.div1 {
				grid-area: 1 / 1 / 2 / 2;
			}

			.div2 {
				grid-area: 1 / 2 / 2 / 3;
			}

			.div3 {
				grid-area: 2 / 1 / 3 / 2;
			}

			.div4 {
				grid-area: 2 / 2 / 3 / 3;
			}
		}

		&.layout-6-grid {
			display: grid;
			grid-template-columns: repeat(3, 1fr);
			grid-template-rows: repeat(2, 1fr);
			grid-column-gap: 20px;
			grid-row-gap: 20px;

			.div1 {
				grid-area: 1 / 1 / 2 / 2;
			}

			.div2 {
				grid-area: 1 / 2 / 2 / 3;
			}

			.div3 {
				grid-area: 1 / 3 / 2 / 4;
			}

			.div4 {
				grid-area: 2 / 3 / 3 / 4;
			}

			.div5 {
				grid-area: 2 / 2 / 3 / 3;
			}

			.div6 {
				grid-area: 2 / 1 / 3 / 2;
			}
		}
	}

	.thumb-box {}

	.item-menu-image {
		width: 120rpx;
		height: 120rpx;
	}
</style>