<template>
	<view class="page-gray color-333 u-font-28">
		<template v-if="true">
			<view class="block u-p-t-32 u-p-b-32" v-if="pageData.table&&pageData.table.id">
				<view>桌位号</view>
				<view class="font-bold u-font-32 u-m-t-16">
					{{pageData.table.name||''}}
				</view>
			</view>
			<view class="block">
				<view class="u-p-b-24 u-m-b-24 border-bottom">
					<view>选择用户</view>
					<view class="u-m-t-24 u-flex u-row-between " @tap="chooseUser">
						<view v-if="!pageData.user||!pageData.user.id">选择用户</view>
						<view class="u-flex" v-if="pageData.user&&pageData.user.id">
							<up-avatar :src="pageData.user.headImg" shape="square" :size="30"></up-avatar>

							<view class="u-m-l-20">
								<view class="">{{pageData.user.nickName}}</view>
							</view>
							<view class="u-font-24 u-m-l-30 u-text-center"><text>余额：</text><text
									class="color-main">{{pageData.user.amount}}</text>
							</view>
							<view class="u-font-24 u-m-l-30 u-text-center"><text>积分：</text><text
									class="color-main">{{pageData.user.accountPoints}}</text></view>
						</view>
						<uni-icons type="right" color="#999" size="20" bold></uni-icons>
					</view>
				</view>
				<view class="  ">
					<view>就餐类型</view>
					<view class="u-m-t-24 u-flex  ">
						<view class="u-flex color-666">
							<up-radio-group :disabled="option.type=='add'" v-model="pageData.eatTypes.active"
								placement="row">
								<up-radio :customStyle="{marginRight: '30px'}"
									v-for="(item, index) in pageData.eatTypes.list" :key="index" :label="item.name"
									:name="item.value">
								</up-radio>
							</up-radio-group>
						</view>
					</view>
				</view>

			</view>

			<template v-if="pageData.user&&pageData.user.id">
				<view class="block">
					<view class="">
						<view class="u-flex border-bottom u-p-b-24 ">
							<up-avatar :src="pageData.user.headImg" shape="square" :size="60"></up-avatar>
							<!-- <image class="headeimg" src="@/static/uni.png" mode=""></image> -->
							<view class="u-m-l-32">
								<view class="">{{pageData.user.nickName}}</view>
								<view class="color-main  u-font-24">{{pageData.user.isVip?'会员':'' }}</view>
							</view>
						</view>
						<view class="u-flex u-m-t-24 u-row-between u-font-24 color-999">
							<view class="u-flex">
								<view>余额</view>
								<view class="color-333 u-m-l-10"> {{pageData.user.amount}}</view>
							</view>
							<view class="u-flex">
								<view>积分</view>
								<view class="color-333 u-m-l-10"> {{pageData.user.accountPoints}}</view>
							</view>
							<view class="u-flex">
								<view class="u-text-center">订单数量</view>
								<view class="color-333 u-m-l-10">{{pageData.user.orderNumber||0}}</view>
							</view>
						</view>
					</view>
				</view>
			</template>
			<template v-if="!pageData.shopInfo.isTableFee&&pageData.table&&pageData.table.id">
				<!-- 不免餐位费 -->
				<view class="block">
					<view class="   ">
						<view>用餐人数（人）</view>
						<picker @change="userNumberChange" :value="userNumbers.defaultCateIndex"
							:range="userNumbers.list">
							<view class="u-m-t-24 u-flex u-row-between ">
								<view class="color-333">{{userNumbers.defaultCateIndex*1+1+'人'}}</view>
								<uni-icons type="right" color="#999" size="16"></uni-icons>
							</view>
						</picker>
					</view>
				</view>
			</template>
			<!-- 	<template v-if="goods.list[0].tableId&&goods.list[0].orderId">
				<view class="block" @tap="rotatingTables"
					style="display: flex;align-items: center;justify-content: space-between;">
					<view>转桌/并桌</view>
					<uni-icons type="right" color="#999" size="16"></uni-icons>
				</view>
			</template> -->

		</template>

		<view class="block">
			<view class="u-p-b-24  ">
				<view class="font-bold">订单备注</view>
				<view class="u-m-t-32 u-flex ">
					<uni-easyinput type="textarea" v-model="pageData.form.note" placeholder="请输入备注"></uni-easyinput>
				</view>
			</view>

		</view>

		<view class="block u-m-b-0">
			<view class="u-flex">
				<view>共</view>
				<view class="fen font-bold">{{goods.list.length}}</view>
				<view>份菜品</view>
			</view>

			<view class="goods u-m-t-32">
				<view class="item u-m-b-48" @click="changeGoodsSel(index)" v-for="(item,index) in goods.list"
					:key="index">
					<view class="u-flex u-row-between ">
						<view class="u-flex">
							<image class="img" v-if="item.coverImg" :src="item.coverImg" mode=""></image>
							<view
								style="background-color: #3f9eff;	width: 84rpx;height: 84rpx;line-height: 84rpx;text-align: center;color: #fff;"
								v-else>
								临时菜
							</view>
							<view class="u-m-l-32">
								<view class="u-flex">
									<view class="u-flex u-m-r-20" v-if="item.is_wait_call" style="flex-shrink: 0;">
										<uni-tag text="等叫"
											custom-style="background-color: #FFF0DF; border-color: #FFF0DF; color: #FF9F2E;">
										</uni-tag>
									</view>
									<view class="u-m-r-20 u-flex" v-if="item.is_gift" style="flex-shrink: 0;">
										<uni-tag text="赠送"
											custom-style="background-color: #FFF0DF; border-color: #FFF0DF; color: #FF9F2E;">
										</uni-tag>
									</view>
									<view class="u-m-r-20 u-flex" v-if="item.pack_number>0" style="flex-shrink: 0;">
										<uni-tag
											custom-style="background-color: #E6F0FF; border-color: #E6F0FF; color: #318AFE;"
											size="small" text="打包" inverted type="success" />
									</view>
									<view class="u-m-r-20 u-flex" v-if="item.is_print" style="flex-shrink: 0;">
										<uni-tag
											custom-style="background-color: #E6F0FF; border-color: #E6F0FF; color: #318AFE;"
											size="small" text="打印" inverted type="success" />
									</view>
									<view>
										{{item.name}}
									</view>
								</view>
								<view class="u-font-24 color-999 u-m-t-10">{{item.specInfo||' '}}</view>
							</view>
						</view>
						<view class="">
							<view class=" u-relative">
								<template v-if="item.is_gift">
									<text class="line-th color-999">￥{{toFixed(item.lowPrice*item.number,item) }}</text>
									<view class="u-absolute" style="right: 0;bottom: 100%;">
										<text class="font-bold">￥0</text>
									</view>
								</template>
								<template v-else>
									<template v-if="item.discount_sale_amount&&item.discount_sale_amount*1>0">
										<text
											class="line-th color-999">￥{{toFixed(item.lowPrice*item.number,item) }}</text>
										<view class="u-absolute" style="right: 0;bottom: 100%;">
											<text
												class="font-bold">￥{{toFixed(item.discount_sale_amount*item.number,item) }}</text>
										</view>
									</template>
									<template
										v-else-if="isVip&&item.lowMemberPrice&&item.lowMemberPrice*1!=item.lowPrice*1">
										<text
											class="line-th color-999">￥{{toFixed(item.lowPrice*item.number,item) }}</text>
										<view class="u-absolute" style="right: 0;bottom: 100%;">
											<text
												class="font-bold">￥{{toFixed(item.lowMemberPrice*item.number,item) }}</text>
										</view>
									</template>
									<template v-else>
										<view class="font-bold">
											<text>￥</text>
											<text class="">{{toFixed(item.lowPrice*item.number,item) }}</text>
										</view>
									</template>

								</template>
							</view>
							<view class="color-999 u-text-right u-font-24 u-m-t-12">×{{item.number}}</view>
						</view>
					</view>
					<template v-if="item.remark">
						<view class="u-p-20 bg-gray u-m-t-16">
							{{item.remark}}
						</view>
					</template>
					<scroll-view class="u-m-t-32" scroll-x="true" v-if="index==goods.sel">
						<view class="  u-flex no-wrap  ">
							<view class="u-flex u-m-r-20 " v-if="!item.is_gift">
								<button class="tag" hover-class="hover-class"
									@tap="showModel('discount',index)">单品打折</button>
							</view>
							<view class="u-flex u-m-r-20 ">
								<!-- <button class="tag" hover-class="hover-class" @tap="showModel('giveFood')">赠菜</button> -->
								<button class="tag" hover-class="hover-class"
									@tap="toggleItem(item,'is_gift')">{{item.is_gift?'取消赠送':'赠送'}}</button>
							</view>
							<view class="u-flex u-m-r-20 ">
								<button class="tag" hover-class="hover-class"
									@tap="showModel('packNumber',index,item)">{{item.pack_number>0?'取消打包':'打包'}}</button>
							</view>
							<view class="u-flex u-m-r-20 ">
								<button class="tag" hover-class="hover-class"
									@tap="toggleItem(item,'is_wait_call')">{{item.is_wait_call?'取消等叫':'等叫'}}</button>
							</view>
							<view class="u-flex u-m-r-20 ">
								<button class="tag" hover-class="hover-class"
									@tap="toggleItem(item,'is_print')">{{item.is_print?'免厨打':'打印'}}</button>
							</view>
							<view class="u-flex u-m-r-20 ">
								<button class="tag" hover-class="hover-class"
									@tap="showModel('remark',index)">单品备注</button>
							</view>
						</view>
					</scroll-view>
				</view>
			</view>
			<view class="border-bottom">
				<template v-if="$seatFee&&$seatFee.totalAmount">
					<view class="u-flex u-row-between u-m-t-18 u-p-b-34 ">
						<view>
							<text>桌位费</text>
						</view>
						<view>￥{{$seatFee.totalAmount.toFixed(2)||'0.00'}}</view>
					</view>
				</template>
				<template v-if="$packFee>0">
					<view class="u-flex u-row-between u-m-t-18 u-p-b-34 ">
						<view>
							<text>打包费</text>
						</view>
						<view>￥{{$packFee||'0.00'}}</view>
					</view>
				</template>
			</view>



			<view class="u-flex u-row-between u-m-t-38">
				<view class="u-flex">
					<view class="u-flex price" v-if="youhui*1>0">
						<view class="">优惠金额</view>
						<view class="font-bold u-font-32">￥{{toFixed(youhui) }}</view>
					</view>
				</view>

				<view class="u-flex price  u-m-l-32">
					<view class="">实收金额</view>
					<view class="font-bold u-font-32">￥{{allPrice }}</view>
				</view>
			</view>


		</view>

		<view :style="{height:bottomHeight+'px'}"></view>
		<view class="safe-bottom fixed">


			<view class="btn ">
				<my-button shape="circle" @click="createAnOrder">
					<view class="font-bold u-font-32">
						{{(pageData.shopInfo.registerType=='before'||pageData.eatTypes.active=='take-out')?'结算': '下单'}}
					</view>
				</my-button>
			</view>

		</view>
		<model-discount title="菜品减免" :ref="setModel" name="discount" :price="modelData.data.salePrice"
			@confirm="discountconfirm"></model-discount>
		<give-food title="赠菜" :ref="setModel" name="giveFood"></give-food>
		<one-remark @confirm="goodsOneRemarkConfirm" title="单品备注" :ref="setModel" name="remark"></one-remark>
		<pack-number @confirm="goodsOnePackNumberConfirm" title="打包" :ref="setModel" name="packNumber"></pack-number>
		<!-- <edit-discount title="优惠金额" :ref="setModel" name="editMoney" :price="allPrice"></edit-discount> -->
	</view>


