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

866 lines
22 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<template>
<div class="mobile-container">
<header class="header">
<div class="user-info" @click="handleUserClick">
<a-avatar
:size="44"
:src="userInfo?.avatar || DEFAULT_AVATAR"
/>
<div class="welcome">
<p class="greeting">{{ greeting }}</p>
<p class="username">{{ displayName }}</p>
</div>
</div>
<a-button class="header-action" type="primary" ghost @click="handleUserClick">
{{ isLoggedIn ? '个人中心' : '去登录' }}
</a-button>
</header>
<div class="search-section">
<a-input-search
v-model:value="searchQuery"
size="large"
placeholder="搜索作品、风格或门店"
enter-button="搜索"
@search="handleSearch"
/>
</div>
<div v-if="announcements.length" class="announcement-bar">
<div class="announcement-track">
<button
v-for="item in announcementLoop"
:key="`${item.id}-${item.loopKey}`"
class="announcement-item"
type="button"
@click="openAnnouncementDetail(item)"
>
<b>{{ item.publisherName || '平台' }}</b>:{{ item.content }}
</button>
</div>
</div>
<a-modal
v-model:open="announcementDetailOpen"
title="公告详情"
:footer="null"
centered
>
<div v-if="selectedAnnouncement" class="announcement-detail">
<div class="announcement-detail__meta">
<span>{{ selectedAnnouncement.publisherName || '平台' }}</span>
<span>{{ formatAnnouncementTime(selectedAnnouncement.publishTime) }}</span>
</div>
<p>{{ selectedAnnouncement.content }}</p>
</div>
</a-modal>
<a-alert
v-if="!isLoggedIn"
class="guest-alert"
type="info"
show-icon
message="当前为游客模式"
description="先逛作品和门店,收藏、加购、下单时再登录即可。"
/>
<section v-if="!isLoggedIn" class="section">
<div class="banner-container">
<div class="banner-carousel">
<a-carousel v-if="bannerImages.length" autoplay :autoplay-speed="3200" effect="fade">
<div
v-for="banner in bannerImages"
:key="banner.id"
class="banner-slide"
@click="openShopById(banner.shopId)"
>
<img :src="banner.url" :alt="banner.shopName" class="banner-img" />
<div class="banner-copy">
<a-tag color="blue">门店推荐</a-tag>
<h3>{{ banner.shopName }}</h3>
<p>{{ banner.businessHours || '欢迎到店体验' }}</p>
</div>
</div>
</a-carousel>
<div v-else class="banner-empty">
<h3>发现适合你的美甲风格</h3>
<p>先看看门店 Banner 和精选作品,再决定今天预约谁。</p>
<a-button type="primary" @click="router.push('/products')">浏览作品</a-button>
</div>
</div>
</div>
</section>
<section class="section">
<div class="section-header">
<h3>精选作品</h3>
<a class="see-all" @click="handleSeeAll('featured')">查看全部</a>
</div>
<div class="horizontal-scroll">
<a-card
v-for="item in featuredItems"
:key="item.id"
class="product-card"
:body-style="{ padding: '12px' }"
hoverable
@click="handleProductClick(item)"
>
<div class="product-img" :style="{ backgroundColor: item.bgColor }">
<img v-if="item.coverUrl" :src="item.coverUrl" :alt="item.name" class="product-cover" />
<span v-else>{{ item.name[0] }}</span>
</div>
<div class="product-info">
<p class="name">{{ item.name }}</p>
<p v-if="item.shopName" class="meta">所属店铺:{{ item.shopName }}</p>
<p class="meta">{{ item.meta }}</p>
<p class="price">¥{{ item.price }}</p>
</div>
</a-card>
</div>
</section>
<section class="section popular-section">
<div class="section-header">
<h3>热门作品</h3>
<a class="see-all" @click="handleSeeAll('popular')">查看全部</a>
</div>
<div class="product-grid">
<a-card
v-for="item in popularItems"
:key="item.id"
class="product-card grid-item"
:body-style="{ padding: '12px' }"
hoverable
@click="handleProductClick(item)"
>
<div class="product-img" :style="{ backgroundColor: item.bgColor }">
<img v-if="item.coverUrl" :src="item.coverUrl" :alt="item.name" class="product-cover" />
<span v-else>{{ item.name[0] }}</span>
</div>
<div class="product-info">
<p class="name">{{ item.name }}</p>
<p v-if="item.shopName" class="meta">所属店铺:{{ item.shopName }}</p>
<p class="meta">{{ item.meta }}</p>
<p class="price">¥{{ item.price }}</p>
</div>
</a-card>
</div>
<div v-if="loading" class="loading-more">
<a-spin size="small" />
<span>加载中...</span>
</div>
<div v-else-if="!hasMore && popularItems.length > 0" class="no-more">
没有更多热门推荐了
</div>
<div v-else-if="popularItems.length === 0 && !loading" class="no-products">
暂无热门作品
</div>
</section>
</div>
</template>
<script setup lang="ts">
/**
* HomeView page script.
* Call guide: the template binds the reactive state below, and the methods are triggered by button clicks, lifecycle hooks, or router events.
*/
import { computed, onMounted, onUnmounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { userApi, type AnnouncementVO, type UserVO } from '../api/user'
import { productApi, type ProductVO } from '../api/product'
import { shopApi, type ShopVO } from '../api/shop'
import { fileApi } from '../api/file'
import { DEFAULT_AVATAR, DEFAULT_PRODUCT_IMAGE } from '@/constants'
import type { IdType } from '@/utils/id'
interface BannerImage {
id: string
shopId: IdType
shopName: string
businessHours?: string
url: string
}
interface ProductCardItem {
id: IdType
name: string
price: string
meta: string
shopName?: string
coverUrl: string
bgColor: string
}
const router = useRouter()
const userInfo = ref<UserVO | null>(null)
const publicShops = ref<ShopVO[]>([])
const bannerImages = ref<BannerImage[]>([])
const featuredItems = ref<ProductCardItem[]>([])
const popularSource = ref<ProductCardItem[]>([])
const popularItems = ref<ProductCardItem[]>([])
const announcements = ref<AnnouncementVO[]>([])
const selectedAnnouncement = ref<AnnouncementVO | null>(null)
const announcementDetailOpen = ref(false)
const productImageCache = ref<Record<string, string>>({})
/** searchQuery is a reactive state variable used by the template and event handlers. */
const searchQuery = ref('')
/** loading is a reactive state variable used by the template and event handlers. */
const loading = ref(false)
/** hasMore is a reactive state variable used by the template and event handlers. */
const hasMore = ref(true)
/** page is a reactive state variable used by the template and event handlers. */
const page = ref(1)
const pageSize = 8
/** isLoggedIn is a reactive state variable used by the template and event handlers. */
const isLoggedIn = computed(() => Boolean(localStorage.getItem('accessToken') || sessionStorage.getItem('accessToken')))
/** greeting is a reactive state variable used by the template and event handlers. */
const greeting = computed(() => (isLoggedIn.value ? '欢迎回来' : '游客模式'))
/** displayName is a reactive state variable used by the template and event handlers. */
const displayName = computed(() => userInfo.value?.nickname || (isLoggedIn.value ? '用户' : '先看看门店和作品'))
/** announcementLoop is a reactive state variable used by the template and event handlers. */
const announcementLoop = computed(() => [...announcements.value, ...announcements.value].map((item, index) => ({ ...item, loopKey: index })))
const openAnnouncementDetail = (item: AnnouncementVO) => {
selectedAnnouncement.value = item
announcementDetailOpen.value = true
}
const formatAnnouncementTime = (value?: string) => {
if (!value) return ''
return value.replace('T', ' ').slice(0, 16)
}
/** getRandomColor is a local helper used by this page script. */
const getRandomColor = (): string => {
const colors = ['var(--theme-primary-soft)', 'var(--secondary-bg-color)', 'var(--theme-page-bg)']
return colors[Math.floor(Math.random() * colors.length)] ?? 'var(--theme-primary-soft)'
}
/** getProductCoverUrl is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const getProductCoverUrl = async (product: ProductVO): Promise<string> => {
const firstImageId = product.imageFileIds?.split(',').map(id => id.trim()).find(Boolean)
if (!firstImageId) {
return DEFAULT_PRODUCT_IMAGE
}
if (!productImageCache.value[firstImageId]) {
try {
productImageCache.value[firstImageId] = await fileApi.getSignedUrl(firstImageId) as unknown as string
} catch (error) {
console.error('获取首页作品封面失败:', error)
productImageCache.value[firstImageId] = DEFAULT_PRODUCT_IMAGE
}
}
return productImageCache.value[firstImageId] || DEFAULT_PRODUCT_IMAGE
}
/** formatProductCards is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const formatProductCards = async (products: ProductVO[]): Promise<ProductCardItem[]> =>
Promise.all(products.map(async item => ({
id: item.id,
name: item.title || item.name || '未命名作品',
price: Number(item.price || 0).toFixed(2),
meta: item.approximateDuration || item.shopName || '支持预约',
shopName: item.shopName,
coverUrl: await getProductCoverUrl(item),
bgColor: getRandomColor()
})))
/** appendPopularItems is a local helper used by this page script. */
const appendPopularItems = (loadMore = false) => {
const nextItems = popularSource.value.slice(0, page.value * pageSize)
popularItems.value = nextItems
hasMore.value = nextItems.length < popularSource.value.length
if (!loadMore && nextItems.length === 0) {
hasMore.value = false
}
}
/** loadUserInfo is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const loadUserInfo = async () => {
if (!isLoggedIn.value) {
userInfo.value = null
return
}
try {
const response = await userApi.getUserInfo()
userInfo.value = response || null
} catch (error) {
console.error('获取用户信息失败:', error)
userInfo.value = null
}
}
/** loadPublicShops is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const loadPublicShops = async () => {
try {
const shops = await shopApi.getPublicShops()
publicShops.value = Array.isArray(shops) ? shops : []
await loadBannerImages()
} catch (error) {
console.error('获取门店列表失败:', error)
publicShops.value = []
bannerImages.value = []
}
}
/** loadBannerImages is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const loadBannerImages = async () => {
const banners: BannerImage[] = []
for (const shop of publicShops.value) {
const coverIds = (shop.coverImageFileId || shop.imageFileIds || '')
.split(',')
.map(id => id.trim())
.filter(Boolean)
for (const id of coverIds) {
try {
const url = await fileApi.getSignedUrl(id) as unknown as string
if (url) {
banners.push({
id: `${shop.id}-${id}`,
shopId: shop.id,
shopName: shop.shopName,
businessHours: shop.businessHours,
url
})
}
} catch (error) {
console.error('获取门店轮播图失败:', error)
}
}
}
bannerImages.value = banners.slice(0, 8)
}
/** loadFeaturedProducts is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const loadFeaturedProducts = async () => {
try {
let products = await productApi.getProductsByTag('精选')
if (!Array.isArray(products) || products.length === 0) {
products = await productApi.getAllProducts()
}
featuredItems.value = await formatProductCards((products || []).slice(0, 6))
} catch (error) {
console.error('获取精选作品失败:', error)
featuredItems.value = []
}
}
/** loadPopularProducts is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const loadPopularProducts = async () => {
loading.value = true
try {
let products = await productApi.getProductsByTag('热门')
if (!Array.isArray(products) || products.length === 0) {
products = await productApi.getAllProducts()
}
popularSource.value = await formatProductCards(products || [])
page.value = 1
appendPopularItems()
} catch (error) {
console.error('获取热门作品失败:', error)
popularSource.value = []
popularItems.value = []
hasMore.value = false
} finally {
loading.value = false
}
}
/** loadAnnouncements is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const loadAnnouncements = async () => {
if (!isLoggedIn.value) {
announcements.value = []
return
}
try {
announcements.value = (await userApi.listMyAnnouncements()) || []
} catch (error) {
console.error('加载公告失败:', error)
announcements.value = []
}
}
/** handleScroll is a local helper used by this page script. */
const handleScroll = () => {
if (loading.value || !hasMore.value) {
return
}
const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
const scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight
const clientHeight = document.documentElement.clientHeight
if (scrollTop + clientHeight >= scrollHeight - 120) {
page.value += 1
appendPopularItems(true)
}
}
/** handleUserClick is a local helper used by this page script. */
const handleUserClick = () => {
if (isLoggedIn.value) {
router.push('/profile')
return
}
message.info('登录后可查看个人中心、收藏和订单')
router.push('/')
}
/** handleSearch is a local helper used by this page script. */
const handleSearch = () => {
const keyword = searchQuery.value.trim()
router.push(keyword ? { path: '/products', query: { keyword } } : '/products')
}
/** handleSeeAll is a local helper used by this page script. */
const handleSeeAll = (type: 'featured' | 'popular') => {
router.push({
path: '/products',
query: type === 'featured' ? { tag: '精选' } : { tag: '热门' }
})
}
/** handleProductClick is a local helper used by this page script. */
const handleProductClick = (item: ProductCardItem) => {
router.push(`/product/${item.id}`)
}
/** openShopById is a local helper used by this page script. */
const openShopById = (shopId: IdType) => {
router.push(`/shop/${shopId}`)
}
onMounted(async () => {
const homeTasks = [
loadUserInfo(),
loadAnnouncements(),
loadFeaturedProducts(),
loadPopularProducts()
]
if (!isLoggedIn.value) {
homeTasks.push(loadPublicShops())
}
await Promise.all(homeTasks)
window.addEventListener('scroll', handleScroll)
})
onUnmounted(() => {
window.removeEventListener('scroll', handleScroll)
})
</script>
<style scoped>
.mobile-container {
background:
linear-gradient(rgba(255, 255, 255, 0.68), rgba(255, 255, 255, 0.92)),
var(--theme-background-image),
var(--theme-page-bg);
background-size: cover, cover, auto;
background-position: center top;
}
.header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 16px 20px 8px;
}
.user-info {
display: flex;
align-items: center;
gap: 12px;
cursor: pointer;
}
.greeting {
font-size: 12px;
color: #8b8b9a;
margin: 0 0 2px;
}
.username {
font-size: 16px;
font-weight: 700;
margin: 0;
color: #1f1f1f;
}
.header-action {
border-radius: 999px;
}
.search-section {
padding: 8px 20px 0;
}
.announcement-bar {
margin: 12px 20px 0;
overflow: hidden;
border-radius: 8px;
background: var(--theme-primary-soft);
border: 1px solid var(--theme-border);
}
.announcement-track {
display: flex;
width: max-content;
gap: 32px;
padding: 9px 14px;
color: var(--theme-primary);
animation: announcement-scroll 22s linear infinite;
}
.announcement-item {
border: 0;
padding: 0;
background: transparent;
color: inherit;
cursor: pointer;
white-space: nowrap;
}
.announcement-item:hover {
color: var(--theme-accent);
}
.announcement-detail {
display: grid;
gap: 14px;
}
.announcement-detail__meta {
display: flex;
justify-content: space-between;
gap: 12px;
color: #8b8b9a;
font-size: 13px;
}
.announcement-detail p {
margin: 0;
color: #1f1f1f;
line-height: 1.8;
white-space: pre-wrap;
}
@keyframes announcement-scroll {
from { transform: translateX(0); }
to { transform: translateX(-50%); }
}
.guest-alert {
margin: 16px 20px 0;
border-radius: 16px;
}
.banner-container {
padding: 0 20px;
}
.banner-carousel {
width: 100%;
border-radius: 18px;
overflow: hidden;
min-height: 220px;
box-shadow: 0 12px 30px rgba(15, 23, 42, 0.12);
background: var(--theme-gradient-soft);
}
.banner-slide {
position: relative;
width: 100%;
aspect-ratio: 16 / 9;
cursor: pointer;
}
.banner-img {
width: 100%;
height: 100%;
object-fit: cover;
}
.banner-copy {
position: absolute;
left: 24px;
bottom: 24px;
padding: 16px 18px;
border-radius: 16px;
background: rgba(255, 255, 255, 0.92);
backdrop-filter: blur(6px);
box-shadow: 0 8px 20px rgba(0, 0, 0, 0.08);
}
.banner-copy h3 {
margin: 10px 0 4px;
font-size: 22px;
color: #1f1f1f;
}
.banner-copy p {
margin: 0;
color: #666;
}
.banner-empty {
min-height: 220px;
display: flex;
flex-direction: column;
align-items: flex-start;
justify-content: center;
gap: 12px;
padding: 28px;
}
.banner-empty h3 {
margin: 0;
font-size: 26px;
color: #1f1f1f;
}
.banner-empty p {
margin: 0;
max-width: 360px;
color: #666;
line-height: 1.7;
}
.section {
padding: 24px 0 0;
}
.section-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 0 20px 14px;
}
.section-header h3 {
margin: 0;
font-size: 18px;
font-weight: 700;
}
.see-all {
color: var(--theme-primary);
font-size: 13px;
}
.horizontal-scroll {
display: flex;
gap: 14px;
overflow-x: auto;
padding: 0 20px;
scrollbar-width: none;
}
.horizontal-scroll::-webkit-scrollbar {
display: none;
}
.product-card {
border-radius: 18px;
}
.horizontal-scroll .product-card {
flex: 0 0 calc((100% - 14px) / 2);
width: calc((100% - 14px) / 2);
max-width: calc((100% - 14px) / 2);
}
.product-card :deep(.ant-card-body) {
padding: 12px;
}
.product-img {
width: 100%;
aspect-ratio: 1;
border-radius: 14px;
overflow: hidden;
display: flex;
align-items: center;
justify-content: center;
margin-bottom: 10px;
font-size: 40px;
font-weight: 700;
color: rgba(0, 0, 0, 0.15);
}
.product-cover {
width: 100%;
height: 100%;
object-fit: cover;
}
.name {
margin: 0 0 4px;
font-size: 14px;
font-weight: 600;
color: #1f1f1f;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.meta {
margin: 0 0 6px;
font-size: 12px;
color: #8b8b9a;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.price {
margin: 0;
font-size: 16px;
font-weight: 700;
color: #ff4d4f;
}
.product-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 14px;
padding: 0 20px;
}
.grid-item {
width: 100%;
}
.loading-more,
.no-more,
.no-products {
display: flex;
justify-content: center;
align-items: center;
gap: 8px;
padding: 24px 0 36px;
color: #8b8b9a;
}
@media (max-width: 420px) {
.header {
gap: 12px;
padding: 14px 16px 8px;
flex-wrap: wrap;
}
.user-info {
min-width: 0;
flex: 1 1 auto;
}
.welcome {
min-width: 0;
}
.greeting,
.username {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.header-action {
flex: 0 0 auto;
}
.search-section {
padding: 8px 16px 0;
}
.guest-alert {
margin: 14px 16px 0;
}
.banner-container,
.horizontal-scroll,
.product-grid {
padding-left: 16px;
padding-right: 16px;
}
.section-header {
padding: 0 16px 12px;
}
.banner-empty {
padding: 22px 18px;
}
.banner-empty h3 {
font-size: 22px;
line-height: 1.35;
}
.banner-empty p {
max-width: none;
font-size: 13px;
line-height: 1.6;
}
.banner-copy {
left: 16px;
right: 16px;
bottom: 16px;
padding: 12px 14px;
}
.banner-copy h3 {
font-size: 18px;
}
.banner-copy p {
font-size: 13px;
}
}
@media (min-width: 992px) {
.header,
.search-section,
.section,
.guest-alert {
max-width: var(--frontend-content-max-width);
margin-left: auto;
margin-right: auto;
}
.banner-container {
padding: 0 24px;
}
.banner-carousel {
max-width: var(--frontend-content-max-width);
}
.horizontal-scroll {
overflow: visible;
flex-wrap: wrap;
}
.horizontal-scroll .product-card {
flex: 0 0 calc(25% - 12px);
width: calc(25% - 12px);
max-width: calc(25% - 12px);
min-width: 180px;
}
.product-grid {
grid-template-columns: repeat(4, minmax(0, 1fr));
}
.product-grid .product-card {
width: 100%;
max-width: none;
min-width: 0;
}
}
</style>