| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034 |
- <template>
- <!-- 点餐页:左上角永远返回主页,顶部固定 -->
- <view class="page-wrap">
- <view class="top-fixed">
- <NavBar :title="navTitle" only-home />
- <view class="top-info">桌号:{{ displayTableNumber }}</view>
- <view class="search-box">
- <view class="search-box-inner">
- <image :src="getFileUrl('img/personal/search.png')" mode="widthFix" class="search-icon"></image>
- <input type="text" placeholder="搜索菜品名称" class="search-input" v-model="searchKeyword"
- @confirm="doSearch" />
- </view>
- </view>
- </view>
- <view class="content">
- <!-- 内容 -->
- <view class="content-box">
- <!-- 左侧分类列表 -->
- <view class="category-list-wrap">
- <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>
- </view>
- <!-- 右侧菜品长列表:按分类分段展示,每段标题 + 该分类下菜品 -->
- <view class="food-list-wrap">
- <scroll-view class="food-list" scroll-y :scroll-into-view="scrollIntoViewId" scroll-with-animation>
- <block v-for="(section, sectionIndex) in sectionList" :key="section.category.id ?? sectionIndex">
- <view :id="'section-' + sectionIndex" class="food-section">
- <view class="food-section__title">{{ section.category.categoryName }}</view>
- <FoodCard v-for="(food, index) in section.cuisines" :key="food.id || food.cuisineId || sectionIndex + '-' + index"
- :food="food" :table-id="tableId" @increase="handleIncrease" @decrease="handleDecrease"/>
- </view>
- </block>
- </scroll-view>
- </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" @close="handleCouponClose" />
- <!-- 购物车弹窗:按接口格式展示 items(含 tags 从 foodList 补全) -->
- <CartModal v-model:open="cartModalOpen" :cart-list="displayCartListWithTags"
- @increase="handleIncrease" @decrease="handleDecrease" @clear="handleCartClear"
- @order-click="handleOrderClick" @close="handleCartClose" />
- <!-- 选择优惠券弹窗:左下角入口为仅查看,购物车内入口为可选 -->
- <SelectCouponModal v-model:open="selectCouponModalOpen" :coupon-list="availableCoupons"
- :selected-coupon-id="selectedCouponId" :view-only="selectCouponViewOnly" @select="handleCouponSelect" @close="handleSelectCouponClose" />
- </view>
- </view>
- </template>
- <script setup>
- import { onLoad, onShow, onUnload } from "@dcloudio/uni-app";
- import NavBar from "@/components/NavBar/index.vue";
- import { ref, computed, nextTick } 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 { getFileUrl } from "@/utils/file.js";
- import { DiningOrderFood, GetCategoriesWithCuisines, GetStoreDetail, getOrderSseConfig, GetOrderCart, PostOrderCartAdd, PostOrderCartUpdate, PostOrderCartClear, PutOrderCartUpdateTableware, GetUserOwnedCouponList } from "@/api/dining.js";
- import { createSSEConnection } from "@/utils/sse.js";
- // 商品图片:取第一张,若为逗号分隔字符串则截取逗号前的第一张
- function firstImage(val) {
- if (val == null || val === '') return '';
- if (Array.isArray(val)) return (val[0] != null && val[0] !== '') ? String(val[0]).split(/[,,]/)[0].trim() : '';
- const str = String(val).trim();
- return str ? str.split(/[,,]/)[0].trim() : '';
- }
- const storeName = ref(''); // 店铺名称,用于导航栏标题
- 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') || '');
- const navTitle = computed(() => storeName.value || '点餐');
- // 桌号展示:优先用接口返回的 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 foodListScrollTop = ref(0);
- const searchKeyword = ref('');
- const couponModalOpen = ref(false);
- const cartModalOpen = ref(false);
- const selectCouponModalOpen = ref(false);
- const selectCouponViewOnly = ref(false); // true=左下角仅查看,false=购物车内可选
- const fromNumberOfDiners = ref(false); // 是否从选座页(就餐人数页)进入,仅此时才调用 update-tableware 接口
- 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, tablewareFee },用于按接口格式展示
- const cartData = ref({ items: [], totalAmount: 0, totalQuantity: 0, tablewareFee: 0 });
- // 右侧长列表:按分类分段,每段为 { category, cuisines },支持一菜多分类(categoryIds)
- const sectionList = computed(() => {
- const cats = categories.value;
- const list = foodList.value;
- if (!cats.length) return [];
- return cats.map((cat) => {
- const cid = String(cat.id ?? cat.categoryId ?? '');
- const cuisines = list.filter((f) => {
- const ids = f.categoryIds ?? (f.categoryId != null ? [f.categoryId] : []);
- return (Array.isArray(ids) ? ids : [ids]).map(String).includes(cid);
- });
- return { category: cat, cuisines };
- });
- });
- // 点击左侧分类时滚动到右侧对应段(scroll-into-view 用)
- const scrollIntoViewId = ref('');
- // 购物车列表:只包含数量>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;
- });
- });
- // 用于展示的购物车列表:数量>0 的项展示;餐具(id=-1)始终展示(含数量为 0);若接口未返回餐具则补默认项
- const displayCartList = computed(() => {
- const apiItems = cartData.value?.items;
- let base = [];
- if (Array.isArray(apiItems) && apiItems.length > 0) {
- base = apiItems.filter((it) => (Number(it?.quantity) || 0) > 0 || Number(it?.cuisineId ?? it?.id) === -1);
- } else {
- base = cartList.value;
- }
- const hasTableware = base.some((it) => Number(it?.cuisineId ?? it?.id) === -1);
- if (!hasTableware) {
- const fee = Number(cartData.value?.tablewareFee) || 0;
- return [...base, { cuisineId: -1, cuisineName: '餐具费', quantity: 0, unitPrice: fee || 0, subtotalAmount: 0 }];
- }
- return base;
- });
- // 将 tags 统一为 [{ text, type }] 格式,且 text 含逗号/顿号时拆成多条(与 FoodCard 一致,分开显示)
- function normalizeTags(raw) {
- if (raw == null) return [];
- let arr = [];
- if (Array.isArray(raw)) arr = raw;
- else if (typeof raw === 'string') {
- const t = raw.trim();
- if (t.startsWith('[')) { try { arr = JSON.parse(t); if (!Array.isArray(arr)) arr = []; } catch { arr = t ? [t] : []; } }
- else arr = t ? t.split(/[,,、\s]+/).map(s => s.trim()).filter(Boolean) : [];
- } else if (raw && typeof raw === 'object') {
- if (Array.isArray(raw.list)) arr = raw.list;
- else if (Array.isArray(raw.items)) arr = raw.items;
- else if (raw.text != null || raw.tagName != null || raw.name != null || raw.label != null || raw.title != null) arr = [raw];
- else arr = [];
- }
- const withText = arr.map((item) => {
- if (item == null) return { text: '', type: '' };
- if (typeof item === 'string') return { text: item, type: '' };
- if (typeof item === 'number') return { text: String(item), type: '' };
- return { text: item.text ?? item.tagName ?? item.name ?? item.label ?? item.title ?? '', type: item.type ?? item.tagType ?? '' };
- }).filter((t) => t.text !== '' && t.text != null);
- return withText.flatMap((t) => {
- const parts = (t.text || '').split(/[,,、\s]+/).map((s) => s.trim()).filter(Boolean);
- return parts.map((p) => ({ text: p, type: t.type }));
- });
- }
- // 购物车展示列表(含标签):从 foodList 补全 cart 项缺失的 tags
- const displayCartListWithTags = computed(() => {
- return displayCartList.value.map((item) => {
- const tags = item?.tags ?? item?.tagList ?? item?.tagNames;
- if (tags != null && (Array.isArray(tags) ? tags.length > 0 : true)) return item;
- const food = findFoodByCartItem(item);
- const fromFood = food?.tags ?? food?.tagList ?? food?.tagNames ?? food?.labels ?? food?.tag;
- const normalized = normalizeTags(fromFood);
- return normalized.length > 0 ? { ...item, tags: normalized } : item;
- });
- });
- // 行小计:接口项用 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);
- });
- // 优惠券列表(由接口 /dining/coupon/storeUsableList 返回后赋值)
- const couponList = ref([]);
- // 门店可用优惠券列表(选择优惠券弹窗用,与 couponList 同步自同一接口)
- const storeUsableCouponList = ref([]);
- // 规范化接口优惠券项为弹窗所需格式(对接 getUserCouponList 返回的 data:id/couponId/userCouponId、name、couponType、discountRate、minimumSpendingAmount、expirationTime 等)
- // couponType 1=满减券显示 nominalValue 为金额,2=折扣券显示 discountRate 为折扣力度
- function normalizeCouponItem(item) {
- if (!item || typeof item !== 'object') return null;
- const raw = item;
- const couponType = Number(raw.couponType) || 0;
- const nominalValue = Number(raw.nominalValue ?? raw.amount ?? 0) || 0;
- const discountRate = ((Number(raw.discountRate) || 0) / 10) || 0;
- const minAmount = Number(raw.minimumSpendingAmount ?? raw.minAmount ?? raw.min_amount ?? 0) || 0;
- const isReceived = raw.canReceived === false;
- let amountDisplay = nominalValue + '元';
- if (couponType === 1) {
- amountDisplay = nominalValue + '元';
- } else if (couponType === 2 && discountRate > 0) {
- amountDisplay = (discountRate % 1 === 0 ? discountRate : discountRate.toFixed(1)) + '折';
- }
- return {
- id: raw.userCouponId ?? raw.id ?? raw.couponId ?? raw.coupon_id ?? '',
- amount: nominalValue,
- minAmount,
- name: raw.name ?? raw.title ?? raw.couponName ?? '',
- expireDate: raw.expirationTime ?? raw.endGetDate ?? raw.validDate ?? raw.expireDate ?? raw.endTime ?? '',
- isReceived,
- couponType,
- discountRate,
- amountDisplay
- };
- }
- // 可用的优惠券列表(选择优惠券弹窗用,来自 storeUsableCouponList)
- const availableCoupons = computed(() => storeUsableCouponList.value);
- // 分类 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 / tablewareFee
- cartData.value = {
- items: list,
- totalAmount: Number(cartRes?.totalAmount) || 0,
- totalQuantity: Number(cartRes?.totalQuantity) || 0,
- tablewareFee: Number(cartRes?.tablewareFee ?? cartRes?.tablewareAmount ?? 0) || 0
- };
- mergeCartIntoFoodList();
- console.log('购物车接口返回(data 层):', cartRes, '解析条数:', list.length);
- } catch (err) {
- console.error('获取购物车失败:', err);
- throw err;
- }
- };
- // 拉取「分类+菜品」一体接口,填充左侧分类与右侧菜品列表(入参 storeId,keyword 选填)
- const fetchCategoriesWithCuisines = async (storeId, keyword = '') => {
- if (!storeId) return;
- try {
- const params = { storeId };
- if (keyword != null && String(keyword).trim() !== '') params.keyword = String(keyword).trim();
- const res = await GetCategoriesWithCuisines(params);
- const raw = res?.data ?? res ?? {};
- const list = raw?.list ?? raw?.data ?? (Array.isArray(raw) ? raw : []);
- const listArr = Array.isArray(list) ? list : [];
- // cuisines 为空的项不加入列表,左侧分类与右侧分段都不展示
- const dataList = listArr.filter((item) => {
- const arr = item.cuisines ?? item.cuisineList ?? [];
- return Array.isArray(arr) && arr.length > 0;
- });
- let cats = [];
- let cuisines = [];
- // 接口返回 data 数组,每项为 { category: { id, categoryName, ... }, cuisines: [...] }
- if (dataList.length > 0 && dataList[0].category != null) {
- cats = dataList.map((item) => {
- const c = item.category || {};
- return {
- id: c.id ?? c.categoryId,
- categoryId: c.id ?? c.categoryId,
- categoryName: c.categoryName ?? c.name ?? ''
- };
- });
- cuisines = dataList.flatMap((item) => {
- const c = item.category || {};
- const cid = c.id ?? c.categoryId;
- const arr = item.cuisines ?? item.cuisineList ?? [];
- return (Array.isArray(arr) ? arr : []).map((dish) => {
- const ids = Array.isArray(dish.categoryIds) ? dish.categoryIds : (dish.categoryId != null ? [dish.categoryId] : [cid]);
- return { ...dish, categoryId: dish.categoryId ?? dish.categoryIds?.[0] ?? cid, categoryIds: ids };
- });
- });
- } else if (dataList.length > 0 && (dataList[0].cuisines != null || dataList[0].cuisineList != null)) {
- const cuisinesKey = dataList[0].cuisines != null ? 'cuisines' : 'cuisineList';
- cats = dataList.map((c) => ({
- id: c.id ?? c.categoryId,
- categoryId: c.id ?? c.categoryId,
- categoryName: c.categoryName ?? c.name ?? ''
- }));
- cuisines = dataList.flatMap((c) => {
- const arr = c[cuisinesKey] ?? [];
- const cid = c.id ?? c.categoryId;
- return (Array.isArray(arr) ? arr : []).map((item) => {
- const ids = Array.isArray(item.categoryIds) ? item.categoryIds : (item.categoryId != null ? [item.categoryId] : [cid]);
- return { ...item, categoryId: item.categoryId ?? item.categoryIds?.[0] ?? cid, categoryIds: ids };
- });
- });
- } else {
- cats = raw?.categories ?? raw?.categoryList ?? [];
- const cuisinesRaw = raw?.cuisines ?? raw?.cuisineList ?? [];
- cuisines = Array.isArray(cuisinesRaw) ? cuisinesRaw : [];
- }
- categories.value = Array.isArray(cats) ? cats : [];
- const normalized = cuisines.map((item) => {
- const categoryId = item.categoryId ?? (categories.value[0]?.id ?? categories.value[0]?.categoryId);
- const rawImg = item.images ?? item.cuisineImage ?? item.image ?? item.imageUrl ?? item.pic ?? item.cover ?? '';
- const img = firstImage(rawImg) || (typeof rawImg === 'string' ? rawImg : (rawImg && (rawImg.url ?? rawImg.path ?? rawImg.src) ? (rawImg.url ?? rawImg.path ?? rawImg.src) : ''));
- return { ...item, images: img, image: img, cuisineImage: img, quantity: item.quantity ?? 0, categoryId, categoryIds: item.categoryIds ?? [categoryId] };
- });
- // 同一菜品可能出现在多个分类下,按 id 去重并合并 categoryIds
- const byId = new Map();
- normalized.forEach((item) => {
- const id = String(item.id ?? item.cuisineId ?? '');
- if (byId.has(id)) {
- const existing = byId.get(id);
- const merged = [...new Set([...(existing.categoryIds || []), ...(item.categoryIds || [])].map(String))];
- byId.set(id, { ...existing, categoryIds: merged });
- } else {
- byId.set(id, item);
- }
- });
- foodList.value = Array.from(byId.values());
- mergeCartIntoFoodList();
- return true;
- } catch (err) {
- console.error('获取分类与菜品失败:', err);
- return false;
- }
- };
- // 选择分类:切换高亮并滚动右侧到对应分段(锚点定位)
- const selectCategory = (index) => {
- currentCategoryIndex.value = index;
- scrollIntoViewId.value = 'section-' + index;
- setTimeout(() => { scrollIntoViewId.value = ''; }, 400);
- };
- // 滚动到指定分段锚点(供搜索后定位用)
- const scrollToSection = (index) => {
- currentCategoryIndex.value = index;
- scrollIntoViewId.value = 'section-' + index;
- setTimeout(() => { scrollIntoViewId.value = ''; }, 400);
- };
- // 搜索:带 keyword 重新请求分类+菜品,结果根据锚点定位到第一个分段
- const doSearch = async () => {
- const storeId = uni.getStorageSync('currentStoreId') || '';
- if (!storeId) return;
- const keyword = searchKeyword.value?.trim() ?? '';
- const ok = await fetchCategoriesWithCuisines(storeId, keyword);
- if (ok) {
- nextTick(() => scrollToSection(0));
- }
- };
- // 根据展示项(可能来自接口 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 };
- };
- // 判断是否为餐具(cuisineId 或 id 为 -1),餐具可修改数量(含减至 0)
- const isTableware = (item) => {
- if (!item) return false;
- const id = item.id ?? item.cuisineId;
- return Number(id) === -1;
- };
- // 更新菜品数量:菜品 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);
- const isTablewareItem = Number(id) === -1;
- if (isTablewareItem && fromNumberOfDiners.value) {
- PutOrderCartUpdateTableware({
- quantity: nextQty,
- tableId: tableId.value
- }).catch((err) => {
- console.error('更新餐具数量失败:', err);
- applyQuantity(prevQty);
- });
- } else if (isTablewareItem) {
- // 非选座页进入:餐具仅本地更新,不调 update-tableware
- } else 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);
- };
- // 拉取用户优惠券列表(GET /dining/coupon/userOwnedByStore,入参 storeId),列表在 SelectCouponModal 中展示
- const fetchUserOwnedCoupons = async () => {
- const storeId = uni.getStorageSync('currentStoreId') || '';
- try {
- const res = await GetUserOwnedCouponList({ storeId });
- // 接口返回 { code, data: [...], msg, success },请求层可能只返回 data,故 res 可能为数组
- const list = Array.isArray(res) ? res : (res?.data ?? res?.records ?? res?.list ?? []);
- const normalized = (Array.isArray(list) ? list : []).map((item) => normalizeCouponItem(item)).filter(Boolean);
- storeUsableCouponList.value = normalized;
- return true;
- } catch (err) {
- console.error('获取用户优惠券失败:', err);
- uni.showToast({ title: '获取优惠券失败', icon: 'none' });
- return false;
- }
- };
- // 打开选择优惠券弹窗。viewOnly=true 仅查看(左下角),false 可选择并默认选中第一张(购物车内)
- const openSelectCouponModal = async (viewOnly = false) => {
- if (cartModalOpen.value) cartModalOpen.value = false;
- if (couponModalOpen.value) couponModalOpen.value = false;
- selectCouponViewOnly.value = viewOnly;
- const ok = await fetchUserOwnedCoupons();
- if (ok) {
- if (!viewOnly) {
- const list = storeUsableCouponList.value;
- if (list && list.length > 0) {
- const first = list[0];
- const firstId = first.id != null && first.id !== '' ? String(first.id) : null;
- selectedCouponId.value = firstId;
- discountAmount.value = first.amount ?? 0;
- } else {
- selectedCouponId.value = null;
- discountAmount.value = 0;
- }
- }
- await nextTick();
- selectCouponModalOpen.value = true;
- }
- };
- // 优惠券点击(左下角):仅查看,不可选择
- const handleCouponClick = () => {
- openSelectCouponModal(true);
- };
- // 选择优惠券点击(购物车内):可选择,默认选中第一张
- const handleSelectCouponClick = () => {
- openSelectCouponModal(false);
- };
- // 处理优惠券选择(单选:只保留当前选中的一张)
- const handleCouponSelect = ({ coupon, index, selectedId }) => {
- selectedCouponId.value = selectedId != null && selectedId !== '' ? String(selectedId) : null;
- // 根据选中的优惠券更新优惠金额
- if (selectedCouponId.value) {
- discountAmount.value = coupon.amount ?? 0;
- } else {
- discountAmount.value = 0;
- }
- // 选择后关闭选择优惠券弹窗,打开购物车弹窗
- selectCouponModalOpen.value = false;
- // 延迟打开购物车弹窗,确保选择优惠券弹窗完全关闭
- setTimeout(() => {
- cartModalOpen.value = true;
- }, 100);
- };
- // 选择优惠券弹窗关闭
- const handleSelectCouponClose = () => {
- selectCouponModalOpen.value = false;
- };
- // 优惠券弹窗关闭
- 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,成功后用接口返回的数据更新购物车
- const handleCartClear = () => {
- const items = cartData.value?.items ?? [];
- const dishItems = items.filter((it) => Number(it?.cuisineId ?? it?.id) !== -1);
- const applyClearResult = (res) => {
- const list = parseCartListFromResponse(res) ?? [];
- pendingCartData = list;
- const totalAmount = Number(res?.totalAmount) || 0;
- const totalQuantity = Number(res?.totalQuantity) || 0;
- const tablewareFee = Number(res?.tablewareFee ?? res?.tablewareAmount ?? 0) || list.reduce((s, it) => {
- if (Number(it?.cuisineId ?? it?.id) !== -1) return s;
- const line = it?.subtotalAmount != null ? Number(it.subtotalAmount) : (Number(it?.quantity) || 0) * (Number(it?.unitPrice ?? it?.price) || 0);
- return s + line;
- }, 0);
- cartData.value = { items: list, totalAmount, totalQuantity, tablewareFee };
- mergeCartIntoFoodList();
- cartModalOpen.value = false;
- uni.showToast({ title: '已清空购物车', icon: 'success' });
- };
- if (!tableId.value) {
- const tablewareItems = items.filter((it) => Number(it?.cuisineId ?? it?.id) === -1);
- const utensilFee = tablewareItems.reduce((sum, it) => {
- const line = it?.subtotalAmount != null ? Number(it.subtotalAmount) : (Number(it?.quantity) || 0) * (Number(it?.unitPrice ?? it?.price) || 0);
- return sum + line;
- }, 0);
- const utensilQty = tablewareItems.reduce((s, i) => s + (Number(i?.quantity) || 0), 0);
- applyClearResult({ items: tablewareItems, totalAmount: utensilFee, totalQuantity: utensilQty, tablewareFee: utensilFee });
- return;
- }
- if (dishItems.length === 0) {
- applyClearResult(cartData.value);
- return;
- }
- PostOrderCartClear(tableId.value)
- .then(applyClearResult)
- .catch((err) => {
- console.error('清空购物车失败:', err);
- uni.showToast({ title: '清空失败,请重试', icon: 'none' });
- });
- };
- // 从购物车项中计算餐具费:cuisineId/id 为 -1 的项为餐具,其金额合计为餐具费
- const getTablewareFeeFromCart = () => {
- const items = cartData.value?.items ?? displayCartList.value ?? [];
- return (Array.isArray(items) ? items : []).reduce((sum, it) => {
- const id = it?.cuisineId ?? it?.id;
- if (Number(id) !== -1) return sum;
- const line = it?.subtotalAmount != null ? Number(it.subtotalAmount) : (Number(it?.quantity) || 0) * (Number(it?.unitPrice ?? it?.price) || 0);
- return sum + line;
- }, 0);
- };
- // 下单点击:先带购物车数据跳转确认订单页,创建订单在确认页点击「确认下单」时再调
- const handleOrderClick = () => {
- // 仅餐具无菜品时不允许下单
- const items = displayCartList.value ?? [];
- const hasDish = items.some((it) => Number(it?.cuisineId ?? it?.id) !== -1);
- if (!hasDish && items.length > 0) {
- uni.showToast({ title: '请至少选择一道菜品', icon: 'none' });
- return;
- }
- if (items.length === 0) {
- uni.showToast({ title: '请先选择菜品', icon: 'none' });
- return;
- }
- const fromApi = Number(cartData.value?.tablewareFee) || 0;
- const fromItems = getTablewareFeeFromCart();
- const utensilFee = fromApi > 0 ? fromApi : fromItems;
- const totalAmount = displayTotalAmount.value;
- const dishTotal = Math.max(0, Number(totalAmount) - Number(utensilFee));
- const cartPayload = {
- list: displayCartListWithTags.value,
- totalAmount,
- dishTotal,
- totalQuantity: displayTotalQuantity.value,
- tableId: tableId.value,
- tableNumber: tableNumber.value,
- diners: currentDiners.value,
- utensilFee: Number(utensilFee) || 0
- };
- 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;
- fromNumberOfDiners.value = diners !== '' && diners != null; // 仅从选座页进入时带 diners 参数
- if (tableid) uni.setStorageSync('currentTableId', tableid);
- if (diners) uni.setStorageSync('currentDiners', diners);
- console.log('点餐页接收参数 - 桌号(tableid):', tableid, '就餐人数(diners):', diners);
- // 更新餐具数量:仅从选座页进入时调用 update-tableware 接口
- if (fromNumberOfDiners.value && tableid) {
- PutOrderCartUpdateTableware({
- quantity: Number(diners) || 1,
- tableId: parseInt(tableid, 10) || 0
- }).catch((err) => console.warn('更新餐具数量失败:', err));
- }
- // 先拉取购物车并缓存,再加载菜品,保证合并时 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,
- tablewareFee: Number(payload?.tablewareFee ?? payload?.tablewareAmount ?? 0) || (cartData.value?.tablewareFee ?? 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;
- storeName.value = data?.storeName ?? data?.storeInfo?.storeName ?? '';
- // 餐具费:点餐页接口可能返回,若购物车未带则用此处兜底
- const fee = Number(data?.tablewareFee ?? data?.tablewareAmount ?? 0) || 0;
- if (fee > 0) cartData.value = { ...cartData.value, tablewareFee: fee };
- // 成功后调接口获取菜品种类(storeId 取自点餐页接口返回,若无则需从别处获取)
- const storeId = res?.storeId ?? data?.storeId ?? '';
- if (storeId) uni.setStorageSync('currentStoreId', storeId);
- if (storeId && !storeName.value) {
- try {
- const storeRes = await GetStoreDetail(storeId);
- const storeData = storeRes?.data ?? storeRes;
- storeName.value = storeData?.storeInfo?.storeName ?? storeData?.storeName ?? '';
- } catch (_) {}
- }
- if (storeId) {
- await fetchCategoriesWithCuisines(storeId, searchKeyword.value?.trim() ?? '');
- }
- } catch (e) {
- console.error('点餐页接口失败:', e);
- tableNumberFetched.value = true;
- }
- } else {
- tableNumberFetched.value = true;
- const storeId = uni.getStorageSync('currentStoreId') || '';
- if (storeId && !storeName.value) {
- try {
- const storeRes = await GetStoreDetail(storeId);
- const storeData = storeRes?.data ?? storeRes;
- storeName.value = storeData?.storeInfo?.storeName ?? storeData?.storeName ?? '';
- } catch (_) {}
- }
- }
- });
- // 回到点餐页时重新获取购物车(从接口拉取最新数据并合并到列表)
- onShow(() => {
- const tableid = tableId.value || uni.getStorageSync('currentTableId') || '';
- if (tableid) {
- fetchAndMergeCart(tableid).catch((err) => console.warn('重新获取购物车失败:', err));
- }
- });
- onUnload(() => {
- if (sseRequestTask && typeof sseRequestTask.abort === 'function') {
- sseRequestTask.abort();
- }
- sseRequestTask = null;
- });
- </script>
- <style lang="scss" scoped>
- .page-wrap {
- height: 100vh;
- overflow: hidden;
- display: flex;
- flex-direction: column;
- background-color: #f7f9fa;
- }
- .top-fixed {
- flex-shrink: 0;
- z-index: 100;
- background-color: #fff;
- padding-bottom: 20rpx;
- }
- .content {
- flex: 1;
- min-height: 0;
- overflow: hidden;
- display: flex;
- flex-direction: column;
- /* 底部预留:BottomActionBar 高度(100rpx) + 内边距(20rpx) + 安全区 */
- padding-bottom: calc(120rpx + constant(safe-area-inset-bottom));
- padding-bottom: calc(120rpx + env(safe-area-inset-bottom));
- box-sizing: border-box;
- }
- .top-info {
- font-size: 28rpx;
- color: #888888;
- text-align: center;
- width: 100%;
- padding: 20rpx 0;
- background-color: #fff;
- }
- .search-box {
- width: 90%;
- margin-left: 5%;
- height: 80rpx;
- background-color: #f5f5f5;
- border-radius: 40rpx;
- margin-top: 20rpx;
- display: flex;
- align-items: center;
- justify-content: center;
- padding: 0 30rpx;
- box-sizing: border-box;
- .search-box-inner {
- display: flex;
- align-items: center;
- justify-content: center;
- }
- .search-icon {
- width: 34rpx;
- height: 34rpx;
- flex-shrink: 0;
- display: block;
- }
- .search-input {
- width: 200rpx;
- height: 80rpx;
- line-height: 80rpx;
- font-size: 28rpx;
- color: #333;
- background: transparent;
- border: none;
- text-align: center;
- vertical-align: middle;
- }
- }
- .content-box {
- flex: 1;
- min-height: 0;
- overflow: hidden;
- display: flex;
- margin-top: 20rpx;
- }
- // 左侧分类列表容器(给 scroll-view 提供固定高度)
- .category-list-wrap {
- width: 180rpx;
- flex-shrink: 0;
- min-height: 0;
- display: flex;
- flex-direction: column;
- overflow: hidden;
- align-self: stretch;
- }
- .category-list {
- flex: 1;
- min-height: 0;
- height: 100%;
- background-color: #fff;
- box-sizing: border-box;
- }
- .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;
- }
- }
- // 右侧菜品列表容器(给 scroll-view 提供固定高度)
- .food-list-wrap {
- flex: 1;
- min-width: 0;
- min-height: 0;
- display: flex;
- flex-direction: column;
- overflow: hidden;
- margin: 0 20rpx;
- }
- .food-list {
- flex: 1;
- min-height: 0;
- height: 100%;
- }
- .food-section {
- margin-bottom: 24rpx;
- &__title {
- font-size: 28rpx;
- font-weight: 600;
- color: #333;
- padding: 16rpx 0 12rpx;
- background-color: #f7f9fa;
- padding-left: 20rpx;
- }
- }
- </style>
|