</template>

<script setup>
	import {
		onLoad,
		onReady,
		onShow,
		onHide
	} from '@dcloudio/uni-app'
	import {
		ref,
		inject,
		onUnmounted,
		nextTick,
		reactive,
		computed,
		watch
	} from 'vue';

	import modelDiscount from './components/discount'
	import giveFood from './components/give-food'
	import packNumber from './components/pack-number'
	import oneRemark from './components/remark'
	// import editDiscount from '@/pagesCreateOrder/components/edit-discount.vue'

	import {
		getSafeBottomHeight
	} from '@/commons/utils/safe-bottom.js'
	import go from '@/commons/utils/go.js';
	import {
		hasPermission
	} from '@/commons/utils/hasPermission.js'
	import {
		getNowCart
	} from '@/pagesCreateOrder/util.js'
	import {
		number
	} from 'uview-plus/libs/function/test';

	import {
		getShopTableDetail
	} from '@/http/api/table.js'
	import {
		getShopInfo
	} from '@/http/api/shop.js'
	import {
		getProductList
	} from '@/http/api/product.js'
	import {
		createOrder,
		getHistoryOrder
	} from '@/http/api/order.js'

	const models = new Map();
	const modelData = reactive({
		data: {},
		selIndex: -1
	})
	const option = reactive({
		id: '',
		tableId: "",
	})
	/**
	 * 用餐人数
	 */
	const userNumbers = reactive({
		list: new Array(100).fill(1).map((v, index) => {
			// return index === 0 ? '无' : index + '人'
			return (index + 1) + '人'
		}),
		defaultCateIndex: 0,
	})
	const f = reactive({})

	let $goods = []
	const goods = reactive({
		list: [],
		sel: 0
	})
	const pageData = reactive({
		shopInfo: {},
		table: {},
		user: {},
		eatTypes: {
			list: [{
					name: "堂食",
					value: "dine-in",
				},
				{
					name: "外带",
					value: "take-out",
				}
				// ,
				// {
				// 	name: "外卖",
				// 	value: "take-away",
				// }
			],
			active: 'dine-in',
			isShow: false,
		},
		form: {
			note: ""
		},
		orderInfo: {}
	})
	const websocketUtil = inject('websocketUtil'); // 注入 WebSocket 工具类实例
	onLoad((opt) => {
		Object.assign(option, opt)
		console.log("opt====", opt);
		if (opt.tableId || opt.tableCode) {
			pageData.table.id = opt.tableId
			pageData.table.tableCode = opt.tableCode
		}
		pageData.shopInfo = uni.getStorageSync('shopInfo')
		console.log(uni.getStorageSync('shopInfo'),'提示1');
		getTbShopInfo()

	})
	let bottomHeight = ref(100)
	onReady(() => {
		getSafeBottomHeight('safe-bottom').then(res => {
			bottomHeight.value = res
		})
	})
	watch(() => userNumbers.defaultCateIndex, (newval) => {
		updateChoseCount()
	})

	watch(() => pageData.eatTypes.active, (newval) => {
		pageData.eatTypes.isShow = true
		changeUseType()
	})
	onShow(() => {
		init()
		watchChooseuser()
		watchChooseTable()
	})
	onHide(() => {
		console.log("onHide")
		websocketUtil.offMessage()
	})
	onUnmounted(() => {
		console.log("onUnmounted")
		websocketUtil.offMessage()
	});

	/**
	 * 获取订单详情
	 * @param {Object} tableCode
	 */
	async function getHistoryOrderDetail(tableCode) {
		let res = await getHistoryOrder({
			tableCode: tableCode
		});
		pageData.orderInfo = res.data;
	}

	//餐位费
	const $seatFee = reactive({
		totalNumber: 0,
		totalAmount: 0,
	})

	/**
	 * 打包费
	 */
	const $packFee = computed(() => {
		let packAmount = 0;
		return goods.list.reduce((prve, cur) => {
			return prve + (cur.packFee || 0) * parseFloat(cur.pack_number).toFixed(2)
		}, 0).toFixed(2)
	})

	/**
	 * 菜品数量
	 */
	const goodsNumber = computed(() => {
		const result = goods.list.reduce((prve, cur) => {
			return prve + cur.number
		}, 0)
		return result
	})

	/**
	 * 判断是否是会员
	 */
	const isVip = computed(() => {
		return pageData.shopInfo.isMemberPrice && pageData.user && pageData.user.id && pageData.user.isVip
	})

	const discount_sale_amount = computed(() => {
		return goods.list.filter((v) => v.discount_sale_amount && v.discount_sale_amount > 0)
			.reduce((a, b) => {
				const lowMemberPrice = b.lowMemberPrice ? b.lowMemberPrice : b.lowPrice
				const tPrice = (isVip.value ? lowMemberPrice : b.lowPrice)
				return a + b.number * (tPrice - b.discount_sale_amount);
			}, 0);
	})

	const goodsPrice = computed(() => {
		const goodsTotalPrice = goods.list.reduce((prve, cur) => {
			const lowMemberPrice = cur.lowMemberPrice ? cur.lowMemberPrice : cur.lowPrice
			const tPrice = Math.floor(((isVip.value ? lowMemberPrice : cur.lowPrice) * cur.number) * 100) /
				100
			return prve + (cur.is_gift ? 0 : tPrice)
		}, 0)
		const tpackFee = $packFee.value > 0 ? $packFee.value * 1 : 0

		return ((goodsTotalPrice - discount_sale_amount.value + tpackFee) || 0).toFixed(2)
	})

	/**
	 * 实收金额
	 */
	const allPrice = computed(() => {
		const n = goodsPrice.value * 1 + $seatFee.totalAmount
		return n.toFixed(2)
	})

	/**
	 * 计算优惠金额
	 */
	const youhui = computed(() => {
		let goodsTotalPrice = 0
		if (pageData.user && pageData.user.id && pageData.user.isVip) {
			goodsTotalPrice = goods.list.reduce((prve, cur) => {
				const tPrice = cur.lowPrice * cur.number
				const tpackFee = (cur.pack_number * 1) > 0 ? cur.packFee * (cur.pack_number * 1) : 0
				return prve + tPrice + tpackFee
			}, 0)
			return (goodsTotalPrice + $seatFee.totalAmount) - allPrice.value
		} else {
			return (discount_sale_amount.value)
		}
		return (goodsTotalPrice + discount_sale_amount.value * 1).toFixed(2)
	})

	function toFixed(price, item) {
		if (item) {
			if (item.productType == 'weight' || item.type == 'weight') {
				return (Math.floor(price * 100) / 100).toFixed(2)
			} else {
				return parseFloat(price).toFixed(2)
			}
		} else {
			return parseFloat(price).toFixed(2)
		}
	}

	async function init() {
		nextTick(() => {
			onMessage()
		})
		// 获取商品列表
		let res = await getProductList({}, 'product', false)
		$goods = res.data
		// console.log("商品列表===",$goods)
		getTableInfo(pageData.table)

	}

	/**
	 * socket消息监听
	 */
	function onMessage() {
		websocketUtil.offMessage()
		websocketUtil.onMessage(res => {
			let msg = JSON.parse(res);
			let cartItem;
			if (msg.msg_id) {
				websocketUtil.send(JSON.stringify({
					type: 'receipt',
					msg_id: msg.msg_id,
				}))
			}
			if (msg.status == 0) {
				infoBox.showToast('添加失败')
				return false;
			}

			switch (msg.operate_type) {
				case 'pad_init':
					goods.list = []
					console.log(msg.data)
					msg.data.map(item => {
						cartItem = getNowCart(item, $goods, pageData.user)
						console.log(cartItem)
						if (cartItem.isGrounding || cartItem.is_temporary == 1) {
							cartControls(cartItem, 'add')
						} else {
							delCart(cartItem.id)
						}

					})
					if (pageData.eatTypes.isShow) {
						if (pageData.eatTypes.active == 'take-out') {
							cartItem.pack_number = cartItem.number
						} else {
							cartItem.pack_number = 0
						}
						let par = {
							type: 'onboc',
							account: uni.getStorageSync("iToken").loginId,
							shop_id: uni.getStorageSync("shopInfo").id,
							operate_type: 'batch',
							table_code: pageData.table.tableCode,
							is_pack: pageData.eatTypes.active == 'take-out' ? 1 : 0,
						}
						updateCart(par)
					}
					// 是否更新就餐人数
					if (!$seatFee.totalNumber) {
						updateChoseCount()
					}

					pageData.eatTypes.isShow = false
					break;
				case 'pad_add':
				case 'add':
					cartItem = getNowCart(msg.data, $goods, pageData.user)
					cartControls(cartItem, 'add')
					break;
				case 'pad_edit':
				case 'edit':
					getCart()
					break;
				case 'pad_del':
				case 'del':
					cartItem = getNowCart(msg.data, $goods, pageData.user)
					cartControls(cartItem, 'del')
					break;
				case 'pad_cleanup':
				case 'cleanup':
					goods.list = []
					$seatFee.totalNumber = 0
					$seatFee.totalAmount = 0
					userNumbers.defaultCateIndex = 0
					init()
					break;
				case 'product_update':
					init()
					break;
			}

		});

	}



	/**
	 * 删除购物车菜品
	 */
	function delCart(cartItem) {
		let params = {
			type: 'pad',
			account: uni.getStorageSync("shopId"),
			shop_id: uni.getStorageSync("shopId"),
			is_gift: 0,
			id: cartItem.id,
			operate_type: 'del',


		}
		websocketUtil.send(JSON.stringify(params))
	}

	/**
	 * socket通知购物车商品数量修改处理
	 */
	function cartControls(cartItem, type) {
		if (!pageData.table.tableCode) {
			pageData.table.tableCode = cartItem.table_code
		}
		let cartIndex = 0;
		goods.list.map((item, index) => {
			if (item.id == cartItem.id) {
				cartIndex = index;
			}
		})

		if (type == 'del') {
			goods.list.splice(cartIndex, 1)
			return;
		}
		if (type == 'add') {
			goods.list.push(cartItem)
		}
		if (type == 'edit') {
			goods.list[cartIndex].number = cartItem.number
		}
	}


	/**
	 * 获取购物车数据
	 */
	function getCart() {
		// 初始化购物车
		websocketUtil.send(JSON.stringify({
			type: 'pad',
			account: uni.getStorageSync("shopInfo").id,
			shop_id: uni.getStorageSync("shopInfo").id,
			operate_type: 'init',
			table_code: pageData.table.tableCode,
		}))

	}

	/**
	 * 获取店铺信息
	 */
	async function getTbShopInfo() {
		const res = await getShopInfo({
			id: uni.getStorageSync('shopId')
		})
		pageData.shopInfo = res.data
		uni.setStorageSync('shopInfo', res.data)
	}

	/**
	 * 获取桌台信息
	 */
	async function getTableInfo(opt) {
		const {
			data: res
		} = await getShopTableDetail({
			id: opt.id,
			tableCode: opt.tableCode
		})
		Object.assign(pageData.table, res)
		if (!pageData.shopInfo.isTableFee && pageData.table && pageData.table.id) {
			userNumbers.list = new Array(res.maxCapacity ? res.maxCapacity * 1 : 100).fill(1).map((v, index) => {
				return (index + 1) + '人'
			})
		}
		// 获取购物车数据
		getCart()
		// 获取购物车数据
		getHistoryOrderDetail(opt.tableCode)
	}

	/**
	 * 更新选择用户
	 */
	function watchChooseuser() {
		uni.$off('choose-user')
		uni.$on('choose-user', (data) => {
			pageData.user = data
		})
	}

	/**
	 * 就餐类型切换监听
	 */
	async function changeUseType() {
		if (!goods.list.length) {
			return
		}
		getCart()
	}

	/**
	 * 购物车数据修改
	 * @param {Object} par
	 */
	function updateCart(par) {
		websocketUtil.send(JSON.stringify({
			type: 'pad',
			account: uni.getStorageSync("shopInfo").id,
			shop_id: uni.getStorageSync("shopInfo").id,
			operate_type: 'edit',
			table_code: pageData.table.tableCode,
			...par
		}))
		getCart()
	}

	/**
	 * 菜品赠送/等叫/打印修改
	 * @param {Object} item
	 */
	function toggleItem(item, key) {
		let par = {
			id: item.id,
			product_id: item.product_id,
			sku_id: item.sku_id
		}
		par[key] = item[key] == 0 ? 1 : 0
		updateCart(par)
	}


	/**
	 * 单品打折
	 * @param {Object} form
	 */
	async function discountconfirm(form) {
		if (form.discountMoney != '.') {
			let str = ''
			if (form.notes) {
				form.notes.forEach(ele => {
					if (ele.checked) {
						str = str + ele.name + ','
					}
				})
			}
			let lowMemberPrice = modelData.data.lowMemberPrice ? modelData.data.lowMemberPrice : modelData.data
				.lowPrice
			let tPrice = (isVip.value ? lowMemberPrice : modelData.data.lowPrice)
			let discount_sale_amount = modelData.data.is_gift ? 0 : form.discountMoney
			let par = {
				id: modelData.data.id,
				product_id: modelData.data.product_id,
				sku_id: modelData.data.sku_id,
				discount_sale_amount: discount_sale_amount,
				discount_sale_note: str + form.note,
			}
			updateCart(par)
		}
	}

	/**
	 * 打包
	 */
	function goodsOnePackNumberConfirm(e) {
		let par = {
			id: modelData.data.id,
			product_id: modelData.data.product_id,
			sku_id: modelData.data.sku_id,
			pack_number: e
		}
		updateCart(par)
	}

	/**
	 * 单品备注确认
	 * @param {Object} e
	 */
	async function goodsOneRemarkConfirm(e) {
		let par = {
			id: modelData.data.id,
			product_id: modelData.data.product_id,
			sku_id: modelData.data.sku_id,
			remark: e.remark
		}
		updateCart(par)
	}

	/**
	 * 设置弹窗信息
	 * @param {Object} el
	 */
	function setModel(el) {
		if (el && el.$attrs['name']) {
			models.set(el.$attrs['name'], el);
		}
	}

	/**
	 * 打开弹窗
	 * @param {Object} key
	 * @param {Object} index
	 */
	function showModel(key, index, item) {
		modelData.data = goods.list[index]
		modelData.selIndex = index
		const model = models.get(key)
		console.log("弹窗数据===", modelData.data)
		if (key == 'packNumber') {
			if (modelData.data.type == 'weight' && item.pack_number <= 0) {
				let par = {
					id: modelData.data.id,
					product_id: modelData.data.product_id,
					sku_id: modelData.data.sku_id,
					pack_number: 1
				}
				updateCart(par)
				return false;
			}
			if (item.pack_number > 0) {
				let par = {
					id: modelData.data.id,
					product_id: modelData.data.product_id,
					sku_id: modelData.data.sku_id,
					pack_number: 0
				}
				updateCart(par)
				return false;
			}
			model && model.open({
				number: item.number
			})

		} else {
			model && model.open({
				packNumber: modelData.data.remark || ''
			})
		}
	}

	function formatPrice(n) {
		return (Math.floor(n * 100) / 100).toFixed(2)
	}

	function rotatingTables() {
		uni.navigateTo({
			url: '/pagesCreateOrder/confirm-order/rotatingTables?item=' + JSON.stringify(goods.list),
		})
	}

	/**
	 * 更新就餐人数
	 */
	async function updateChoseCount() {
		const maxCapacity = pageData.table && pageData.table.id ? (pageData.table.maxCapacity || 0) : 100
		if (pageData.table && pageData.table.id && userNumbers.defaultCateIndex * 1 + 1 > maxCapacity) {
			// uni.$utils.showToast('当前台桌最大人数为: ' + maxCapacity)
			userNumbers.defaultCateIndex = maxCapacity - 1
			return
		}
		console.log(pageData.shopInfo)
		console.log(!pageData.shopInfo.isTableFee)
		if (!pageData.shopInfo.isTableFee && pageData.table && pageData.table.id && goods.list.length > 0) {
			//不免餐位费
			console.log("不免餐位费")
			let seatFee = {
				totalNumber: userNumbers.defaultCateIndex * 1 + 1,
				totalAmount: (userNumbers.defaultCateIndex * 1 + 1) * pageData.shopInfo.tableFee,
			}
			Object.assign($seatFee, seatFee)
			userNumbers.defaultCateIndex = $seatFee.totalNumber - 1
		}

	}

	/**
	 * 选择就餐人数
	 * @param {Object} e
	 */
	function userNumberChange(e) {
		userNumbers.defaultCateIndex = e.detail.value
	}

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

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

	function watchChooseTable() {
		uni.$off('choose-table')
		uni.$on('choose-table', (data) => {
			pageData.table = data
			console.log("台桌信息", pageData.table);
		})
	}

	function changeGoodsSel(index) {
		goods.sel = index
	}


	/**
	 * 创建订单
	 */
	async function createAnOrder() {
		if (pageData.shopInfo.registerType == 'before' || pageData.eatTypes.active == 'take-out') {
			const canJiesuan = await hasPermission('允许收款')
			if (!canJiesuan) {
				return
			}
		}

		let vipPrice = isVip.value ? 1 : 0
		let placeNum = pageData.orderInfo ? pageData.orderInfo.placeNum + 1 : 1;
		let originAmount = goodsPrice.value * 1 + youhui.value * 1
		let par = {
			shopId: pageData.shopInfo.id, //店铺Id
			userId: pageData.user.userId, //用户Id
			tableCode: pageData.table.tableCode, //台桌编码
			dineMode: pageData.eatTypes.active, //用餐模式 堂食 dine-in 外带 take-out 外卖 take-away
			remark: pageData.form.note, //备注
			seatNum: 0, //用餐人数
			packFee: $packFee.value, //打包费
			originAmount: originAmount, //订单原金额（包含打包费+餐位费） 不含折扣价格
			placeNum: placeNum, //当前订单下单次数
			waitCall: 0, //是否等叫 0 否 1 等叫
			vipPrice: vipPrice, //是否使用会员价
		}
		if (!pageData.shopInfo.isTableFee && pageData.table && pageData.table.id) {
			par.seatNum = userNumbers.defaultCateIndex * 1 + 1
		}
		if (pageData.orderInfo) {
			par.orderId = pageData.orderInfo.id
		}
		// console.log(par,22222222);
		const res = await createOrder(par)
		if(res.code==500){
			uni.showToast({
				title: res.msg,
				icon: 'none'
			})
			return
		}
		uni.$emit('update:createOrderIndex')
		websocketUtil.send(JSON.stringify({
			type: 'pad',
			account: uni.getStorageSync("shopInfo").id,
			shop_id: uni.getStorageSync("shopInfo").id,
			operate_type: 'cleanup',
			table_code: pageData.table.tableCode,
		}))
		uni.removeStorageSync("table_code")
		if (pageData.shopInfo.registerType == 'before' || pageData.eatTypes.active == 'take-out') {
			//先付
			return go.to('PAGES_ORDER_PAY', {
				orderId: res.data.id,
				isNowPay: true
			}, 'redirect')
		} else {
			//后付
			if (option.isCreateOrderToDetail != '0') {
				go.to('PAGES_ORDER_DETAIL', {
					id: res.data.id
				}, 'redirect')
			} else {
				uni.navigateBack({
					delta: 2
				})
			}
		}
		uni.showToast({
			title: '提交成功',
			icon: 'none'
		})

	}
