index.vue 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009
  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="showCheckoutDiscountRow" 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. let sum = 0;
  170. for (const it of list) {
  171. const ls = Number(it.lineSubtotal);
  172. if (Number.isFinite(ls) && ls > 0) {
  173. sum += ls;
  174. continue;
  175. }
  176. const q = Number(it.quantity) || 1;
  177. const u = Number(it.price) || 0;
  178. sum += u * q;
  179. }
  180. return Math.max(0, Math.round(sum * 100) / 100);
  181. }
  182. const dt = orderInfo.value.dishTotal;
  183. if (dt != null && dt !== '') {
  184. const d = Number(dt);
  185. if (!Number.isNaN(d)) return Math.max(0, d);
  186. }
  187. const total = Number(orderInfo.value.totalAmount) || 0;
  188. const fee = Number(orderInfo.value.serviceFee) || 0;
  189. return Math.max(0, total - fee);
  190. });
  191. /** 是否展示「优惠金额」行:有优惠额,或已选折扣券且 discountRate 有效 */
  192. const showCheckoutDiscountRow = computed(() => {
  193. const o = orderInfo.value;
  194. if ((Number(o.discountAmount) || 0) > 0) return true;
  195. return (
  196. Number(o.couponType) === 2 &&
  197. o.couponId != null &&
  198. String(o.couponId).trim() !== '' &&
  199. Number(o.discountRate) > 0
  200. );
  201. });
  202. /** 是否已在结算页选定优惠券(含订单带入) */
  203. const hasCheckoutCouponChosen = computed(() => {
  204. const o = orderInfo.value;
  205. if ((o.discountAmount ?? 0) > 0) return true;
  206. if (o.couponId != null && String(o.couponId).trim() !== '') return true;
  207. if (selectedCouponId.value != null && String(selectedCouponId.value).trim() !== '') return true;
  208. return false;
  209. });
  210. /** 优惠券行文案:优先展示券名称,缺省时再展示面值/折扣简短文案 */
  211. const couponRowDisplayName = computed(() => {
  212. const o = orderInfo.value;
  213. const name = String(o.couponName ?? '').trim();
  214. if (name) return name;
  215. const type = Number(o.couponType);
  216. if (type === 1 && o.nominalValue != null && o.nominalValue !== '') {
  217. const val = Number(o.nominalValue);
  218. return Number.isNaN(val) ? '已选优惠券' : `${val}元`;
  219. }
  220. if (type === 2 && o.discountRate != null && o.discountRate !== '') {
  221. const rate = Number(o.discountRate);
  222. return Number.isNaN(rate) ? '已选优惠券' : `${rate}折`;
  223. }
  224. return '已选优惠券';
  225. });
  226. // 点击优惠券行:打开选择弹窗(列表已在进入页面时拉取,不再请求接口)
  227. const onCouponRowClick = () => {
  228. couponModalOpen.value = true;
  229. };
  230. /**
  231. * 拉取结算页用户持有优惠券(GET /dining/coupon/userOwned,一次性返回)
  232. * @param {{ reset?: boolean; silentNoStore?: boolean }} options
  233. * silentNoStore:无门店时不 toast(用于进入页面预拉取)
  234. */
  235. async function fetchCheckoutCouponList(options = { reset: true }) {
  236. const { reset = true, silentNoStore = false } = options;
  237. const storeId = orderInfo.value.storeId || uni.getStorageSync('currentStoreId') || '';
  238. if (!storeId) {
  239. if (!silentNoStore) {
  240. uni.showToast({ title: '暂无门店信息', icon: 'none' });
  241. }
  242. return false;
  243. }
  244. if (!reset) {
  245. return true;
  246. }
  247. if (checkoutCouponLoading.value) return false;
  248. checkoutCouponLoading.value = true;
  249. try {
  250. const amount = Math.max(0, Math.round((Number(foodSubtotalForDisplay.value) || 0) * 100) / 100);
  251. const res = await diningApi.GetUserCouponUserOwned({ storeId, amount });
  252. const { list: rawList } = parseCouponListPage(res);
  253. const arr = Array.isArray(rawList) ? rawList : [];
  254. const normalized = arr
  255. .map((item) => {
  256. const n = normalizeUserCouponListItem(item, 0);
  257. if (!n) return null;
  258. const apiRate = item?.discountRate ?? item?.discount_rate;
  259. if (Number(n.couponType) === 2 && apiRate != null && apiRate !== '') {
  260. const num = Number(apiRate);
  261. if (Number.isFinite(num)) {
  262. return { ...n, _sourceDiscountRate: num };
  263. }
  264. }
  265. return n;
  266. })
  267. .filter(Boolean);
  268. couponList.value = normalized;
  269. checkoutCouponHasMore.value = false;
  270. syncCheckoutSelectedCouponId();
  271. return true;
  272. } catch (err) {
  273. console.error('获取优惠券失败:', err);
  274. uni.showToast({ title: '获取优惠券失败', icon: 'none' });
  275. couponList.value = [];
  276. checkoutCouponHasMore.value = false;
  277. syncCheckoutSelectedCouponId();
  278. return false;
  279. } finally {
  280. checkoutCouponLoading.value = false;
  281. }
  282. }
  283. function handleCheckoutCouponLoadMore() {
  284. if (!checkoutCouponLoading.value && checkoutCouponHasMore.value) {
  285. fetchCheckoutCouponList({ reset: false });
  286. }
  287. }
  288. /**
  289. * 统一为应付公式折数 zhe(1=一折,10=十折):优惠 = 基数×(1−zhe/10)
  290. * - 与 couponNormalize 一致:接口 10 表示 1折(列表 discountRate/10 展示为 1折)
  291. * - 88→8.8折;0.88/0.1→8.8/1折;1~9 为折数;≥100 为十折
  292. */
  293. function normalizeZheRateForCheckoutFormula(r) {
  294. if (!Number.isFinite(r) || r <= 0) return 0;
  295. if (r >= 100) return 10;
  296. if (r > 10 && r < 100) return Math.round((r / 10) * 100) / 100;
  297. if (r === 10) return 1;
  298. if (r > 0 && r < 1) return Math.round(r * 10 * 100) / 100;
  299. if (r >= 1 && r < 10) return Math.round(r * 100) / 100;
  300. return 0;
  301. }
  302. /** 折扣券:仅用接口/券上的 discountRate(及 _sourceDiscountRate 保留的原始值)计算折标,不用 amount 代替 */
  303. function resolveCheckoutDiscountCouponRate(coupon) {
  304. if (!coupon || Number(coupon.couponType) !== 2) return 0;
  305. const rawVal =
  306. coupon._sourceDiscountRate ??
  307. coupon.discountRate ??
  308. coupon.discount_rate;
  309. if (rawVal == null || rawVal === '') return 0;
  310. const dr = Number(rawVal);
  311. if (!Number.isFinite(dr) || dr <= 0) return 0;
  312. return normalizeZheRateForCheckoutFormula(dr);
  313. }
  314. // 选择优惠券后更新订单优惠与应付金额
  315. const handleCouponSelect = ({ coupon, selectedId }) => {
  316. const hasSelected = selectedId != null && selectedId !== '';
  317. if (!hasSelected) {
  318. selectedCouponId.value = null;
  319. orderInfo.value.couponId = null;
  320. orderInfo.value.discountAmount = 0;
  321. orderInfo.value.couponName = '';
  322. orderInfo.value.couponType = null;
  323. orderInfo.value.discountRate = null;
  324. orderInfo.value.nominalValue = null;
  325. updateCheckoutPayAmount();
  326. couponModalOpen.value = false;
  327. return;
  328. }
  329. if (!coupon) {
  330. couponModalOpen.value = false;
  331. return;
  332. }
  333. const couponType = Number(coupon.couponType) || 0;
  334. const foodSubtotal = Number(foodSubtotalForDisplay.value) || 0;
  335. const threshold = getCouponMinSpendThreshold(coupon);
  336. // 有门槛(minimumSpendingAmount/minAmount > 0):菜品总价须 ≥ 门槛
  337. if (threshold > 0 && foodSubtotal < threshold) {
  338. uni.showToast({ title: '未达到优惠券使用门槛', icon: 'none' });
  339. return;
  340. }
  341. selectedCouponId.value = String(selectedId);
  342. orderInfo.value.couponId = coupon?.couponId ?? coupon?.id ?? String(selectedId) ?? null;
  343. orderInfo.value.couponName = String(coupon.name ?? coupon.title ?? coupon.couponName ?? '').trim();
  344. orderInfo.value.couponType = couponType || null;
  345. const nvRaw = coupon.nominalValue;
  346. if (nvRaw != null && nvRaw !== '') {
  347. const nv = Number(nvRaw);
  348. orderInfo.value.nominalValue = Number.isFinite(nv) ? nv : null;
  349. } else if (couponType === 1) {
  350. orderInfo.value.nominalValue = Number(coupon.amount) || null;
  351. } else {
  352. orderInfo.value.nominalValue = null;
  353. }
  354. const food = foodSubtotal;
  355. const fee = Number(orderInfo.value.serviceFee) || 0;
  356. const baseForDiscount = food + fee;
  357. if (couponType === 2) {
  358. const rate = resolveCheckoutDiscountCouponRate(coupon);
  359. orderInfo.value.discountRate = rate > 0 ? rate : null;
  360. if (rate > 0 && baseForDiscount > 0) {
  361. const rawDiscount = Math.round(baseForDiscount * (1 - rate / 10) * 100) / 100;
  362. orderInfo.value.discountAmount = Math.max(0, Math.min(rawDiscount, baseForDiscount));
  363. } else {
  364. orderInfo.value.discountAmount = 0;
  365. }
  366. } else {
  367. orderInfo.value.discountRate = null;
  368. orderInfo.value.discountAmount =
  369. Number(coupon.nominalValue) || Number(coupon.amount) || 0;
  370. }
  371. updateCheckoutPayAmount();
  372. couponModalOpen.value = false;
  373. };
  374. // 应付金额 = 菜品总价 + 服务费 − 优惠金额(不低于 0.01 元)
  375. const updateCheckoutPayAmount = () => {
  376. const food = Number(foodSubtotalForDisplay.value) || 0;
  377. const fee = Number(orderInfo.value.serviceFee) || 0;
  378. const discount = Number(orderInfo.value.discountAmount) || 0;
  379. let raw = Math.round((food + fee - discount) * 100) / 100;
  380. if (!Number.isFinite(raw) || raw < MIN_CHECKOUT_PAY_YUAN) {
  381. raw = MIN_CHECKOUT_PAY_YUAN;
  382. }
  383. orderInfo.value.payAmount = raw;
  384. };
  385. /** 服务费变化后:折扣券(按菜品+服务费为基数)需重算优惠金额 */
  386. function recalcDiscountAfterServiceFeeChange() {
  387. const ct = Number(orderInfo.value.couponType) || 0;
  388. if (ct !== 2 || orderInfo.value.discountRate == null || !orderInfo.value.couponId) return;
  389. const food = Number(foodSubtotalForDisplay.value) || 0;
  390. const fee = Number(orderInfo.value.serviceFee) || 0;
  391. const base = food + fee;
  392. const rate = Number(orderInfo.value.discountRate) || 0;
  393. if (base <= 0) return;
  394. const rawDiscount = Math.round(base * (1 - rate / 10) * 100) / 100;
  395. orderInfo.value.discountAmount = Math.max(0, Math.min(rawDiscount, base));
  396. }
  397. /**
  398. * 从估算接口 data 解析 feeType:后端可能放在顶层,也可能在 items[].feeType(如按人数规则)
  399. * 任一为 1 则视为按人数计费,修改人数需重新请求 estimate
  400. */
  401. function parseEstimateFeeType(res) {
  402. if (res == null || typeof res !== 'object') return null;
  403. const top = res.feeType != null && res.feeType !== '' ? Number(res.feeType) : NaN;
  404. if (top === 1) return 1;
  405. const items = Array.isArray(res.items) ? res.items : [];
  406. for (const it of items) {
  407. const ft = it?.feeType != null && it.feeType !== '' ? Number(it.feeType) : NaN;
  408. if (ft === 1) return 1;
  409. }
  410. if (!Number.isNaN(top)) return top;
  411. for (const it of items) {
  412. const ft = it?.feeType != null && it.feeType !== '' ? Number(it.feeType) : NaN;
  413. if (!Number.isNaN(ft)) return ft;
  414. }
  415. return null;
  416. }
  417. /**
  418. * 服务费估算(本版本关闭:不参与服务费)
  419. */
  420. async function fetchServiceFeeEstimate() {
  421. orderInfo.value.serviceFee = 0;
  422. estimateFeeType.value = null;
  423. recalcDiscountAfterServiceFeeChange();
  424. updateCheckoutPayAmount();
  425. /* 原 /store/dining/service-fee/estimate 逻辑(恢复时整段移出注释)
  426. const storeId = orderInfo.value.storeId || uni.getStorageSync('currentStoreId') || '';
  427. const tableId = getTableIdForServiceFeeEstimate();
  428. if (!storeId || !tableId) return;
  429. const dinerCount = parseDinerCount(orderInfo.value.diners);
  430. const goodsSubtotal = Math.max(0, Math.round((Number(foodSubtotalForDisplay.value) || 0) * 100) / 100);
  431. try {
  432. const res = await diningApi.GetServiceFeeEstimate({
  433. storeId: String(storeId),
  434. tableId,
  435. dinerCount,
  436. goodsSubtotal
  437. });
  438. estimateFeeType.value = parseEstimateFeeType(res);
  439. const fee =
  440. Number(
  441. res?.serviceFee ??
  442. res?.estimatedServiceFee ??
  443. res?.fee ??
  444. res?.amount ??
  445. (typeof res === 'number' ? res : 0)
  446. ) || 0;
  447. orderInfo.value.serviceFee = fee;
  448. recalcDiscountAfterServiceFeeChange();
  449. updateCheckoutPayAmount();
  450. } catch (e) {
  451. console.warn('结算页服务费估算失败:', e);
  452. }
  453. */
  454. }
  455. function formatPrice(price) {
  456. const num = Number(price);
  457. return Number.isNaN(num) ? '0.00' : num.toFixed(2);
  458. }
  459. // 取第一张图:逗号分隔取首段,数组取首项,对象取 url/path/src(与 orderDetail 一致)
  460. function firstImage(val) {
  461. if (val == null || val === '') return '';
  462. if (Array.isArray(val)) {
  463. const first = val[0];
  464. if (first != null && first !== '') {
  465. if (typeof first === 'object' && first !== null) return first.url ?? first.path ?? first.src ?? first.link ?? '';
  466. return String(first).split(/[,,]/)[0].trim();
  467. }
  468. return '';
  469. }
  470. if (typeof val === 'object') return val.url ?? val.path ?? val.src ?? val.link ?? '';
  471. const str = String(val).trim();
  472. return str ? str.split(/[,,]/)[0].trim() : '';
  473. }
  474. function getItemImage(item) {
  475. const raw = item?.image ?? item?.cuisineImage ?? item?.imageUrl ?? item?.images ?? item?.pic ?? item?.cover ?? '';
  476. const url = firstImage(raw) || (typeof raw === 'string' ? raw.split(/[,,]/)[0]?.trim() : '');
  477. if (url && typeof url === 'string' && (url.startsWith('http') || url.startsWith('//'))) return url;
  478. return getFileUrl(url || 'img/icon/shop.png');
  479. }
  480. // 将 tags 统一为 [{ text, type }] 格式
  481. function normalizeTags(raw) {
  482. if (raw == null) return [];
  483. let arr = [];
  484. if (Array.isArray(raw)) arr = raw;
  485. else if (typeof raw === 'string') {
  486. const t = raw.trim();
  487. if (t.startsWith('[')) { try { arr = JSON.parse(t); if (!Array.isArray(arr)) arr = []; } catch { arr = t ? [t] : []; } }
  488. else arr = t ? t.split(/[,,、\s]+/).map(s => s.trim()).filter(Boolean) : [];
  489. } else if (raw && typeof raw === 'object') arr = Array.isArray(raw.list) ? raw.list : Array.isArray(raw.items) ? raw.items : [];
  490. return arr.map((it) => {
  491. if (it == null) return { text: '', type: '' };
  492. if (typeof it === 'string') return { text: it, type: '' };
  493. if (typeof it === 'number') return { text: String(it), type: '' };
  494. return { text: it.text ?? it.tagName ?? it.name ?? it.label ?? it.title ?? '', type: it.type ?? it.tagType ?? '' };
  495. }).filter((t) => t.text !== '' && t.text != null);
  496. }
  497. // 接口订单项转列表项:图片取首张(逗号/数组/对象与 orderDetail 一致)
  498. function normalizeOrderItem(item) {
  499. const rawTags = item?.tags ?? item?.tagList ?? item?.tagNames ?? item?.labels ?? item?.tag;
  500. const rawImg = item?.images ?? item?.image ?? item?.cuisineImage ?? item?.imageUrl ?? item?.pic ?? item?.cover ?? '';
  501. const imageUrl = firstImage(rawImg) || (typeof rawImg === 'string' ? rawImg.split(/[,,]/)[0]?.trim() : '') || 'img/icon/shop.png';
  502. const qty = Number(item?.quantity ?? 1) || 1;
  503. /** 行成交价小计(元):与购物车/服务费估算 goodsSubtotal 一致 */
  504. let lineSubtotal = 0;
  505. if (item?.subtotalAmount != null && item.subtotalAmount !== '') {
  506. lineSubtotal = Number(item.subtotalAmount) || 0;
  507. } else if (item?.totalPrice != null && item.totalPrice !== '') {
  508. lineSubtotal = Number(item.totalPrice) || 0;
  509. } else {
  510. const unit = Number(item?.unitPrice ?? item?.price ?? 0) || 0;
  511. lineSubtotal = unit * qty;
  512. }
  513. if (lineSubtotal <= 0) {
  514. const unit = Number(item?.unitPrice ?? item?.price ?? item?.salePrice ?? 0) || 0;
  515. const fallback = unit * qty;
  516. if (fallback > 0) lineSubtotal = fallback;
  517. }
  518. const unitForDisplay =
  519. Number(item?.unitPrice ?? item?.price ?? 0) ||
  520. (qty > 0 ? lineSubtotal / qty : 0);
  521. return {
  522. id: item?.id ?? item?.cuisineId,
  523. name: item?.cuisineName ?? item?.name ?? '',
  524. price: unitForDisplay,
  525. lineSubtotal,
  526. image: imageUrl,
  527. quantity: qty,
  528. tags: normalizeTags(rawTags)
  529. };
  530. }
  531. /** 桌台主键:store_table.id,不可用桌号展示文案代替 */
  532. function getTableIdForServiceFeeEstimate() {
  533. const t = orderInfo.value.tableId;
  534. if (t != null && String(t).trim() !== '') return String(t).trim();
  535. return String(uni.getStorageSync('currentTableId') || '').trim();
  536. }
  537. /** 根据 orderInfo.couponId 与券列表对齐选中态(弹窗单选 id 为 userCoupon 实例 id) */
  538. function syncCheckoutSelectedCouponId() {
  539. const cid = orderInfo.value.couponId;
  540. if (cid == null || String(cid).trim() === '') {
  541. selectedCouponId.value = null;
  542. return;
  543. }
  544. const s = String(cid).trim();
  545. const list = couponList.value ?? [];
  546. const hit = list.find(
  547. (c) =>
  548. String(c?.couponId ?? '') === s ||
  549. String(c?.id ?? '') === s ||
  550. String(c?.userCouponId ?? '') === s
  551. );
  552. selectedCouponId.value = hit ? String(hit.id) : null;
  553. }
  554. /** 从订单详情接口回显优惠券(与下单/锁单时服务端数据一致) */
  555. function applyCheckoutCouponFromOrderRaw(raw) {
  556. const cid = raw?.couponId ?? raw?.userCouponId ?? raw?.memberCouponId ?? null;
  557. const discountAmt =
  558. Number(raw?.discountAmount ?? raw?.couponAmount ?? raw?.couponDiscount ?? 0) || 0;
  559. const hasCoupon =
  560. (cid != null && String(cid).trim() !== '') ||
  561. discountAmt > 0 ||
  562. (String(raw?.couponName ?? '').trim() !== '');
  563. if (!hasCoupon) {
  564. orderInfo.value.couponId = null;
  565. orderInfo.value.couponName = '';
  566. orderInfo.value.couponType = null;
  567. orderInfo.value.discountRate = null;
  568. orderInfo.value.nominalValue = null;
  569. orderInfo.value.discountAmount = 0;
  570. selectedCouponId.value = null;
  571. updateCheckoutPayAmount();
  572. return;
  573. }
  574. orderInfo.value.couponId = cid != null && String(cid).trim() !== '' ? String(cid).trim() : null;
  575. orderInfo.value.couponName = String(raw?.couponName ?? '').trim();
  576. orderInfo.value.couponType = raw?.couponType ?? null;
  577. const rawRate = raw?.discountRate;
  578. if (rawRate != null && rawRate !== '') {
  579. const zhe = normalizeZheRateForCheckoutFormula(Number(rawRate));
  580. orderInfo.value.discountRate = zhe > 0 ? zhe : null;
  581. } else {
  582. orderInfo.value.discountRate = null;
  583. }
  584. orderInfo.value.nominalValue = raw?.nominalValue ?? null;
  585. orderInfo.value.discountAmount = discountAmt;
  586. recalcDiscountAfterServiceFeeChange();
  587. updateCheckoutPayAmount();
  588. }
  589. const fetchOrderDetail = async () => {
  590. const id = orderId.value || '';
  591. if (!id) return;
  592. try {
  593. const res = await diningApi.GetOrderInfo(id);
  594. const raw = res?.data ?? res ?? {};
  595. orderInfo.value.orderNo = raw?.orderNo ?? raw?.orderId ?? '';
  596. orderInfo.value.storeId = raw?.storeId ?? raw?.store_id ?? '';
  597. // tableId 须为门店桌台表主键(store_table.id),勿用 tableNumber(展示用桌号)冒充
  598. orderInfo.value.tableId =
  599. raw?.tableId ??
  600. raw?.storeTableId ??
  601. raw?.store_table_id ??
  602. raw?.diningTableId ??
  603. '';
  604. orderInfo.value.tableNumber = raw?.tableNumber ?? raw?.tableNo ?? '';
  605. const dc = raw?.dinerCount ?? raw?.diners ?? '';
  606. orderInfo.value.diners =
  607. dc !== '' && dc != null ? String(parseDinerCount(dc)) : String(MIN_DINERS);
  608. orderInfo.value.contactPhone = raw?.contactPhone ?? raw?.phone ?? '';
  609. orderInfo.value.remark = raw?.remark ?? '';
  610. const total = Number(raw?.totalAmount ?? raw?.orderAmount ?? raw?.foodAmount ?? 0) || 0;
  611. orderInfo.value.totalAmount = total;
  612. orderInfo.value.dishTotal = raw?.dishTotal != null ? Number(raw.dishTotal) : null;
  613. // 本版本不参与服务费:不从订单拉取服务费
  614. orderInfo.value.serviceFee = 0;
  615. const list = raw?.orderItemList ?? raw?.orderItems ?? raw?.items ?? raw?.detailList ?? [];
  616. foodList.value = (Array.isArray(list) ? list : []).map(normalizeOrderItem);
  617. applyCheckoutCouponFromOrderRaw(raw);
  618. await fetchServiceFeeEstimate(); // 本版为 no-op(不参与服务费)
  619. } catch (err) {
  620. console.error('获取订单详情失败:', err);
  621. uni.showToast({ title: '加载失败', icon: 'none' });
  622. }
  623. };
  624. const handleConfirmPay = async () => {
  625. const id = orderId.value || '';
  626. if (!id) {
  627. uni.showToast({ title: '缺少订单ID', icon: 'none' });
  628. return;
  629. }
  630. const userStore = useUserStore();
  631. const openid = userStore.getOpenId || '';
  632. if (!openid) {
  633. uni.showToast({ title: '请先登录', icon: 'none' });
  634. return;
  635. }
  636. const payAmountVal = Math.round((Number(orderInfo.value.payAmount ?? 0) || 0) * 100) / 100;
  637. if (payAmountVal < MIN_CHECKOUT_PAY_YUAN) {
  638. uni.showToast({ title: '订单金额异常', icon: 'none' });
  639. return;
  640. }
  641. const orderNo = orderInfo.value.orderNo || '';
  642. if (!orderNo) {
  643. uni.showToast({ title: '缺少订单号', icon: 'none' });
  644. return;
  645. }
  646. const price = Math.round(payAmountVal * 100);
  647. uni.showLoading({ title: '拉起支付...' });
  648. try {
  649. const storeId = orderInfo.value.storeId || uni.getStorageSync('currentStoreId') || '';
  650. const u = userStore.getUserInfo || {};
  651. const payerId = u.id ?? u.userId ?? u.user_id ?? '';
  652. const couponIdVal =
  653. orderInfo.value.couponId != null && orderInfo.value.couponId !== ''
  654. ? String(orderInfo.value.couponId)
  655. : selectedCouponId.value != null && selectedCouponId.value !== ''
  656. ? String(selectedCouponId.value)
  657. : '';
  658. const discountAmountVal = Number(orderInfo.value.discountAmount) || 0;
  659. // const serviceFeeVal = Math.round((Number(orderInfo.value.serviceFee ?? 0) || 0) * 100) / 100;
  660. const res = await diningApi.PostOrderPay({
  661. orderNo,
  662. payer: openid,
  663. price,
  664. subject: '订单支付',
  665. storeId: storeId || undefined,
  666. couponId: couponIdVal || undefined,
  667. payerId: payerId ? String(payerId) : undefined,
  668. discountAmount: discountAmountVal,
  669. payAmount: payAmountVal
  670. // serviceFee: serviceFeeVal // 本版本不参与服务费
  671. });
  672. uni.hideLoading();
  673. uni.requestPayment({
  674. provider: 'wxpay',
  675. timeStamp: res.timestamp,
  676. nonceStr: res.nonce,
  677. package: res.prepayId,
  678. signType: res.signType,
  679. paySign: res.sign,
  680. success: () => {
  681. uni.showToast({ title: '支付成功', icon: 'success' });
  682. const oid = orderId.value || '';
  683. if (oid) {
  684. diningApi.PostOrderSettlementUnlock({ orderId: oid }).catch((e) => console.warn('解锁订单失败:', e));
  685. }
  686. const payType = 'wechatPayPartnerMininProgram';
  687. // 查询支付结果需用 prePay 返回的 transactionId,与订单号 orderNo 可能不同
  688. const prePayTid =
  689. res?.transactionId ??
  690. res?.transaction_id ??
  691. res?.outTradeNo ??
  692. orderNo;
  693. const sid = orderInfo.value.storeId || uni.getStorageSync('currentStoreId') || '';
  694. const q = [`id=${encodeURIComponent(oid)}`, `payType=${encodeURIComponent(payType)}`, `transactionId=${encodeURIComponent(String(prePayTid ?? ''))}`];
  695. if (sid) q.push(`storeId=${encodeURIComponent(sid)}`);
  696. setTimeout(() => go(`/pages/paymentSuccess/index?${q.join('&')}`), 1500);
  697. },
  698. fail: (err) => {
  699. const msg = err?.errMsg ?? err?.message ?? '支付失败';
  700. if (String(msg).includes('cancel')) {
  701. uni.showToast({ title: '已取消支付', icon: 'none' });
  702. } else {
  703. uni.showToast({ title: msg || '支付失败', icon: 'none' });
  704. }
  705. }
  706. });
  707. } catch (e) {
  708. uni.hideLoading();
  709. uni.showToast({ title: e?.message || '获取支付参数失败', icon: 'none' });
  710. }
  711. };
  712. onLoad(async (options) => {
  713. const id = options?.orderId ?? options?.id ?? '';
  714. orderId.value = id;
  715. if (options?.orderNo) orderInfo.value.orderNo = options.orderNo;
  716. if (options?.tableId) orderInfo.value.tableId = options.tableId;
  717. if (options?.tableNumber) orderInfo.value.tableNumber = options.tableNumber;
  718. if (options?.diners != null && options?.diners !== '') {
  719. orderInfo.value.diners = String(parseDinerCount(options.diners));
  720. uni.setStorageSync('currentDiners', orderInfo.value.diners);
  721. }
  722. if (options?.remark != null && options?.remark !== '') orderInfo.value.remark = decodeURIComponent(options.remark);
  723. if (options?.totalAmount != null && options?.totalAmount !== '') {
  724. const p = Math.round((Number(options.totalAmount) || 0) * 100) / 100;
  725. orderInfo.value.payAmount = p < MIN_CHECKOUT_PAY_YUAN ? MIN_CHECKOUT_PAY_YUAN : p;
  726. }
  727. if (id) {
  728. await fetchOrderDetail();
  729. }
  730. await fetchCheckoutCouponList({ reset: true, silentNoStore: true });
  731. });
  732. onShow(() => {
  733. const id = orderId.value || '';
  734. if (id) {
  735. diningApi.PostOrderSettlementLock({ orderId: id }).catch((e) => console.warn('锁定订单失败:', e));
  736. }
  737. });
  738. onUnload(() => {
  739. const id = orderId.value || '';
  740. if (id) {
  741. diningApi.PostOrderSettlementUnlock({ orderId: id }).catch((e) => console.warn('解锁订单失败:', e));
  742. }
  743. });
  744. </script>
  745. <style lang="scss" scoped>
  746. .content {
  747. padding: 0 30rpx 300rpx;
  748. }
  749. .card {
  750. background-color: #fff;
  751. border-radius: 24rpx;
  752. padding: 30rpx 0;
  753. margin-top: 20rpx;
  754. .card-header {
  755. display: flex;
  756. align-items: center;
  757. padding: 0 30rpx;
  758. height: 40rpx;
  759. position: relative;
  760. font-size: 27rpx;
  761. color: #151515;
  762. font-weight: bold;
  763. }
  764. .tag {
  765. width: 10rpx;
  766. height: 42rpx;
  767. background: linear-gradient(35deg, #FCB73F 0%, #FC733D 100%);
  768. border-radius: 0;
  769. position: absolute;
  770. left: 0;
  771. top: 0;
  772. }
  773. .card-content {
  774. padding: 0 30rpx;
  775. }
  776. .info-item {
  777. display: flex;
  778. justify-content: space-between;
  779. align-items: center;
  780. margin-top: 20rpx;
  781. font-size: 27rpx;
  782. .info-item-label {
  783. color: #666666;
  784. }
  785. .info-item-value {
  786. color: #151515;
  787. &.remark-text {
  788. flex: 1;
  789. text-align: right;
  790. word-break: break-all;
  791. }
  792. }
  793. &--coupon .coupon-value {
  794. display: flex;
  795. align-items: center;
  796. gap: 8rpx;
  797. }
  798. .coupon-amount {
  799. color: #E61F19;
  800. }
  801. .coupon-placeholder {
  802. color: #999999;
  803. }
  804. .coupon-arrow {
  805. color: #999;
  806. margin-left: 4rpx;
  807. }
  808. &--clickable {
  809. cursor: pointer;
  810. }
  811. }
  812. .price-line {
  813. display: flex;
  814. justify-content: space-between;
  815. align-items: center;
  816. margin-top: 24rpx;
  817. padding-top: 24rpx;
  818. border-top: 1rpx solid #f0f0f0;
  819. font-size: 28rpx;
  820. font-weight: bold;
  821. .price-line-label {
  822. color: #151515;
  823. }
  824. .price-line-value {
  825. color: #E61F19;
  826. }
  827. }
  828. .info-food {
  829. .food-item {
  830. display: flex;
  831. align-items: center;
  832. padding: 20rpx 0;
  833. border-bottom: 1rpx solid #f5f5f5;
  834. &:last-child {
  835. border-bottom: none;
  836. }
  837. &__image {
  838. width: 120rpx;
  839. height: 120rpx;
  840. border-radius: 12rpx;
  841. flex-shrink: 0;
  842. background: #f5f5f5;
  843. }
  844. &__info {
  845. flex: 1;
  846. margin-left: 24rpx;
  847. min-width: 0;
  848. }
  849. &__name {
  850. font-size: 28rpx;
  851. color: #151515;
  852. font-weight: 500;
  853. }
  854. &__desc {
  855. font-size: 22rpx;
  856. color: #999;
  857. margin-top: 6rpx;
  858. }
  859. &__tag {
  860. margin-right: 4rpx;
  861. &.signature {
  862. color: #FC793D;
  863. }
  864. &.spicy {
  865. color: #2E2E2E;
  866. }
  867. }
  868. &__right {
  869. flex-shrink: 0;
  870. text-align: right;
  871. }
  872. &__price .price-main {
  873. font-size: 28rpx;
  874. color: #151515;
  875. font-weight: 600;
  876. }
  877. &__quantity {
  878. font-size: 24rpx;
  879. color: #999;
  880. margin-top: 6rpx;
  881. }
  882. }
  883. }
  884. }
  885. .bottom-button {
  886. position: fixed;
  887. left: 0;
  888. right: 0;
  889. bottom: 0;
  890. padding: 20rpx 30rpx;
  891. padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  892. background: #fff;
  893. box-shadow: 0 -2rpx 12rpx rgba(0, 0, 0, 0.06);
  894. .bottom-button-text {
  895. height: 88rpx;
  896. line-height: 88rpx;
  897. text-align: center;
  898. background: linear-gradient(90deg, #FCB73F 0%, #FC733D 100%);
  899. color: #fff;
  900. font-size: 32rpx;
  901. font-weight: bold;
  902. border-radius: 44rpx;
  903. }
  904. .hover-active {
  905. opacity: 0.9;
  906. }
  907. }
  908. .coupon-modal-wrapper {
  909. position: relative;
  910. z-index: 99999;
  911. :deep(.uni-popup) {
  912. z-index: 99999 !important;
  913. top: 0 !important;
  914. left: 0 !important;
  915. right: 0 !important;
  916. bottom: 0 !important;
  917. }
  918. :deep(.uni-popup__wrapper) {
  919. z-index: 99999 !important;
  920. }
  921. :deep(.select-coupon-modal__list) {
  922. padding-bottom: calc(60rpx + env(safe-area-inset-bottom));
  923. }
  924. :deep(.select-coupon-modal__empty) {
  925. margin-bottom: 60rpx;
  926. }
  927. }
  928. </style>