| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584 |
- <template>
- <!-- 下单页面 -->
- <view class="content">
- <!-- 订单卡片 -->
- <view class="card">
- <view class="card-header">
- <view class='tag'></view>
- <view class="card-header-title">订单信息</view>
- </view>
- <view class="card-content">
- <view class="info-item">
- <view class="info-item-label">就餐桌号</view>
- <view class="info-item-value">{{ orderInfo.tableNumber || orderInfo.tableId || '—' }}</view>
- </view>
- <view class="info-item">
- <view class="info-item-label">用餐人数</view>
- <view class="info-item-value">{{ orderInfo.diners || '—' }}</view>
- </view>
- <view class="info-item">
- <view class="info-item-label">联系电话</view>
- <view class="info-item-value">{{ orderInfo.contactPhone || '—' }}</view>
- </view>
- <view class="info-item">
- <view class="info-item-label">备注信息</view>
- </view>
- <textarea
- v-model="orderInfo.remark"
- placeholder="请输入特殊需求,如少辣、不要香菜等(最多30字)"
- class="info-item-textarea"
- maxlength="30"
- ></textarea>
- </view>
- </view>
- <!-- 菜品清单 -->
- <view class="card">
- <view class="card-header">
- <view class='tag'></view>
- <view class="card-header-title">菜品清单</view>
- </view>
- <view class="card-content">
- <view class="info-food">
- <view v-for="(item, index) in foodList" :key="item.id || item.cuisineId || index" class="food-item">
- <!-- 菜品图片:兼容 cuisineImage/image,逗号分隔取首图 -->
- <image :src="getItemImage(item)" mode="aspectFill" class="food-item__image"></image>
- <!-- 菜品信息 -->
- <view class="food-item__info">
- <view class="food-item__name">{{ item.name || item.cuisineName }}</view>
- <view class="food-item__desc" v-if="item.tags && item.tags.length > 0">
- <text v-for="(tag, tagIndex) in item.tags" :key="tagIndex" class="food-item__tag"
- :class="tag.type">{{ tag.text }}<text v-if="tagIndex < item.tags.length - 1">,</text>
- </text>
- </view>
- </view>
- <!-- 价格和数量 -->
- <view class="food-item__right">
- <view class="food-item__price">
- <text class="price-main">¥{{ formatPrice(getItemPrice(item)) }}</text>
- </view>
- <view class="food-item__quantity">{{ item.quantity || 1 }}份</view>
- </view>
- </view>
- </view>
- </view>
- </view>
- <!-- 总价 -->
- <view class="card">
- <view class="card-header">
- <view class='tag'></view>
- <view class="card-header-title">价格明细</view>
- </view>
- <view class="card-content">
- <view class="info-item">
- <view class="info-item-label">菜品总价</view>
- <view class="info-item-value">¥{{ formatPrice(dishTotal) }}</view>
- </view>
- <view class="info-item">
- <view class="info-item-label">服务费</view>
- <view class="info-item-value">¥{{ formatPrice(orderInfo.serviceFee ?? 0) }}</view>
- </view>
- <view class="price-line">
- <view class="price-line-label">应付金额</view>
- <view class="price-line-value">¥{{ formatPrice(orderInfo.payAmount ?? orderInfo.totalAmount) }}</view>
- </view>
- </view>
- </view>
- <!-- 底部按钮:确认下单(去结算请走 pages/checkout/index) -->
- <view class="bottom-button">
- <view class="bottom-button-text" hover-class="hover-active" @click="handleConfirmOrder">确认下单</view>
- </view>
- </view>
- </template>
- <script setup>
- import { onLoad, onShow, onUnload } from "@dcloudio/uni-app";
- import { ref, computed } from "vue";
- import { go } from "@/utils/utils.js";
- import { getFileUrl } from "@/utils/file.js";
- import { useUserStore } from "@/store/user.js";
- import * as diningApi from "@/api/dining.js";
- // 订单信息(从购物车带过来或 URL 参数)
- const orderInfo = ref({
- orderNo: '',
- tableId: '',
- tableNumber: '',
- diners: '',
- contactPhone: '',
- remark: '',
- totalAmount: 0,
- dishTotal: null,
- serviceFee: 0,
- discountAmount: 0,
- payAmount: 0,
- couponId: null
- });
- // 菜品列表(从购物车带过来)
- const foodList = ref([]);
- // 菜品清单展示:排除特殊占位项(id/cuisineId === -1)
- const displayFoodList = computed(() => {
- return (foodList.value ?? []).filter((it) => Number(it?.id ?? it?.cuisineId) !== -1);
- });
- // 菜品成交价小计(元,不含服务费):与点餐页购物车、服务费估算 goodsSubtotal 一致
- const dishTotal = computed(() => {
- const list = displayFoodList.value ?? [];
- const sum = list.reduce((s, it) => {
- if (it?.subtotalAmount != null && it.subtotalAmount !== '') {
- return s + (Number(it.subtotalAmount) || 0);
- }
- const qty = Number(it?.quantity) || 0;
- const unitPrice =
- Number(it?.unitPrice ?? it?.price ?? it?.salePrice ?? it?.totalPrice ?? 0) || 0;
- return s + qty * unitPrice;
- }, 0);
- return Math.max(0, Math.round(sum * 100) / 100);
- });
- function getItemImage(item) {
- const raw = item?.cuisineImage ?? item?.image ?? item?.imageUrl ?? '';
- const url = typeof raw === 'string' ? raw.split(',')[0].trim() : raw;
- return url ? getFileUrl(url) : '';
- }
- // 单品单价:列表展示用 unitPrice/price
- function getItemPrice(item) {
- const p = item?.unitPrice ?? item?.price ?? item?.totalPrice ?? item?.salePrice ?? 0;
- return Number(p) || 0;
- }
- function formatPrice(price) {
- const num = Number(price);
- return Number.isNaN(num) ? '0.00' : num.toFixed(2);
- }
- // 应付金额 = 菜品总价 + 服务费(优惠券在结算页选择)
- const updatePayAmount = () => {
- const dish = dishTotal.value;
- const fee = Number(orderInfo.value.serviceFee) || 0;
- orderInfo.value.payAmount = Math.max(0, dish + fee);
- orderInfo.value.totalAmount = orderInfo.value.payAmount;
- };
- /** 解析 /service-fee/estimate 的 data:顶层 serviceFee 或 items[].amount 汇总(与结算页接口结构一致) */
- function parseServiceFeeFromEstimate(res) {
- if (res == null) return 0;
- if (typeof res === 'number' && Number.isFinite(res)) return Math.max(0, res);
- if (typeof res !== 'object') return 0;
- const top = Number(
- res.serviceFee ?? res.estimatedServiceFee ?? res.fee ?? res.amount ?? NaN
- );
- if (Number.isFinite(top) && top > 0) return top;
- const items = Array.isArray(res.items) ? res.items : [];
- const sumItems = items.reduce(
- (s, it) => s + (Number(it?.amount ?? it?.fee ?? it?.serviceFee ?? 0) || 0),
- 0
- );
- if (sumItems > 0) return sumItems;
- if (Number.isFinite(top)) return Math.max(0, top);
- return 0;
- }
- /** 加载时按门店/桌台/人数/菜品小计拉取服务端服务费估算 */
- async function fetchServiceFeeEstimate(storeIdFromCart) {
- const storeId =
- (storeIdFromCart != null && String(storeIdFromCart).trim() !== '' ? String(storeIdFromCart).trim() : '') ||
- uni.getStorageSync('currentStoreId') ||
- '';
- const tableId =
- (orderInfo.value.tableId != null && String(orderInfo.value.tableId).trim() !== ''
- ? String(orderInfo.value.tableId).trim()
- : '') || String(uni.getStorageSync('currentTableId') || '').trim();
- if (!storeId || !tableId) return;
- const rawDiners = Number(orderInfo.value.diners);
- const dinerCount = Number.isFinite(rawDiners) && rawDiners > 0 ? Math.floor(rawDiners) : 1;
- const goodsSubtotal = Number(dishTotal.value.toFixed(2));
- try {
- const res = await diningApi.GetServiceFeeEstimate({
- storeId,
- tableId,
- dinerCount,
- goodsSubtotal
- });
- const fee = parseServiceFeeFromEstimate(res);
- orderInfo.value.serviceFee = fee;
- updatePayAmount();
- } catch (e) {
- console.warn('服务费估算失败:', e);
- }
- }
- // 将 tags 统一为 [{ text, type }] 格式
- 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') arr = Array.isArray(raw.list) ? raw.list : Array.isArray(raw.items) ? raw.items : [];
- return arr.map((it) => {
- if (it == null) return { text: '', type: '' };
- if (typeof it === 'string') return { text: it, type: '' };
- if (typeof it === 'number') return { text: String(it), type: '' };
- return { text: it.text ?? it.tagName ?? it.name ?? it.label ?? it.title ?? '', type: it.type ?? it.tagType ?? '' };
- }).filter((t) => t.text !== '' && t.text != null);
- }
- // 将存储的购物车项转为确认页展示格式(兼容 cuisineName/cuisineImage/unitPrice/tags 等)
- function normalizeCartItem(item) {
- const image = item?.cuisineImage ?? item?.image ?? item?.imageUrl ?? '';
- const url = typeof image === 'string' ? image.split(',')[0].trim() : image;
- const rawTags = item?.tags ?? item?.tagList ?? item?.tagNames ?? item?.labels ?? item?.tag;
- return {
- id: item?.id ?? item?.cuisineId,
- name: item?.name ?? item?.cuisineName,
- cuisineName: item?.cuisineName,
- price: item?.unitPrice ?? item?.price,
- image: url,
- cuisineImage: item?.cuisineImage,
- quantity: Number(item?.quantity) || 0,
- tags: normalizeTags(rawTags),
- subtotalAmount: item?.subtotalAmount,
- remark: item?.remark
- };
- }
- const handleConfirmOrder = async () => {
- const tableId =
- (orderInfo.value.tableId != null && String(orderInfo.value.tableId).trim() !== ''
- ? String(orderInfo.value.tableId).trim()
- : '') || String(uni.getStorageSync('currentTableId') || '').trim();
- const contactPhone = orderInfo.value.contactPhone ?? '';
- const dinerCount = Number(orderInfo.value.diners) || 0;
- if (!tableId) {
- uni.showToast({ title: '请先选择桌号', icon: 'none' });
- return;
- }
- if (!contactPhone) {
- uni.showToast({ title: '请先填写联系电话', icon: 'none' });
- return;
- }
- const remark = (orderInfo.value.remark ?? '').trim().slice(0, 30);
- uni.showLoading({ title: '提交中...' });
- try {
- const serviceFeeVal = Number(orderInfo.value.serviceFee) || 0;
- const payAmount = Number((Number(orderInfo.value.payAmount) ?? 0).toFixed(2));
- const totalAmount = Number((Number(dishTotal.value) ?? 0).toFixed(2));
- const createParams = {
- tableId,
- contactPhone,
- totalAmount,
- tablewareFee: 0,
- serviceFee: serviceFeeVal,
- payAmount,
- dinerCount: dinerCount || undefined,
- immediatePay: 0,
- remark: remark || undefined
- };
- const res = await diningApi.PostOrderCreate(createParams);
- uni.hideLoading();
- const orderId = res?.id ?? res?.orderId ?? res?.data?.id ?? res?.data?.orderId;
- const orderNo = res?.orderNo ?? res?.data?.orderNo ?? orderId ?? '';
- const total = orderInfo.value.payAmount ?? orderInfo.value.totalAmount ?? 0;
- // 结果页「去结算」需带 orderId/orderNo/金额/备注,用于确认支付
- uni.setStorageSync('lastPlaceOrderInfo', JSON.stringify({
- orderId: orderId ?? undefined,
- orderNo: orderNo ?? undefined,
- tableId: orderInfo.value.tableId,
- tableNumber: orderInfo.value.tableNumber,
- diners: orderInfo.value.diners,
- totalAmount: total,
- remark: (orderInfo.value.remark ?? '').trim().slice(0, 30)
- }));
- // 确认下单成功后即将跳转,此时页面不会触发 onUnload,需主动调用解锁
- const unlockFn = diningApi.PostOrderUnlock || diningApi.postOrderUnlock;
- if (typeof unlockFn === 'function' && tableId) {
- unlockFn({ tableId }).catch((err) => console.warn('解锁订单失败:', err));
- }
- if (orderId != null) {
- go(`/pages/result/index?id=${encodeURIComponent(orderId)}`);
- } else {
- go('/pages/result/index');
- }
- } catch (e) {
- uni.hideLoading();
- uni.showToast({ title: e?.message || '下单失败', icon: 'none' });
- }
- };
- onLoad((options) => {
- const userStore = useUserStore();
- const contactPhone = userStore.getUserInfo?.phone ?? userStore.getUserInfo?.contactPhone ?? userStore.getUserInfo?.mobile ?? '';
- orderInfo.value.contactPhone = contactPhone;
- let cartStoreId = '';
- const raw = uni.getStorageSync('placeOrderCart');
- if (raw) {
- try {
- const data = JSON.parse(raw);
- const list = Array.isArray(data.list) ? data.list : [];
- foodList.value = list.map(normalizeCartItem).filter((item) => (item.quantity || 0) > 0);
- if (data.tableId != null) orderInfo.value.tableId = data.tableId;
- if (data.tableNumber != null) orderInfo.value.tableNumber = data.tableNumber;
- if (data.diners != null) orderInfo.value.diners = data.diners;
- if (data.remark != null) orderInfo.value.remark = data.remark;
- if (data.storeId != null && data.storeId !== '') cartStoreId = String(data.storeId);
- const total = Number(data.totalAmount) || 0;
- orderInfo.value.totalAmount = total;
- if (data.dishTotal != null && data.dishTotal !== '') orderInfo.value.dishTotal = Number(data.dishTotal) || 0;
- orderInfo.value.serviceFee =
- Number(data.serviceFee ?? data.serviceCharge ?? data.utensilFee ?? data.tablewareFee ?? 0) ||
- 0;
- updatePayAmount();
- } catch (e) {
- console.error('解析购物车数据失败:', e);
- orderInfo.value.serviceFee = 0;
- }
- } else {
- orderInfo.value.serviceFee = 0;
- }
- if (orderInfo.value.tableId) uni.setStorageSync('currentTableId', String(orderInfo.value.tableId));
- fetchServiceFeeEstimate(cartStoreId);
- // 不再主动调用 userOwnedByStore,优惠券在点击「优惠券」行打开弹窗时再拉取
- });
- // 每次进入页面(含从其他页返回)都调用锁定订单接口
- onShow(() => {
- const tableId = orderInfo.value?.tableId;
- if (tableId) {
- (diningApi.PostOrderLock || diningApi.postOrderLock)({ tableId }).catch((err) => {
- console.warn('锁定订单失败:', err);
- });
- }
- });
- // 离开页面时调用解锁订单接口
- onUnload(() => {
- const tableId = orderInfo.value?.tableId;
- if (tableId && typeof (diningApi.PostOrderUnlock || diningApi.postOrderUnlock) === 'function') {
- (diningApi.PostOrderUnlock || diningApi.postOrderUnlock)({ tableId }).catch((err) => {
- console.warn('解锁订单失败:', err);
- });
- }
- });
- </script>
- <style lang="scss" scoped>
- .content {
- padding: 0 30rpx 300rpx;
- }
- .card {
- background-color: #fff;
- border-radius: 24rpx;
- padding: 30rpx 0;
- margin-top: 20rpx;
- .card-header {
- display: flex;
- justify-content: space-between;
- align-items: center;
- padding: 0 30rpx;
- height: 40rpx;
- position: relative;
- font-size: 27rpx;
- color: #151515;
- font-weight: bold;
- }
- .tag {
- width: 10rpx;
- height: 42rpx;
- background: linear-gradient(35deg, #FCB73F 0%, #FC733D 100%);
- border-radius: 0rpx 0rpx 0rpx 0rpx;
- position: absolute;
- left: 0;
- top: 0;
- }
- .card-content {
- padding: 0 30rpx;
- }
- .info-item {
- display: flex;
- justify-content: space-between;
- align-items: center;
- margin-top: 20rpx;
- font-size: 27rpx;
- .info-item-label {
- color: #666666;
- }
- .info-item-value {
- color: #151515;
- }
- &--clickable {
- cursor: pointer;
- }
- &--coupon .coupon-value {
- display: flex;
- align-items: center;
- gap: 8rpx;
- }
- .coupon-amount {
- color: #E61F19;
- }
- .coupon-placeholder {
- color: #999999;
- }
- .coupon-arrow {
- color: #999999;
- font-size: 32rpx;
- }
- }
- .info-item-textarea {
- width: 100%;
- height: 115rpx;
- border-radius: 8rpx;
- border: 1rpx solid #F2F2F2;
- margin-top: 20rpx;
- font-size: 23rpx;
- color: #AAAAAA;
- box-sizing: border-box;
- padding: 20rpx;
- }
- .info-food {
- margin-top: 20rpx;
- }
- .food-item {
- display: flex;
- align-items: center;
- padding: 20rpx 0;
- &:last-child {
- border-bottom: none;
- }
- &__image {
- width: 118rpx;
- height: 118rpx;
- border-radius: 8rpx;
- flex-shrink: 0;
- background-color: #f5f5f5;
- }
- &__info {
- flex: 1;
- margin-left: 20rpx;
- display: flex;
- flex-direction: column;
- justify-content: center;
- }
- &__name {
- font-size: 28rpx;
- font-weight: bold;
- color: #151515;
- margin-bottom: 8rpx;
- }
- &__desc {
- font-size: 24rpx;
- color: #666666;
- line-height: 1.5;
- }
- &__tag {
- font-size: 24rpx;
- color: #666666;
- }
- &__right {
- display: flex;
- flex-direction: column;
- align-items: flex-end;
- justify-content: center;
- margin-left: 20rpx;
- }
- &__price {
- display: flex;
- align-items: baseline;
- color: #151515;
- font-weight: bold;
- margin-bottom: 8rpx;
- .price-symbol {
- font-size: 20rpx;
- margin-right: 2rpx;
- }
- .price-main {
- font-size: 28rpx;
- }
- .price-decimal {
- font-size: 24rpx;
- }
- }
- &__quantity {
- font-size: 24rpx;
- color: #797979;
- }
- }
- .price-line {
- display: flex;
- justify-content: space-between;
- align-items: center;
- margin-top: 20rpx;
- font-size: 27rpx;
- color: #151515;
- border-top: 1rpx solid rgba(170, 170, 170, 0.15);
- font-weight: bold;
- padding-top: 20rpx;
- }
- }
- .bottom-button {
- width: 100%;
- background-color: #fff;
- padding: 20rpx 30rpx;
- box-sizing: border-box;
- position: fixed;
- bottom: 0;
- left: 0;
- right: 0;
- z-index: 999;
- padding-bottom: env(safe-area-inset-bottom);
- box-shadow: 0rpx -11rpx 46rpx 0rpx rgba(0, 0, 0, 0.05);
- .bottom-button-text {
- font-size: 32rpx;
- font-weight: bold;
- color: #fff;
- width: 695rpx;
- height: 80rpx;
- background: linear-gradient(90deg, #FCB73F 0%, #FC743D 100%);
- border-radius: 23rpx 23rpx 23rpx 23rpx;
- display: flex;
- align-items: center;
- justify-content: center;
- }
- }
- </style>
|