Files
JayuCloud/YumiNail-Frontend/src/views/ProductDetailView.vue
T

353 lines
15 KiB
Vue

<template>
<div class="detail-page">
<header class="detail-header">
<a-button type="text" @click="router.back()"><LeftOutlined /></a-button>
<h1>{{ productTitle }}</h1>
<a-button type="text" @click="handleFavoriteClick">
<component :is="isFavorite ? StarFilled : StarOutlined" :class="{ active: isFavorite }" />
</a-button>
</header>
<main class="detail-content">
<a-result v-if="loadError" status="warning" title="暂时无法查看作品详情" :sub-title="loadError">
<template #extra>
<a-button type="primary" @click="router.back()">返回上一页</a-button>
</template>
</a-result>
<template v-else>
<section class="media-section">
<img :src="productImages[0] || DEFAULT_PRODUCT_IMAGE" :alt="productTitle" />
</section>
<section class="info-section">
<div class="title-row">
<div>
<h2>{{ productTitle }}</h2>
<p class="price">¥{{ Number(product.price || 0).toFixed(2) }}</p>
</div>
<a-tag color="blue">{{ product.approximateDuration || '以门店确认为准' }}</a-tag>
</div>
<div class="metrics">
<button type="button" @click="openShopDetail" :disabled="!shopInfo?.id">
<ShopOutlined />
<span>门店</span>
<strong>{{ shopInfo?.shopName || '暂未绑定门店' }}</strong>
</button>
<div>
<TeamOutlined />
<span>可约美甲师</span>
<strong>{{ artistCountText }}</strong>
</div>
<div>
<CalendarOutlined />
<span>可约时间</span>
<strong>{{ earliestBookableText }}</strong>
</div>
</div>
<div v-if="shopInfo" class="shop-panel" @click="openShopDetail">
<strong>{{ shopInfo.shopName }}</strong>
<span>{{ shopInfo.address || '门店地址待完善' }}</span>
<span>{{ shopInfo.businessHours || '营业时间待完善' }}</span>
</div>
<div class="actions-row">
<button type="button" :class="{ active: isLiked }" @click="handleLikeClick">
<component :is="isLiked ? HeartFilled : HeartOutlined" />
{{ product.likeCount || 0 }} 点赞
</button>
<button type="button" :class="{ active: isFavorite }" @click="handleFavoriteClick">
<component :is="isFavorite ? StarFilled : StarOutlined" />
{{ product.collectCount || 0 }} 收藏
</button>
</div>
<div class="tags">
<a-tag v-for="tag in product.tagInfos || []" :key="tag.id">{{ tag.tagName }}</a-tag>
<a-tag v-if="!product.tagInfos?.length">暂无标签</a-tag>
</div>
<div class="description">
<h3>款式说明</h3>
<p>{{ product.description || '店家暂未补充作品说明。' }}</p>
</div>
</section>
<section class="comment-section">
<div class="section-head">
<h3>作品评论</h3>
<span>{{ comments.length }} 条</span>
</div>
<div class="comment-editor">
<a-textarea v-model:value="commentText" :maxlength="300" :rows="3" :placeholder="replyTarget ? `回复 ${replyTarget.userNickname || '用户'}` : '说说你的看法'" />
<div class="comment-tools">
<a-button v-if="replyTarget" type="text" @click="replyTarget = null">取消回复</a-button>
<a-button type="primary" :loading="submittingComment" @click="submitComment">发布</a-button>
</div>
</div>
<a-empty v-if="!comments.length" description="还没有评论,来写第一条吧" />
<div v-for="comment in comments" :key="comment.id" class="comment-item">
<div class="comment-main">
<strong>{{ comment.userNickname || '用户' }}</strong>
<span>{{ formatTime(comment.createTime) }}</span>
</div>
<p>{{ comment.commentContent }}</p>
<button type="button" @click="replyTarget = comment">回复</button>
<div v-if="comment.replies?.length" class="reply-list">
<div v-for="reply in comment.replies" :key="reply.id" class="reply-item">
<strong>{{ reply.userNickname || '用户' }}</strong>
<span>{{ reply.commentContent }}</span>
</div>
</div>
</div>
</section>
</template>
</main>
<footer v-if="!loadError" class="detail-footer">
<a-button size="large" @click="handleAddToCart"><ShoppingCartOutlined />加入购物车</a-button>
<a-button type="primary" size="large" @click="handleBuyNow"><ThunderboltOutlined />立即预约</a-button>
</footer>
</div>
</template>
<script setup lang="ts">
import { computed, inject, onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
CalendarOutlined,
HeartFilled,
HeartOutlined,
LeftOutlined,
ShoppingCartOutlined,
ShopOutlined,
StarFilled,
StarOutlined,
TeamOutlined,
ThunderboltOutlined
} from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { cartApi } from '@/api/cart'
import { commentApi, type CommentVO } from '@/api/comment'
import { fileApi } from '@/api/file'
import { productApi, type ProductVO } from '@/api/product'
import { productLikeApi } from '@/api/productLike'
import { shopApi, type ShopVO } from '@/api/shop'
import { wishlistApi } from '@/api/wishlist'
import { DEFAULT_PRODUCT_IMAGE } from '@/constants'
import type { IdType } from '@/utils/id'
import { toOptionalIdString } from '@/utils/id'
import { runWithGlobalLoading } from '@/utils/action-loading'
const route = useRoute()
const router = useRouter()
const updateCartCount = inject<() => Promise<void>>('updateCartCount', async () => {})
const product = ref<ProductVO>({} as ProductVO)
const shopInfo = ref<ShopVO | null>(null)
const productImages = ref<string[]>([])
const imageIdCache = ref<Record<string, string>>({})
const comments = ref<CommentVO[]>([])
const commentText = ref('')
const replyTarget = ref<CommentVO | null>(null)
const submittingComment = ref(false)
const isFavorite = ref(false)
const isLiked = ref(false)
const loadError = ref('')
const isLoggedIn = computed(() => Boolean(localStorage.getItem('accessToken') || sessionStorage.getItem('accessToken')))
const productTitle = computed(() => product.value.title || product.value.name || '作品详情')
const artistCount = computed(() => {
if (typeof product.value.availableBookableArtistCount === 'number') return product.value.availableBookableArtistCount
return String(product.value.bookableArtists || '').split(',').map(id => id.trim()).filter(Boolean).length
})
const artistCountText = computed(() => artistCount.value > 0 ? `${artistCount.value} 位` : (product.value.bookableArtistRestricted ? '暂无可约' : '门店安排'))
const earliestBookableText = computed(() => shopInfo.value?.businessHours || '以门店安排为准')
const requireLogin = (actionText: string) => {
if (isLoggedIn.value) return true
message.info(`${actionText}前请先登录`)
router.push('/')
return false
}
const loadProductImages = async () => {
const fileIds = product.value.imageFileIds?.split(',').map(id => id.trim()).filter(Boolean) || []
if (!fileIds.length) {
productImages.value = [DEFAULT_PRODUCT_IMAGE]
return
}
const urls: string[] = []
for (const id of fileIds) {
try {
if (!imageIdCache.value[id]) imageIdCache.value[id] = await fileApi.getSignedUrl(id) as unknown as string
if (imageIdCache.value[id]) urls.push(imageIdCache.value[id])
} catch {}
}
productImages.value = urls.length ? urls : [DEFAULT_PRODUCT_IMAGE]
}
const loadShopInfo = async (shopId?: IdType | null) => {
shopInfo.value = shopId ? await shopApi.getShopById(shopId).catch(() => null) : null
}
const loadComments = async () => {
if (!product.value.id) return
comments.value = await commentApi.listByProduct(product.value.id).catch(() => [])
}
const checkInteractionStatus = async () => {
if (!isLoggedIn.value || !product.value.id) {
isFavorite.value = false
isLiked.value = false
return
}
const [favorite, liked] = await Promise.all([
wishlistApi.checkWishlist(product.value.id).catch(() => false),
productLikeApi.checkLikeStatus(product.value.id).catch(() => false)
])
isFavorite.value = Boolean(favorite)
isLiked.value = Boolean(liked)
}
const fetchProductDetail = async () => {
loadError.value = ''
try {
const productId = toOptionalIdString(route.params.id)
if (!productId) throw new Error('作品不存在')
const response = await productApi.getProductById(productId)
if (!response?.id) throw new Error('作品不存在或已下架')
product.value = response
await Promise.all([loadProductImages(), loadShopInfo(response.shopId), checkInteractionStatus(), loadComments()])
} catch (error: any) {
loadError.value = error?.message || '网络异常,请稍后再试'
}
}
const openShopDetail = () => {
if (shopInfo.value?.id) router.push(`/shop/${shopInfo.value.id}`)
}
const handleFavoriteClick = async () => {
if (!product.value.id || !requireLogin('收藏作品')) return
await runWithGlobalLoading(async () => {
if (isFavorite.value) {
await wishlistApi.removeFromWishlist(product.value.id)
product.value.collectCount = Math.max(0, Number(product.value.collectCount || 0) - 1)
message.success('已取消收藏')
} else {
await wishlistApi.addToWishlist(product.value.id)
product.value.collectCount = Number(product.value.collectCount || 0) + 1
message.success('已加入收藏')
}
isFavorite.value = !isFavorite.value
}).catch((error: any) => message.error(error?.message || '收藏操作失败'))
}
const handleLikeClick = async () => {
if (!product.value.id || !requireLogin('点赞作品')) return
await runWithGlobalLoading(async () => {
if (isLiked.value) {
await productLikeApi.unlikeProduct(product.value.id)
product.value.likeCount = Math.max(0, Number(product.value.likeCount || 0) - 1)
message.success('已取消点赞')
} else {
await productLikeApi.likeProduct(product.value.id)
product.value.likeCount = Number(product.value.likeCount || 0) + 1
message.success('已点赞')
}
isLiked.value = !isLiked.value
}).catch((error: any) => message.error(error?.message || '点赞操作失败'))
}
const handleAddToCart = async () => {
if (!product.value.id || !requireLogin('加入购物车')) return
await runWithGlobalLoading(() => cartApi.addToCart({ productId: product.value.id, quantity: 1 }))
await updateCartCount()
message.success('已加入购物车')
}
const handleBuyNow = async () => {
if (!product.value.id || !requireLogin('预约下单')) return
await handleAddToCart()
router.push('/cart')
}
const submitComment = async () => {
if (!product.value.id || !requireLogin('发表评论')) return
const content = commentText.value.trim()
if (!content) return message.warning('请输入评论内容')
submittingComment.value = true
try {
await commentApi.create({
productId: product.value.id,
shopId: product.value.shopId,
parentCommentId: replyTarget.value?.id,
commentContent: content
})
commentText.value = ''
replyTarget.value = null
await loadComments()
message.success('评论已发布')
} catch (error: any) {
message.error(error?.message || '评论发布失败')
} finally {
submittingComment.value = false
}
}
const formatTime = (value?: string) => value ? value.replace('T', ' ').slice(0, 16) : ''
onMounted(() => {
void fetchProductDetail()
})
</script>
<style scoped>
.detail-page { min-height: 100vh; background: #f6f7f9; }
.detail-header { position: sticky; top: 0; z-index: 20; display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 12px 16px; background: rgba(255,255,255,.96); border-bottom: 1px solid #eceff3; backdrop-filter: blur(10px); }
.detail-header h1 { flex: 1; margin: 0; font-size: 17px; text-align: center; color: #20232a; }
.detail-header .active { color: #e65d7a; }
.detail-content { max-width: 1040px; margin: 0 auto; padding: 18px 16px 118px; }
.media-section { overflow: hidden; border-radius: 8px; background: #fff; }
.media-section img { display: block; width: 100%; aspect-ratio: 16 / 10; object-fit: cover; }
.info-section, .comment-section { margin-top: 14px; padding: 22px; border-radius: 8px; background: #fff; border: 1px solid #edf0f4; }
.title-row { display: flex; justify-content: space-between; gap: 16px; }
.title-row h2 { margin: 0 0 8px; font-size: 24px; color: #20232a; }
.price { margin: 0; font-size: 26px; font-weight: 700; color: #d94f69; }
.metrics { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 10px; margin-top: 18px; }
.metrics > div, .metrics > button { display: grid; gap: 4px; padding: 14px; border: 1px solid #edf0f4; border-radius: 8px; background: #fbfcfe; text-align: left; }
.metrics svg { color: #3b82f6; }
.metrics span { font-size: 12px; color: #7b8494; }
.metrics strong { color: #20232a; }
.shop-panel { display: grid; gap: 6px; margin-top: 18px; padding: 16px; border-radius: 8px; background: #f7f9fc; cursor: pointer; color: #5f6876; }
.shop-panel strong { color: #20232a; }
.actions-row { display: flex; flex-wrap: wrap; gap: 10px; margin-top: 18px; }
.actions-row button { display: inline-flex; align-items: center; gap: 8px; padding: 9px 14px; border: 1px solid #edf0f4; border-radius: 999px; background: #fff; color: #5f6876; }
.actions-row button.active { color: #d94f69; border-color: #ffd7e0; background: #fff5f7; }
.tags { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 18px; }
.description { margin-top: 22px; }
.description h3, .section-head h3 { margin: 0; font-size: 18px; color: #20232a; }
.description p { margin: 10px 0 0; color: #5f6876; line-height: 1.8; }
.section-head { display: flex; align-items: center; justify-content: space-between; margin-bottom: 16px; }
.section-head span { color: #7b8494; }
.comment-editor { padding: 14px; border: 1px solid #edf0f4; border-radius: 8px; background: #fbfcfe; }
.comment-tools { display: flex; justify-content: flex-end; gap: 8px; margin-top: 10px; }
.comment-item { padding: 16px 0; border-bottom: 1px solid #edf0f4; }
.comment-item:last-child { border-bottom: 0; }
.comment-main { display: flex; justify-content: space-between; gap: 12px; color: #7b8494; }
.comment-main strong { color: #20232a; }
.comment-item p { margin: 8px 0; color: #3b4350; line-height: 1.7; }
.comment-item button { padding: 0; border: 0; background: transparent; color: #3b82f6; cursor: pointer; }
.reply-list { margin-top: 10px; padding: 10px 12px; border-radius: 8px; background: #f7f9fc; }
.reply-item { display: flex; gap: 8px; padding: 6px 0; color: #5f6876; }
.reply-item strong { color: #20232a; }
.detail-footer { position: fixed; left: 0; right: 0; bottom: 0; z-index: 30; display: flex; gap: 12px; padding: 14px 16px calc(14px + env(safe-area-inset-bottom)); background: rgba(255,255,255,.96); border-top: 1px solid #eceff3; backdrop-filter: blur(10px); }
.detail-footer :deep(.ant-btn) { flex: 1; height: 46px; border-radius: 999px; font-weight: 700; }
@media (max-width: 720px) { .metrics { grid-template-columns: 1fr; } .title-row { flex-direction: column; } }
</style>