index.vue 34 KB

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