detail.vue 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. <template>
  2. <view class="safe-page detail-page">
  3. <scroll-view scroll-y class="detail-scroll">
  4. <swiper v-if="images.length" class="swiper" circular indicator-dots>
  5. <swiper-item v-for="img in images" :key="img">
  6. <image class="hero-img" :src="img" mode="aspectFill" />
  7. </swiper-item>
  8. </swiper>
  9. <view v-else class="empty-img">订餐</view>
  10. <view v-if="item" class="card main-card">
  11. <view class="title-row">
  12. <view class="name">{{ item.itemName }}</view>
  13. <view class="price">¥{{ formatMoney(finalSalePrice) }}</view>
  14. </view>
  15. <view v-if="item.tags?.length" class="tags">
  16. <text v-for="tag in item.tags" :key="tag" class="tag">{{ tag }}</text>
  17. </view>
  18. <view :class="['stock', soldOut && 'danger']">{{ stockText }}</view>
  19. </view>
  20. <view v-if="item" class="card info-card" @click="goServiceAreaSelect">
  21. <view class="section-title">当前服务区域</view>
  22. <view class="area-row">
  23. <view>
  24. <view class="area-name">{{ currentServiceArea?.name || item.serviceArea?.name || item.restaurant?.name || '未选择服务区域' }}</view>
  25. <view class="muted">{{ currentServiceArea?.floorLabel || currentServiceArea?.locationLabel || item.serviceArea?.locationLabel || item.serviceArea?.address || item.restaurant?.locationLabel || item.restaurant?.address || '暂无位置信息' }}</view>
  26. <view v-if="currentServiceArea?.phone || item.serviceArea?.phone || item.restaurant?.phone" class="muted">电话:{{ currentServiceArea?.phone || item.serviceArea?.phone || item.restaurant?.phone }}</view>
  27. </view>
  28. <view class="switch-link">切换</view>
  29. </view>
  30. </view>
  31. <view v-if="item" class="card info-card">
  32. <view class="section-title">取餐信息</view>
  33. <view class="info-line">取货方式:自提</view>
  34. <view class="info-line">取货日期:{{ item.pickupDate || item.menuDate || '以订单为准' }}</view>
  35. <view class="info-line">取餐点:{{ item.pickupLocation || currentServiceArea?.pickupLocation || '以现场通知为准' }}</view>
  36. </view>
  37. <view v-if="item" class="card info-card">
  38. <view class="section-title">下单倒计时</view>
  39. <view :class="['countdown', hasDeadline && countdown <= 0 && 'danger']">{{ countdownText }}</view>
  40. </view>
  41. <view v-if="item?.specs?.length" class="card info-card">
  42. <view class="section-title">菜品规格</view>
  43. <view class="specs">
  44. <view v-for="spec in item.specs" :key="spec.id || spec.name" :class="['spec', isSpecSelected(spec) && 'active']" @click="selectSpec(spec)">
  45. <view>{{ spec.name }}</view>
  46. <view v-if="spec.description" class="muted">{{ spec.description }}</view>
  47. <view class="muted">{{ specStockText(spec) }}</view>
  48. </view>
  49. </view>
  50. </view>
  51. <view v-if="item" class="card info-card">
  52. <view class="section-title">购买数量</view>
  53. <view class="stepper-row">
  54. <view class="stepper">
  55. <view :class="['step-btn', quantity <= 1 && 'step-disabled']" @click="changeQuantity(-1)">-</view>
  56. <text class="step-num">{{ quantity }}</text>
  57. <view :class="['step-btn', quantity >= maxQuantity && 'step-disabled']" @click="changeQuantity(1)">+</view>
  58. </view>
  59. <view v-if="maxQuantityText" class="muted step-tip">{{ maxQuantityText }}</view>
  60. </view>
  61. </view>
  62. <view v-if="item?.descriptionHtml" class="card info-card">
  63. <view class="section-title">菜品描述</view>
  64. <rich-text :nodes="item.descriptionHtml" />
  65. </view>
  66. <view class="detail-bottom-spacer" />
  67. </scroll-view>
  68. <view class="bottom-bar">
  69. <button :class="['buy-btn', (!canBuy || loading) && 'disabled']" :disabled="!canBuy || loading" @click="buyNow">{{ buttonText }}</button>
  70. </view>
  71. </view>
  72. </template>
  73. <script setup lang="ts">
  74. import { computed, onUnmounted, ref } from 'vue'
  75. import { onLoad } from '@dcloudio/uni-app'
  76. import { fetchMealMenuItemDetail } from '@/api/modules/meal'
  77. import { fetchCompanyMealMenuItemDetail, trialCompanyMealOrder } from '@/api/modules/companyMeal'
  78. import { useCompanyStore } from '@/store/modules/company'
  79. import { useMealStore } from '@/store/modules/meal'
  80. import type { FoodMealMenuItemDetail, FoodMealMenuItemSpec } from '@/types/meal'
  81. import { formatMoney } from '@/utils/money'
  82. import { requireLoginNavigate } from '@/utils/auth'
  83. type StockSnapshot = {
  84. stockQuantity?: number | null
  85. soldQuantity?: number | null
  86. remainingQuantity?: number | null
  87. soldOut?: boolean
  88. limitQuantityPerUser?: number | null
  89. }
  90. type SpecWithStock = FoodMealMenuItemSpec & StockSnapshot
  91. const company = useCompanyStore()
  92. const meal = useMealStore()
  93. const item = ref<FoodMealMenuItemDetail | null>(null)
  94. const loading = ref(false)
  95. const menuItemId = ref('')
  96. const mode = ref<'personal' | 'company'>('personal')
  97. const companyId = ref('')
  98. const countdown = ref(0)
  99. const selectedSpec = ref<SpecWithStock | null>(null)
  100. const quantity = ref(1)
  101. let timer: ReturnType<typeof setInterval> | null = null
  102. let countdownRefreshed = false
  103. const currentServiceArea = computed(() => item.value?.serviceArea || meal.currentServiceArea || item.value?.restaurant)
  104. const detailServiceAreaId = computed(() => item.value?.serviceAreaId || item.value?.serviceArea?.id || item.value?.restaurantId || item.value?.restaurant?.id)
  105. const serviceAreaChanged = computed(() => {
  106. return Boolean(meal.currentServiceArea?.id && detailServiceAreaId.value && meal.currentServiceArea.id !== detailServiceAreaId.value)
  107. })
  108. const images = computed(() => item.value?.images?.length ? item.value.images : (item.value?.itemImage ? [item.value.itemImage] : []))
  109. const hasSpecs = computed(() => Boolean(item.value?.specs?.length))
  110. const finalSalePrice = computed(() => selectedSpec.value?.salePrice ?? item.value?.salePrice ?? 0)
  111. const currentStockSource = computed<StockSnapshot | null>(() => selectedSpec.value || item.value)
  112. const currentLimitQuantityPerUser = computed(() => selectedSpec.value?.limitQuantityPerUser ?? item.value?.limitQuantityPerUser ?? null)
  113. const currentRemainingQuantity = computed(() => currentStockSource.value ? remainingQuantity(currentStockSource.value) : null)
  114. const soldOut = computed(() => {
  115. if (selectedSpec.value?.soldOut === true) return true
  116. if (!selectedSpec.value && item.value?.soldOut === true) return true
  117. return currentRemainingQuantity.value != null && currentRemainingQuantity.value <= 0
  118. })
  119. const hasDeadline = computed(() => item.value?.deadlineRemainSeconds != null)
  120. const maxQuantity = computed(() => {
  121. const stock = currentRemainingQuantity.value == null ? 999 : currentRemainingQuantity.value
  122. const limit = currentLimitQuantityPerUser.value == null ? 999 : currentLimitQuantityPerUser.value
  123. return Math.max(Math.min(stock, limit), 1)
  124. })
  125. const maxQuantityText = computed(() => {
  126. const remain = currentRemainingQuantity.value
  127. const limit = currentLimitQuantityPerUser.value
  128. if (remain != null && limit != null) return `本单最多可选 ${Math.min(remain, limit)} 份`
  129. if (remain != null) return `本单最多可选 ${remain} 份`
  130. if (limit != null) return `每人限购 ${limit} 份`
  131. return ''
  132. })
  133. const canBuy = computed(() => Boolean(item.value && !soldOut.value && item.value.orderable !== false && (!hasDeadline.value || countdown.value > 0)))
  134. const stockText = computed(() => {
  135. const remain = currentRemainingQuantity.value
  136. const stock = remain == null ? '库存充足' : (remain <= 0 ? '仅剩 0,已售罄' : `仅剩 ${remain} 份`)
  137. if (currentLimitQuantityPerUser.value != null) return `${stock},每人限购 ${currentLimitQuantityPerUser.value} 份`
  138. return stock
  139. })
  140. const countdownText = computed(() => {
  141. if (item.value?.orderable === false) return item.value.notOrderableReason || '已停止接单'
  142. if (hasDeadline.value && countdown.value <= 0) return '已截单/停止接单'
  143. if (!hasDeadline.value) return '随时可订'
  144. const h = Math.floor(countdown.value / 3600).toString().padStart(2, '0')
  145. const m = Math.floor((countdown.value % 3600) / 60).toString().padStart(2, '0')
  146. const s = Math.floor(countdown.value % 60).toString().padStart(2, '0')
  147. return `${h}:${m}:${s}`
  148. })
  149. const buttonText = computed(() => {
  150. if (soldOut.value) return '已售罄'
  151. if (item.value?.orderable === false) return '已停止接单'
  152. if (hasDeadline.value && countdown.value <= 0) return '已截单'
  153. return '立即购买'
  154. })
  155. onLoad(async query => {
  156. menuItemId.value = String(query?.menuItemId || '')
  157. mode.value = query?.mode === 'company' ? 'company' : 'personal'
  158. companyId.value = String(query?.companyId || '')
  159. await loadDetail()
  160. })
  161. onUnmounted(() => stopTimer())
  162. async function loadDetail() {
  163. if (!menuItemId.value) return
  164. loading.value = true
  165. try {
  166. const currentCompanyId = companyId.value || company.currentCompany?.companyId
  167. const res = mode.value === 'company' && currentCompanyId
  168. ? await fetchCompanyMealMenuItemDetail(currentCompanyId, menuItemId.value)
  169. : await fetchMealMenuItemDetail(menuItemId.value)
  170. const detail = res.data
  171. item.value = detail
  172. selectedSpec.value = detail.specs?.find(spec => !specSoldOut(spec)) || detail.specs?.[0] || null
  173. quantity.value = 1
  174. countdown.value = Math.max(Number(detail.deadlineRemainSeconds || 0), 0)
  175. countdownRefreshed = false
  176. startTimer()
  177. } finally {
  178. loading.value = false
  179. }
  180. }
  181. function startTimer() {
  182. stopTimer()
  183. if (!item.value || !hasDeadline.value || countdown.value <= 0) return
  184. timer = setInterval(async () => {
  185. countdown.value = Math.max(countdown.value - 1, 0)
  186. if (countdown.value <= 0) {
  187. stopTimer()
  188. if (!countdownRefreshed) {
  189. countdownRefreshed = true
  190. await refreshDetailOnce()
  191. }
  192. }
  193. }, 1000)
  194. }
  195. function stopTimer() {
  196. if (timer) clearInterval(timer)
  197. timer = null
  198. }
  199. async function refreshDetailOnce() {
  200. if (!menuItemId.value) return
  201. const currentCompanyId = companyId.value || company.currentCompany?.companyId
  202. const res = mode.value === 'company' && currentCompanyId
  203. ? await fetchCompanyMealMenuItemDetail(currentCompanyId, menuItemId.value)
  204. : await fetchMealMenuItemDetail(menuItemId.value)
  205. const detail = res.data
  206. item.value = detail
  207. selectedSpec.value = detail.specs?.find(spec => selectedSpec.value?.id ? spec.id === selectedSpec.value.id : spec.name === selectedSpec.value?.name) as SpecWithStock || detail.specs?.find(spec => !specSoldOut(spec)) || detail.specs?.[0] || null
  208. countdown.value = Math.max(Number(detail.deadlineRemainSeconds || 0), 0)
  209. }
  210. function modeQuery() {
  211. const params = [`mode=${mode.value}`]
  212. const currentCompanyId = companyId.value || company.currentCompany?.companyId
  213. if (mode.value === 'company' && currentCompanyId) params.push(`companyId=${encodeURIComponent(currentCompanyId)}`)
  214. return params.join('&')
  215. }
  216. function goServiceAreaSelect() {
  217. uni.navigateTo({ url: `/package-views/pages/meal/restaurant-select?from=detail&${modeQuery()}` })
  218. }
  219. function remainingQuantity(source: { stockQuantity?: number | null; soldQuantity?: number | null; remainingQuantity?: number | null }) {
  220. if (source.remainingQuantity != null) return source.remainingQuantity
  221. if (source.stockQuantity == null) return null
  222. return Math.max(source.stockQuantity - (source.soldQuantity || 0), 0)
  223. }
  224. function specSoldOut(spec: FoodMealMenuItemSpec) {
  225. const snapshot = spec as SpecWithStock
  226. const remain = remainingQuantity(snapshot)
  227. return snapshot.soldOut === true || (remain != null && remain <= 0)
  228. }
  229. function specStockText(spec: FoodMealMenuItemSpec) {
  230. const snapshot = spec as SpecWithStock
  231. const remain = remainingQuantity(snapshot)
  232. const stock = remain == null ? '库存充足' : (remain <= 0 ? '仅剩 0,已售罄' : `仅剩 ${remain} 份`)
  233. if (snapshot.limitQuantityPerUser != null) return `${stock},每人限购 ${snapshot.limitQuantityPerUser} 份`
  234. return stock
  235. }
  236. function selectSpec(spec: FoodMealMenuItemSpec) {
  237. selectedSpec.value = spec as SpecWithStock
  238. quantity.value = 1
  239. }
  240. function changeQuantity(delta: number) {
  241. if (delta < 0 && quantity.value <= 1) return
  242. if (delta > 0 && quantity.value >= maxQuantity.value) return
  243. const next = Math.max(1, Math.min(quantity.value + delta, maxQuantity.value))
  244. if (next === quantity.value && delta > 0) {
  245. uni.showToast({ title: '已达可选上限', icon: 'none' })
  246. }
  247. quantity.value = next
  248. }
  249. function isSpecSelected(spec: FoodMealMenuItemSpec) {
  250. if (!selectedSpec.value) return false
  251. if (selectedSpec.value.id || spec.id) return selectedSpec.value.id === spec.id
  252. return selectedSpec.value.name === spec.name
  253. }
  254. async function buyNow() {
  255. if (!item.value || !canBuy.value) return
  256. if (serviceAreaChanged.value) {
  257. uni.showModal({
  258. title: '服务区域已切换',
  259. content: '请返回菜单重新选择当前服务区域的菜品',
  260. confirmText: '返回菜单',
  261. success: res => {
  262. if (res.confirm) uni.redirectTo({ url: `/package-views/pages/meal/menu?${modeQuery()}` })
  263. }
  264. })
  265. return
  266. }
  267. if (!requireLoginNavigate(`/package-views/pages/meal/detail?menuItemId=${encodeURIComponent(menuItemId.value)}&${modeQuery()}`)) return
  268. if (hasSpecs.value && !selectedSpec.value?.id) {
  269. uni.showToast({ title: '请选择规格', icon: 'none' })
  270. return
  271. }
  272. const currentCompanyId = companyId.value || company.currentCompany?.companyId
  273. if (mode.value === 'company' && !currentCompanyId) {
  274. uni.showToast({ title: '请选择企业', icon: 'none' })
  275. return
  276. }
  277. const serviceArea = item.value.serviceArea || item.value.restaurant || currentServiceArea.value
  278. const stockSnapshot = selectedSpec.value || item.value
  279. const checkoutItem = {
  280. menuItemId: item.value.id,
  281. specId: selectedSpec.value?.id,
  282. specName: selectedSpec.value?.name,
  283. specDescription: selectedSpec.value?.description,
  284. quantity: quantity.value,
  285. itemName: item.value.itemName,
  286. salePrice: finalSalePrice.value,
  287. totalAmount: finalSalePrice.value * quantity.value,
  288. stockQuantity: stockSnapshot.stockQuantity,
  289. soldQuantity: stockSnapshot.soldQuantity,
  290. remainingQuantity: remainingQuantity(stockSnapshot),
  291. limitQuantityPerUser: stockSnapshot.limitQuantityPerUser
  292. }
  293. let trial
  294. if (mode.value === 'company' && currentCompanyId) {
  295. const trialRes = await trialCompanyMealOrder({
  296. companyId: currentCompanyId,
  297. serviceAreaId: detailServiceAreaId.value || serviceArea?.id,
  298. menuId: item.value.menuId,
  299. mealDate: item.value.menuDate || '',
  300. mealType: item.value.mealType || '',
  301. items: [{ menuItemId: item.value.id, specId: selectedSpec.value?.id, quantity: quantity.value }]
  302. })
  303. trial = {
  304. originalAmount: trialRes.data.originalAmount,
  305. discountAmount: trialRes.data.discountAmount,
  306. companyPayAmount: trialRes.data.companyPayAmount,
  307. employeePayAmount: trialRes.data.employeePayAmount
  308. }
  309. }
  310. uni.setStorageSync('meal_checkout_payload', {
  311. mode: mode.value,
  312. ...(mode.value === 'company' ? { companyId: currentCompanyId, companyName: company.currentCompany?.companyName, trial } : {}),
  313. menuId: item.value.menuId,
  314. serviceAreaId: detailServiceAreaId.value || serviceArea?.id,
  315. serviceAreaName: item.value.serviceAreaName || serviceArea?.name,
  316. serviceAreaPhone: serviceArea?.phone,
  317. serviceArea,
  318. mealDate: item.value.menuDate,
  319. mealType: item.value.mealType,
  320. pickupType: 'pickup',
  321. pickupDate: item.value.pickupDate || item.value.menuDate,
  322. pickupLocation: item.value.pickupLocation || item.value.serviceArea?.pickupLocation || item.value.restaurant?.pickupLocation || serviceArea?.pickupLocation,
  323. deadlineTime: item.value.deadlineTime,
  324. deadlineRemainSeconds: countdown.value,
  325. items: [checkoutItem],
  326. totalAmount: finalSalePrice.value * quantity.value
  327. })
  328. uni.navigateTo({ url: '/package-views/pages/meal/checkout' })
  329. }
  330. </script>
  331. <style scoped lang="scss">
  332. .detail-page {
  333. height: 100vh;
  334. padding: 0;
  335. overflow: hidden;
  336. }
  337. .detail-scroll {
  338. height: calc(100vh - 148rpx - env(safe-area-inset-bottom));
  339. padding: 24rpx 24rpx 0;
  340. box-sizing: border-box;
  341. }
  342. .detail-bottom-spacer {
  343. height: 40rpx;
  344. }
  345. .swiper,
  346. .hero-img,
  347. .empty-img {
  348. width: 100%;
  349. height: 430rpx;
  350. border-radius: 28rpx;
  351. overflow: hidden;
  352. }
  353. .empty-img {
  354. display: flex;
  355. align-items: center;
  356. justify-content: center;
  357. color: #00838f;
  358. background: #e0f7fa;
  359. font-size: 42rpx;
  360. font-weight: 700;
  361. }
  362. .main-card,
  363. .info-card {
  364. margin-top: 22rpx;
  365. }
  366. .title-row,
  367. .area-row {
  368. display: flex;
  369. justify-content: space-between;
  370. gap: 20rpx;
  371. }
  372. .name {
  373. flex: 1;
  374. font-size: 38rpx;
  375. font-weight: 700;
  376. }
  377. .price {
  378. color: #ef4444;
  379. font-size: 38rpx;
  380. font-weight: 800;
  381. }
  382. .tags {
  383. margin-top: 18rpx;
  384. display: flex;
  385. gap: 10rpx;
  386. flex-wrap: wrap;
  387. }
  388. .tag {
  389. padding: 5rpx 14rpx;
  390. border-radius: 999rpx;
  391. background: #fff7ed;
  392. color: #f97316;
  393. font-size: 22rpx;
  394. }
  395. .stock,
  396. .countdown {
  397. margin-top: 18rpx;
  398. font-size: 30rpx;
  399. font-weight: 700;
  400. color: #16a34a;
  401. }
  402. .danger {
  403. color: #ef4444;
  404. }
  405. .section-title {
  406. font-size: 30rpx;
  407. font-weight: 700;
  408. margin-bottom: 16rpx;
  409. }
  410. .area-name {
  411. font-weight: 700;
  412. font-size: 30rpx;
  413. }
  414. .switch-link {
  415. color: #f97316;
  416. font-weight: 700;
  417. }
  418. .info-line {
  419. margin-top: 10rpx;
  420. color: #334155;
  421. }
  422. .specs {
  423. display: flex;
  424. flex-direction: column;
  425. gap: 14rpx;
  426. }
  427. .spec {
  428. padding: 18rpx;
  429. border-radius: 18rpx;
  430. border: 2rpx solid #e2e8f0;
  431. }
  432. .spec.disabled {
  433. opacity: 0.58;
  434. }
  435. .spec-head {
  436. display: flex;
  437. align-items: center;
  438. justify-content: space-between;
  439. gap: 16rpx;
  440. font-weight: 700;
  441. }
  442. .spec-price {
  443. color: #ef4444;
  444. }
  445. .spec.active {
  446. border-color: #00bcd4;
  447. background: #e0f7fa;
  448. }
  449. .stepper-row {
  450. display: flex;
  451. align-items: center;
  452. justify-content: space-between;
  453. gap: 20rpx;
  454. }
  455. .stepper {
  456. display: flex;
  457. align-items: center;
  458. gap: 24rpx;
  459. }
  460. .step-btn {
  461. width: 56rpx;
  462. height: 56rpx;
  463. line-height: 52rpx;
  464. padding: 0;
  465. border-radius: 50%;
  466. border: 2rpx solid #e2e8f0;
  467. background: #f8fafc;
  468. font-size: 32rpx;
  469. color: #334155;
  470. }
  471. .step-btn[disabled],
  472. .step-disabled {
  473. opacity: 0.4;
  474. }
  475. .step-num {
  476. min-width: 48rpx;
  477. text-align: center;
  478. font-size: 32rpx;
  479. font-weight: 700;
  480. }
  481. .step-tip {
  482. font-size: 24rpx;
  483. }
  484. .bottom-bar {
  485. position: fixed;
  486. left: 0;
  487. right: 0;
  488. bottom: 0;
  489. padding: 20rpx 28rpx calc(20rpx + env(safe-area-inset-bottom));
  490. background: #fff;
  491. box-shadow: 0 -8rpx 30rpx rgba(15, 23, 42, 0.08);
  492. }
  493. .buy-btn {
  494. height: 88rpx;
  495. line-height: 88rpx;
  496. border-radius: 999rpx;
  497. background: #00bcd4;
  498. color: #fff;
  499. font-weight: 700;
  500. }
  501. .buy-btn.disabled {
  502. background: #cbd5e1;
  503. }
  504. </style>