</script>

<style lang="scss" scoped>
	.fen {
		color: #FF9F2E;
	}

	.page-gray {
		padding: 32rpx 28rpx 0 28rpx;
	}

	.headeimg {
		width: 84rpx;
		height: 84rpx;
		border-radius: 12rpx 12rpx 12rpx 12rpx;
	}

	.block {
		background-color: #fff;
		padding: 32rpx 24rpx;
		border-radius: 18rpx;
		margin-bottom: 32rpx;
	}

	.textarea {
		border-radius: 12rpx 12rpx 12rpx 12rpx;
		padding: 32rpx 0 32rpx 24rpx;
		border: 1px solid #999999;
		overflow: hidden;
	}

	.goods {
		// padding-bottom: 30rpx;
		border-bottom: 1px dashed #E5E5E5;

		.item {
			.img {
				width: 84rpx;
				height: 84rpx;
				border-radius: 8rpx 8rpx 8rpx 8rpx;
			}
		}
	}

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

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

	.price {
		color: #EB4F4F;
	}

	.opacity0 {
		opacity: 0;
	}

	.fixed {
		position: fixed;
	}

	.safe-bottom {
		padding: 34rpx 28rpx;
		background-color: #fff;
		left: 0;
		right: 0;
		bottom: 0;
		z-index: 10;

		.btn {
			padding: 0 88rpx 56rpx 88rpx;
		}
	}

	.tag {
		background-color: #fff;
		border: 1px solid #E5E5E5;
		line-height: inherit;
		font-size: 24rpx;
		color: #666666;
		padding: 6rpx 16rpx;
		border-radius: 100rpx;
	}

	.hover-class {
		background-color: #E5E5E5;
	}
</style>