index.vue 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931
  1. <template>
  2. <!-- 确认支付页面:订单信息、菜品清单、价格明细、确认支付 -->
  3. <view class="content">
  4. <view class="card">
  5. <view class="card-header">
  6. <view class="tag"></view>
  7. <view class="card-header-title">订单信息</view>
  8. </view>
  9. <view class="card-content">
  10. <view class="info-item">
  11. <view class="info-item-label">就餐桌号</view>
  12. <view class="info-item-value">{{ orderInfo.tableNumber || orderInfo.tableId || '—' }}</view>
  13. </view>
  14. <view class="info-item">
  15. <view class="info-item-label">用餐人数</view>
  16. <view class="info-item-value">{{ dinerCount }}人</view>
  17. </view>
  18. <view class="info-item">
  19. <view class="info-item-label">联系电话</view>
  20. <view class="info-item-value">{{ orderInfo.contactPhone || '—' }}</view>
  21. </view>
  22. <view class="info-item">
  23. <view class="info-item-label">备注信息</view>
  24. <view class="info-item-value remark-text">{{ (orderInfo.remark || '').trim() || '无' }}</view>
  25. </view>
  26. </view>
  27. </view>
  28. <view class="card" v-if="displayFoodList.length > 0">
  29. <view class="card-header">
  30. <view class="tag"></view>
  31. <view class="card-header-title">菜品清单</view>
  32. </view>
  33. <view class="card-content">
  34. <view class="info-food">
  35. <view v-for="(item, index) in displayFoodList" :key="item.id || index" class="food-item">
  36. <image :src="getItemImage(item)" mode="aspectFill" class="food-item__image"></image>
  37. <view class="food-item__info">
  38. <view class="food-item__name">{{ item.name }}</view>
  39. <view class="food-item__desc" v-if="item.tags && item.tags.length > 0">
  40. <text v-for="(tag, tagIndex) in item.tags" :key="tagIndex" class="food-item__tag"
  41. :class="tag.type">{{ tag.text }}<text v-if="tagIndex < item.tags.length - 1">,</text>
  42. </text>
  43. </view>
  44. </view>
  45. <view class="food-item__right">
  46. <view class="food-item__price">
  47. <text class="price-main">¥{{ formatPrice(item.price) }}</text>
  48. </view>
  49. <view class="food-item__quantity">{{ item.quantity || 1 }}份</view>
  50. </view>
  51. </view>
  52. </view>
  53. </view>
  54. </view>
  55. <view class="card">
  56. <view class="card-header">
  57. <view class="tag"></view>
  58. <view class="card-header-title">价格明细</view>
  59. </view>
  60. <view class="card-content">
  61. <view class="info-item">
  62. <view class="info-item-label">菜品总价</view>
  63. <view class="info-item-value">¥{{ formatPrice(foodSubtotalForDisplay) }}</view>
  64. </view>
  65. <!-- 本版本不参与服务费
  66. <view class="info-item">
  67. <view class="info-item-label">服务费</view>
  68. <view class="info-item-value">¥{{ formatPrice(orderInfo.serviceFee ?? 0) }}</view>
  69. </view>
  70. -->
  71. <view class="info-item info-item--coupon info-item--clickable" @click="onCouponRowClick">
  72. <view class="info-item-label">优惠券</view>
  73. <view class="info-item-value coupon-value">
  74. <text v-if="hasCheckoutCouponChosen" class="coupon-amount">{{ couponRowDisplayName }}</text>
  75. <text v-else class="coupon-placeholder">请选择</text>
  76. <text class="coupon-arrow">›</text>
  77. </view>
  78. </view>
  79. <view v-if="(orderInfo.discountAmount ?? 0) > 0" class="info-item info-item--coupon">
  80. <view class="info-item-label">优惠金额</view>
  81. <view class="info-item-value coupon-value">
  82. <text class="coupon-amount">-¥{{ formatPrice(orderInfo.discountAmount) }}</text>
  83. </view>
  84. </view>
  85. <view class="price-line">
  86. <view class="price-line-label">应付金额</view>
  87. <view class="price-line-value">¥{{ formatPrice(orderInfo.payAmount ?? 0) }}</view>
  88. </view>
  89. </view>
  90. </view>
  91. <view class="bottom-button">
  92. <view class="bottom-button-text" hover-class="hover-active" @click="handleConfirmPay">确认支付 ¥{{ formatPrice(orderInfo.payAmount ?? 0) }}</view>
  93. </view>
  94. <!-- 选择优惠券弹窗 -->
  95. <view class="coupon-modal-wrapper">
  96. <SelectCouponModal
  97. v-model:open="couponModalOpen"
  98. :coupon-list="couponList"
  99. :selected-coupon-id="selectedCouponId"
  100. :view-only="false"
  101. :dish-amount="foodSubtotalForDisplay"
  102. :list-loading="checkoutCouponLoading"
  103. :list-has-more="checkoutCouponHasMore"
  104. @load-more="handleCheckoutCouponLoadMore"
  105. @select="handleCouponSelect"
  106. @close="couponModalOpen = false"
  107. />
  108. </view>
  109. </view>
  110. </template>
  111. <script setup>
  112. import { onLoad, onShow, onUnload } from '@dcloudio/uni-app';
  113. import { ref, computed } from 'vue';
  114. import { go } from '@/utils/utils.js';
  115. import { getFileUrl } from '@/utils/file.js';
  116. import { useUserStore } from '@/store/user.js';
  117. import * as diningApi from '@/api/dining.js';
  118. import { normalizeUserCouponListItem, parseCouponListPage, getCouponMinSpendThreshold } from '@/utils/couponNormalize.js';
  119. import SelectCouponModal from '@/pages/orderFood/components/SelectCouponModal.vue';
  120. const orderId = ref('');
  121. /** 用餐人数上限(与选人数页「查看更多」一致) */
  122. const MAX_DINERS = 16;
  123. const MIN_DINERS = 1;
  124. /** 应付金额下限(元),算出低于此值时按 0.01 展示并支付 */
  125. const MIN_CHECKOUT_PAY_YUAN = 0.01;
  126. const orderInfo = ref({
  127. orderNo: '',
  128. storeId: '',
  129. tableId: '',
  130. tableNumber: '',
  131. diners: '',
  132. contactPhone: '',
  133. remark: '',
  134. totalAmount: 0,
  135. dishTotal: null,
  136. couponId: null,
  137. couponName: '',
  138. couponType: null, // 1 满减 2 折扣
  139. discountRate: null, // 折扣券力度,如 5.5 表示 5.5折
  140. nominalValue: null, // 满减券面额
  141. discountAmount: 0,
  142. payAmount: 0,
  143. serviceFee: 0
  144. });
  145. const foodList = ref([]);
  146. /** 服务费估算接口返回的 feeType;为 1 表示按人数计费,修改人数时需重新估算 */
  147. const estimateFeeType = ref(null);
  148. // 优惠券选择(结算页)
  149. const couponModalOpen = ref(false);
  150. const couponList = ref([]);
  151. const selectedCouponId = ref(null);
  152. const checkoutCouponLoading = ref(false);
  153. const checkoutCouponHasMore = ref(false);
  154. // 菜品清单展示(排除特殊占位 id=-1)
  155. const displayFoodList = computed(() =>
  156. (foodList.value ?? []).filter((it) => Number(it?.id ?? it?.cuisineId) !== -1)
  157. );
  158. function parseDinerCount(val) {
  159. const n = Number(val);
  160. if (!Number.isFinite(n) || n < MIN_DINERS) return MIN_DINERS;
  161. return Math.min(MAX_DINERS, Math.floor(n));
  162. }
  163. /** 当前用餐人数(数字,结算页只读展示) */
  164. const dinerCount = computed(() => parseDinerCount(orderInfo.value.diners));
  165. // 展示用菜品小计:有明细时与行成交价一致;否则用接口 dishTotal 或 totalAmount − 服务费
  166. const foodSubtotalForDisplay = computed(() => {
  167. const list = displayFoodList.value;
  168. if (list.length > 0) {
  169. const sum = list.reduce((s, it) => s + (Number(it.lineSubtotal) || 0), 0);
  170. return Math.max(0, Math.round(sum * 100) / 100);
  171. }
  172. const dt = orderInfo.value.dishTotal;
  173. if (dt != null && dt !== '') {
  174. const d = Number(dt);
  175. if (!Number.isNaN(d)) return Math.max(0, d);
  176. }
  177. const total = Number(orderInfo.value.totalAmount) || 0;
  178. const fee = Number(orderInfo.value.serviceFee) || 0;
  179. return Math.max(0, total - fee);
  180. });
  181. /** 是否已在结算页选定优惠券(含订单带入) */
  182. const hasCheckoutCouponChosen = computed(() => {
  183. const o = orderInfo.value;
  184. if ((o.discountAmount ?? 0) > 0) return true;
  185. if (o.couponId != null && String(o.couponId).trim() !== '') return true;
  186. if (selectedCouponId.value != null && String(selectedCouponId.value).trim() !== '') return true;
  187. return false;
  188. });
  189. /** 优惠券行文案:优先展示券名称,缺省时再展示面值/折扣简短文案 */
  190. const couponRowDisplayName = computed(() => {
  191. const o = orderInfo.value;
  192. const name = String(o.couponName ?? '').trim();
  193. if (name) return name;
  194. const type = Number(o.couponType);
  195. if (type === 1 && o.nominalValue != null && o.nominalValue !== '') {
  196. const val = Number(o.nominalValue);
  197. return Number.isNaN(val) ? '已选优惠券' : `${val}元`;
  198. }
  199. if (type === 2 && o.discountRate != null && o.discountRate !== '') {
  200. const rate = Number(o.discountRate);
  201. return Number.isNaN(rate) ? '已选优惠券' : `${rate}折`;
  202. }
  203. return '已选优惠券';
  204. });
  205. // 点击优惠券行:打开选择弹窗(列表已在进入页面时拉取,不再请求接口)
  206. const onCouponRowClick = () => {
  207. couponModalOpen.value = true;
  208. };
  209. /**
  210. * 拉取结算页用户持有优惠券(GET /dining/coupon/userOwned,一次性返回)
  211. * @param {{ reset?: boolean; silentNoStore?: boolean }} options
  212. * silentNoStore:无门店时不 toast(用于进入页面预拉取)
  213. */
  214. async function fetchCheckoutCouponList(options = { reset: true }) {
  215. const { reset = true, silentNoStore = false } = options;
  216. const storeId = orderInfo.value.storeId || uni.getStorageSync('currentStoreId') || '';
  217. if (!storeId) {
  218. if (!silentNoStore) {
  219. uni.showToast({ title: '暂无门店信息', icon: 'none' });
  220. }
  221. return false;
  222. }
  223. if (!reset) {
  224. return true;
  225. }
  226. if (checkoutCouponLoading.value) return false;
  227. checkoutCouponLoading.value = true;
  228. try {
  229. const amount = Math.max(0, Math.round((Number(foodSubtotalForDisplay.value) || 0) * 100) / 100);
  230. const res = await diningApi.GetUserCouponUserOwned({ storeId, amount });
  231. const { list: rawList } = parseCouponListPage(res);
  232. const arr = Array.isArray(rawList) ? rawList : [];
  233. const normalized = arr
  234. .map((item) => normalizeUserCouponListItem(item, 0))
  235. .filter(Boolean);
  236. couponList.value = normalized;
  237. checkoutCouponHasMore.value = false;
  238. syncCheckoutSelectedCouponId();
  239. return true;
  240. } catch (err) {
  241. console.error('获取优惠券失败:', err);
  242. uni.showToast({ title: '获取优惠券失败', icon: 'none' });
  243. couponList.value = [];
  244. checkoutCouponHasMore.value = false;
  245. syncCheckoutSelectedCouponId();
  246. return false;
  247. } finally {
  248. checkoutCouponLoading.value = false;
  249. }
  250. }
  251. function handleCheckoutCouponLoadMore() {
  252. if (!checkoutCouponLoading.value && checkoutCouponHasMore.value) {
  253. fetchCheckoutCouponList({ reset: false });
  254. }
  255. }
  256. // 选择优惠券后更新订单优惠与应付金额
  257. const handleCouponSelect = ({ coupon, selectedId }) => {
  258. const hasSelected = selectedId != null && selectedId !== '';
  259. if (!hasSelected) {
  260. selectedCouponId.value = null;
  261. orderInfo.value.couponId = null;
  262. orderInfo.value.discountAmount = 0;
  263. orderInfo.value.couponName = '';
  264. orderInfo.value.couponType = null;
  265. orderInfo.value.discountRate = null;
  266. orderInfo.value.nominalValue = null;
  267. updateCheckoutPayAmount();
  268. couponModalOpen.value = false;
  269. return;
  270. }
  271. if (!coupon) {
  272. couponModalOpen.value = false;
  273. return;
  274. }
  275. const couponType = Number(coupon.couponType) || 0;
  276. const foodSubtotal = Number(foodSubtotalForDisplay.value) || 0;
  277. const threshold = getCouponMinSpendThreshold(coupon);
  278. // 有门槛(minimumSpendingAmount/minAmount > 0):菜品总价须 ≥ 门槛
  279. if (threshold > 0 && foodSubtotal < threshold) {
  280. uni.showToast({ title: '未达到优惠券使用门槛', icon: 'none' });
  281. return;
  282. }
  283. selectedCouponId.value = String(selectedId);
  284. orderInfo.value.couponId = coupon?.couponId ?? coupon?.id ?? String(selectedId) ?? null;
  285. orderInfo.value.couponName = String(coupon.name ?? coupon.title ?? coupon.couponName ?? '').trim();
  286. orderInfo.value.couponType = couponType || null;
  287. orderInfo.value.discountRate = coupon.discountRate != null ? coupon.discountRate : null;
  288. const nvRaw = coupon.nominalValue;
  289. if (nvRaw != null && nvRaw !== '') {
  290. const nv = Number(nvRaw);
  291. orderInfo.value.nominalValue = Number.isFinite(nv) ? nv : null;
  292. } else if (couponType === 1) {
  293. orderInfo.value.nominalValue = Number(coupon.amount) || null;
  294. } else {
  295. orderInfo.value.nominalValue = null;
  296. }
  297. const food = foodSubtotal;
  298. const fee = Number(orderInfo.value.serviceFee) || 0;
  299. const baseForDiscount = food + fee;
  300. if (couponType === 2 && coupon.discountRate != null && baseForDiscount > 0) {
  301. const rate = Number(coupon.discountRate) || 0;
  302. orderInfo.value.discountAmount = Math.round(baseForDiscount * (1 - rate / 10) * 100) / 100;
  303. } else {
  304. orderInfo.value.discountAmount =
  305. Number(coupon.nominalValue) || Number(coupon.amount) || 0;
  306. }
  307. updateCheckoutPayAmount();
  308. couponModalOpen.value = false;
  309. };
  310. // 应付金额 = 菜品总价 + 服务费 − 优惠金额(不低于 0.01 元)
  311. const updateCheckoutPayAmount = () => {
  312. const food = Number(foodSubtotalForDisplay.value) || 0;
  313. const fee = Number(orderInfo.value.serviceFee) || 0;
  314. const discount = Number(orderInfo.value.discountAmount) || 0;
  315. let raw = Math.round((food + fee - discount) * 100) / 100;
  316. if (!Number.isFinite(raw) || raw < MIN_CHECKOUT_PAY_YUAN) {
  317. raw = MIN_CHECKOUT_PAY_YUAN;
  318. }
  319. orderInfo.value.payAmount = raw;
  320. };
  321. /** 服务费变化后:折扣券(按菜品+服务费为基数)需重算优惠金额 */
  322. function recalcDiscountAfterServiceFeeChange() {
  323. const ct = Number(orderInfo.value.couponType) || 0;
  324. if (ct !== 2 || orderInfo.value.discountRate == null || !orderInfo.value.couponId) return;
  325. const food = Number(foodSubtotalForDisplay.value) || 0;
  326. const fee = Number(orderInfo.value.serviceFee) || 0;
  327. const base = food + fee;
  328. const rate = Number(orderInfo.value.discountRate) || 0;
  329. if (base <= 0) return;
  330. orderInfo.value.discountAmount = Math.round(base * (1 - rate / 10) * 100) / 100;
  331. }
  332. /**
  333. * 从估算接口 data 解析 feeType:后端可能放在顶层,也可能在 items[].feeType(如按人数规则)
  334. * 任一为 1 则视为按人数计费,修改人数需重新请求 estimate
  335. */
  336. function parseEstimateFeeType(res) {
  337. if (res == null || typeof res !== 'object') return null;
  338. const top = res.feeType != null && res.feeType !== '' ? Number(res.feeType) : NaN;
  339. if (top === 1) return 1;
  340. const items = Array.isArray(res.items) ? res.items : [];
  341. for (const it of items) {
  342. const ft = it?.feeType != null && it.feeType !== '' ? Number(it.feeType) : NaN;
  343. if (ft === 1) return 1;
  344. }
  345. if (!Number.isNaN(top)) return top;
  346. for (const it of items) {
  347. const ft = it?.feeType != null && it.feeType !== '' ? Number(it.feeType) : NaN;
  348. if (!Number.isNaN(ft)) return ft;
  349. }
  350. return null;
  351. }
  352. /**
  353. * 服务费估算(本版本关闭:不参与服务费)
  354. */
  355. async function fetchServiceFeeEstimate() {
  356. orderInfo.value.serviceFee = 0;
  357. estimateFeeType.value = null;
  358. recalcDiscountAfterServiceFeeChange();
  359. updateCheckoutPayAmount();
  360. /* 原 /store/dining/service-fee/estimate 逻辑(恢复时整段移出注释)
  361. const storeId = orderInfo.value.storeId || uni.getStorageSync('currentStoreId') || '';
  362. const tableId = getTableIdForServiceFeeEstimate();
  363. if (!storeId || !tableId) return;
  364. const dinerCount = parseDinerCount(orderInfo.value.diners);
  365. const goodsSubtotal = Math.max(0, Math.round((Number(foodSubtotalForDisplay.value) || 0) * 100) / 100);
  366. try {
  367. const res = await diningApi.GetServiceFeeEstimate({
  368. storeId: String(storeId),
  369. tableId,
  370. dinerCount,
  371. goodsSubtotal
  372. });
  373. estimateFeeType.value = parseEstimateFeeType(res);
  374. const fee =
  375. Number(
  376. res?.serviceFee ??
  377. res?.estimatedServiceFee ??
  378. res?.fee ??
  379. res?.amount ??
  380. (typeof res === 'number' ? res : 0)
  381. ) || 0;
  382. orderInfo.value.serviceFee = fee;
  383. recalcDiscountAfterServiceFeeChange();
  384. updateCheckoutPayAmount();
  385. } catch (e) {
  386. console.warn('结算页服务费估算失败:', e);
  387. }
  388. */
  389. }
  390. function formatPrice(price) {
  391. const num = Number(price);
  392. return Number.isNaN(num) ? '0.00' : num.toFixed(2);
  393. }
  394. // 取第一张图:逗号分隔取首段,数组取首项,对象取 url/path/src(与 orderDetail 一致)
  395. function firstImage(val) {
  396. if (val == null || val === '') return '';
  397. if (Array.isArray(val)) {
  398. const first = val[0];
  399. if (first != null && first !== '') {
  400. if (typeof first === 'object' && first !== null) return first.url ?? first.path ?? first.src ?? first.link ?? '';
  401. return String(first).split(/[,,]/)[0].trim();
  402. }
  403. return '';
  404. }
  405. if (typeof val === 'object') return val.url ?? val.path ?? val.src ?? val.link ?? '';
  406. const str = String(val).trim();
  407. return str ? str.split(/[,,]/)[0].trim() : '';
  408. }
  409. function getItemImage(item) {
  410. const raw = item?.image ?? item?.cuisineImage ?? item?.imageUrl ?? item?.images ?? item?.pic ?? item?.cover ?? '';
  411. const url = firstImage(raw) || (typeof raw === 'string' ? raw.split(/[,,]/)[0]?.trim() : '');
  412. if (url && typeof url === 'string' && (url.startsWith('http') || url.startsWith('//'))) return url;
  413. return getFileUrl(url || 'img/icon/shop.png');
  414. }
  415. // 将 tags 统一为 [{ text, type }] 格式
  416. function normalizeTags(raw) {
  417. if (raw == null) return [];
  418. let arr = [];
  419. if (Array.isArray(raw)) arr = raw;
  420. else if (typeof raw === 'string') {
  421. const t = raw.trim();
  422. if (t.startsWith('[')) { try { arr = JSON.parse(t); if (!Array.isArray(arr)) arr = []; } catch { arr = t ? [t] : []; } }
  423. else arr = t ? t.split(/[,,、\s]+/).map(s => s.trim()).filter(Boolean) : [];
  424. } else if (raw && typeof raw === 'object') arr = Array.isArray(raw.list) ? raw.list : Array.isArray(raw.items) ? raw.items : [];
  425. return arr.map((it) => {
  426. if (it == null) return { text: '', type: '' };
  427. if (typeof it === 'string') return { text: it, type: '' };
  428. if (typeof it === 'number') return { text: String(it), type: '' };
  429. return { text: it.text ?? it.tagName ?? it.name ?? it.label ?? it.title ?? '', type: it.type ?? it.tagType ?? '' };
  430. }).filter((t) => t.text !== '' && t.text != null);
  431. }
  432. // 接口订单项转列表项:图片取首张(逗号/数组/对象与 orderDetail 一致)
  433. function normalizeOrderItem(item) {
  434. const rawTags = item?.tags ?? item?.tagList ?? item?.tagNames ?? item?.labels ?? item?.tag;
  435. const rawImg = item?.images ?? item?.image ?? item?.cuisineImage ?? item?.imageUrl ?? item?.pic ?? item?.cover ?? '';
  436. const imageUrl = firstImage(rawImg) || (typeof rawImg === 'string' ? rawImg.split(/[,,]/)[0]?.trim() : '') || 'img/icon/shop.png';
  437. const qty = Number(item?.quantity ?? 1) || 1;
  438. /** 行成交价小计(元):与购物车/服务费估算 goodsSubtotal 一致 */
  439. let lineSubtotal = 0;
  440. if (item?.subtotalAmount != null && item.subtotalAmount !== '') {
  441. lineSubtotal = Number(item.subtotalAmount) || 0;
  442. } else if (item?.totalPrice != null && item.totalPrice !== '') {
  443. lineSubtotal = Number(item.totalPrice) || 0;
  444. } else {
  445. const unit = Number(item?.unitPrice ?? item?.price ?? 0) || 0;
  446. lineSubtotal = unit * qty;
  447. }
  448. const unitForDisplay =
  449. Number(item?.unitPrice ?? item?.price ?? 0) ||
  450. (qty > 0 ? lineSubtotal / qty : 0);
  451. return {
  452. id: item?.id ?? item?.cuisineId,
  453. name: item?.cuisineName ?? item?.name ?? '',
  454. price: unitForDisplay,
  455. lineSubtotal,
  456. image: imageUrl,
  457. quantity: qty,
  458. tags: normalizeTags(rawTags)
  459. };
  460. }
  461. /** 桌台主键:store_table.id,不可用桌号展示文案代替 */
  462. function getTableIdForServiceFeeEstimate() {
  463. const t = orderInfo.value.tableId;
  464. if (t != null && String(t).trim() !== '') return String(t).trim();
  465. return String(uni.getStorageSync('currentTableId') || '').trim();
  466. }
  467. /** 根据 orderInfo.couponId 与券列表对齐选中态(弹窗单选 id 为 userCoupon 实例 id) */
  468. function syncCheckoutSelectedCouponId() {
  469. const cid = orderInfo.value.couponId;
  470. if (cid == null || String(cid).trim() === '') {
  471. selectedCouponId.value = null;
  472. return;
  473. }
  474. const s = String(cid).trim();
  475. const list = couponList.value ?? [];
  476. const hit = list.find(
  477. (c) =>
  478. String(c?.couponId ?? '') === s ||
  479. String(c?.id ?? '') === s ||
  480. String(c?.userCouponId ?? '') === s
  481. );
  482. selectedCouponId.value = hit ? String(hit.id) : null;
  483. }
  484. /** 从订单详情接口回显优惠券(与下单/锁单时服务端数据一致) */
  485. function applyCheckoutCouponFromOrderRaw(raw) {
  486. const cid = raw?.couponId ?? raw?.userCouponId ?? raw?.memberCouponId ?? null;
  487. const discountAmt =
  488. Number(raw?.discountAmount ?? raw?.couponAmount ?? raw?.couponDiscount ?? 0) || 0;
  489. const hasCoupon =
  490. (cid != null && String(cid).trim() !== '') ||
  491. discountAmt > 0 ||
  492. (String(raw?.couponName ?? '').trim() !== '');
  493. if (!hasCoupon) {
  494. orderInfo.value.couponId = null;
  495. orderInfo.value.couponName = '';
  496. orderInfo.value.couponType = null;
  497. orderInfo.value.discountRate = null;
  498. orderInfo.value.nominalValue = null;
  499. orderInfo.value.discountAmount = 0;
  500. selectedCouponId.value = null;
  501. updateCheckoutPayAmount();
  502. return;
  503. }
  504. orderInfo.value.couponId = cid != null && String(cid).trim() !== '' ? String(cid).trim() : null;
  505. orderInfo.value.couponName = String(raw?.couponName ?? '').trim();
  506. orderInfo.value.couponType = raw?.couponType ?? null;
  507. const rawRate = raw?.discountRate;
  508. orderInfo.value.discountRate =
  509. rawRate != null && rawRate !== '' ? (Number(rawRate) || 0) / 10 : null;
  510. orderInfo.value.nominalValue = raw?.nominalValue ?? null;
  511. orderInfo.value.discountAmount = discountAmt;
  512. recalcDiscountAfterServiceFeeChange();
  513. updateCheckoutPayAmount();
  514. }
  515. const fetchOrderDetail = async () => {
  516. const id = orderId.value || '';
  517. if (!id) return;
  518. try {
  519. const res = await diningApi.GetOrderInfo(id);
  520. const raw = res?.data ?? res ?? {};
  521. orderInfo.value.orderNo = raw?.orderNo ?? raw?.orderId ?? '';
  522. orderInfo.value.storeId = raw?.storeId ?? raw?.store_id ?? '';
  523. // tableId 须为门店桌台表主键(store_table.id),勿用 tableNumber(展示用桌号)冒充
  524. orderInfo.value.tableId =
  525. raw?.tableId ??
  526. raw?.storeTableId ??
  527. raw?.store_table_id ??
  528. raw?.diningTableId ??
  529. '';
  530. orderInfo.value.tableNumber = raw?.tableNumber ?? raw?.tableNo ?? '';
  531. const dc = raw?.dinerCount ?? raw?.diners ?? '';
  532. orderInfo.value.diners =
  533. dc !== '' && dc != null ? String(parseDinerCount(dc)) : String(MIN_DINERS);
  534. orderInfo.value.contactPhone = raw?.contactPhone ?? raw?.phone ?? '';
  535. orderInfo.value.remark = raw?.remark ?? '';
  536. const total = Number(raw?.totalAmount ?? raw?.orderAmount ?? raw?.foodAmount ?? 0) || 0;
  537. orderInfo.value.totalAmount = total;
  538. orderInfo.value.dishTotal = raw?.dishTotal != null ? Number(raw.dishTotal) : null;
  539. // 本版本不参与服务费:不从订单拉取服务费
  540. orderInfo.value.serviceFee = 0;
  541. const list = raw?.orderItemList ?? raw?.orderItems ?? raw?.items ?? raw?.detailList ?? [];
  542. foodList.value = (Array.isArray(list) ? list : []).map(normalizeOrderItem);
  543. applyCheckoutCouponFromOrderRaw(raw);
  544. await fetchServiceFeeEstimate(); // 本版为 no-op(不参与服务费)
  545. } catch (err) {
  546. console.error('获取订单详情失败:', err);
  547. uni.showToast({ title: '加载失败', icon: 'none' });
  548. }
  549. };
  550. const handleConfirmPay = async () => {
  551. const id = orderId.value || '';
  552. if (!id) {
  553. uni.showToast({ title: '缺少订单ID', icon: 'none' });
  554. return;
  555. }
  556. const userStore = useUserStore();
  557. const openid = userStore.getOpenId || '';
  558. if (!openid) {
  559. uni.showToast({ title: '请先登录', icon: 'none' });
  560. return;
  561. }
  562. const payAmountVal = Math.round((Number(orderInfo.value.payAmount ?? 0) || 0) * 100) / 100;
  563. if (payAmountVal < MIN_CHECKOUT_PAY_YUAN) {
  564. uni.showToast({ title: '订单金额异常', icon: 'none' });
  565. return;
  566. }
  567. const orderNo = orderInfo.value.orderNo || '';
  568. if (!orderNo) {
  569. uni.showToast({ title: '缺少订单号', icon: 'none' });
  570. return;
  571. }
  572. const price = Math.round(payAmountVal * 100);
  573. uni.showLoading({ title: '拉起支付...' });
  574. try {
  575. const storeId = orderInfo.value.storeId || uni.getStorageSync('currentStoreId') || '';
  576. const u = userStore.getUserInfo || {};
  577. const payerId = u.id ?? u.userId ?? u.user_id ?? '';
  578. const couponIdVal =
  579. orderInfo.value.couponId != null && orderInfo.value.couponId !== ''
  580. ? String(orderInfo.value.couponId)
  581. : selectedCouponId.value != null && selectedCouponId.value !== ''
  582. ? String(selectedCouponId.value)
  583. : '';
  584. const discountAmountVal = Number(orderInfo.value.discountAmount) || 0;
  585. // const serviceFeeVal = Math.round((Number(orderInfo.value.serviceFee ?? 0) || 0) * 100) / 100;
  586. const res = await diningApi.PostOrderPay({
  587. orderNo,
  588. payer: openid,
  589. price,
  590. subject: '订单支付',
  591. storeId: storeId || undefined,
  592. couponId: couponIdVal || undefined,
  593. payerId: payerId ? String(payerId) : undefined,
  594. discountAmount: discountAmountVal,
  595. payAmount: payAmountVal
  596. // serviceFee: serviceFeeVal // 本版本不参与服务费
  597. });
  598. uni.hideLoading();
  599. uni.requestPayment({
  600. provider: 'wxpay',
  601. timeStamp: res.timestamp,
  602. nonceStr: res.nonce,
  603. package: res.prepayId,
  604. signType: res.signType,
  605. paySign: res.sign,
  606. success: () => {
  607. uni.showToast({ title: '支付成功', icon: 'success' });
  608. const oid = orderId.value || '';
  609. if (oid) {
  610. diningApi.PostOrderSettlementUnlock({ orderId: oid }).catch((e) => console.warn('解锁订单失败:', e));
  611. }
  612. const payType = 'wechatPayPartnerMininProgram';
  613. // 查询支付结果需用 prePay 返回的 transactionId,与订单号 orderNo 可能不同
  614. const prePayTid =
  615. res?.transactionId ??
  616. res?.transaction_id ??
  617. res?.outTradeNo ??
  618. orderNo;
  619. const sid = orderInfo.value.storeId || uni.getStorageSync('currentStoreId') || '';
  620. const q = [`id=${encodeURIComponent(oid)}`, `payType=${encodeURIComponent(payType)}`, `transactionId=${encodeURIComponent(String(prePayTid ?? ''))}`];
  621. if (sid) q.push(`storeId=${encodeURIComponent(sid)}`);
  622. setTimeout(() => go(`/pages/paymentSuccess/index?${q.join('&')}`), 1500);
  623. },
  624. fail: (err) => {
  625. const msg = err?.errMsg ?? err?.message ?? '支付失败';
  626. if (String(msg).includes('cancel')) {
  627. uni.showToast({ title: '已取消支付', icon: 'none' });
  628. } else {
  629. uni.showToast({ title: msg || '支付失败', icon: 'none' });
  630. }
  631. }
  632. });
  633. } catch (e) {
  634. uni.hideLoading();
  635. uni.showToast({ title: e?.message || '获取支付参数失败', icon: 'none' });
  636. }
  637. };
  638. onLoad(async (options) => {
  639. const id = options?.orderId ?? options?.id ?? '';
  640. orderId.value = id;
  641. if (options?.orderNo) orderInfo.value.orderNo = options.orderNo;
  642. if (options?.tableId) orderInfo.value.tableId = options.tableId;
  643. if (options?.tableNumber) orderInfo.value.tableNumber = options.tableNumber;
  644. if (options?.diners != null && options?.diners !== '') {
  645. orderInfo.value.diners = String(parseDinerCount(options.diners));
  646. uni.setStorageSync('currentDiners', orderInfo.value.diners);
  647. }
  648. if (options?.remark != null && options?.remark !== '') orderInfo.value.remark = decodeURIComponent(options.remark);
  649. if (options?.totalAmount != null && options?.totalAmount !== '') {
  650. const p = Math.round((Number(options.totalAmount) || 0) * 100) / 100;
  651. orderInfo.value.payAmount = p < MIN_CHECKOUT_PAY_YUAN ? MIN_CHECKOUT_PAY_YUAN : p;
  652. }
  653. if (id) {
  654. await fetchOrderDetail();
  655. }
  656. await fetchCheckoutCouponList({ reset: true, silentNoStore: true });
  657. });
  658. onShow(() => {
  659. const id = orderId.value || '';
  660. if (id) {
  661. diningApi.PostOrderSettlementLock({ orderId: id }).catch((e) => console.warn('锁定订单失败:', e));
  662. }
  663. });
  664. onUnload(() => {
  665. const id = orderId.value || '';
  666. if (id) {
  667. diningApi.PostOrderSettlementUnlock({ orderId: id }).catch((e) => console.warn('解锁订单失败:', e));
  668. }
  669. });
  670. </script>
  671. <style lang="scss" scoped>
  672. .content {
  673. padding: 0 30rpx 300rpx;
  674. }
  675. .card {
  676. background-color: #fff;
  677. border-radius: 24rpx;
  678. padding: 30rpx 0;
  679. margin-top: 20rpx;
  680. .card-header {
  681. display: flex;
  682. align-items: center;
  683. padding: 0 30rpx;
  684. height: 40rpx;
  685. position: relative;
  686. font-size: 27rpx;
  687. color: #151515;
  688. font-weight: bold;
  689. }
  690. .tag {
  691. width: 10rpx;
  692. height: 42rpx;
  693. background: linear-gradient(35deg, #FCB73F 0%, #FC733D 100%);
  694. border-radius: 0;
  695. position: absolute;
  696. left: 0;
  697. top: 0;
  698. }
  699. .card-content {
  700. padding: 0 30rpx;
  701. }
  702. .info-item {
  703. display: flex;
  704. justify-content: space-between;
  705. align-items: center;
  706. margin-top: 20rpx;
  707. font-size: 27rpx;
  708. .info-item-label {
  709. color: #666666;
  710. }
  711. .info-item-value {
  712. color: #151515;
  713. &.remark-text {
  714. flex: 1;
  715. text-align: right;
  716. word-break: break-all;
  717. }
  718. }
  719. &--coupon .coupon-value {
  720. display: flex;
  721. align-items: center;
  722. gap: 8rpx;
  723. }
  724. .coupon-amount {
  725. color: #E61F19;
  726. }
  727. .coupon-placeholder {
  728. color: #999999;
  729. }
  730. .coupon-arrow {
  731. color: #999;
  732. margin-left: 4rpx;
  733. }
  734. &--clickable {
  735. cursor: pointer;
  736. }
  737. }
  738. .price-line {
  739. display: flex;
  740. justify-content: space-between;
  741. align-items: center;
  742. margin-top: 24rpx;
  743. padding-top: 24rpx;
  744. border-top: 1rpx solid #f0f0f0;
  745. font-size: 28rpx;
  746. font-weight: bold;
  747. .price-line-label {
  748. color: #151515;
  749. }
  750. .price-line-value {
  751. color: #E61F19;
  752. }
  753. }
  754. .info-food {
  755. .food-item {
  756. display: flex;
  757. align-items: center;
  758. padding: 20rpx 0;
  759. border-bottom: 1rpx solid #f5f5f5;
  760. &:last-child {
  761. border-bottom: none;
  762. }
  763. &__image {
  764. width: 120rpx;
  765. height: 120rpx;
  766. border-radius: 12rpx;
  767. flex-shrink: 0;
  768. background: #f5f5f5;
  769. }
  770. &__info {
  771. flex: 1;
  772. margin-left: 24rpx;
  773. min-width: 0;
  774. }
  775. &__name {
  776. font-size: 28rpx;
  777. color: #151515;
  778. font-weight: 500;
  779. }
  780. &__desc {
  781. font-size: 22rpx;
  782. color: #999;
  783. margin-top: 6rpx;
  784. }
  785. &__tag {
  786. margin-right: 4rpx;
  787. &.signature {
  788. color: #FC793D;
  789. }
  790. &.spicy {
  791. color: #2E2E2E;
  792. }
  793. }
  794. &__right {
  795. flex-shrink: 0;
  796. text-align: right;
  797. }
  798. &__price .price-main {
  799. font-size: 28rpx;
  800. color: #151515;
  801. font-weight: 600;
  802. }
  803. &__quantity {
  804. font-size: 24rpx;
  805. color: #999;
  806. margin-top: 6rpx;
  807. }
  808. }
  809. }
  810. }
  811. .bottom-button {
  812. position: fixed;
  813. left: 0;
  814. right: 0;
  815. bottom: 0;
  816. padding: 20rpx 30rpx;
  817. padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  818. background: #fff;
  819. box-shadow: 0 -2rpx 12rpx rgba(0, 0, 0, 0.06);
  820. .bottom-button-text {
  821. height: 88rpx;
  822. line-height: 88rpx;
  823. text-align: center;
  824. background: linear-gradient(90deg, #FCB73F 0%, #FC733D 100%);
  825. color: #fff;
  826. font-size: 32rpx;
  827. font-weight: bold;
  828. border-radius: 44rpx;
  829. }
  830. .hover-active {
  831. opacity: 0.9;
  832. }
  833. }
  834. .coupon-modal-wrapper {
  835. position: relative;
  836. z-index: 99999;
  837. :deep(.uni-popup) {
  838. z-index: 99999 !important;
  839. top: 0 !important;
  840. left: 0 !important;
  841. right: 0 !important;
  842. bottom: 0 !important;
  843. }
  844. :deep(.uni-popup__wrapper) {
  845. z-index: 99999 !important;
  846. }
  847. :deep(.select-coupon-modal__list) {
  848. padding-bottom: calc(60rpx + env(safe-area-inset-bottom));
  849. }
  850. :deep(.select-coupon-modal__empty) {
  851. margin-bottom: 60rpx;
  852. }
  853. }
  854. </style>