index.vue 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  1. <template>
  2. <!-- 下单页面 -->
  3. <view class="content">
  4. <!-- 订单卡片 -->
  5. <view class="card">
  6. <view class="card-header">
  7. <view class='tag'></view>
  8. <view class="card-header-title">订单信息</view>
  9. </view>
  10. <view class="card-content">
  11. <view class="info-item">
  12. <view class="info-item-label">就餐桌号</view>
  13. <view class="info-item-value">{{ orderInfo.tableNumber || orderInfo.tableId || '—' }}</view>
  14. </view>
  15. <view class="info-item">
  16. <view class="info-item-label">用餐人数</view>
  17. <view class="info-item-value">{{ orderInfo.diners || '—' }}</view>
  18. </view>
  19. <view class="info-item">
  20. <view class="info-item-label">联系电话</view>
  21. <view class="info-item-value">{{ orderInfo.contactPhone || '—' }}</view>
  22. </view>
  23. <view class="info-item">
  24. <view class="info-item-label">备注信息</view>
  25. </view>
  26. <textarea
  27. v-model="orderInfo.remark"
  28. placeholder="请输入特殊需求,如少辣、不要香菜等(最多30字)"
  29. class="info-item-textarea"
  30. maxlength="30"
  31. ></textarea>
  32. </view>
  33. </view>
  34. <!-- 菜品清单 -->
  35. <view class="card">
  36. <view class="card-header">
  37. <view class='tag'></view>
  38. <view class="card-header-title">菜品清单</view>
  39. </view>
  40. <view class="card-content">
  41. <view class="info-food">
  42. <view v-for="(item, index) in foodList" :key="item.id || item.cuisineId || index" class="food-item">
  43. <!-- 菜品图片:兼容 cuisineImage/image,逗号分隔取首图 -->
  44. <image :src="getItemImage(item)" mode="aspectFill" class="food-item__image"></image>
  45. <!-- 菜品信息 -->
  46. <view class="food-item__info">
  47. <view class="food-item__name">{{ item.name || item.cuisineName }}</view>
  48. <view class="food-item__desc" v-if="item.tags && item.tags.length > 0">
  49. <text v-for="(tag, tagIndex) in item.tags" :key="tagIndex" class="food-item__tag"
  50. :class="tag.type">{{ tag.text }}<text v-if="tagIndex < item.tags.length - 1">,</text>
  51. </text>
  52. </view>
  53. </view>
  54. <!-- 价格和数量 -->
  55. <view class="food-item__right">
  56. <view class="food-item__price">
  57. <text class="price-main">¥{{ formatPrice(getItemPrice(item)) }}</text>
  58. </view>
  59. <view class="food-item__quantity">{{ item.quantity || 1 }}份</view>
  60. </view>
  61. </view>
  62. </view>
  63. </view>
  64. </view>
  65. <!-- 总价 -->
  66. <view class="card">
  67. <view class="card-header">
  68. <view class='tag'></view>
  69. <view class="card-header-title">价格明细</view>
  70. </view>
  71. <view class="card-content">
  72. <view class="info-item">
  73. <view class="info-item-label">菜品总价</view>
  74. <view class="info-item-value">¥{{ formatPrice(dishTotal) }}</view>
  75. </view>
  76. <view class="info-item">
  77. <view class="info-item-label">服务费</view>
  78. <view class="info-item-value">¥{{ formatPrice(orderInfo.serviceFee ?? 0) }}</view>
  79. </view>
  80. <view class="price-line">
  81. <view class="price-line-label">应付金额</view>
  82. <view class="price-line-value">¥{{ formatPrice(orderInfo.payAmount ?? orderInfo.totalAmount) }}</view>
  83. </view>
  84. </view>
  85. </view>
  86. <!-- 底部按钮:确认下单(去结算请走 pages/checkout/index) -->
  87. <view class="bottom-button">
  88. <view class="bottom-button-text" hover-class="hover-active" @click="handleConfirmOrder">确认下单</view>
  89. </view>
  90. </view>
  91. </template>
  92. <script setup>
  93. import { onLoad, onShow, onUnload } from "@dcloudio/uni-app";
  94. import { ref, computed } from "vue";
  95. import { go } from "@/utils/utils.js";
  96. import { getFileUrl } from "@/utils/file.js";
  97. import { useUserStore } from "@/store/user.js";
  98. import * as diningApi from "@/api/dining.js";
  99. // 订单信息(从购物车带过来或 URL 参数)
  100. const orderInfo = ref({
  101. orderNo: '',
  102. tableId: '',
  103. tableNumber: '',
  104. diners: '',
  105. contactPhone: '',
  106. remark: '',
  107. totalAmount: 0,
  108. dishTotal: null,
  109. serviceFee: 0,
  110. discountAmount: 0,
  111. payAmount: 0,
  112. couponId: null
  113. });
  114. // 菜品列表(从购物车带过来)
  115. const foodList = ref([]);
  116. // 菜品清单展示:排除特殊占位项(id/cuisineId === -1)
  117. const displayFoodList = computed(() => {
  118. return (foodList.value ?? []).filter((it) => Number(it?.id ?? it?.cuisineId) !== -1);
  119. });
  120. // 菜品成交价小计(元,不含服务费):与点餐页购物车、服务费估算 goodsSubtotal 一致
  121. const dishTotal = computed(() => {
  122. const list = displayFoodList.value ?? [];
  123. const sum = list.reduce((s, it) => {
  124. if (it?.subtotalAmount != null && it.subtotalAmount !== '') {
  125. return s + (Number(it.subtotalAmount) || 0);
  126. }
  127. const qty = Number(it?.quantity) || 0;
  128. const unitPrice =
  129. Number(it?.unitPrice ?? it?.price ?? it?.salePrice ?? it?.totalPrice ?? 0) || 0;
  130. return s + qty * unitPrice;
  131. }, 0);
  132. return Math.max(0, Math.round(sum * 100) / 100);
  133. });
  134. function getItemImage(item) {
  135. const raw = item?.cuisineImage ?? item?.image ?? item?.imageUrl ?? '';
  136. const url = typeof raw === 'string' ? raw.split(',')[0].trim() : raw;
  137. return url ? getFileUrl(url) : '';
  138. }
  139. // 单品单价:列表展示用 unitPrice/price
  140. function getItemPrice(item) {
  141. const p = item?.unitPrice ?? item?.price ?? item?.totalPrice ?? item?.salePrice ?? 0;
  142. return Number(p) || 0;
  143. }
  144. function formatPrice(price) {
  145. const num = Number(price);
  146. return Number.isNaN(num) ? '0.00' : num.toFixed(2);
  147. }
  148. // 应付金额 = 菜品总价 + 服务费(优惠券在结算页选择)
  149. const updatePayAmount = () => {
  150. const dish = dishTotal.value;
  151. const fee = Number(orderInfo.value.serviceFee) || 0;
  152. orderInfo.value.payAmount = Math.max(0, dish + fee);
  153. orderInfo.value.totalAmount = orderInfo.value.payAmount;
  154. };
  155. /** 解析 /service-fee/estimate 的 data:顶层 serviceFee 或 items[].amount 汇总(与结算页接口结构一致) */
  156. function parseServiceFeeFromEstimate(res) {
  157. if (res == null) return 0;
  158. if (typeof res === 'number' && Number.isFinite(res)) return Math.max(0, res);
  159. if (typeof res !== 'object') return 0;
  160. const top = Number(
  161. res.serviceFee ?? res.estimatedServiceFee ?? res.fee ?? res.amount ?? NaN
  162. );
  163. if (Number.isFinite(top) && top > 0) return top;
  164. const items = Array.isArray(res.items) ? res.items : [];
  165. const sumItems = items.reduce(
  166. (s, it) => s + (Number(it?.amount ?? it?.fee ?? it?.serviceFee ?? 0) || 0),
  167. 0
  168. );
  169. if (sumItems > 0) return sumItems;
  170. if (Number.isFinite(top)) return Math.max(0, top);
  171. return 0;
  172. }
  173. /** 加载时按门店/桌台/人数/菜品小计拉取服务端服务费估算 */
  174. async function fetchServiceFeeEstimate(storeIdFromCart) {
  175. const storeId =
  176. (storeIdFromCart != null && String(storeIdFromCart).trim() !== '' ? String(storeIdFromCart).trim() : '') ||
  177. uni.getStorageSync('currentStoreId') ||
  178. '';
  179. const tableId =
  180. (orderInfo.value.tableId != null && String(orderInfo.value.tableId).trim() !== ''
  181. ? String(orderInfo.value.tableId).trim()
  182. : '') || String(uni.getStorageSync('currentTableId') || '').trim();
  183. if (!storeId || !tableId) return;
  184. const rawDiners = Number(orderInfo.value.diners);
  185. const dinerCount = Number.isFinite(rawDiners) && rawDiners > 0 ? Math.floor(rawDiners) : 1;
  186. const goodsSubtotal = Number(dishTotal.value.toFixed(2));
  187. try {
  188. const res = await diningApi.GetServiceFeeEstimate({
  189. storeId,
  190. tableId,
  191. dinerCount,
  192. goodsSubtotal
  193. });
  194. const fee = parseServiceFeeFromEstimate(res);
  195. orderInfo.value.serviceFee = fee;
  196. updatePayAmount();
  197. } catch (e) {
  198. console.warn('服务费估算失败:', e);
  199. }
  200. }
  201. // 将 tags 统一为 [{ text, type }] 格式
  202. function normalizeTags(raw) {
  203. if (raw == null) return [];
  204. let arr = [];
  205. if (Array.isArray(raw)) arr = raw;
  206. else if (typeof raw === 'string') {
  207. const t = raw.trim();
  208. if (t.startsWith('[')) { try { arr = JSON.parse(t); if (!Array.isArray(arr)) arr = []; } catch { arr = t ? [t] : []; } }
  209. else arr = t ? t.split(/[,,、\s]+/).map(s => s.trim()).filter(Boolean) : [];
  210. } else if (raw && typeof raw === 'object') arr = Array.isArray(raw.list) ? raw.list : Array.isArray(raw.items) ? raw.items : [];
  211. return arr.map((it) => {
  212. if (it == null) return { text: '', type: '' };
  213. if (typeof it === 'string') return { text: it, type: '' };
  214. if (typeof it === 'number') return { text: String(it), type: '' };
  215. return { text: it.text ?? it.tagName ?? it.name ?? it.label ?? it.title ?? '', type: it.type ?? it.tagType ?? '' };
  216. }).filter((t) => t.text !== '' && t.text != null);
  217. }
  218. // 将存储的购物车项转为确认页展示格式(兼容 cuisineName/cuisineImage/unitPrice/tags 等)
  219. function normalizeCartItem(item) {
  220. const image = item?.cuisineImage ?? item?.image ?? item?.imageUrl ?? '';
  221. const url = typeof image === 'string' ? image.split(',')[0].trim() : image;
  222. const rawTags = item?.tags ?? item?.tagList ?? item?.tagNames ?? item?.labels ?? item?.tag;
  223. return {
  224. id: item?.id ?? item?.cuisineId,
  225. name: item?.name ?? item?.cuisineName,
  226. cuisineName: item?.cuisineName,
  227. price: item?.unitPrice ?? item?.price,
  228. image: url,
  229. cuisineImage: item?.cuisineImage,
  230. quantity: Number(item?.quantity) || 0,
  231. tags: normalizeTags(rawTags),
  232. subtotalAmount: item?.subtotalAmount,
  233. remark: item?.remark
  234. };
  235. }
  236. const handleConfirmOrder = async () => {
  237. const tableId =
  238. (orderInfo.value.tableId != null && String(orderInfo.value.tableId).trim() !== ''
  239. ? String(orderInfo.value.tableId).trim()
  240. : '') || String(uni.getStorageSync('currentTableId') || '').trim();
  241. const contactPhone = orderInfo.value.contactPhone ?? '';
  242. const dinerCount = Number(orderInfo.value.diners) || 0;
  243. if (!tableId) {
  244. uni.showToast({ title: '请先选择桌号', icon: 'none' });
  245. return;
  246. }
  247. if (!contactPhone) {
  248. uni.showToast({ title: '请先填写联系电话', icon: 'none' });
  249. return;
  250. }
  251. const remark = (orderInfo.value.remark ?? '').trim().slice(0, 30);
  252. uni.showLoading({ title: '提交中...' });
  253. try {
  254. const serviceFeeVal = Number(orderInfo.value.serviceFee) || 0;
  255. const payAmount = Number((Number(orderInfo.value.payAmount) ?? 0).toFixed(2));
  256. const totalAmount = Number((Number(dishTotal.value) ?? 0).toFixed(2));
  257. const createParams = {
  258. tableId,
  259. contactPhone,
  260. totalAmount,
  261. tablewareFee: 0,
  262. serviceFee: serviceFeeVal,
  263. payAmount,
  264. dinerCount: dinerCount || undefined,
  265. immediatePay: 0,
  266. remark: remark || undefined
  267. };
  268. const res = await diningApi.PostOrderCreate(createParams);
  269. uni.hideLoading();
  270. const orderId = res?.id ?? res?.orderId ?? res?.data?.id ?? res?.data?.orderId;
  271. const orderNo = res?.orderNo ?? res?.data?.orderNo ?? orderId ?? '';
  272. const total = orderInfo.value.payAmount ?? orderInfo.value.totalAmount ?? 0;
  273. // 结果页「去结算」需带 orderId/orderNo/金额/备注,用于确认支付
  274. uni.setStorageSync('lastPlaceOrderInfo', JSON.stringify({
  275. orderId: orderId ?? undefined,
  276. orderNo: orderNo ?? undefined,
  277. tableId: orderInfo.value.tableId,
  278. tableNumber: orderInfo.value.tableNumber,
  279. diners: orderInfo.value.diners,
  280. totalAmount: total,
  281. remark: (orderInfo.value.remark ?? '').trim().slice(0, 30)
  282. }));
  283. // 确认下单成功后即将跳转,此时页面不会触发 onUnload,需主动调用解锁
  284. const unlockFn = diningApi.PostOrderUnlock || diningApi.postOrderUnlock;
  285. if (typeof unlockFn === 'function' && tableId) {
  286. unlockFn({ tableId }).catch((err) => console.warn('解锁订单失败:', err));
  287. }
  288. if (orderId != null) {
  289. go(`/pages/result/index?id=${encodeURIComponent(orderId)}`);
  290. } else {
  291. go('/pages/result/index');
  292. }
  293. } catch (e) {
  294. uni.hideLoading();
  295. uni.showToast({ title: e?.message || '下单失败', icon: 'none' });
  296. }
  297. };
  298. onLoad((options) => {
  299. const userStore = useUserStore();
  300. const contactPhone = userStore.getUserInfo?.phone ?? userStore.getUserInfo?.contactPhone ?? userStore.getUserInfo?.mobile ?? '';
  301. orderInfo.value.contactPhone = contactPhone;
  302. let cartStoreId = '';
  303. const raw = uni.getStorageSync('placeOrderCart');
  304. if (raw) {
  305. try {
  306. const data = JSON.parse(raw);
  307. const list = Array.isArray(data.list) ? data.list : [];
  308. foodList.value = list.map(normalizeCartItem).filter((item) => (item.quantity || 0) > 0);
  309. if (data.tableId != null) orderInfo.value.tableId = data.tableId;
  310. if (data.tableNumber != null) orderInfo.value.tableNumber = data.tableNumber;
  311. if (data.diners != null) orderInfo.value.diners = data.diners;
  312. if (data.remark != null) orderInfo.value.remark = data.remark;
  313. if (data.storeId != null && data.storeId !== '') cartStoreId = String(data.storeId);
  314. const total = Number(data.totalAmount) || 0;
  315. orderInfo.value.totalAmount = total;
  316. if (data.dishTotal != null && data.dishTotal !== '') orderInfo.value.dishTotal = Number(data.dishTotal) || 0;
  317. orderInfo.value.serviceFee =
  318. Number(data.serviceFee ?? data.serviceCharge ?? data.utensilFee ?? data.tablewareFee ?? 0) ||
  319. 0;
  320. updatePayAmount();
  321. } catch (e) {
  322. console.error('解析购物车数据失败:', e);
  323. orderInfo.value.serviceFee = 0;
  324. }
  325. } else {
  326. orderInfo.value.serviceFee = 0;
  327. }
  328. if (orderInfo.value.tableId) uni.setStorageSync('currentTableId', String(orderInfo.value.tableId));
  329. fetchServiceFeeEstimate(cartStoreId);
  330. // 不再主动调用 userOwnedByStore,优惠券在点击「优惠券」行打开弹窗时再拉取
  331. });
  332. // 每次进入页面(含从其他页返回)都调用锁定订单接口
  333. onShow(() => {
  334. const tableId = orderInfo.value?.tableId;
  335. if (tableId) {
  336. (diningApi.PostOrderLock || diningApi.postOrderLock)({ tableId }).catch((err) => {
  337. console.warn('锁定订单失败:', err);
  338. });
  339. }
  340. });
  341. // 离开页面时调用解锁订单接口
  342. onUnload(() => {
  343. const tableId = orderInfo.value?.tableId;
  344. if (tableId && typeof (diningApi.PostOrderUnlock || diningApi.postOrderUnlock) === 'function') {
  345. (diningApi.PostOrderUnlock || diningApi.postOrderUnlock)({ tableId }).catch((err) => {
  346. console.warn('解锁订单失败:', err);
  347. });
  348. }
  349. });
  350. </script>
  351. <style lang="scss" scoped>
  352. .content {
  353. padding: 0 30rpx 300rpx;
  354. }
  355. .card {
  356. background-color: #fff;
  357. border-radius: 24rpx;
  358. padding: 30rpx 0;
  359. margin-top: 20rpx;
  360. .card-header {
  361. display: flex;
  362. justify-content: space-between;
  363. align-items: center;
  364. padding: 0 30rpx;
  365. height: 40rpx;
  366. position: relative;
  367. font-size: 27rpx;
  368. color: #151515;
  369. font-weight: bold;
  370. }
  371. .tag {
  372. width: 10rpx;
  373. height: 42rpx;
  374. background: linear-gradient(35deg, #FCB73F 0%, #FC733D 100%);
  375. border-radius: 0rpx 0rpx 0rpx 0rpx;
  376. position: absolute;
  377. left: 0;
  378. top: 0;
  379. }
  380. .card-content {
  381. padding: 0 30rpx;
  382. }
  383. .info-item {
  384. display: flex;
  385. justify-content: space-between;
  386. align-items: center;
  387. margin-top: 20rpx;
  388. font-size: 27rpx;
  389. .info-item-label {
  390. color: #666666;
  391. }
  392. .info-item-value {
  393. color: #151515;
  394. }
  395. &--clickable {
  396. cursor: pointer;
  397. }
  398. &--coupon .coupon-value {
  399. display: flex;
  400. align-items: center;
  401. gap: 8rpx;
  402. }
  403. .coupon-amount {
  404. color: #E61F19;
  405. }
  406. .coupon-placeholder {
  407. color: #999999;
  408. }
  409. .coupon-arrow {
  410. color: #999999;
  411. font-size: 32rpx;
  412. }
  413. }
  414. .info-item-textarea {
  415. width: 100%;
  416. height: 115rpx;
  417. border-radius: 8rpx;
  418. border: 1rpx solid #F2F2F2;
  419. margin-top: 20rpx;
  420. font-size: 23rpx;
  421. color: #AAAAAA;
  422. box-sizing: border-box;
  423. padding: 20rpx;
  424. }
  425. .info-food {
  426. margin-top: 20rpx;
  427. }
  428. .food-item {
  429. display: flex;
  430. align-items: center;
  431. padding: 20rpx 0;
  432. &:last-child {
  433. border-bottom: none;
  434. }
  435. &__image {
  436. width: 118rpx;
  437. height: 118rpx;
  438. border-radius: 8rpx;
  439. flex-shrink: 0;
  440. background-color: #f5f5f5;
  441. }
  442. &__info {
  443. flex: 1;
  444. margin-left: 20rpx;
  445. display: flex;
  446. flex-direction: column;
  447. justify-content: center;
  448. }
  449. &__name {
  450. font-size: 28rpx;
  451. font-weight: bold;
  452. color: #151515;
  453. margin-bottom: 8rpx;
  454. }
  455. &__desc {
  456. font-size: 24rpx;
  457. color: #666666;
  458. line-height: 1.5;
  459. }
  460. &__tag {
  461. font-size: 24rpx;
  462. color: #666666;
  463. }
  464. &__right {
  465. display: flex;
  466. flex-direction: column;
  467. align-items: flex-end;
  468. justify-content: center;
  469. margin-left: 20rpx;
  470. }
  471. &__price {
  472. display: flex;
  473. align-items: baseline;
  474. color: #151515;
  475. font-weight: bold;
  476. margin-bottom: 8rpx;
  477. .price-symbol {
  478. font-size: 20rpx;
  479. margin-right: 2rpx;
  480. }
  481. .price-main {
  482. font-size: 28rpx;
  483. }
  484. .price-decimal {
  485. font-size: 24rpx;
  486. }
  487. }
  488. &__quantity {
  489. font-size: 24rpx;
  490. color: #797979;
  491. }
  492. }
  493. .price-line {
  494. display: flex;
  495. justify-content: space-between;
  496. align-items: center;
  497. margin-top: 20rpx;
  498. font-size: 27rpx;
  499. color: #151515;
  500. border-top: 1rpx solid rgba(170, 170, 170, 0.15);
  501. font-weight: bold;
  502. padding-top: 20rpx;
  503. }
  504. }
  505. .bottom-button {
  506. width: 100%;
  507. background-color: #fff;
  508. padding: 20rpx 30rpx;
  509. box-sizing: border-box;
  510. position: fixed;
  511. bottom: 0;
  512. left: 0;
  513. right: 0;
  514. z-index: 999;
  515. padding-bottom: env(safe-area-inset-bottom);
  516. box-shadow: 0rpx -11rpx 46rpx 0rpx rgba(0, 0, 0, 0.05);
  517. .bottom-button-text {
  518. font-size: 32rpx;
  519. font-weight: bold;
  520. color: #fff;
  521. width: 695rpx;
  522. height: 80rpx;
  523. background: linear-gradient(90deg, #FCB73F 0%, #FC743D 100%);
  524. border-radius: 23rpx 23rpx 23rpx 23rpx;
  525. display: flex;
  526. align-items: center;
  527. justify-content: center;
  528. }
  529. }
  530. </style>