| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703 |
- <template>
- <!-- 点餐页 -->
- <view class="content">
- <view class="top-info">桌号:{{ displayTableNumber }} 就餐人数:{{ currentDiners }}人</view>
- <!-- 搜索 -->
- <input type="text" placeholder="请输入菜品名称" class="search-input" />
- <!-- 内容 -->
- <view class="content-box">
- <!-- 左侧分类列表 -->
- <scroll-view class="category-list" scroll-y>
- <view v-for="(category, index) in categories" :key="index" class="category-item"
- :class="{ active: currentCategoryIndex === index }" @click="selectCategory(index)">
- {{ category.categoryName }}
- </view>
- </scroll-view>
- <!-- 右侧菜品列表 -->
- <scroll-view class="food-list" scroll-y>
- <FoodCard v-for="(food, index) in currentFoodList" :key="food.id || food.cuisineId || index" :food="food"
- :table-id="tableId" @increase="handleIncrease" @decrease="handleDecrease"/>
- </scroll-view>
- </view>
- <!-- 底部下单:按接口格式展示 totalQuantity / totalAmount -->
- <BottomActionBar :cart-list="displayCartList" :total-quantity="displayTotalQuantity"
- :total-amount="displayTotalAmount" @coupon-click="handleCouponClick" @cart-click="handleCartClick"
- @order-click="handleOrderClick" />
- <!-- 领取优惠券弹窗 -->
- <CouponModal v-model:open="couponModalOpen" :coupon-list="couponList" @receive="handleCouponReceive"
- @close="handleCouponClose" />
- <!-- 购物车弹窗:按接口格式展示 items(cuisineName/cuisineImage/quantity/unitPrice/subtotalAmount/remark) -->
- <CartModal v-model:open="cartModalOpen" :cart-list="displayCartList" :discount-amount="discountAmount"
- @increase="handleIncrease" @decrease="handleDecrease" @clear="handleCartClear"
- @coupon-click="handleSelectCouponClick" @order-click="handleOrderClick" @close="handleCartClose" />
- <!-- 选择优惠券弹窗 -->
- <SelectCouponModal v-model:open="selectCouponModalOpen" :coupon-list="availableCoupons"
- :selected-coupon-id="selectedCouponId" @select="handleCouponSelect" @close="handleSelectCouponClose" />
- </view>
- </template>
- <script setup>
- import { onLoad, onUnload } from "@dcloudio/uni-app";
- import { ref, computed } from "vue";
- import FoodCard from "./components/FoodCard.vue";
- import BottomActionBar from "./components/BottomActionBar.vue";
- import CouponModal from "./components/CouponModal.vue";
- import CartModal from "./components/CartModal.vue";
- import SelectCouponModal from "./components/SelectCouponModal.vue";
- import { go } from "@/utils/utils.js";
- import { DiningOrderFood, GetStoreCategories, GetStoreCuisines, getOrderSseConfig, GetOrderCart, PostOrderCartAdd, PostOrderCartUpdate, PostOrderCartClear } from "@/api/dining.js";
- import { createSSEConnection } from "@/utils/sse.js";
- const tableId = ref(''); // 桌号ID,来自上一页 url 参数 tableid,用于接口入参
- const tableNumber = ref(''); // 桌号展示,来自 dining/page-info 接口返回的 tableNumber
- const tableNumberFetched = ref(false); // 是否已请求过桌号(避免未返回前用 tableId 展示导致闪一下 43)
- const currentDiners = ref(uni.getStorageSync('currentDiners') || '');
- // 桌号展示:优先用接口返回的 tableNumber,未请求完前不显示 tableId,避免闪 43 再变 2
- const displayTableNumber = computed(() => {
- if (tableNumber.value) return tableNumber.value;
- if (tableNumberFetched.value && tableId.value) return tableId.value;
- return '—';
- });
- let sseRequestTask = null; // 订单 SSE 连接(封装后兼容小程序),页面卸载时需 abort()
- const currentCategoryIndex = ref(0);
- const couponModalOpen = ref(false);
- const cartModalOpen = ref(false);
- const selectCouponModalOpen = ref(false);
- const discountAmount = ref(12); // 优惠金额,示例数据
- const selectedCouponId = ref(null); // 选中的优惠券ID
- // 分类列表(由接口 /store/info/categories 返回后赋值)
- const categories = ref([]);
- // 菜品列表(由接口 /store/info/cuisines 按分类拉取并合并,每项含 quantity、categoryId)
- const foodList = ref([]);
- // SSE 连接建立后拉取的购物车数据,在 foodList 就绪后合并
- let pendingCartData = null;
- // 购物车接口返回的完整数据:{ items, totalAmount, totalQuantity },用于按接口格式展示
- const cartData = ref({ items: [], totalAmount: 0, totalQuantity: 0 });
- // 当前分类的菜品列表(按当前选中的分类 id 过滤)
- const currentFoodList = computed(() => {
- const cat = categories.value[currentCategoryIndex.value];
- if (!cat) return [];
- const categoryId = cat.id ?? cat.categoryId;
- return foodList.value.filter((food) => String(food?.categoryId ?? '') === String(categoryId ?? ''));
- });
- // 购物车列表:只包含数量>0 的菜品,并按菜品 id 去重(同一菜品只算一条,避免金额叠加)
- const cartList = computed(() => {
- const withQty = foodList.value.filter((food) => (food.quantity || 0) > 0);
- const seen = new Set();
- return withQty.filter((f) => {
- const id = String(f?.id ?? '');
- if (seen.has(id)) return false;
- seen.add(id);
- return true;
- });
- });
- // 用于展示的购物车列表:优先使用接口返回的 items(含 cuisineName/cuisineImage/unitPrice/subtotalAmount/remark),只展示数量>0
- const displayCartList = computed(() => {
- const apiItems = cartData.value?.items;
- if (Array.isArray(apiItems) && apiItems.length > 0) {
- return apiItems.filter((it) => (Number(it?.quantity) || 0) > 0);
- }
- return cartList.value;
- });
- // 行小计:接口项用 subtotalAmount,否则 数量×单价(与 BottomActionBar/CartModal 一致)
- const getItemLinePrice = (item) => {
- if (item?.subtotalAmount != null) return Number(item.subtotalAmount);
- const qty = Number(item?.quantity) || 0;
- const unitPrice = Number(item?.unitPrice ?? item?.price ?? item?.salePrice ?? item?.totalPrice ?? 0) || 0;
- return qty * unitPrice;
- };
- // 展示用总数量:优先接口/本地 cartData.totalQuantity,否则从展示列表计算
- const displayTotalQuantity = computed(() => {
- const apiItems = cartData.value?.items;
- if (Array.isArray(apiItems) && apiItems.length > 0 && cartData.value?.totalQuantity != null) {
- return Number(cartData.value.totalQuantity);
- }
- return displayCartList.value.reduce((sum, item) => sum + (Number(item?.quantity) || 0), 0);
- });
- // 展示用总金额:优先接口/本地 cartData.totalAmount,否则从展示列表按行小计累加
- const displayTotalAmount = computed(() => {
- const apiItems = cartData.value?.items;
- if (Array.isArray(apiItems) && apiItems.length > 0 && cartData.value?.totalAmount != null) {
- return Number(cartData.value.totalAmount);
- }
- return displayCartList.value.reduce((sum, item) => sum + getItemLinePrice(item), 0);
- });
- // 优惠券列表(示例数据)
- const couponList = ref([
- {
- id: 1,
- amount: 38,
- minAmount: 158,
- name: '优惠券名称',
- expireDate: '2024/07/28',
- isReceived: false
- },
- {
- id: 2,
- amount: 8,
- minAmount: 158,
- name: '优惠券名称',
- expireDate: '2024/07/28',
- isReceived: false
- },
- {
- id: 3,
- amount: 682,
- minAmount: 1580,
- name: '优惠券名称',
- expireDate: '2024/07/28',
- isReceived: true
- },
- {
- id: 4,
- amount: 1038,
- minAmount: 1580,
- name: '优惠券名称',
- expireDate: '2024/07/28',
- isReceived: true
- }
- ]);
- // 可用的优惠券列表(已领取的优惠券)
- const availableCoupons = computed(() => {
- return couponList.value.filter(coupon => coupon.isReceived);
- });
- // 分类 id 统一转字符串,避免 number/string 比较导致误判
- const sameCategory = (a, b) => String(a ?? '') === String(b ?? '');
- // 将购物车数量同步到菜品列表:用购物车接口的 items 按 cuisineId 匹配 foodList 中的菜品并更新 quantity;items 为空时清空所有菜品数量
- const mergeCartIntoFoodList = () => {
- const cartItems = pendingCartData ?? cartData.value?.items ?? [];
- if (!Array.isArray(cartItems)) return;
- if (!foodList.value.length) {
- if (cartItems.length > 0) console.log('购物车已缓存,等 foodList 加载后再同步到菜品列表');
- return;
- }
- foodList.value = foodList.value.map((item) => {
- const itemId = String(item?.id ?? item?.cuisineId ?? '');
- const cartItem = cartItems.find((c) => {
- const cId = String(c?.id ?? c?.cuisineId ?? c?.foodId ?? c?.dishId ?? '');
- return cId && cId === itemId;
- });
- const qty = cartItem
- ? Number(cartItem.quantity ?? cartItem.num ?? cartItem.count ?? 0) || 0
- : 0;
- return { ...item, quantity: qty };
- });
- pendingCartData = null;
- console.log('购物车数量已同步到菜品列表', cartItems.length ? '' : '(已清空)');
- };
- // 从接口返回的 data 层中解析出购物车数组(/store/order/cart/{id} 返回在 items 下)
- function parseCartListFromResponse(cartRes) {
- if (cartRes == null) return [];
- if (Array.isArray(cartRes.items)) return cartRes.items;
- // 优先 items(当前接口约定),再兼容 list / data / records 等
- const firstLevel =
- cartRes.items ??
- cartRes.list ??
- cartRes.data ??
- cartRes.records ??
- cartRes.cartList ??
- cartRes.cartItems ??
- cartRes.cart?.list ??
- cartRes.cart?.items ??
- cartRes.result?.list ??
- cartRes.result?.data ??
- cartRes.result?.items;
- if (Array.isArray(firstLevel)) return firstLevel;
- if (typeof cartRes === 'object') {
- const arr = Object.values(cartRes).find((v) => Array.isArray(v));
- if (arr) return arr;
- }
- return [];
- }
- // 调获取购物车接口并合并到 foodList(需在 foodList 有数据后调用才能返显到购物车)
- // 注意:request 层在 code=200 时只返回 res.data.data,故 cartRes 已是后端 data 层
- const fetchAndMergeCart = async (tableid) => {
- if (!tableid) return;
- try {
- const cartRes = await GetOrderCart(tableid);
- const list = parseCartListFromResponse(cartRes);
- pendingCartData = list;
- // 按接口格式绑定:data.items / totalAmount / totalQuantity
- cartData.value = {
- items: list,
- totalAmount: Number(cartRes?.totalAmount) || 0,
- totalQuantity: Number(cartRes?.totalQuantity) || 0
- };
- mergeCartIntoFoodList();
- console.log('购物车接口返回(data 层):', cartRes, '解析条数:', list.length);
- } catch (err) {
- console.error('获取购物车失败:', err);
- throw err;
- }
- };
- // 根据分类 id 拉取菜品并合并到 foodList,切换分类时保留其他分类已选菜品及本分类已选数量
- const fetchCuisinesByCategoryId = async (categoryId) => {
- if (!categoryId) return;
- try {
- const res = await GetStoreCuisines({ categoryId });
- const list = res?.list ?? res?.data ?? (Array.isArray(res) ? res : []);
- const normalized = (Array.isArray(list) ? list : []).map(item => ({
- ...item,
- quantity: item.quantity ?? 0,
- categoryId: item.categoryId ?? categoryId
- }));
- // 其他分类的菜品原样保留(含已选数量)
- const rest = foodList.value.filter(f => !sameCategory(f.categoryId, categoryId));
- // 本分类:按菜品 id 从整份列表里取已选数量,id 一致则自动带上数量
- const merged = normalized.map((newItem) => {
- const existing = foodList.value.find(
- (e) => String(e?.id ?? e?.cuisineId ?? '') === String(newItem?.id ?? newItem?.cuisineId ?? '')
- );
- const quantity = existing ? existing.quantity : (newItem.quantity ?? 0);
- return { ...newItem, quantity };
- });
- foodList.value = [...rest, ...merged];
- // 切换分类后,把购物车数量再同步到当前分类的菜品列表
- mergeCartIntoFoodList();
- } catch (err) {
- console.error('获取菜品失败:', err);
- }
- };
- // 选择分类:切换高亮并拉取该分类菜品
- const selectCategory = async (index) => {
- currentCategoryIndex.value = index;
- const cat = categories.value[index];
- if (!cat) return;
- const categoryId = cat.id ?? cat.categoryId;
- await fetchCuisinesByCategoryId(categoryId);
- };
- // 根据展示项(可能来自接口 cuisineId 或 foodList 的 id)找到 foodList 中的菜品
- const findFoodByCartItem = (item) => {
- const id = item?.id ?? item?.cuisineId;
- if (id == null) return null;
- return foodList.value.find((f) => String(f?.id ?? f?.cuisineId ?? '') === String(id));
- };
- // 同步 cartData:根据 cuisineId 更新 items 中对应项的 quantity、subtotalAmount,并重算 totalAmount、totalQuantity
- const syncCartDataFromFoodList = () => {
- const items = cartData.value?.items ?? [];
- if (!items.length) return;
- let totalAmount = 0;
- let totalQuantity = 0;
- const nextItems = items.map((it) => {
- const food = findFoodByCartItem(it);
- const qty = food != null ? (food.quantity || 0) : (it.quantity || 0);
- const unitPrice = Number(it?.unitPrice ?? it?.price ?? 0) || 0;
- const subtotalAmount = qty * unitPrice;
- totalAmount += subtotalAmount;
- totalQuantity += qty;
- return { ...it, quantity: qty, subtotalAmount };
- });
- cartData.value = { ...cartData.value, items: nextItems, totalAmount, totalQuantity };
- };
- // 更新菜品数量:菜品 id 一致则全部同步为同一数量,触发响应式;新增加入购物车时调接口;并同步 cartData
- // Update 接口返回 400 时不改页面数量和金额(会回滚本地状态)
- const updateFoodQuantity = (food, delta) => {
- if (!food) return;
- const id = food.id ?? food.cuisineId;
- const prevQty = food.quantity || 0;
- const nextQty = Math.max(0, prevQty + delta);
- const sameId = (item) =>
- String(item?.id ?? item?.cuisineId ?? '') === String(id ?? '');
- const items = cartData.value?.items ?? [];
- const idx = items.findIndex((it) => String(it?.cuisineId ?? it?.id ?? '') === String(id));
- const applyQuantity = (qty) => {
- foodList.value = foodList.value.map((item) =>
- sameId(item) ? { ...item, quantity: qty } : item
- );
- const currentItems = cartData.value?.items ?? [];
- const currentIdx = currentItems.findIndex((it) => String(it?.cuisineId ?? it?.id ?? '') === String(id));
- if (currentIdx >= 0) {
- const it = currentItems[currentIdx];
- const unitPrice = Number(it?.unitPrice ?? it?.price ?? 0) || 0;
- const nextItems = currentItems.slice();
- nextItems[currentIdx] = { ...it, quantity: qty, subtotalAmount: qty * unitPrice };
- const totalAmount = nextItems.reduce((s, i) => s + (Number(i.subtotalAmount) || 0), 0);
- const totalQuantity = nextItems.reduce((s, i) => s + (Number(i.quantity) || 0), 0);
- cartData.value = { ...cartData.value, items: nextItems, totalAmount, totalQuantity };
- } else if (qty > 0) {
- const unitPrice = Number(food?.price ?? food?.unitPrice ?? food?.salePrice ?? 0) || 0;
- const newItem = {
- cuisineId: id,
- cuisineName: food?.name ?? food?.cuisineName ?? '',
- cuisineImage: food?.image ?? food?.cuisineImage ?? food?.imageUrl ?? '',
- quantity: qty,
- unitPrice,
- subtotalAmount: qty * unitPrice
- };
- const nextItems = [...currentItems, newItem];
- const totalAmount = nextItems.reduce((s, i) => s + (Number(i.subtotalAmount) || 0), 0);
- const totalQuantity = nextItems.reduce((s, i) => s + (Number(i.quantity) || 0), 0);
- cartData.value = { ...cartData.value, items: nextItems, totalAmount, totalQuantity };
- }
- };
- applyQuantity(nextQty);
- if (tableId.value && delta !== 0) {
- const needAdd = delta > 0 && (idx < 0 || nextQty === 1);
- if (needAdd) {
- PostOrderCartAdd({
- cuisineId: id,
- quantity: nextQty,
- tableId: tableId.value
- }).catch((err) => {
- console.error('加入购物车失败:', err);
- applyQuantity(prevQty);
- });
- } else {
- PostOrderCartUpdate({
- cuisineId: id,
- quantity: nextQty,
- tableId: tableId.value
- }).catch((err) => {
- console.error('更新购物车失败:', err);
- applyQuantity(prevQty);
- });
- }
- }
- };
- // 增加数量:支持传入接口项(cuisineId)或菜品项(id),先解析为 foodList 中的 food
- const handleIncrease = (item) => {
- const food = item?.id != null && item?.cuisineId == null ? item : findFoodByCartItem(item) ?? item;
- updateFoodQuantity(food, 1);
- };
- // 减少数量
- const handleDecrease = (item) => {
- const food = item?.id != null && item?.cuisineId == null ? item : findFoodByCartItem(item) ?? item;
- if (food && (food.quantity || 0) > 0) updateFoodQuantity(food, -1);
- };
- // 优惠券点击(领取优惠券弹窗)
- const handleCouponClick = () => {
- // 先关闭其他弹窗
- if (cartModalOpen.value) {
- cartModalOpen.value = false;
- }
- if (selectCouponModalOpen.value) {
- selectCouponModalOpen.value = false;
- }
- couponModalOpen.value = true;
- };
- // 选择优惠券点击(从购物车弹窗中点击)
- const handleSelectCouponClick = () => {
- // 先关闭其他弹窗
- if (cartModalOpen.value) {
- cartModalOpen.value = false;
- }
- if (couponModalOpen.value) {
- couponModalOpen.value = false;
- }
- // 打开选择优惠券弹窗
- selectCouponModalOpen.value = true;
- };
- // 处理优惠券选择
- const handleCouponSelect = ({ coupon, index, selectedId }) => {
- selectedCouponId.value = selectedId;
- // 根据选中的优惠券更新优惠金额
- if (selectedId) {
- discountAmount.value = coupon.amount;
- } else {
- discountAmount.value = 0;
- }
- // 选择后关闭选择优惠券弹窗,打开购物车弹窗
- selectCouponModalOpen.value = false;
- // 延迟打开购物车弹窗,确保选择优惠券弹窗完全关闭
- setTimeout(() => {
- cartModalOpen.value = true;
- }, 100);
- };
- // 选择优惠券弹窗关闭
- const handleSelectCouponClose = () => {
- selectCouponModalOpen.value = false;
- };
- // 优惠券领取
- const handleCouponReceive = ({ coupon, index }) => {
- console.log('领取优惠券:', coupon);
- // 更新优惠券状态
- couponList.value[index].isReceived = true;
- uni.showToast({
- title: '领取成功',
- icon: 'success'
- });
- // TODO: 调用接口领取优惠券
- };
- // 优惠券弹窗关闭
- const handleCouponClose = () => {
- couponModalOpen.value = false;
- };
- // 购物车点击
- const handleCartClick = () => {
- if (displayCartList.value.length === 0) {
- uni.showToast({
- title: '购物车为空',
- icon: 'none'
- });
- return;
- }
- // 先关闭其他弹窗
- if (couponModalOpen.value) {
- couponModalOpen.value = false;
- }
- if (selectCouponModalOpen.value) {
- selectCouponModalOpen.value = false;
- }
- cartModalOpen.value = true;
- };
- // 购物车弹窗关闭
- const handleCartClose = () => {
- cartModalOpen.value = false;
- };
- // 清空购物车:调用 /store/order/cart/clear,入参 tableId,成功后清空本地并关闭弹窗
- const handleCartClear = () => {
- if (!tableId.value) {
- foodList.value = foodList.value.map((f) => ({ ...f, quantity: 0 }));
- cartData.value = { items: [], totalAmount: 0, totalQuantity: 0 };
- cartModalOpen.value = false;
- uni.showToast({ title: '已清空购物车', icon: 'success' });
- return;
- }
- PostOrderCartClear(tableId.value)
- .then(() => {
- foodList.value = foodList.value.map((f) => ({ ...f, quantity: 0 }));
- cartData.value = { items: [], totalAmount: 0, totalQuantity: 0 };
- cartModalOpen.value = false;
- uni.showToast({ title: '已清空购物车', icon: 'success' });
- })
- .catch((err) => {
- console.error('清空购物车失败:', err);
- uni.showToast({ title: '清空失败,请重试', icon: 'none' });
- });
- };
- // 下单点击:先带购物车数据跳转确认订单页,创建订单在确认页点击「确认下单」时再调
- const handleOrderClick = () => {
- const cartPayload = {
- list: displayCartList.value,
- totalAmount: displayTotalAmount.value,
- totalQuantity: displayTotalQuantity.value,
- tableId: tableId.value,
- tableNumber: tableNumber.value,
- diners: currentDiners.value
- };
- uni.setStorageSync('placeOrderCart', JSON.stringify(cartPayload));
- const query = [];
- if (tableId.value) query.push(`tableId=${encodeURIComponent(tableId.value)}`);
- if (tableNumber.value) query.push(`tableNumber=${encodeURIComponent(tableNumber.value)}`);
- if (currentDiners.value) query.push(`diners=${encodeURIComponent(currentDiners.value)}`);
- go(query.length ? `/pages/placeOrder/index?${query.join('&')}` : '/pages/placeOrder/index');
- };
- onLoad(async (options) => {
- // 获取上一页(选择就餐人数页)传来的桌号和就餐人数
- const tableid = options.tableid || '';
- const diners = options.diners || '';
- tableId.value = tableid;
- currentDiners.value = diners;
- if (tableid) uni.setStorageSync('currentTableId', tableid);
- console.log('点餐页接收参数 - 桌号(tableid):', tableid, '就餐人数(diners):', diners);
- // 先拉取购物车并缓存,再加载菜品,保证合并时 pendingCartData 已就绪,避免不返显
- if (tableid) {
- await fetchAndMergeCart(tableid).catch((err) => console.error('获取购物车失败:', err));
- }
- // 页面加载时创建订单 SSE 连接(仅 SSE 使用 utils/sse 封装,兼容微信小程序)
- if (tableid) {
- try {
- const sseConfig = getOrderSseConfig(tableid);
- sseRequestTask = createSSEConnection(sseConfig.url, sseConfig);
- sseRequestTask.onMessage((msg) => {
- console.log('SSE 收到:', msg);
- if (msg.event === 'cart_update' && msg.data) {
- try {
- const payload = typeof msg.data === 'string' ? JSON.parse(msg.data) : msg.data;
- const items = payload?.items ?? [];
- cartData.value = {
- items: Array.isArray(items) ? items : [],
- totalAmount: Number(payload?.totalAmount) || 0,
- totalQuantity: Number(payload?.totalQuantity) || 0
- };
- pendingCartData = null;
- mergeCartIntoFoodList();
- } catch (e) {
- console.error('SSE 购物车数据解析失败:', e);
- }
- }
- });
- sseRequestTask.onOpen(async () => {
- console.log('SSE 连接已建立');
- await fetchAndMergeCart(tableid).catch(() => {});
- });
- sseRequestTask.onError((err) => console.error('SSE 错误:', err));
- } catch (e) {
- console.error('SSE 连接失败:', e);
- }
- }
- // 调用点餐页接口,入参 dinerCount、tableId
- if (tableid || diners) {
- try {
- const res = await DiningOrderFood({
- tableId: tableid,
- dinerCount: diners
- });
- console.log('点餐页接口返回:', res);
- const data = res?.data ?? res ?? {};
- tableNumber.value = data?.tableNumber ?? data?.tableNo ?? '';
- tableNumberFetched.value = true;
- // 成功后调接口获取菜品种类(storeId 取自点餐页接口返回,若无则需从别处获取)
- const storeId = res?.storeId ?? data?.storeId ?? '';
- if (storeId) uni.setStorageSync('currentStoreId', storeId);
- if (storeId) {
- try {
- const categoriesRes = await GetStoreCategories({ storeId });
- const list = categoriesRes?.list ?? categoriesRes?.data ?? categoriesRes;
- if (Array.isArray(list) && list.length) {
- categories.value = list;
- // 默认用第一项的分类 id 拉取菜品
- const firstCat = list[0];
- const firstCategoryId = firstCat.id ?? firstCat.categoryId;
- if (firstCategoryId) {
- const cuisinesRes = await GetStoreCuisines({ categoryId: firstCategoryId });
- const cuisinesList = cuisinesRes?.list ?? cuisinesRes?.data ?? (Array.isArray(cuisinesRes) ? cuisinesRes : []);
- foodList.value = (Array.isArray(cuisinesList) ? cuisinesList : []).map(item => ({
- ...item,
- quantity: item.quantity ?? 0,
- categoryId: item.categoryId ?? firstCategoryId
- }));
- console.log('默认分类菜品:', cuisinesRes);
- mergeCartIntoFoodList();
- }
- }
- console.log('菜品种类:', categoriesRes);
- } catch (err) {
- console.error('获取菜品种类失败:', err);
- }
- }
- } catch (e) {
- console.error('点餐页接口失败:', e);
- tableNumberFetched.value = true;
- }
- } else {
- tableNumberFetched.value = true;
- }
- });
- onUnload(() => {
- if (sseRequestTask && typeof sseRequestTask.abort === 'function') {
- sseRequestTask.abort();
- }
- sseRequestTask = null;
- });
- </script>
- <style lang="scss" scoped>
- .content {
- display: flex;
- flex-direction: column;
- height: 100vh;
- background-color: #f7f9fa;
- padding-bottom: 100rpx;
- box-sizing: border-box;
- }
- .top-info {
- font-size: 28rpx;
- color: #888888;
- text-align: center;
- width: 100%;
- padding: 20rpx 0;
- background-color: #fff;
- }
- .search-input {
- width: 90%;
- margin-left: 5%;
- height: 80rpx;
- background-color: #fff;
- border-radius: 40rpx;
- padding: 0 20rpx;
- margin-top: 20rpx;
- box-sizing: border-box;
- font-size: 28rpx;
- text-align: center;
- }
- .content-box {
- display: flex;
- flex: 1;
- overflow: hidden;
- margin-top: 20rpx;
- }
- // 左侧分类列表
- .category-list {
- width: 180rpx;
- background-color: #fff;
- height: 100%;
- }
- .category-item {
- height: 100rpx;
- display: flex;
- align-items: center;
- justify-content: center;
- font-size: 28rpx;
- color: #999;
- background-color: #fff;
- transition: all 0.3s;
- &.active {
- background-color: #fff4e6;
- color: #333;
- font-weight: 600;
- }
- }
- // 右侧菜品列表
- .food-list {
- flex: 1;
- // background-color: #fff;
- // padding: 0 20rpx;
- margin: 0 20rpx;
- }
- </style>
|