功能:新增微信小程序界面

This commit is contained in:
xiaowang
2026-04-01 15:18:35 +08:00
parent bb2d8c4410
commit 7fa67d0511
92 changed files with 7463 additions and 0 deletions
+562
View File
@@ -0,0 +1,562 @@
const authApi = require('../../api/auth')
const shopApi = require('../../api/shop')
const userApi = require('../../api/user')
const navigation = require('../../utils/navigation')
const { runWithLoading } = require('../../utils/loading')
const phoneRegex = /^1[3-9]\d{9}$/
Page({
data: {
redirect: '',
activeTab: 'login',
loginType: 'password',
loading: false,
shops: [],
registerShopIndex: -1,
registerShopDisplayName: '',
loginShops: [],
loginShopIndex: -1,
loginShopDisplayName: '',
allowLoginShopless: false,
loginShopMessage: '',
loginAccountStatusText: '',
loginAccountStatusType: '',
registerAccountStatusText: '',
registerAccountStatusType: '',
registerPhoneStatusText: '',
registerPhoneStatusType: '',
countdown: 0,
forgotCountdown: 0,
showResetPanel: false,
form: {
account: '',
password: '',
confirmPassword: '',
nickname: '',
phone: '',
verificationCode: '',
shopId: '',
rememberMe: true
},
resetForm: {
phone: '',
verificationCode: '',
newPassword: ''
}
},
onLoad(options) {
this.setData({
redirect: options && options.redirect ? options.redirect : ''
})
this.loadShopOptions()
},
async loadShopOptions() {
try {
const shops = await shopApi.getShopsSimple()
this.setData({
shops: Array.isArray(shops) ? shops : []
})
} catch (error) {
wx.showToast({
title: '门店列表加载失败',
icon: 'none'
})
}
},
handleTabChange(event) {
const tab = event.currentTarget.dataset.tab
this.setData({
activeTab: tab,
showResetPanel: false,
loginAccountStatusText: '',
loginAccountStatusType: '',
registerAccountStatusText: '',
registerAccountStatusType: '',
registerPhoneStatusText: '',
registerPhoneStatusType: ''
})
},
handleLoginTypeChange(event) {
const type = event.currentTarget.dataset.type
this.setData({
loginType: type,
loginShops: [],
loginShopIndex: -1,
loginShopDisplayName: '',
allowLoginShopless: false,
loginShopMessage: '',
loginAccountStatusText: '',
loginAccountStatusType: '',
'form.shopId': ''
})
},
handleToggleResetPanel() {
this.setData({
showResetPanel: !this.data.showResetPanel
})
},
handleInputChange(event) {
const field = event.currentTarget.dataset.field
this.setData({
[`form.${field}`]: event.detail.value
})
},
handleResetInputChange(event) {
const field = event.currentTarget.dataset.field
this.setData({
[`resetForm.${field}`]: event.detail.value
})
},
handleRegisterShopChange(event) {
const index = Number(event.detail.value)
const shop = this.data.shops[index]
this.setData({
registerShopIndex: index,
registerShopDisplayName: shop ? shop.shopName || shop.name || '' : '',
'form.shopId': shop ? shop.id : ''
})
},
handleLoginShopChange(event) {
const index = Number(event.detail.value)
const shop = this.data.loginShops[index]
this.setData({
loginShopIndex: index,
loginShopDisplayName: shop ? shop.shopName || '' : '',
'form.shopId': shop ? shop.id : ''
})
},
async handleAccountBlur() {
const account = this.data.form.account.trim()
if (!account) {
return
}
if (this.data.activeTab === 'register') {
await this.checkRegisterAccountAvailability()
return
}
if (this.data.loginType !== 'password') {
return
}
await Promise.all([
this.checkLoginAccountAvailability(),
this.loadLoginShopsByAccount()
])
},
async handlePhoneBlur() {
const phone = this.data.form.phone.trim()
if (!phone) {
return
}
if (this.data.activeTab === 'register') {
if (phoneRegex.test(phone)) {
await this.checkRegisterPhoneAvailability()
}
return
}
if (this.data.loginType !== 'phone' || !phoneRegex.test(phone)) {
return
}
await this.loadLoginShopsByPhone()
},
applyLoginShopSelection(selection) {
const shops = Array.isArray(selection && selection.shops) ? selection.shops : []
const allowLoginShopless = Boolean(selection && selection.allowShoplessLogin)
let loginShopIndex = -1
let loginShopDisplayName = ''
let shopId = ''
if (!allowLoginShopless && shops.length === 1) {
loginShopIndex = 0
loginShopDisplayName = shops[0].shopName || ''
shopId = shops[0].id
}
this.setData({
loginShops: shops,
allowLoginShopless,
loginShopMessage: (selection && selection.message) || '',
loginShopIndex,
loginShopDisplayName,
'form.shopId': shopId
})
},
async checkLoginAccountAvailability() {
try {
const result = await userApi.checkLoginAccountAvailability(this.data.form.account.trim())
this.setData({
loginAccountStatusText: result && result.message ? result.message : '',
loginAccountStatusType: result && result.exists ? 'success' : 'error'
})
return Boolean(result && result.exists)
} catch (error) {
this.setData({
loginAccountStatusText: '',
loginAccountStatusType: ''
})
return false
}
},
async loadLoginShopsByAccount() {
try {
const result = await userApi.getLoginShopsByAccount(this.data.form.account.trim())
this.applyLoginShopSelection(result)
} catch (error) {
this.applyLoginShopSelection({
allowShoplessLogin: true,
message: '当前环境暂未开启门店预选,可直接登录',
shops: []
})
}
},
async loadLoginShopsByPhone() {
try {
const result = await userApi.getLoginShopsByPhone(this.data.form.phone.trim())
this.applyLoginShopSelection(result)
} catch (error) {
this.applyLoginShopSelection({
allowShoplessLogin: true,
message: '当前环境暂未开启门店预选,可直接登录',
shops: []
})
}
},
async checkRegisterAccountAvailability() {
try {
const result = await userApi.checkAccountAvailability(this.data.form.account.trim())
this.setData({
registerAccountStatusText: result && result.message ? result.message : '',
registerAccountStatusType: result && result.available ? 'success' : 'error'
})
return Boolean(result && result.available)
} catch (error) {
this.setData({
registerAccountStatusText: '',
registerAccountStatusType: ''
})
return false
}
},
async checkRegisterPhoneAvailability() {
try {
const result = await userApi.checkPhoneAvailability(this.data.form.phone.trim())
this.setData({
registerPhoneStatusText: result && result.message ? result.message : '',
registerPhoneStatusType: result && result.available ? 'success' : 'error'
})
return Boolean(result && result.available)
} catch (error) {
this.setData({
registerPhoneStatusText: '',
registerPhoneStatusType: ''
})
return false
}
},
startCountdown(fieldName) {
this.setData({
[fieldName]: 60
})
const timer = setInterval(() => {
const nextValue = this.data[fieldName] - 1
this.setData({
[fieldName]: nextValue
})
if (nextValue <= 0) {
clearInterval(timer)
}
}, 1000)
},
async handleSendCode() {
if (this.data.countdown > 0) {
return
}
const phone = this.data.form.phone.trim()
if (!phoneRegex.test(phone)) {
wx.showToast({
title: '请输入正确的手机号',
icon: 'none'
})
return
}
if (this.data.activeTab === 'register') {
const phoneAvailable = await this.checkRegisterPhoneAvailability()
if (!phoneAvailable) {
wx.showToast({
title: this.data.registerPhoneStatusText || '该手机号已被注册',
icon: 'none'
})
return
}
}
try {
await runWithLoading(() => userApi.sendVerificationCode({
phone
}))
wx.showToast({
title: '验证码已发送',
icon: 'none'
})
this.startCountdown('countdown')
} catch (error) {
wx.showToast({
title: error.message || '验证码发送失败',
icon: 'none'
})
}
},
async handleSendForgotCode() {
if (this.data.forgotCountdown > 0) {
return
}
const phone = this.data.resetForm.phone.trim()
if (!phoneRegex.test(phone)) {
wx.showToast({
title: '请输入正确的手机号',
icon: 'none'
})
return
}
try {
await runWithLoading(() => authApi.sendVerificationCode({
phone
}))
wx.showToast({
title: '验证码已发送',
icon: 'none'
})
this.startCountdown('forgotCountdown')
} catch (error) {
wx.showToast({
title: error.message || '验证码发送失败',
icon: 'none'
})
}
},
validateLoginForm() {
const form = this.data.form
if (this.data.loginType === 'password') {
if (!form.account.trim() || !form.password) {
return '请输入账号和密码'
}
} else if (!phoneRegex.test(form.phone.trim()) || !form.verificationCode.trim()) {
return '请输入正确的手机号和验证码'
}
if (!this.data.allowLoginShopless && this.data.loginShops.length && !form.shopId) {
return '请选择登录门店'
}
return ''
},
async validateRegisterForm() {
const form = this.data.form
if (!form.nickname.trim()) {
return '请输入昵称'
}
if (!form.account.trim()) {
return '请输入账号'
}
if (!phoneRegex.test(form.phone.trim())) {
return '请输入正确的手机号'
}
if (!form.verificationCode.trim()) {
return '请输入验证码'
}
if (!form.password || form.password.length < 6) {
return '密码至少 6 位'
}
if (form.password !== form.confirmPassword) {
return '两次输入的密码不一致'
}
if (!form.shopId) {
return '请选择门店'
}
const [accountAvailable, phoneAvailable] = await Promise.all([
this.checkRegisterAccountAvailability(),
this.checkRegisterPhoneAvailability()
])
if (!accountAvailable || !phoneAvailable) {
return '请先处理注册信息中的占用问题'
}
return ''
},
async handleSubmit() {
this.setData({
loading: true
})
try {
if (this.data.activeTab === 'login') {
const loginError = this.validateLoginForm()
if (loginError) {
throw new Error(loginError)
}
let payload
await runWithLoading(async () => {
payload = this.data.loginType === 'phone'
? await authApi.phoneLogin({
phone: this.data.form.phone.trim(),
verificationCode: this.data.form.verificationCode.trim(),
shopId: this.data.form.shopId || undefined
})
: await authApi.login({
account: this.data.form.account.trim(),
password: this.data.form.password,
rememberMe: true,
shopId: this.data.form.shopId || undefined
})
})
getApp().setUserSession(payload)
wx.showToast({
title: '登录成功',
icon: 'none'
})
try {
await navigation.redirectAfterLogin(this.data.redirect)
} catch (redirectError) {
console.error('登录后跳转失败,已回退到首页:', redirectError)
await navigation.switchTab('/pages/home/index')
}
return
}
const registerError = await this.validateRegisterForm()
if (registerError) {
throw new Error(registerError)
}
await runWithLoading(() => authApi.register({
account: this.data.form.account.trim(),
password: this.data.form.password,
nickname: this.data.form.nickname.trim(),
phone: this.data.form.phone.trim(),
verificationCode: this.data.form.verificationCode.trim(),
shopId: this.data.form.shopId
}))
wx.showToast({
title: '注册成功,请登录',
icon: 'none'
})
this.setData({
activeTab: 'login',
loginType: 'password',
'form.password': '',
'form.confirmPassword': '',
'form.verificationCode': ''
})
} catch (error) {
wx.showToast({
title: error.message || (this.data.activeTab === 'login' ? '登录失败' : '注册失败'),
icon: 'none'
})
} finally {
this.setData({
loading: false
})
}
},
async handleResetPassword() {
const form = this.data.resetForm
if (!phoneRegex.test(form.phone.trim())) {
wx.showToast({
title: '请输入正确的手机号',
icon: 'none'
})
return
}
if (!form.verificationCode.trim()) {
wx.showToast({
title: '请输入验证码',
icon: 'none'
})
return
}
if (!form.newPassword || form.newPassword.length < 6) {
wx.showToast({
title: '新密码至少 6 位',
icon: 'none'
})
return
}
this.setData({
loading: true
})
try {
await runWithLoading(() => authApi.resetPasswordByPhone({
phone: form.phone.trim(),
verificationCode: form.verificationCode.trim(),
newPassword: form.newPassword
}))
wx.showToast({
title: '密码已重置,请重新登录',
icon: 'none'
})
this.setData({
showResetPanel: false,
resetForm: {
phone: '',
verificationCode: '',
newPassword: ''
}
})
} catch (error) {
wx.showToast({
title: error.message || '密码重置失败',
icon: 'none'
})
} finally {
this.setData({
loading: false
})
}
}
})
+5
View File
@@ -0,0 +1,5 @@
{
"usingComponents": {
"navigation-bar": "/components/navigation-bar/navigation-bar"
}
}
+132
View File
@@ -0,0 +1,132 @@
<navigation-bar title="账号中心" back="{{false}}" color="#2d2430" background="#fff7f8"></navigation-bar>
<view class="page-shell auth-page">
<view class="page-content auth-content">
<view class="page-hero auth-hero">
<text class="hero-kicker">YUMI NAIL</text>
<text class="hero-title">{{activeTab === 'login' ? '登录后继续预约与收藏' : '注册账号,开始你的美甲旅程'}}</text>
<text class="hero-desc">支持账号密码或手机验证码,绑定门店后,下单和查看记录都会更顺手。</text>
<view class="auth-benefits">
<view class="auth-benefit">
<text class="auth-benefit-title">收藏同步</text>
<text class="auth-benefit-desc">喜欢的作品随时可回看</text>
</view>
<view class="auth-benefit">
<text class="auth-benefit-title">预约顺手</text>
<text class="auth-benefit-desc">登录后直接补全预约信息</text>
</view>
<view class="auth-benefit">
<text class="auth-benefit-title">门店绑定</text>
<text class="auth-benefit-desc">注册时即可关联常用门店</text>
</view>
</view>
</view>
<view class="page-card auth-card">
<view class="tab-row">
<view class="tab-item {{activeTab === 'login' ? 'active' : ''}}" data-tab="login" bindtap="handleTabChange">登录</view>
<view class="tab-item {{activeTab === 'register' ? 'active' : ''}}" data-tab="register" bindtap="handleTabChange">注册</view>
</view>
<view wx:if="{{activeTab === 'login'}}" class="toggle-row">
<view class="toggle-item {{loginType === 'password' ? 'active' : ''}}" data-type="password" bindtap="handleLoginTypeChange">账号密码登录</view>
<view class="toggle-item {{loginType === 'phone' ? 'active' : ''}}" data-type="phone" bindtap="handleLoginTypeChange">验证码登录</view>
</view>
<view class="auth-helper">
{{activeTab === 'login' ? (loginType === 'password' ? '输入账号和密码即可登录。' : '手机号登录时会发送短信验证码。') : '注册前会实时检查账号和手机号是否已被占用。'}}
</view>
<block wx:if="{{activeTab === 'register'}}">
<view class="field-block">
<text class="field-label">昵称</text>
<input class="field-input" placeholder="请输入昵称" placeholder-class="field-placeholder" value="{{form.nickname}}" data-field="nickname" bindinput="handleInputChange"></input>
</view>
</block>
<view class="field-block">
<text class="field-label">账号</text>
<input class="field-input" placeholder="请输入账号" placeholder-class="field-placeholder" value="{{form.account}}" data-field="account" bindinput="handleInputChange" bindblur="handleAccountBlur"></input>
<text wx:if="{{activeTab === 'login' && loginAccountStatusText}}" class="status-text {{loginAccountStatusType}}">{{loginAccountStatusText}}</text>
<text wx:if="{{activeTab === 'register' && registerAccountStatusText}}" class="status-text {{registerAccountStatusType}}">{{registerAccountStatusText}}</text>
</view>
<view wx:if="{{activeTab === 'register' || loginType === 'phone'}}" class="field-block">
<text class="field-label">手机号</text>
<input class="field-input" type="number" placeholder="请输入手机号" placeholder-class="field-placeholder" value="{{form.phone}}" data-field="phone" bindinput="handleInputChange" bindblur="handlePhoneBlur"></input>
<text wx:if="{{activeTab === 'register' && registerPhoneStatusText}}" class="status-text {{registerPhoneStatusType}}">{{registerPhoneStatusText}}</text>
</view>
<view wx:if="{{activeTab === 'login' && loginType === 'password'}}" class="field-block">
<text class="field-label">密码</text>
<input class="field-input" password placeholder="请输入密码" placeholder-class="field-placeholder" value="{{form.password}}" data-field="password" bindinput="handleInputChange"></input>
</view>
<view wx:if="{{activeTab === 'register' || loginType === 'phone'}}" class="field-block">
<text class="field-label">验证码</text>
<view class="code-row">
<input class="field-input code-input" type="number" placeholder="请输入验证码" placeholder-class="field-placeholder" value="{{form.verificationCode}}" data-field="verificationCode" bindinput="handleInputChange"></input>
<view class="code-btn {{countdown > 0 ? 'disabled' : ''}}" bindtap="handleSendCode">{{countdown > 0 ? countdown + 's' : '发送验证码'}}</view>
</view>
</view>
<view wx:if="{{activeTab === 'register'}}" class="field-block">
<text class="field-label">密码</text>
<input class="field-input" password placeholder="请输入密码" placeholder-class="field-placeholder" value="{{form.password}}" data-field="password" bindinput="handleInputChange"></input>
</view>
<view wx:if="{{activeTab === 'register'}}" class="field-block">
<text class="field-label">确认密码</text>
<input class="field-input" password placeholder="请再次输入密码" placeholder-class="field-placeholder" value="{{form.confirmPassword}}" data-field="confirmPassword" bindinput="handleInputChange"></input>
</view>
<view wx:if="{{activeTab === 'register'}}" class="field-block">
<text class="field-label">选择门店</text>
<picker mode="selector" range="{{shops}}" range-key="shopName" value="{{registerShopIndex}}" bindchange="handleRegisterShopChange">
<view class="field-picker">{{registerShopDisplayName || '请选择门店'}}</view>
</picker>
</view>
<view wx:if="{{activeTab === 'login' && !allowLoginShopless && loginShops.length}}" class="field-block">
<text class="field-label">选择登录门店</text>
<picker mode="selector" range="{{loginShops}}" range-key="shopName" value="{{loginShopIndex}}" bindchange="handleLoginShopChange">
<view class="field-picker">{{loginShopDisplayName || '请选择登录门店'}}</view>
</picker>
</view>
<view wx:if="{{activeTab === 'login' && loginShopMessage}}" class="hint-card login-shop-tip">{{loginShopMessage}}</view>
<view wx:if="{{activeTab === 'login'}}" class="aux-row">
<text class="aux-link" bindtap="handleToggleResetPanel">忘记密码?</text>
</view>
<view class="primary-btn submit-btn" bindtap="handleSubmit">{{activeTab === 'login' ? '立即登录' : '完成注册'}}</view>
</view>
<view wx:if="{{showResetPanel}}" class="page-card reset-card">
<view class="section-title">重置密码</view>
<view class="section-subtitle">使用手机验证码设置新的登录密码。</view>
<view class="field-block">
<text class="field-label">手机号</text>
<input class="field-input" type="number" placeholder="请输入绑定手机号" placeholder-class="field-placeholder" value="{{resetForm.phone}}" data-field="phone" bindinput="handleResetInputChange"></input>
</view>
<view class="field-block">
<text class="field-label">验证码</text>
<view class="code-row">
<input class="field-input code-input" type="number" placeholder="请输入验证码" placeholder-class="field-placeholder" value="{{resetForm.verificationCode}}" data-field="verificationCode" bindinput="handleResetInputChange"></input>
<view class="code-btn {{forgotCountdown > 0 ? 'disabled' : ''}}" bindtap="handleSendForgotCode">{{forgotCountdown > 0 ? forgotCountdown + 's' : '发送验证码'}}</view>
</view>
</view>
<view class="field-block">
<text class="field-label">新密码</text>
<input class="field-input" password placeholder="请输入新密码" placeholder-class="field-placeholder" value="{{resetForm.newPassword}}" data-field="newPassword" bindinput="handleResetInputChange"></input>
</view>
<view class="primary-btn submit-btn" bindtap="handleResetPassword">确认重置密码</view>
</view>
</view>
</view>
+154
View File
@@ -0,0 +1,154 @@
.auth-page {
background:
radial-gradient(circle at top right, rgba(255, 204, 219, 0.4), transparent 30%),
linear-gradient(180deg, #fff7f8 0%, #fffdfb 100%);
}
.auth-content {
padding-top: 12rpx;
}
.auth-hero {
background:
radial-gradient(circle at top right, rgba(255, 190, 209, 0.44), transparent 34%),
linear-gradient(145deg, #fffdfd 0%, #fff2f6 58%, #ffe8ef 100%);
}
.auth-benefits {
display: flex;
gap: 14rpx;
margin-top: 28rpx;
}
.auth-benefit {
flex: 1;
min-width: 0;
padding: 20rpx 18rpx;
border-radius: 24rpx;
background: rgba(255, 255, 255, 0.82);
}
.auth-benefit-title {
display: block;
font-size: 24rpx;
font-weight: 700;
color: #2d2430;
}
.auth-benefit-desc {
display: block;
margin-top: 10rpx;
font-size: 21rpx;
line-height: 1.6;
color: #8d7a84;
}
.auth-card,
.reset-card {
padding: 28rpx;
}
.auth-card {
margin-top: 24rpx;
}
.reset-card {
margin-top: 24rpx;
}
.tab-row,
.toggle-row {
display: flex;
align-items: center;
gap: 12rpx;
}
.tab-row {
margin-bottom: 22rpx;
}
.toggle-row {
margin-bottom: 18rpx;
padding: 10rpx;
border-radius: 999rpx;
background: #fbf5f7;
}
.tab-item,
.toggle-item {
display: flex;
align-items: center;
justify-content: center;
flex: 1;
height: 76rpx;
border-radius: 999rpx;
color: #8d7a84;
font-size: 26rpx;
font-weight: 600;
}
.tab-item.active,
.toggle-item.active {
background: #fde8ef;
color: #c6597d;
}
.auth-helper {
margin-bottom: 10rpx;
font-size: 23rpx;
line-height: 1.7;
color: #8d7a84;
}
.field-block {
margin-top: 18rpx;
}
.code-row {
display: flex;
align-items: center;
gap: 14rpx;
}
.code-input {
flex: 1;
}
.code-btn {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 180rpx;
height: 92rpx;
padding: 0 18rpx;
border-radius: 24rpx;
background: #fde8ef;
color: #c6597d;
font-size: 24rpx;
font-weight: 700;
}
.code-btn.disabled {
background: #f3e7eb;
color: #a998a0;
}
.aux-row {
display: flex;
justify-content: flex-end;
margin-top: 20rpx;
}
.aux-link {
font-size: 24rpx;
color: #c6597d;
font-weight: 600;
}
.login-shop-tip {
margin-top: 18rpx;
}
.submit-btn {
margin-top: 28rpx;
}
+496
View File
@@ -0,0 +1,496 @@
const cartApi = require('../../api/cart')
const couponApi = require('../../api/coupon')
const orderApi = require('../../api/order')
const auth = require('../../utils/auth')
const navigation = require('../../utils/navigation')
const { resolveLegacyImage } = require('../../utils/file')
const { NO_COUPON_KEY } = require('../../utils/config')
const { runWithLoading } = require('../../utils/loading')
const {
buildAppointmentValue,
formatDateTime,
formatPrice,
getMinDateText,
isPastAppointment,
parseAppointmentParts
} = require('../../utils/format')
function getCouponKey(coupon) {
return `${coupon.sourceType || 'USER_COUPON'}:${coupon.id}`
}
function getCouponDisplay(coupon) {
if (Number(coupon.couponType) === 1) {
return `${coupon.couponName} ${coupon.discountValue} 折`
}
return `${coupon.couponName} 满 ${coupon.minAmount} 减 ${coupon.reduceAmount}`
}
function calculateCouponDiscount(coupon, amount) {
if (!coupon || amount <= 0) {
return 0
}
if (Number(coupon.couponType) === 1) {
const discountValue = Number(coupon.discountValue || 0)
return discountValue ? amount - amount * discountValue / 10 : 0
}
if (Number(coupon.couponType) === 2) {
return Number(coupon.reduceAmount || 0)
}
return 0
}
function buildCheckoutIssues(items) {
const issues = []
const selectedItems = items.filter(item => item.selected)
if (!selectedItems.length) {
issues.push('请先勾选要结算的作品')
return issues
}
const missingArtist = selectedItems.find(item => !item.artistId)
if (missingArtist) {
issues.push(`请先为“${missingArtist.productTitle}”选择美甲师`)
}
const missingTime = selectedItems.find(item => !item.appointmentValue)
if (missingTime) {
issues.push(`请先为“${missingTime.productTitle}”选择预约时间`)
}
const expiredTime = selectedItems.find(item => item.appointmentValue && isPastAppointment(item.appointmentValue))
if (expiredTime) {
issues.push(`“${expiredTime.productTitle}”的预约时间已过,请重新选择`)
}
const shopIds = Array.from(new Set(selectedItems.map(item => item.shopId).filter(Boolean)))
if (shopIds.length > 1) {
issues.push('跨门店作品请分开结算')
}
const artistIds = Array.from(new Set(selectedItems.map(item => item.artistId).filter(Boolean)))
if (artistIds.length > 1) {
issues.push('不同美甲师的项目请分开结算')
}
return issues
}
Page({
data: {
isLoggedIn: false,
loading: false,
minDate: getMinDateText(),
cartItems: [],
availableCoupons: [],
selectedCouponKey: NO_COUPON_KEY,
selectedCount: 0,
totalQuantity: 0,
subtotalAmount: 0,
subtotalText: '¥0.00',
discountAmountText: '¥0.00',
totalAmountText: '¥0.00',
checkoutIssues: []
},
onShow() {
this.loadCartItems()
},
async onPullDownRefresh() {
await this.loadCartItems()
wx.stopPullDownRefresh()
},
getSelectedItems() {
return this.data.cartItems.filter(item => item.selected)
},
getSelectedCoupon() {
return this.data.availableCoupons.find(item => item.key === this.data.selectedCouponKey) || null
},
refreshSummary() {
const selectedItems = this.getSelectedItems()
const selectedCoupon = this.getSelectedCoupon()
const selectedCount = selectedItems.length
const totalQuantity = selectedItems.reduce((sum, item) => sum + Number(item.quantity || 0), 0)
const subtotalAmount = selectedItems.reduce((sum, item) => sum + Number(item.price || 0) * Number(item.quantity || 0), 0)
const discountAmount = calculateCouponDiscount(selectedCoupon, subtotalAmount)
const totalAmount = Math.max(0, subtotalAmount - discountAmount)
const checkoutIssues = buildCheckoutIssues(this.data.cartItems)
this.setData({
selectedCount,
totalQuantity,
subtotalAmount,
subtotalText: `¥${formatPrice(subtotalAmount)}`,
discountAmountText: `¥${formatPrice(discountAmount)}`,
totalAmountText: `¥${formatPrice(totalAmount)}`,
checkoutIssues
})
},
async loadCartItems() {
const isLoggedIn = auth.isLoggedIn()
this.setData({
isLoggedIn,
loading: isLoggedIn
})
if (!isLoggedIn) {
this.setData({
cartItems: [],
availableCoupons: [],
selectedCouponKey: NO_COUPON_KEY,
loading: false
})
this.refreshSummary()
return
}
try {
const cartItems = await cartApi.getCartList()
const list = Array.isArray(cartItems) ? cartItems : []
const formattedItems = await Promise.all(list.map(async item => {
const appointmentParts = parseAppointmentParts(item.appointmentTime)
const productImageUrl = await resolveLegacyImage(item.productImage)
const availableArtists = Array.isArray(item.availableArtists) ? item.availableArtists.map(artist => ({
id: artist.id,
name: artist.name,
avatar: artist.avatar
})) : []
const artist = availableArtists.find(current => String(current.id) === String(item.artistId || ''))
return {
...item,
productImageUrl,
priceText: `¥${formatPrice(item.price)}`,
selected: true,
artistId: item.artistId || '',
artistName: artist ? artist.name : '',
availableArtists,
appointmentDate: appointmentParts.date,
appointmentClock: appointmentParts.clock,
appointmentValue: buildAppointmentValue(appointmentParts.date, appointmentParts.clock)
}
}))
this.setData({
cartItems: formattedItems,
selectedCouponKey: NO_COUPON_KEY
})
await this.loadAvailableCoupons()
} catch (error) {
this.setData({
cartItems: []
})
wx.showToast({
title: error.message || '购物车加载失败',
icon: 'none'
})
} finally {
this.setData({
loading: false
})
this.refreshSummary()
}
},
async loadAvailableCoupons() {
const selectedItems = this.getSelectedItems()
if (!selectedItems.length) {
this.setData({
availableCoupons: [],
selectedCouponKey: NO_COUPON_KEY
})
this.refreshSummary()
return
}
const tags = new Set()
const subtotalAmount = selectedItems.reduce((sum, item) => sum + Number(item.price || 0) * Number(item.quantity || 0), 0)
selectedItems.forEach(item => {
String(item.tagNames || '')
.split(',')
.map(tag => tag.trim())
.filter(Boolean)
.forEach(tag => tags.add(tag))
})
try {
const coupons = await couponApi.getAvailableCoupons(
Array.from(tags).join(','),
subtotalAmount,
selectedItems[0].shopId
)
const list = Array.isArray(coupons) ? coupons.map(item => ({
...item,
key: getCouponKey(item),
displayText: getCouponDisplay(item)
})) : []
let selectedCouponKey = this.data.selectedCouponKey
if (selectedCouponKey !== NO_COUPON_KEY && !list.find(item => item.key === selectedCouponKey)) {
selectedCouponKey = NO_COUPON_KEY
}
if (selectedCouponKey === NO_COUPON_KEY) {
const vipCoupons = list
.filter(item => item.sourceType === 'SYSTEM_VIP')
.sort((left, right) => calculateCouponDiscount(right, subtotalAmount) - calculateCouponDiscount(left, subtotalAmount))
if (vipCoupons.length) {
selectedCouponKey = vipCoupons[0].key
}
}
this.setData({
availableCoupons: list,
selectedCouponKey
})
} catch (error) {
this.setData({
availableCoupons: [],
selectedCouponKey: NO_COUPON_KEY
})
} finally {
this.refreshSummary()
}
},
handleOpenAuth() {
navigation.openAuth('/pages/cart/index')
},
handleBrowseProducts() {
navigation.switchTab('/pages/products/index')
},
async handleToggleSelect(event) {
const index = Number(event.currentTarget.dataset.index)
const cartItems = this.data.cartItems.slice()
const item = cartItems[index]
if (!item) {
return
}
item.selected = !item.selected
this.setData({
cartItems
})
if (cartItems.some(current => current.selected)) {
await runWithLoading(() => this.loadAvailableCoupons())
return
}
await this.loadAvailableCoupons()
},
async handleChangeQuantity(event) {
const index = Number(event.currentTarget.dataset.index)
const delta = Number(event.currentTarget.dataset.delta)
const cartItems = this.data.cartItems.slice()
const item = cartItems[index]
if (!item) {
return
}
const nextQuantity = Number(item.quantity || 0) + delta
if (nextQuantity < 1 || nextQuantity > 99) {
return
}
item.quantity = nextQuantity
this.setData({
cartItems
})
this.refreshSummary()
try {
await runWithLoading(async () => {
await cartApi.updateCartQuantity({
productId: item.productId,
quantity: nextQuantity
})
await this.loadAvailableCoupons()
})
await getApp().updateCartBadge()
} catch (error) {
item.quantity -= delta
this.setData({
cartItems
})
this.refreshSummary()
wx.showToast({
title: error.message || '数量更新失败',
icon: 'none'
})
}
},
async handleRemoveItem(event) {
const index = Number(event.currentTarget.dataset.index)
const cartItems = this.data.cartItems.slice()
const item = cartItems[index]
if (!item) {
return
}
const confirmed = await new Promise(resolve => {
wx.showModal({
title: '移除作品',
content: '确认从购物车移除这件作品吗?',
success: res => resolve(Boolean(res.confirm))
})
})
if (!confirmed) {
return
}
try {
await runWithLoading(() => cartApi.removeFromCart(item.productId))
wx.showToast({
title: '已移出购物车',
icon: 'none'
})
await getApp().updateCartBadge()
this.loadCartItems()
} catch (error) {
wx.showToast({
title: error.message || '移除失败',
icon: 'none'
})
}
},
handleOpenProduct(event) {
const productId = event.currentTarget.dataset.productId
if (!productId) {
return
}
navigation.navigate('/pages/product-detail/index', {
id: productId
})
},
async handleChooseArtist(event) {
const index = Number(event.currentTarget.dataset.index)
const cartItems = this.data.cartItems.slice()
const item = cartItems[index]
if (!item) {
return
}
if (!item.availableArtists.length) {
wx.showToast({
title: '当前作品暂时没有可预约美甲师',
icon: 'none'
})
return
}
const tapIndex = await new Promise(resolve => {
wx.showActionSheet({
itemList: item.availableArtists.map(artist => artist.name),
success: res => resolve(res.tapIndex),
fail: () => resolve(-1)
})
})
if (tapIndex < 0 || tapIndex >= item.availableArtists.length) {
return
}
const artist = item.availableArtists[tapIndex]
item.artistId = artist.id
item.artistName = artist.name
this.setData({
cartItems
})
this.refreshSummary()
},
handleDateChange(event) {
const index = Number(event.currentTarget.dataset.index)
const cartItems = this.data.cartItems.slice()
const item = cartItems[index]
if (!item) {
return
}
item.appointmentDate = event.detail.value
item.appointmentValue = buildAppointmentValue(item.appointmentDate, item.appointmentClock)
this.setData({
cartItems
})
this.refreshSummary()
},
handleTimeChange(event) {
const index = Number(event.currentTarget.dataset.index)
const cartItems = this.data.cartItems.slice()
const item = cartItems[index]
if (!item) {
return
}
item.appointmentClock = event.detail.value
item.appointmentValue = buildAppointmentValue(item.appointmentDate, item.appointmentClock)
this.setData({
cartItems
})
this.refreshSummary()
},
handleCouponChange(event) {
this.setData({
selectedCouponKey: event.detail.value
})
this.refreshSummary()
},
async handleCheckout() {
const selectedItems = this.getSelectedItems()
const checkoutIssues = buildCheckoutIssues(this.data.cartItems)
if (checkoutIssues.length) {
wx.showToast({
title: checkoutIssues[0],
icon: 'none'
})
return
}
try {
const selectedCoupon = this.getSelectedCoupon()
await runWithLoading(() => orderApi.createOrder({
couponId: selectedCoupon ? selectedCoupon.id : undefined,
couponSourceType: selectedCoupon ? selectedCoupon.sourceType : (this.data.selectedCouponKey === NO_COUPON_KEY ? NO_COUPON_KEY : undefined),
items: selectedItems.map(item => ({
productId: item.productId,
quantity: item.quantity,
artistId: item.artistId,
appointmentTime: item.appointmentValue
}))
}))
wx.showToast({
title: '订单创建成功',
icon: 'none'
})
await getApp().updateCartBadge()
await this.loadCartItems()
navigation.navigate('/pages/orders/index')
} catch (error) {
wx.showToast({
title: error.message || '订单创建失败',
icon: 'none'
})
}
}
})
+6
View File
@@ -0,0 +1,6 @@
{
"usingComponents": {
"navigation-bar": "/components/navigation-bar/navigation-bar"
},
"enablePullDownRefresh": true
}
+159
View File
@@ -0,0 +1,159 @@
<navigation-bar title="购物车" back="{{false}}" color="#2d2430" background="#fff7f8"></navigation-bar>
<view class="page-shell cart-page">
<view class="page-content cart-content">
<view wx:if="{{!isLoggedIn}}" class="page-card empty-card">
<text class="empty-title">登录后查看购物车</text>
<text class="empty-desc">把喜欢的作品加进购物车后,就能补全预约信息并提交订单。</text>
<view class="ghost-btn" bindtap="handleOpenAuth">去登录</view>
</view>
<block wx:elif="{{cartItems.length}}">
<view class="page-hero cart-hero">
<text class="hero-kicker">结算准备</text>
<text class="hero-title">已选 {{selectedCount}} 个预约项目</text>
<text class="hero-desc">先确认美甲师和预约时间,再统一提交订单,避免来回修改。</text>
<view class="summary-strip">
<view class="summary-metric">
<text class="summary-label">选中项目</text>
<text class="summary-value">{{selectedCount}} 项</text>
<text class="summary-note">可分批勾选结算</text>
</view>
<view class="summary-metric">
<text class="summary-label">数量合计</text>
<text class="summary-value">{{totalQuantity}} 件</text>
<text class="summary-note">支持直接增减数量</text>
</view>
<view class="summary-metric">
<text class="summary-label">待支付</text>
<text class="summary-value">{{totalAmountText}}</text>
<text class="summary-note">已自动计算优惠</text>
</view>
</view>
</view>
<view wx:if="{{checkoutIssues.length}}" class="issue-card">
<view class="issue-title">下单前还需要完善</view>
<view wx:for="{{checkoutIssues}}" wx:key="*this" class="issue-item">{{index + 1}}. {{item}}</view>
</view>
<view wx:for="{{cartItems}}" wx:key="id" class="page-card cart-item-card">
<view class="cart-item-top">
<view class="select-dot {{item.selected ? 'active' : ''}}" data-index="{{index}}" bindtap="handleToggleSelect"></view>
<image class="cart-thumb" src="{{item.productImageUrl}}" mode="aspectFill" data-product-id="{{item.productId}}" bindtap="handleOpenProduct"></image>
<view class="cart-main">
<view class="cart-title-row">
<view class="cart-title" data-product-id="{{item.productId}}" bindtap="handleOpenProduct">{{item.productTitle}}</view>
<view class="cart-price">{{item.priceText}}</view>
</view>
<view class="cart-meta-row">
<text class="meta-chip">{{item.selected ? '已选中' : '未选中'}}</text>
<text wx:if="{{item.approximateDuration}}" class="cart-meta">预计时长 {{item.approximateDuration}}</text>
</view>
</view>
</view>
<view class="selector-group">
<view class="selector-row {{item.selected && !item.artistId ? 'issue' : ''}}" data-index="{{index}}" bindtap="handleChooseArtist">
<text class="selector-label">美甲师</text>
<text class="selector-value">{{item.artistName || '请选择美甲师'}}</text>
</view>
<view class="time-grid">
<picker mode="date" value="{{item.appointmentDate}}" start="{{minDate}}" data-index="{{index}}" bindchange="handleDateChange">
<view class="selector-row compact {{item.selected && !item.appointmentDate ? 'issue' : ''}}">
<text class="selector-label">日期</text>
<text class="selector-value">{{item.appointmentDate || '选择日期'}}</text>
</view>
</picker>
<picker mode="time" value="{{item.appointmentClock}}" data-index="{{index}}" bindchange="handleTimeChange">
<view class="selector-row compact {{item.selected && !item.appointmentClock ? 'issue' : ''}}">
<text class="selector-label">时间</text>
<text class="selector-value">{{item.appointmentClock || '选择时间'}}</text>
</view>
</picker>
</view>
<view wx:if="{{item.appointmentValue}}" class="appointment-preview">
当前预约:{{item.appointmentValue}}
</view>
</view>
<view class="cart-item-foot">
<view class="qty-box">
<view class="qty-btn" data-index="{{index}}" data-delta="-1" bindtap="handleChangeQuantity">-</view>
<text class="qty-value">{{item.quantity}}</text>
<view class="qty-btn" data-index="{{index}}" data-delta="1" bindtap="handleChangeQuantity">+</view>
</view>
<view class="remove-btn" data-index="{{index}}" bindtap="handleRemoveItem">移除</view>
</view>
</view>
<view wx:if="{{selectedCount}}" class="page-card coupon-card">
<view class="section-title">优惠方式</view>
<view class="section-subtitle">系统会优先帮你匹配最合适的 VIP 自动折扣,普通优惠券仍可手动改选。</view>
<radio-group bindchange="handleCouponChange">
<label class="coupon-option">
<radio value="NONE" checked="{{selectedCouponKey === 'NONE'}}" color="#c6597d"></radio>
<view class="coupon-texts">
<view class="coupon-name">不使用优惠</view>
</view>
</label>
<label wx:for="{{availableCoupons}}" wx:key="key" wx:for-item="coupon" class="coupon-option {{selectedCouponKey === coupon.key ? 'active' : ''}}">
<radio value="{{coupon.key}}" checked="{{selectedCouponKey === coupon.key}}" color="#c6597d"></radio>
<view class="coupon-texts">
<view class="coupon-name">{{coupon.displayText}}</view>
<view class="coupon-desc">{{coupon.sourceType === 'SYSTEM_VIP' ? 'VIP 自动折扣' : '用户优惠券'}}</view>
</view>
<view class="coupon-tag">{{coupon.sourceType === 'SYSTEM_VIP' ? '推荐' : '手动选择'}}</view>
</label>
</radio-group>
</view>
<view class="page-card summary-card">
<view class="summary-row">
<text>选中项目</text>
<text>{{selectedCount}} 项</text>
</view>
<view class="summary-row">
<text>作品数量</text>
<text>{{totalQuantity}} 件</text>
</view>
<view class="summary-row">
<text>小计</text>
<text>{{subtotalText}}</text>
</view>
<view class="summary-row">
<text>优惠</text>
<text>-{{discountAmountText}}</text>
</view>
<view class="summary-row total">
<text>合计</text>
<text>{{totalAmountText}}</text>
</view>
</view>
</block>
<view wx:elif="{{loading}}" class="page-card empty-card">
<text class="empty-title">正在加载购物车</text>
</view>
<view wx:else class="page-card empty-card">
<text class="empty-title">购物车还是空的</text>
<text class="empty-desc">先把喜欢的作品加进来,再补充预约时间和美甲师。</text>
<view class="ghost-btn" bindtap="handleBrowseProducts">去逛作品</view>
</view>
</view>
<view wx:if="{{isLoggedIn && cartItems.length}}" class="checkout-bar">
<view class="checkout-copy">
<view class="checkout-total">{{totalAmountText}}</view>
<view class="checkout-meta">已选 {{selectedCount}} 项</view>
</view>
<view class="checkout-btn" bindtap="handleCheckout">提交订单</view>
</view>
</view>
+326
View File
@@ -0,0 +1,326 @@
.cart-page {
padding-bottom: calc(env(safe-area-inset-bottom) + 150rpx);
}
.cart-content {
padding-bottom: 20rpx;
}
.cart-hero {
background:
radial-gradient(circle at top right, rgba(255, 192, 210, 0.42), transparent 34%),
linear-gradient(145deg, #fffdfd 0%, #fff2f6 56%, #ffe7ef 100%);
}
.issue-card {
margin-top: 20rpx;
margin-bottom: 20rpx;
padding: 22rpx 24rpx;
border-radius: 24rpx;
background: #fff7e8;
color: #9b6900;
}
.issue-title {
font-size: 28rpx;
font-weight: 700;
}
.issue-item {
margin-top: 10rpx;
font-size: 24rpx;
line-height: 1.7;
}
.cart-item-card + .cart-item-card,
.coupon-card,
.summary-card {
margin-top: 20rpx;
}
.cart-item-card {
padding: 24rpx;
}
.cart-item-top {
display: flex;
align-items: flex-start;
gap: 16rpx;
}
.select-dot {
width: 34rpx;
height: 34rpx;
margin-top: 8rpx;
border-radius: 50%;
border: 4rpx solid #d8c4cc;
}
.select-dot.active {
border-color: #c6597d;
background: #c6597d;
}
.cart-thumb {
width: 140rpx;
height: 140rpx;
border-radius: 22rpx;
background: #f6edf1;
}
.cart-main {
flex: 1;
}
.cart-title-row {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 16rpx;
}
.cart-title {
flex: 1;
min-width: 0;
font-size: 30rpx;
font-weight: 700;
line-height: 1.5;
color: #2d2430;
}
.cart-price {
font-size: 30rpx;
font-weight: 700;
color: #d5536f;
}
.cart-meta-row {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 12rpx;
margin-top: 12rpx;
}
.meta-chip {
display: inline-flex;
align-items: center;
justify-content: center;
height: 42rpx;
padding: 0 16rpx;
border-radius: 999rpx;
background: #fff1f5;
color: #c6597d;
font-size: 20rpx;
font-weight: 700;
}
.cart-meta {
font-size: 24rpx;
color: #8d7a84;
}
.selector-group {
margin-top: 24rpx;
}
.selector-row {
display: flex;
align-items: center;
justify-content: space-between;
min-height: 76rpx;
padding: 0 22rpx;
border-radius: 20rpx;
background: #fbf5f7;
}
.selector-row.compact {
min-height: 72rpx;
}
.selector-row.issue {
background: #fff7e8;
}
.selector-label {
font-size: 24rpx;
color: #8d7a84;
}
.selector-value {
font-size: 24rpx;
color: #2d2430;
font-weight: 600;
}
.time-grid {
display: flex;
gap: 14rpx;
margin-top: 14rpx;
}
.time-grid picker {
flex: 1;
}
.appointment-preview {
margin-top: 14rpx;
font-size: 24rpx;
color: #8d7a84;
}
.cart-item-foot {
display: flex;
align-items: center;
justify-content: space-between;
margin-top: 24rpx;
}
.qty-box {
display: flex;
align-items: center;
gap: 16rpx;
}
.qty-btn {
display: inline-flex;
align-items: center;
justify-content: center;
width: 56rpx;
height: 56rpx;
border-radius: 50%;
background: #fbf5f7;
color: #7a5262;
font-size: 34rpx;
}
.qty-value {
min-width: 48rpx;
text-align: center;
font-size: 28rpx;
font-weight: 700;
color: #2d2430;
}
.remove-btn {
font-size: 24rpx;
color: #d5536f;
font-weight: 700;
}
.coupon-card,
.summary-card {
padding: 26rpx;
}
.coupon-option {
display: flex;
align-items: center;
gap: 18rpx;
margin-top: 20rpx;
padding: 20rpx 0;
border-top: 2rpx solid #f6eaee;
}
.coupon-option:first-child {
border-top: 0;
padding-top: 10rpx;
}
.coupon-option.active {
color: #c6597d;
}
.coupon-texts {
flex: 1;
}
.coupon-name {
font-size: 26rpx;
font-weight: 700;
color: #2d2430;
}
.coupon-desc {
margin-top: 8rpx;
font-size: 22rpx;
color: #8d7a84;
}
.coupon-tag {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 92rpx;
height: 44rpx;
padding: 0 14rpx;
border-radius: 999rpx;
background: #fff1f5;
color: #c6597d;
font-size: 20rpx;
font-weight: 700;
}
.summary-row {
display: flex;
align-items: center;
justify-content: space-between;
padding: 10rpx 0;
font-size: 26rpx;
color: #5d4b55;
}
.summary-row.total {
margin-top: 10rpx;
padding-top: 18rpx;
border-top: 2rpx solid #f3e7eb;
font-size: 30rpx;
font-weight: 700;
color: #2d2430;
}
.checkout-bar {
position: fixed;
left: 24rpx;
right: 24rpx;
bottom: calc(env(safe-area-inset-bottom) + 20rpx);
z-index: 20;
display: flex;
align-items: center;
justify-content: space-between;
gap: 20rpx;
padding: 18rpx 20rpx;
border-radius: 30rpx;
background: rgba(255, 255, 255, 0.98);
box-shadow: 0 18rpx 50rpx rgba(122, 67, 88, 0.12);
}
.checkout-copy {
flex: 1;
}
.checkout-total {
font-size: 36rpx;
font-weight: 800;
color: #d5536f;
}
.checkout-meta {
margin-top: 8rpx;
font-size: 22rpx;
color: #8d7a84;
}
.checkout-btn {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 220rpx;
height: 84rpx;
padding: 0 26rpx;
border-radius: 999rpx;
background: linear-gradient(135deg, #ff8cb0 0%, #c6597d 100%);
color: #ffffff;
font-size: 28rpx;
font-weight: 700;
}
+72
View File
@@ -0,0 +1,72 @@
const couponApi = require('../../api/coupon')
const auth = require('../../utils/auth')
const navigation = require('../../utils/navigation')
function getBenefitText(coupon) {
if (Number(coupon.couponType) === 1) {
return `${coupon.discountValue} 折`
}
return `满 ${coupon.minAmount} 减 ${coupon.reduceAmount}`
}
Page({
data: {
loading: false,
isLoggedIn: false,
coupons: []
},
onShow() {
this.loadCoupons()
},
async loadCoupons() {
const isLoggedIn = auth.isLoggedIn()
this.setData({
isLoggedIn,
loading: isLoggedIn
})
if (!isLoggedIn) {
this.setData({
coupons: [],
loading: false
})
return
}
try {
const coupons = await couponApi.listUserCoupons()
const list = Array.isArray(coupons) ? coupons.map(item => ({
...item,
benefitText: getBenefitText(item),
periodText: `${String(item.startTime || '').slice(0, 10)} - ${String(item.endTime || '').slice(0, 10)}`,
sourceText: item.sourceType === 'SYSTEM_VIP' ? 'VIP 自动匹配' : '用户优惠券'
})) : []
this.setData({
coupons: list
})
} catch (error) {
this.setData({
coupons: []
})
wx.showToast({
title: error.message || '优惠券加载失败',
icon: 'none'
})
} finally {
this.setData({
loading: false
})
}
},
handleOpenAuth() {
navigation.openAuth('/pages/coupons/index')
},
handleBack() {
navigation.goBack('/pages/profile/index')
}
})
+5
View File
@@ -0,0 +1,5 @@
{
"usingComponents": {
"navigation-bar": "/components/navigation-bar/navigation-bar"
}
}
+40
View File
@@ -0,0 +1,40 @@
<navigation-bar title="我的优惠券" color="#2d2430" background="#fff7f8" bindback="handleBack"></navigation-bar>
<view class="page-shell coupons-page">
<view class="page-content">
<view wx:if="{{!isLoggedIn}}" class="page-card empty-card">
<text class="empty-title">登录后查看优惠券</text>
<text class="empty-desc">可用优惠、VIP 自动折扣都会统一展示在这里。</text>
<view class="ghost-btn" bindtap="handleOpenAuth">去登录</view>
</view>
<block wx:elif="{{coupons.length}}">
<view class="page-hero coupons-hero">
<text class="hero-kicker">优惠资产</text>
<text class="hero-title">当前有 {{coupons.length}} 张可查看</text>
<text class="hero-desc">普通优惠券和系统自动匹配的 VIP 折扣都会在结算前统一展示。</text>
</view>
<view wx:for="{{coupons}}" wx:key="id" class="page-card coupon-card">
<view class="coupon-top">
<view>
<view class="coupon-title">{{item.couponName}}</view>
<view class="coupon-source">{{item.sourceText}}</view>
</view>
<view class="coupon-status">{{item.statusName || '待使用'}}</view>
</view>
<view class="coupon-benefit">{{item.benefitText}}</view>
<view class="coupon-period">{{item.periodText}}</view>
</view>
</block>
<view wx:elif="{{loading}}" class="page-card empty-card">
<text class="empty-title">正在加载优惠内容</text>
</view>
<view wx:else class="page-card empty-card">
<text class="empty-title">你还没有优惠券</text>
<text class="empty-desc">下单前系统也会自动帮你匹配最合适的优惠方式。</text>
</view>
</view>
</view>
+58
View File
@@ -0,0 +1,58 @@
.coupons-hero {
margin-bottom: 20rpx;
}
.coupon-card + .coupon-card {
margin-top: 20rpx;
}
.coupon-card {
padding: 26rpx 28rpx;
background: linear-gradient(135deg, #fff8fa 0%, #fff1f5 100%);
}
.coupon-top {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 20rpx;
}
.coupon-title {
font-size: 30rpx;
font-weight: 700;
color: #2d2430;
}
.coupon-source {
margin-top: 10rpx;
font-size: 22rpx;
color: #8d7a84;
}
.coupon-status {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 140rpx;
height: 52rpx;
padding: 0 18rpx;
border-radius: 999rpx;
background: rgba(255, 255, 255, 0.8);
color: #c6597d;
font-size: 22rpx;
font-weight: 700;
}
.coupon-benefit {
margin-top: 26rpx;
font-size: 42rpx;
font-weight: 800;
color: #d5536f;
}
.coupon-period {
margin-top: 18rpx;
font-size: 24rpx;
color: #8d7a84;
}
+223
View File
@@ -0,0 +1,223 @@
const auth = require('../../utils/auth')
const navigation = require('../../utils/navigation')
const { buildProductCards } = require('../../utils/product')
const { resolveImageList } = require('../../utils/file')
const { DEFAULT_SHOP_IMAGE } = require('../../utils/config')
const productApi = require('../../api/product')
const shopApi = require('../../api/shop')
const userApi = require('../../api/user')
Page({
data: {
initialized: false,
loading: false,
isLoggedIn: false,
userInfo: null,
greeting: '欢迎来到 Yumi Nail',
displayName: '先看看门店和作品',
searchKeyword: '',
bannerImages: [],
featuredItems: [],
popularSource: [],
popularItems: [],
popularPage: 1,
pageSize: 6,
hasMore: false
},
onLoad() {
this.loadHomeData()
},
onShow() {
this.syncUserState()
if (this.data.initialized && this.data.isLoggedIn) {
this.loadUserProfile()
}
},
async onPullDownRefresh() {
await this.loadHomeData()
wx.stopPullDownRefresh()
},
onReachBottom() {
if (!this.data.hasMore) {
return
}
const nextPage = this.data.popularPage + 1
const nextItems = this.data.popularSource.slice(0, nextPage * this.data.pageSize)
this.setData({
popularPage: nextPage,
popularItems: nextItems,
hasMore: nextItems.length < this.data.popularSource.length
})
},
syncUserState() {
const app = getApp()
const userInfo = auth.getStoredUserInfo()
const isLoggedIn = auth.isLoggedIn()
if (app) {
app.globalData.userInfo = userInfo
app.globalData.isLoggedIn = isLoggedIn
}
this.setData({
isLoggedIn,
userInfo,
greeting: isLoggedIn ? '欢迎回来' : '游客模式',
displayName: isLoggedIn
? ((userInfo && userInfo.nickname) || 'Yumi 用户')
: '先逛逛喜欢的款式和门店'
})
},
async loadUserProfile() {
if (!auth.isLoggedIn()) {
this.syncUserState()
return
}
try {
const userInfo = await userApi.getUserInfo()
getApp().refreshUserInfo(userInfo)
this.syncUserState()
} catch (error) {}
},
async loadHomeData() {
this.setData({ loading: true })
this.syncUserState()
try {
await Promise.all([
this.loadUserProfile(),
this.loadBannerImages(),
this.loadFeaturedProducts(),
this.loadPopularProducts()
])
this.setData({
initialized: true
})
} catch (error) {
wx.showToast({
title: error.message || '首页加载失败',
icon: 'none'
})
} finally {
this.setData({ loading: false })
}
},
async loadBannerImages() {
const shops = await shopApi.getPublicShops()
const list = Array.isArray(shops) ? shops : []
const banners = []
for (let index = 0; index < list.length; index += 1) {
const shop = list[index]
const imageIds = shop.coverImageFileId || shop.imageFileIds
const urls = await resolveImageList(imageIds, DEFAULT_SHOP_IMAGE)
if (urls[0]) {
banners.push({
id: `${shop.id}-${index}`,
shopId: shop.id,
shopName: shop.shopName,
businessHours: shop.businessHours || '欢迎到店体验',
imageUrl: urls[0]
})
}
}
this.setData({
bannerImages: banners.slice(0, 6)
})
},
async loadFeaturedProducts() {
let products = await productApi.getProductsByTag('精选')
if (!Array.isArray(products) || !products.length) {
products = await productApi.getAllProducts()
}
const cards = await buildProductCards((products || []).slice(0, 6))
this.setData({
featuredItems: cards
})
},
async loadPopularProducts() {
let products = await productApi.getProductsByTag('热门')
if (!Array.isArray(products) || !products.length) {
products = await productApi.getAllProducts()
}
const cards = await buildProductCards(products || [])
const initialItems = cards.slice(0, this.data.pageSize)
this.setData({
popularSource: cards,
popularItems: initialItems,
popularPage: 1,
hasMore: initialItems.length < cards.length
})
},
handleSearchInput(event) {
this.setData({
searchKeyword: event.detail.value
})
},
handleSearchConfirm() {
navigation.openProducts({
keyword: this.data.searchKeyword.trim()
})
},
handleBannerTap(event) {
const shopId = event.currentTarget.dataset.shopId
if (!shopId) {
return
}
navigation.navigate('/pages/shop-detail/index', {
id: shopId,
returnTo: navigation.getCurrentPageUrl()
})
},
handleProfileTap() {
if (this.data.isLoggedIn) {
navigation.switchTab('/pages/profile/index')
return
}
navigation.openAuth()
},
handleProductSelect(event) {
const product = event.detail || {}
if (!product.id) {
return
}
navigation.navigate('/pages/product-detail/index', {
id: product.id
})
},
handleSeeAllFeatured() {
navigation.openProducts({
tag: '精选'
})
},
handleSeeAllPopular() {
navigation.openProducts({
tag: '热门'
})
}
})
+7
View File
@@ -0,0 +1,7 @@
{
"usingComponents": {
"navigation-bar": "/components/navigation-bar/navigation-bar",
"product-card": "/components/product-card/product-card"
},
"enablePullDownRefresh": true
}
+137
View File
@@ -0,0 +1,137 @@
<view class="home-page-root">
<navigation-bar title="Yumi Nail" back="{{false}}" color="#2d2430" background="#fff7f8"></navigation-bar>
<scroll-view class="home-scroll" scroll-y enable-flex enhanced show-scrollbar="false">
<view class="page-shell home-page">
<view class="page-content">
<view class="page-hero home-hero">
<text class="hero-kicker">{{isLoggedIn ? greeting : 'YUMI NAIL 小程序'}}</text>
<text class="hero-title">{{displayName}}</text>
<text class="hero-desc">先看门店氛围,再挑喜欢的作品,最后一站式完成收藏、加购和预约。</text>
<view class="hero-action-row">
<view class="hero-action primary" bindtap="handleProfileTap">{{isLoggedIn ? '进入个人中心' : '立即登录'}}</view>
<view class="hero-action secondary" bindtap="handleSeeAllPopular">看看热门作品</view>
</view>
<view class="search-box">
<input
class="search-input"
placeholder="搜索作品、风格或门店"
placeholder-class="field-placeholder"
value="{{searchKeyword}}"
bindinput="handleSearchInput"
bindconfirm="handleSearchConfirm"
confirm-type="search"
/>
<view class="search-btn" bindtap="handleSearchConfirm">搜索</view>
</view>
<view class="summary-strip">
<view class="summary-metric">
<text class="summary-label">门店橱窗</text>
<text class="summary-value">{{bannerImages.length ? bannerImages.length : 0}} 家</text>
<text class="summary-note">先看环境,再决定去哪家</text>
</view>
<view class="summary-metric">
<text class="summary-label">精选作品</text>
<text class="summary-value">{{featuredItems.length ? featuredItems.length : 0}} 款</text>
<text class="summary-note">适合快速找到灵感</text>
</view>
<view class="summary-metric">
<text class="summary-label">热门推荐</text>
<text class="summary-value">{{popularItems.length ? popularItems.length : 0}} 条</text>
<text class="summary-note">当前最受欢迎的预约款式</text>
</view>
</view>
<view wx:if="{{!isLoggedIn}}" class="guest-tip">
登录后可同步收藏、购物车和预约记录,切换设备也不会丢。
</view>
</view>
<view class="section-block">
<view class="section-head">
<view class="section-copy">
<text class="section-kicker">门店氛围</text>
<text class="section-title">先看看线下环境</text>
<text class="section-subtitle">轮播展示门店图片和营业时间,帮助你快速判断想去的店。</text>
</view>
</view>
<view wx:if="{{bannerImages.length}}" class="banner-box page-card">
<swiper class="banner-swiper" indicator-dots autoplay circular interval="3200">
<swiper-item wx:for="{{bannerImages}}" wx:key="id">
<view class="banner-item" data-shop-id="{{item.shopId}}" bindtap="handleBannerTap">
<image class="banner-image" src="{{item.imageUrl}}" mode="aspectFill"></image>
<view class="banner-mask">
<view class="banner-badge">门店实拍</view>
<view class="banner-title">{{item.shopName}}</view>
<view class="banner-desc">{{item.businessHours}}</view>
</view>
</view>
</swiper-item>
</swiper>
</view>
<view wx:else class="page-card empty-card">
<text class="empty-title">门店内容正在补充中</text>
<text class="empty-desc">可以先浏览精选作品,稍后再回来查看门店环境展示。</text>
</view>
</view>
<view class="section-block">
<view class="section-head">
<view class="section-copy">
<text class="section-kicker">快速入门</text>
<text class="section-title">精选作品</text>
<text class="section-subtitle">适合先快速逛一圈的热门款式,向右滑动查看更多。</text>
</view>
<view class="section-link" bindtap="handleSeeAllFeatured">查看全部</view>
</view>
<view wx:if="{{featuredItems.length}}" class="featured-panel">
<scroll-view class="featured-scroll" scroll-x enable-flex>
<view class="featured-list">
<view wx:for="{{featuredItems}}" wx:key="id" class="featured-card">
<product-card item="{{item}}" bindselect="handleProductSelect"></product-card>
</view>
</view>
</scroll-view>
</view>
<view wx:else class="page-card empty-card">
<text class="empty-title">精选作品正在整理中</text>
<text class="empty-desc">等门店补齐款式后,这里会优先展示最值得先看的内容。</text>
</view>
</view>
<view class="section-block">
<view class="section-head">
<view class="section-copy">
<text class="section-kicker">热门预约</text>
<text class="section-title">最近大家都在看</text>
<text class="section-subtitle">结合点赞和收藏热度展示当前最受欢迎的款式。</text>
</view>
<view class="section-link" bindtap="handleSeeAllPopular">查看全部</view>
</view>
<view wx:if="{{popularItems.length}}" class="popular-grid">
<view wx:for="{{popularItems}}" wx:key="id" class="popular-card">
<product-card item="{{item}}" show-stats="{{true}}" bindselect="handleProductSelect"></product-card>
</view>
</view>
<view wx:elif="{{loading}}" class="page-card empty-card">
<text class="empty-title">正在加载首页内容</text>
</view>
<view wx:else class="page-card empty-card">
<text class="empty-title">还没有热门作品</text>
<text class="empty-desc">当前门店还在补充作品数据,稍后再回来看看。</text>
</view>
</view>
</view>
</view>
</scroll-view>
</view>
+150
View File
@@ -0,0 +1,150 @@
.home-page-root {
height: 100vh;
display: flex;
flex-direction: column;
overflow: hidden;
}
.home-scroll {
flex: 1;
min-height: 0;
}
.home-page {
min-height: 100%;
background:
radial-gradient(circle at top right, rgba(255, 196, 214, 0.4), transparent 36%),
linear-gradient(180deg, #fff7f8 0%, #fffdfb 100%);
}
.home-hero {
background:
radial-gradient(circle at top right, rgba(255, 186, 207, 0.5), transparent 36%),
linear-gradient(145deg, #fffdfd 0%, #fff2f6 52%, #ffe8ef 100%);
}
.search-box {
display: flex;
align-items: center;
gap: 16rpx;
margin-top: 30rpx;
padding: 10rpx;
border-radius: 999rpx;
background: rgba(255, 255, 255, 0.92);
}
.search-input {
flex: 1;
height: 72rpx;
padding: 0 24rpx;
font-size: 28rpx;
color: #2d2430;
}
.search-btn {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 150rpx;
height: 72rpx;
border-radius: 999rpx;
background: linear-gradient(135deg, #ff8cb0 0%, #c6597d 100%);
color: #ffffff;
font-size: 26rpx;
font-weight: 700;
}
.guest-tip {
margin-top: 24rpx;
padding: 20rpx 24rpx;
border-radius: 22rpx;
background: rgba(255, 255, 255, 0.85);
color: #8d7a84;
font-size: 24rpx;
line-height: 1.7;
}
.banner-box {
overflow: hidden;
border-radius: 34rpx;
}
.banner-swiper,
.banner-item {
width: 100%;
height: 396rpx;
}
.banner-item {
position: relative;
}
.banner-image {
width: 100%;
height: 100%;
}
.banner-mask {
position: absolute;
left: 24rpx;
right: 24rpx;
bottom: 24rpx;
padding: 22rpx 24rpx;
border-radius: 24rpx;
background: rgba(255, 255, 255, 0.9);
}
.banner-badge {
display: inline-flex;
align-items: center;
justify-content: center;
padding: 8rpx 18rpx;
border-radius: 999rpx;
background: #fce8ef;
color: #c6597d;
font-size: 22rpx;
font-weight: 700;
}
.banner-title {
margin-top: 14rpx;
font-size: 34rpx;
font-weight: 700;
color: #2d2430;
}
.banner-desc {
margin-top: 8rpx;
font-size: 24rpx;
color: #8d7a84;
}
.featured-panel {
padding: 2rpx 0 4rpx;
}
.featured-scroll {
width: 100%;
white-space: nowrap;
}
.featured-list {
display: inline-flex;
gap: 18rpx;
padding: 4rpx 2rpx 12rpx;
}
.featured-card {
width: 332rpx;
}
.popular-grid {
display: flex;
flex-wrap: wrap;
gap: 18rpx;
padding-top: 2rpx;
}
.popular-card {
width: calc(50% - 9rpx);
}
+7
View File
@@ -0,0 +1,7 @@
Page({
onLoad() {
wx.switchTab({
url: '/pages/home/index'
})
}
})
+5
View File
@@ -0,0 +1,5 @@
{
"usingComponents": {
"navigation-bar": "/components/navigation-bar/navigation-bar"
}
}
+7
View File
@@ -0,0 +1,7 @@
<navigation-bar title="Yumi Nail" back="{{false}}" color="#2d2430" background="#fff7f8"></navigation-bar>
<view class="redirect-page">
<view class="redirect-card">
<view class="redirect-title">正在进入首页</view>
<view class="redirect-desc">这个 `pages/index` 是初始化遗留页,当前实际首页是 `pages/home/index`。</view>
</view>
</view>
+33
View File
@@ -0,0 +1,33 @@
page {
height: 100vh;
background: #fff7f8;
}
.redirect-page {
min-height: calc(100vh - 88rpx);
display: flex;
align-items: center;
justify-content: center;
padding: 32rpx;
}
.redirect-card {
width: 100%;
padding: 40rpx 32rpx;
border-radius: 28rpx;
background: #ffffff;
box-shadow: 0 18rpx 50rpx rgba(122, 67, 88, 0.08);
}
.redirect-title {
font-size: 34rpx;
font-weight: 700;
color: #2d2430;
}
.redirect-desc {
margin-top: 18rpx;
font-size: 24rpx;
line-height: 1.7;
color: #8d7a84;
}
+108
View File
@@ -0,0 +1,108 @@
const orderApi = require('../../api/order')
const auth = require('../../utils/auth')
const navigation = require('../../utils/navigation')
const { resolveLegacyImage } = require('../../utils/file')
const { formatDateTime, formatPrice, getOrderStatusClass, getOrderStatusText } = require('../../utils/format')
const { runWithLoading } = require('../../utils/loading')
Page({
data: {
loading: false,
isLoggedIn: false,
orders: []
},
onShow() {
this.loadOrders()
},
async loadOrders() {
const isLoggedIn = auth.isLoggedIn()
this.setData({
isLoggedIn,
loading: isLoggedIn
})
if (!isLoggedIn) {
this.setData({
orders: [],
loading: false
})
return
}
try {
const orders = await orderApi.getOrderList()
const list = Array.isArray(orders) ? orders : []
const formattedOrders = await Promise.all(list.map(async order => ({
...order,
statusText: getOrderStatusText(order),
statusClass: getOrderStatusClass(order),
actualAmountText: `¥${formatPrice(order.actualAmount)}`,
items: await Promise.all((order.items || []).map(async item => ({
...item,
productImageUrl: await resolveLegacyImage(item.productImage),
priceText: `¥${formatPrice(item.price)}`,
appointmentText: formatDateTime(item.appointmentTime)
})))
})))
this.setData({
orders: formattedOrders
})
} catch (error) {
this.setData({
orders: []
})
wx.showToast({
title: error.message || '订单列表加载失败',
icon: 'none'
})
} finally {
this.setData({
loading: false
})
}
},
handleOpenAuth() {
navigation.openAuth('/pages/orders/index')
},
handleBack() {
navigation.goBack('/pages/profile/index')
},
async handleCancelOrder(event) {
const orderId = event.currentTarget.dataset.orderId
if (!orderId) {
return
}
const result = await new Promise(resolve => {
wx.showModal({
title: '取消订单',
content: '确认取消这笔订单吗?',
success: modalRes => resolve(Boolean(modalRes.confirm))
})
})
if (!result) {
return
}
try {
await runWithLoading(() => orderApi.cancelOrder(orderId))
wx.showToast({
title: '订单已取消',
icon: 'none'
})
this.loadOrders()
} catch (error) {
wx.showToast({
title: error.message || '取消订单失败',
icon: 'none'
})
}
}
})
+5
View File
@@ -0,0 +1,5 @@
{
"usingComponents": {
"navigation-bar": "/components/navigation-bar/navigation-bar"
}
}
+53
View File
@@ -0,0 +1,53 @@
<navigation-bar title="我的订单" color="#2d2430" background="#fff7f8" bindback="handleBack"></navigation-bar>
<view class="page-shell orders-page">
<view class="page-content">
<view wx:if="{{!isLoggedIn}}" class="page-card empty-card">
<text class="empty-title">登录后查看订单</text>
<text class="empty-desc">预约状态、取消进度和服务记录都会展示在这里。</text>
<view class="ghost-btn" bindtap="handleOpenAuth">去登录</view>
</view>
<block wx:elif="{{orders.length}}">
<view class="page-hero orders-hero">
<text class="hero-kicker">预约记录</text>
<text class="hero-title">共 {{orders.length}} 笔订单</text>
<text class="hero-desc">这里展示每笔订单的状态、项目、预约时间以及取消入口。</text>
</view>
<view wx:for="{{orders}}" wx:key="id" class="page-card order-card">
<view class="order-head">
<view class="order-head-copy">
<text class="order-label">订单号</text>
<text class="order-no">{{item.orderNo}}</text>
</view>
<text class="order-status {{item.statusClass}}">{{item.statusText}}</text>
</view>
<view wx:for="{{item.items}}" wx:key="id" wx:for-item="orderItem" class="order-item">
<image class="order-thumb" src="{{orderItem.productImageUrl}}" mode="aspectFill"></image>
<view class="order-main">
<view class="order-title">{{orderItem.productTitle}}</view>
<view class="order-line">{{orderItem.priceText}} x {{orderItem.quantity}}</view>
<view wx:if="{{orderItem.artistName}}" class="order-line">美甲师:{{orderItem.artistName}}</view>
<view wx:if="{{orderItem.appointmentText}}" class="order-line">预约时间:{{orderItem.appointmentText}}</view>
</view>
</view>
<view class="order-foot">
<text class="order-amount">总计:{{item.actualAmountText}}</text>
<view wx:if="{{item.status == 1}}" class="cancel-btn" data-order-id="{{item.id}}" bindtap="handleCancelOrder">取消订单</view>
</view>
</view>
</block>
<view wx:elif="{{loading}}" class="page-card empty-card">
<text class="empty-title">正在加载订单</text>
</view>
<view wx:else class="page-card empty-card">
<text class="empty-title">你还没有订单</text>
<text class="empty-desc">选到喜欢的款式后,加入购物车即可发起预约。</text>
</view>
</view>
</view>
+126
View File
@@ -0,0 +1,126 @@
.orders-hero {
margin-bottom: 20rpx;
}
.order-card + .order-card {
margin-top: 20rpx;
}
.order-card {
padding: 26rpx;
}
.order-head,
.order-foot {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 18rpx;
}
.order-head {
padding-bottom: 18rpx;
border-bottom: 2rpx solid #f3e7eb;
}
.order-head-copy {
flex: 1;
min-width: 0;
}
.order-label {
display: block;
font-size: 22rpx;
color: #8d7a84;
}
.order-no {
display: block;
margin-top: 10rpx;
font-size: 24rpx;
line-height: 1.6;
color: #5d4b55;
}
.order-status {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 120rpx;
height: 48rpx;
padding: 0 16rpx;
border-radius: 999rpx;
font-size: 22rpx;
font-weight: 700;
}
.order-status.pending {
background: #fff6e8;
color: #cb7b00;
}
.order-status.completed {
background: #ecfbf3;
color: #2ea36f;
}
.order-status.cancelled {
background: #fff1f5;
color: #d5536f;
}
.order-item {
display: flex;
gap: 18rpx;
margin-top: 22rpx;
}
.order-thumb {
width: 132rpx;
height: 132rpx;
border-radius: 20rpx;
background: #f6edf1;
}
.order-main {
flex: 1;
}
.order-title {
font-size: 28rpx;
font-weight: 700;
color: #2d2430;
line-height: 1.5;
}
.order-line {
margin-top: 10rpx;
font-size: 24rpx;
color: #8d7a84;
line-height: 1.6;
}
.order-foot {
margin-top: 24rpx;
align-items: center;
}
.order-amount {
font-size: 28rpx;
font-weight: 700;
color: #2d2430;
}
.cancel-btn {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 144rpx;
height: 60rpx;
padding: 0 18rpx;
border-radius: 999rpx;
background: #fff1f5;
color: #d5536f;
font-size: 24rpx;
font-weight: 700;
}
+301
View File
@@ -0,0 +1,301 @@
const cartApi = require('../../api/cart')
const productApi = require('../../api/product')
const productLikeApi = require('../../api/product-like')
const shopApi = require('../../api/shop')
const wishlistApi = require('../../api/wishlist')
const auth = require('../../utils/auth')
const navigation = require('../../utils/navigation')
const { resolveImageList } = require('../../utils/file')
const { DEFAULT_PRODUCT_IMAGE } = require('../../utils/config')
const { formatPrice, getProductTitle, splitCsv } = require('../../utils/format')
const { runWithLoading } = require('../../utils/loading')
function parseTimeRange(businessHours) {
if (!businessHours) {
return null
}
const matched = String(businessHours).replace(/\s+/g, '').match(/(\d{1,2}:\d{2}).*?(\d{1,2}:\d{2})/)
if (!matched) {
return null
}
return {
start: matched[1],
end: matched[2]
}
}
function estimateEarliestBookable(businessHours) {
const range = parseTimeRange(businessHours)
if (!range) {
return businessHours || '以门店安排为准'
}
const next = new Date(Date.now() + 30 * 60 * 1000)
const openTime = new Date(next)
const closeTime = new Date(next)
const startParts = range.start.split(':').map(Number)
const endParts = range.end.split(':').map(Number)
openTime.setHours(startParts[0], startParts[1], 0, 0)
closeTime.setHours(endParts[0], endParts[1], 0, 0)
if (next <= openTime) {
return `今天 ${range.start}`
}
if (next >= closeTime) {
return `明天 ${range.start}`
}
const month = String(next.getMonth() + 1).padStart(2, '0')
const date = String(next.getDate()).padStart(2, '0')
const hour = String(next.getHours()).padStart(2, '0')
const minute = String(next.getMinutes()).padStart(2, '0')
return `${month}-${date} ${hour}:${minute}`
}
Page({
data: {
loading: true,
loadError: '',
productId: '',
product: null,
productImages: [],
shopInfo: null,
isFavorite: false,
isLiked: false,
artistCountText: '门店安排',
earliestBookableText: '以门店安排为准'
},
onLoad(options) {
this.setData({
productId: options && options.id ? options.id : ''
})
this.loadProductDetail()
},
async onPullDownRefresh() {
await this.loadProductDetail()
wx.stopPullDownRefresh()
},
async loadProductDetail() {
const productId = this.data.productId
if (!productId) {
this.setData({
loading: false,
loadError: '作品 ID 不存在'
})
return
}
this.setData({
loading: true,
loadError: ''
})
try {
const product = await productApi.getProductById(productId)
const productImages = await resolveImageList(product.imageFileIds, DEFAULT_PRODUCT_IMAGE)
const shopInfo = product.shopId ? await shopApi.getShopById(product.shopId) : null
const artistCount = typeof product.availableBookableArtistCount === 'number'
? product.availableBookableArtistCount
: splitCsv(product.bookableArtists).length
const formattedProduct = {
...product,
displayTitle: getProductTitle(product),
priceText: `¥${formatPrice(product.price)}`,
descriptionText: product.description || '店家还没有补充作品说明。'
}
this.setData({
product: formattedProduct,
productImages,
shopInfo,
artistCountText: artistCount > 0 ? `${artistCount} 位可预约` : (product.bookableArtistRestricted ? '暂时没有' : '门店安排'),
earliestBookableText: estimateEarliestBookable(shopInfo && shopInfo.businessHours)
})
if (auth.isLoggedIn()) {
this.loadInteractionStatus()
} else {
this.setData({
isFavorite: false,
isLiked: false
})
}
} catch (error) {
this.setData({
loadError: error.message || '作品详情加载失败'
})
} finally {
this.setData({
loading: false
})
}
},
async loadInteractionStatus() {
const product = this.data.product
if (!product || !product.id) {
return
}
try {
const [isFavorite, isLiked] = await Promise.all([
wishlistApi.checkWishlist(product.id),
productLikeApi.checkLikeStatus(product.id)
])
this.setData({
isFavorite: Boolean(isFavorite),
isLiked: Boolean(isLiked)
})
} catch (error) {}
},
handleBack() {
navigation.goBack('/pages/products/index')
},
handlePreviewImage(event) {
const current = event.currentTarget.dataset.url
if (!current) {
return
}
wx.previewImage({
current,
urls: this.data.productImages
})
},
handleOpenShop() {
const shopInfo = this.data.shopInfo
if (!shopInfo || !shopInfo.id) {
return
}
navigation.navigate('/pages/shop-detail/index', {
id: shopInfo.id,
returnTo: navigation.getCurrentPageUrl()
})
},
async handleToggleFavorite() {
const product = this.data.product
if (!product || !product.id || !navigation.ensureLogin('收藏作品')) {
return
}
try {
const nextFavorite = !this.data.isFavorite
if (this.data.isFavorite) {
await runWithLoading(() => wishlistApi.removeFromWishlist(product.id))
product.collectCount = Math.max(0, Number(product.collectCount || 0) - 1)
} else {
await runWithLoading(() => wishlistApi.addToWishlist(product.id))
product.collectCount = Number(product.collectCount || 0) + 1
}
this.setData({
isFavorite: nextFavorite,
product
})
wx.showToast({
title: nextFavorite ? '已加入收藏' : '已取消收藏',
icon: 'none'
})
} catch (error) {
wx.showToast({
title: error.message || '收藏操作失败',
icon: 'none'
})
}
},
async handleToggleLike() {
const product = this.data.product
if (!product || !product.id || !navigation.ensureLogin('点赞作品')) {
return
}
try {
const nextLiked = !this.data.isLiked
if (this.data.isLiked) {
await runWithLoading(() => productLikeApi.unlikeProduct(product.id))
product.likeCount = Math.max(0, Number(product.likeCount || 0) - 1)
} else {
await runWithLoading(() => productLikeApi.likeProduct(product.id))
product.likeCount = Number(product.likeCount || 0) + 1
}
this.setData({
isLiked: nextLiked,
product
})
wx.showToast({
title: nextLiked ? '已点赞' : '已取消点赞',
icon: 'none'
})
} catch (error) {
wx.showToast({
title: error.message || '点赞操作失败',
icon: 'none'
})
}
},
async handleAddToCart() {
const product = this.data.product
if (!product || !product.id || !navigation.ensureLogin('加购')) {
return
}
try {
await runWithLoading(() => cartApi.addToCart({
productId: product.id,
quantity: 1
}))
await getApp().updateCartBadge()
wx.showToast({
title: '已加入购物车',
icon: 'none'
})
} catch (error) {
wx.showToast({
title: error.message || '加入购物车失败',
icon: 'none'
})
}
},
async handleBuyNow() {
const product = this.data.product
if (!product || !product.id || !navigation.ensureLogin('预约下单')) {
return
}
try {
await runWithLoading(() => cartApi.addToCart({
productId: product.id,
quantity: 1
}))
await getApp().updateCartBadge()
wx.switchTab({
url: '/pages/cart/index'
})
} catch (error) {
wx.showToast({
title: error.message || '操作失败',
icon: 'none'
})
}
}
})
@@ -0,0 +1,5 @@
{
"usingComponents": {
"navigation-bar": "/components/navigation-bar/navigation-bar"
}
}
@@ -0,0 +1,88 @@
<navigation-bar title="{{product ? product.displayTitle : '作品详情'}}" color="#2d2430" background="#fff7f8" bindback="handleBack"></navigation-bar>
<view class="page-shell detail-page">
<view wx:if="{{loadError}}" class="page-content">
<view class="page-card empty-card">
<text class="empty-title">暂时无法查看作品详情</text>
<text class="empty-desc">{{loadError}}</text>
<view class="ghost-btn" bindtap="handleBack">返回上一页</view>
</view>
</view>
<block wx:elif="{{product}}">
<view class="media-box">
<swiper class="media-swiper" indicator-dots autoplay circular>
<swiper-item wx:for="{{productImages}}" wx:key="*this">
<image class="media-image" src="{{item}}" mode="aspectFill" data-url="{{item}}" bindtap="handlePreviewImage"></image>
</swiper-item>
</swiper>
<view class="media-mask">
<view class="media-badges">
<view class="chip">{{product.approximateDuration || '时长待确认'}}</view>
<view class="soft-chip">{{artistCountText}}</view>
</view>
</view>
</view>
<view class="page-content detail-content">
<view class="page-card info-card">
<view class="detail-head">
<text class="section-kicker">作品详情</text>
<view class="product-title">{{product.displayTitle}}</view>
<view class="product-price">{{product.priceText}}</view>
<view class="product-brief">适合先看作品风格、门店信息和可预约情况,再决定是否立即下单。</view>
</view>
<view class="summary-strip detail-summary">
<view class="summary-metric" bindtap="handleOpenShop">
<text class="summary-label">所属门店</text>
<text class="summary-value detail-summary-value">{{shopInfo ? shopInfo.shopName : '待绑定'}}</text>
<text class="summary-note">点击查看门店详情</text>
</view>
<view class="summary-metric">
<text class="summary-label">可约美甲师</text>
<text class="summary-value detail-summary-value">{{artistCountText}}</text>
<text class="summary-note">预约前可在购物车继续选择</text>
</view>
<view class="summary-metric">
<text class="summary-label">最早可约</text>
<text class="summary-value detail-summary-value">{{earliestBookableText}}</text>
<text class="summary-note">以门店营业时间为准</text>
</view>
</view>
<view wx:if="{{shopInfo}}" class="shop-box" bindtap="handleOpenShop">
<view class="shop-box-head">
<view class="shop-name">{{shopInfo.shopName}}</view>
<view class="shop-link">查看门店</view>
</view>
<view class="shop-meta">{{shopInfo.address || '门店地址待补充'}}</view>
<view class="shop-meta">{{shopInfo.businessHours || '营业时间待补充'}}</view>
</view>
<view class="actions-row">
<view class="action-pill {{isLiked ? 'active' : ''}}" bindtap="handleToggleLike">
点赞 {{product.likeCount || 0}}
</view>
<view class="action-pill {{isFavorite ? 'active' : ''}}" bindtap="handleToggleFavorite">
收藏 {{product.collectCount || 0}}
</view>
</view>
<view wx:if="{{product.tagInfos && product.tagInfos.length}}" class="tags-wrap">
<view wx:for="{{product.tagInfos}}" wx:key="id" class="tag-chip">{{item.tagName}}</view>
</view>
<view class="desc-block">
<view class="section-title">款式说明</view>
<view class="desc-text">{{product.descriptionText}}</view>
</view>
</view>
</view>
<view class="footer-bar">
<view class="footer-btn secondary" bindtap="handleAddToCart">加入购物车</view>
<view class="footer-btn primary" bindtap="handleBuyNow">立即预约</view>
</view>
</block>
</view>
@@ -0,0 +1,193 @@
.detail-page {
padding-bottom: calc(env(safe-area-inset-bottom) + 160rpx);
}
.media-box {
position: relative;
overflow: hidden;
border-radius: 0 0 40rpx 40rpx;
}
.media-swiper,
.media-image {
width: 100%;
height: 640rpx;
}
.media-mask {
position: absolute;
left: 24rpx;
right: 24rpx;
bottom: 28rpx;
}
.media-badges {
display: flex;
flex-wrap: wrap;
gap: 12rpx;
}
.detail-content {
margin-top: -48rpx;
}
.info-card {
padding: 32rpx 30rpx;
}
.detail-head {
padding-bottom: 10rpx;
}
.product-title {
margin-top: 16rpx;
font-size: 42rpx;
font-weight: 700;
line-height: 1.4;
color: #2d2430;
}
.product-price {
margin-top: 12rpx;
font-size: 38rpx;
font-weight: 700;
color: #d5536f;
}
.product-brief {
margin-top: 14rpx;
font-size: 24rpx;
line-height: 1.8;
color: #8d7a84;
}
.detail-summary {
margin-top: 24rpx;
}
.detail-summary-value {
font-size: 26rpx;
line-height: 1.5;
}
.shop-box {
margin-top: 28rpx;
padding: 24rpx;
border-radius: 24rpx;
background: linear-gradient(135deg, #fff8fa 0%, #fff1f5 100%);
}
.shop-box-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16rpx;
}
.shop-name {
font-size: 30rpx;
font-weight: 700;
color: #2d2430;
}
.shop-link {
font-size: 24rpx;
color: #c6597d;
font-weight: 700;
}
.shop-meta {
margin-top: 10rpx;
font-size: 24rpx;
color: #8d7a84;
line-height: 1.7;
}
.actions-row {
display: flex;
gap: 16rpx;
margin-top: 28rpx;
}
.action-pill {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 180rpx;
height: 68rpx;
padding: 0 24rpx;
border-radius: 999rpx;
background: #fbf5f7;
color: #7a5262;
font-size: 24rpx;
font-weight: 600;
}
.action-pill.active {
background: #fde8ef;
color: #c6597d;
}
.tags-wrap {
display: flex;
flex-wrap: wrap;
gap: 12rpx;
margin-top: 24rpx;
}
.tag-chip {
display: inline-flex;
align-items: center;
justify-content: center;
padding: 10rpx 18rpx;
border-radius: 999rpx;
background: #fbecf1;
color: #c6597d;
font-size: 22rpx;
}
.desc-block {
margin-top: 28rpx;
}
.desc-text {
margin-top: 16rpx;
font-size: 26rpx;
line-height: 1.8;
color: #5d4b55;
}
.footer-bar {
position: fixed;
left: 24rpx;
right: 24rpx;
bottom: calc(env(safe-area-inset-bottom) + 20rpx);
z-index: 20;
display: flex;
gap: 16rpx;
padding: 18rpx;
border-radius: 30rpx;
background: rgba(255, 255, 255, 0.96);
box-shadow: 0 18rpx 50rpx rgba(122, 67, 88, 0.12);
}
.footer-btn {
display: flex;
align-items: center;
justify-content: center;
flex: 1;
height: 88rpx;
border-radius: 999rpx;
font-size: 28rpx;
font-weight: 700;
}
.footer-btn.secondary {
background: #fbf5f7;
color: #7a5262;
}
.footer-btn.primary {
background: linear-gradient(135deg, #ff8cb0 0%, #c6597d 100%);
color: #ffffff;
}
+174
View File
@@ -0,0 +1,174 @@
const tagApi = require('../../api/tag')
const productApi = require('../../api/product')
const { buildProductCards } = require('../../utils/product')
const navigation = require('../../utils/navigation')
const { runWithLoading } = require('../../utils/loading')
Page({
data: {
initialized: false,
loading: false,
categories: ['全部'],
selectedCategory: '全部',
searchKeyword: '',
products: [],
activeBannerText: ''
},
onLoad(options) {
this.bootstrapPage(options || {})
},
onShow() {
const app = getApp()
const pendingFilter = app && app.globalData ? app.globalData.pendingProductFilter : null
if (this.data.initialized && pendingFilter && (pendingFilter.keyword || pendingFilter.tag)) {
if (app && app.globalData) {
app.globalData.pendingProductFilter = null
}
this.applyFilter(pendingFilter)
}
},
async onPullDownRefresh() {
await this.loadProducts()
wx.stopPullDownRefresh()
},
async bootstrapPage(options) {
this.setData({
loading: true
})
try {
await this.loadTags()
await this.applyInitialFilter(options)
this.setData({
initialized: true
})
} catch (error) {
wx.showToast({
title: error.message || '作品列表加载失败',
icon: 'none'
})
} finally {
this.setData({
loading: false
})
}
},
async loadTags() {
const tags = await tagApi.getAllTags()
const names = Array.isArray(tags) ? tags.map(item => item.tagName).filter(Boolean) : []
this.setData({
categories: ['全部'].concat(names)
})
},
async applyInitialFilter(options) {
const app = getApp()
const pendingFilter = app && app.globalData ? app.globalData.pendingProductFilter : null
if (pendingFilter && (pendingFilter.keyword || pendingFilter.tag)) {
if (app && app.globalData) {
app.globalData.pendingProductFilter = null
}
await this.applyFilter(pendingFilter)
return
}
await this.applyFilter(options || {})
},
async applyFilter(filter) {
const keyword = (filter.keyword || '').trim()
const tag = (filter.tag || '').trim()
this.setData({
searchKeyword: keyword,
selectedCategory: tag && this.data.categories.includes(tag) ? tag : '全部'
})
await this.loadProducts()
},
async loadProducts() {
this.setData({
loading: true
})
try {
let products = []
const keyword = this.data.searchKeyword.trim()
const tag = this.data.selectedCategory
if (keyword) {
products = await productApi.searchProducts(keyword)
} else if (tag !== '全部') {
products = await productApi.getProductsByTag(tag)
} else {
products = await productApi.getAllProducts()
}
const cards = await buildProductCards(products || [])
this.setData({
products: cards,
activeBannerText: keyword
? `正在显示“${keyword}”的搜索结果`
: (tag !== '全部' ? `当前按“${tag}”筛选` : '')
})
} catch (error) {
this.setData({
products: [],
activeBannerText: ''
})
wx.showToast({
title: error.message || '作品列表加载失败',
icon: 'none'
})
} finally {
this.setData({
loading: false
})
}
},
handleSearchInput(event) {
this.setData({
searchKeyword: event.detail.value
})
},
async handleSearchConfirm() {
this.setData({
selectedCategory: '全部'
})
await runWithLoading(() => this.loadProducts())
},
async handleSelectCategory(event) {
const category = event.currentTarget.dataset.category
this.setData({
selectedCategory: category,
searchKeyword: ''
})
await runWithLoading(() => this.loadProducts())
},
async handleResetFilters() {
this.setData({
selectedCategory: '全部',
searchKeyword: ''
})
await runWithLoading(() => this.loadProducts())
},
handleProductSelect(event) {
const product = event.detail || {}
if (!product.id) {
return
}
navigation.navigate('/pages/product-detail/index', {
id: product.id
})
}
})
+7
View File
@@ -0,0 +1,7 @@
{
"usingComponents": {
"navigation-bar": "/components/navigation-bar/navigation-bar",
"product-card": "/components/product-card/product-card"
},
"enablePullDownRefresh": true
}
+63
View File
@@ -0,0 +1,63 @@
<navigation-bar title="作品库" back="{{false}}" color="#2d2430" background="#fff7f8"></navigation-bar>
<view class="page-shell product-page">
<view class="page-content">
<view class="page-hero product-hero">
<text class="hero-kicker">作品筛选</text>
<text class="hero-title">{{selectedCategory !== '全部' ? selectedCategory : '找到适合你的美甲款式'}}</text>
<text class="hero-desc">{{activeBannerText ? activeBannerText : '按标签筛选或输入关键词搜索,先缩小范围,再挑喜欢的作品。'}}</text>
<view class="search-card">
<view class="search-row">
<input
class="search-input"
placeholder="搜索作品名称或关键词"
placeholder-class="field-placeholder"
value="{{searchKeyword}}"
bindinput="handleSearchInput"
bindconfirm="handleSearchConfirm"
confirm-type="search"
/>
<view class="search-btn" bindtap="handleSearchConfirm">搜索</view>
</view>
<scroll-view class="category-scroll" scroll-x enable-flex>
<view class="category-list">
<view
wx:for="{{categories}}"
wx:key="*this"
class="category-item {{selectedCategory === item ? 'active' : ''}}"
data-category="{{item}}"
bindtap="handleSelectCategory"
>
{{item}}
</view>
</view>
</scroll-view>
</view>
</view>
<view class="results-head">
<view class="results-count">{{products.length ? products.length : 0}} 个结果</view>
<view wx:if="{{searchKeyword || selectedCategory !== '全部'}}" class="ghost-btn results-reset" bindtap="handleResetFilters">重置筛选</view>
</view>
<view wx:if="{{activeBannerText}}" class="filter-banner">{{activeBannerText}}</view>
<view wx:if="{{products.length}}" class="product-grid">
<view wx:for="{{products}}" wx:key="id" class="product-grid-item">
<product-card item="{{item}}" show-stats="{{true}}" bindselect="handleProductSelect"></product-card>
</view>
</view>
<view wx:elif="{{loading}}" class="page-card empty-card">
<text class="empty-title">正在加载作品</text>
</view>
<view wx:else class="page-card empty-card">
<text class="empty-title">暂时没有匹配的作品</text>
<text class="empty-desc">可以换个关键词试试,或者先浏览全部作品。</text>
<view class="ghost-btn" bindtap="handleResetFilters">查看全部</view>
</view>
</view>
</view>
+117
View File
@@ -0,0 +1,117 @@
.product-page {
background:
radial-gradient(circle at top left, rgba(255, 207, 220, 0.35), transparent 34%),
linear-gradient(180deg, #fff8fa 0%, #fffdfc 100%);
}
.product-hero {
background:
radial-gradient(circle at top right, rgba(255, 194, 211, 0.42), transparent 34%),
linear-gradient(145deg, #fffdfd 0%, #fff3f7 56%, #ffe7ef 100%);
}
.search-card {
margin-top: 28rpx;
padding: 22rpx;
border-radius: 28rpx;
background: rgba(255, 255, 255, 0.78);
}
.search-row {
display: flex;
align-items: center;
gap: 14rpx;
}
.search-input {
flex: 1;
height: 76rpx;
padding: 0 24rpx;
border-radius: 999rpx;
background: #fbf5f7;
color: #2d2430;
font-size: 28rpx;
}
.search-btn {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 132rpx;
height: 76rpx;
border-radius: 999rpx;
background: linear-gradient(135deg, #ff8cb0 0%, #c6597d 100%);
color: #ffffff;
font-size: 26rpx;
font-weight: 700;
}
.category-scroll {
width: 100%;
margin-top: 24rpx;
white-space: nowrap;
}
.category-list {
display: inline-flex;
gap: 16rpx;
padding-bottom: 8rpx;
}
.category-item {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 120rpx;
height: 60rpx;
padding: 0 22rpx;
border-radius: 999rpx;
background: #f7edf1;
color: #8d7a84;
font-size: 24rpx;
font-weight: 600;
}
.category-item.active {
background: #fde8ef;
color: #c6597d;
}
.results-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16rpx;
margin-top: 24rpx;
}
.results-count {
font-size: 26rpx;
font-weight: 700;
color: #5d4b55;
}
.results-reset {
min-width: 0;
}
.filter-banner {
margin-top: 20rpx;
padding: 20rpx 24rpx;
border-radius: 22rpx;
background: #fff1f5;
color: #b45172;
font-size: 24rpx;
line-height: 1.7;
}
.product-grid {
display: flex;
flex-wrap: wrap;
gap: 18rpx;
margin-top: 24rpx;
}
.product-grid-item {
width: calc(50% - 9rpx);
}
+190
View File
@@ -0,0 +1,190 @@
const authApi = require('../../api/auth')
const couponApi = require('../../api/coupon')
const orderApi = require('../../api/order')
const userApi = require('../../api/user')
const wishlistApi = require('../../api/wishlist')
const auth = require('../../utils/auth')
const navigation = require('../../utils/navigation')
const { DEFAULT_AVATAR } = require('../../utils/config')
const { runWithLoading } = require('../../utils/loading')
Page({
data: {
isLoggedIn: false,
loading: false,
needSetPassword: false,
userInfo: null,
orderCount: 0,
couponCount: 0,
wishlistCount: 0,
defaultAvatar: DEFAULT_AVATAR
},
onShow() {
this.loadProfile()
},
async loadProfile() {
const isLoggedIn = auth.isLoggedIn()
this.setData({
isLoggedIn,
needSetPassword: auth.getNeedSetPassword(),
loading: isLoggedIn
})
if (!isLoggedIn) {
this.setData({
userInfo: null,
orderCount: 0,
couponCount: 0,
wishlistCount: 0,
loading: false
})
return
}
try {
const [userInfo, orders, coupons, wishlist] = await Promise.all([
userApi.getUserInfo(),
orderApi.getOrderList(),
couponApi.listUserCoupons(),
wishlistApi.getWishlist()
])
getApp().refreshUserInfo(userInfo)
this.setData({
userInfo,
orderCount: Array.isArray(orders) ? orders.length : 0,
couponCount: Array.isArray(coupons) ? coupons.length : 0,
wishlistCount: Array.isArray(wishlist) ? wishlist.length : 0
})
} catch (error) {
wx.showToast({
title: error.message || '个人中心加载失败',
icon: 'none'
})
} finally {
this.setData({
loading: false
})
}
},
handleOpenAuth() {
navigation.openAuth('/pages/profile/index')
},
handleOpenSettings() {
if (!this.data.isLoggedIn) {
this.handleOpenAuth()
return
}
navigation.navigate('/pages/settings/index')
},
handleOpenOrders() {
if (!navigation.ensureLogin('查看订单')) {
return
}
navigation.navigate('/pages/orders/index')
},
handleOpenWishlist() {
if (!navigation.ensureLogin('查看收藏')) {
return
}
navigation.navigate('/pages/wishlist/index')
},
handleOpenCoupons() {
if (!navigation.ensureLogin('查看优惠券')) {
return
}
navigation.navigate('/pages/coupons/index')
},
async handleSwitchShop() {
if (!navigation.ensureLogin('切换门店')) {
return
}
const userInfo = this.data.userInfo
const shopIds = userInfo && Array.isArray(userInfo.shopIds) ? userInfo.shopIds : []
const shopNames = userInfo && Array.isArray(userInfo.shopNames) ? userInfo.shopNames : []
if (!shopIds.length) {
wx.showToast({
title: '当前账号还没有可用门店',
icon: 'none'
})
return
}
if (shopIds.length === 1) {
navigation.navigate('/pages/shop-detail/index', {
id: shopIds[0],
returnTo: navigation.getCurrentPageUrl()
})
return
}
const selection = await new Promise(resolve => {
wx.showActionSheet({
itemList: shopNames.map((name, index) => name || `门店 ${shopIds[index]}`),
success: res => resolve(res.tapIndex),
fail: () => resolve(-1)
})
})
if (selection < 0 || selection >= shopIds.length) {
return
}
try {
const payload = await runWithLoading(() => authApi.switchShop({
shopId: shopIds[selection]
}))
getApp().setUserSession(payload)
wx.showToast({
title: '门店已切换',
icon: 'none'
})
this.loadProfile()
} catch (error) {
wx.showToast({
title: error.message || '门店切换失败',
icon: 'none'
})
}
},
async handleLogout() {
if (!this.data.isLoggedIn) {
this.handleOpenAuth()
return
}
const confirmed = await new Promise(resolve => {
wx.showModal({
title: '退出登录',
content: '退出后需要重新登录才能查看订单和继续下单。',
success: res => resolve(Boolean(res.confirm))
})
})
if (!confirmed) {
return
}
try {
await runWithLoading(() => authApi.logout())
} catch (error) {}
getApp().clearUserSession()
await this.loadProfile()
wx.showToast({
title: '已退出登录',
icon: 'none'
})
}
})
+5
View File
@@ -0,0 +1,5 @@
{
"usingComponents": {
"navigation-bar": "/components/navigation-bar/navigation-bar"
}
}
+87
View File
@@ -0,0 +1,87 @@
<view class="profile-page-root">
<navigation-bar title="个人中心" back="{{false}}" color="#ffffff" background="transparent"></navigation-bar>
<view class="profile-bg"></view>
<scroll-view class="profile-scroll" scroll-y enable-flex enhanced show-scrollbar="false">
<view class="page-shell profile-page">
<view class="page-content profile-content">
<view wx:if="{{!isLoggedIn}}" class="page-card guest-card">
<image class="guest-avatar" src="{{defaultAvatar}}" mode="aspectFill"></image>
<view class="guest-title">还没有登录账号</view>
<view class="guest-desc">登录后可以查看订单、收藏作品、领取和使用优惠。</view>
<view class="primary-btn" bindtap="handleOpenAuth">去登录</view>
</view>
<block wx:elif="{{userInfo}}">
<view class="page-card profile-card">
<view class="profile-top">
<image class="avatar" src="{{userInfo.avatar || defaultAvatar}}" mode="aspectFill"></image>
<view class="profile-copy">
<view class="nickname">{{userInfo.nickname || 'Yumi 用户'}}</view>
<view class="account">{{userInfo.account}}</view>
<view wx:if="{{userInfo.signature}}" class="signature">{{userInfo.signature}}</view>
</view>
</view>
<view class="summary-strip profile-stats">
<view class="summary-metric" bindtap="handleOpenOrders">
<text class="summary-label">订单</text>
<text class="summary-value">{{orderCount}}</text>
<text class="summary-note">查看预约记录</text>
</view>
<view class="summary-metric" bindtap="handleOpenWishlist">
<text class="summary-label">收藏</text>
<text class="summary-value">{{wishlistCount}}</text>
<text class="summary-note">回看喜欢的作品</text>
</view>
<view class="summary-metric" bindtap="handleOpenCoupons">
<text class="summary-label">优惠券</text>
<text class="summary-value">{{couponCount}}</text>
<text class="summary-note">结算前可直接使用</text>
</view>
</view>
<view class="shop-box" bindtap="handleSwitchShop">
<view>
<view class="shop-label">当前登录门店</view>
<view class="shop-name">{{userInfo.shopName || '暂未选择门店'}}</view>
</view>
<view class="shop-link">{{(userInfo.shopIds && userInfo.shopIds.length > 1) ? '切换' : '查看'}}</view>
</view>
<view wx:if="{{needSetPassword}}" class="password-tip">
建议尽快补充登录密码,之后切换设备会更方便。
</view>
<view class="secondary-btn edit-btn" bindtap="handleOpenSettings">编辑资料与设置</view>
</view>
<view class="page-card menu-card">
<view class="section-title">常用入口</view>
<view class="section-subtitle">订单、收藏、优惠券和账号设置都集中在这里。</view>
<view class="menu-item" bindtap="handleOpenOrders">
<text>我的订单</text>
<text class="menu-arrow">></text>
</view>
<view class="menu-item" bindtap="handleOpenWishlist">
<text>我的收藏</text>
<text class="menu-arrow">></text>
</view>
<view class="menu-item" bindtap="handleOpenCoupons">
<text>我的优惠券</text>
<text class="menu-arrow">></text>
</view>
<view class="menu-item" bindtap="handleOpenSettings">
<text>设置中心</text>
<text class="menu-arrow">></text>
</view>
<view class="menu-item logout-item" bindtap="handleLogout">
<text>退出登录</text>
<text class="menu-arrow">></text>
</view>
</view>
</block>
</view>
</view>
</scroll-view>
</view>
+175
View File
@@ -0,0 +1,175 @@
.profile-page-root {
height: 100vh;
display: flex;
flex-direction: column;
overflow: hidden;
}
.profile-scroll {
flex: 1;
min-height: 0;
}
.profile-page {
min-height: 100%;
background: linear-gradient(180deg, #d66c90 0%, #fff8fa 260rpx, #fffdfc 100%);
}
.profile-bg {
position: fixed;
top: 0;
left: 0;
right: 0;
height: 280rpx;
background: linear-gradient(135deg, #d66c90 0%, #9a4f6d 100%);
}
.profile-content {
position: relative;
z-index: 1;
padding-top: 120rpx;
}
.guest-card,
.profile-card,
.menu-card {
padding: 28rpx;
}
.guest-card {
display: flex;
flex-direction: column;
align-items: center;
gap: 18rpx;
text-align: center;
}
.guest-avatar {
width: 120rpx;
height: 120rpx;
border-radius: 50%;
}
.guest-title {
font-size: 34rpx;
font-weight: 700;
color: #2d2430;
}
.guest-desc {
font-size: 24rpx;
line-height: 1.7;
color: #8d7a84;
}
.profile-top {
display: flex;
gap: 20rpx;
}
.avatar {
width: 120rpx;
height: 120rpx;
border-radius: 50%;
background: #f7edf1;
}
.profile-copy {
flex: 1;
}
.nickname {
font-size: 38rpx;
font-weight: 700;
color: #2d2430;
}
.account,
.signature {
margin-top: 10rpx;
font-size: 24rpx;
color: #8d7a84;
line-height: 1.6;
}
.profile-stats {
margin-top: 26rpx;
}
.shop-box {
display: flex;
align-items: center;
justify-content: space-between;
gap: 18rpx;
margin-top: 26rpx;
padding: 22rpx 24rpx;
border-radius: 24rpx;
background: #fff1f5;
}
.shop-label {
font-size: 22rpx;
color: #8d7a84;
}
.shop-name {
margin-top: 10rpx;
font-size: 28rpx;
font-weight: 700;
color: #2d2430;
}
.shop-link {
font-size: 24rpx;
color: #c6597d;
font-weight: 700;
}
.password-tip {
margin-top: 22rpx;
padding: 20rpx 24rpx;
border-radius: 20rpx;
background: #fff7e8;
color: #9b6900;
font-size: 24rpx;
line-height: 1.7;
}
.edit-btn {
margin-top: 24rpx;
}
.menu-card {
margin-top: 20rpx;
}
.menu-item {
display: flex;
align-items: center;
justify-content: space-between;
height: 92rpx;
border-bottom: 2rpx solid #f3e7eb;
font-size: 28rpx;
color: #2d2430;
}
.menu-item:first-of-type {
margin-top: 18rpx;
}
.menu-item:last-child {
border-bottom: 0;
}
.menu-arrow {
color: #c3aab4;
}
.logout-item {
color: #d5536f;
font-weight: 700;
}
.logout-item .menu-arrow {
color: #e0a7b5;
}
+244
View File
@@ -0,0 +1,244 @@
const authApi = require('../../api/auth')
const userApi = require('../../api/user')
const auth = require('../../utils/auth')
const navigation = require('../../utils/navigation')
const { DEFAULT_AVATAR } = require('../../utils/config')
const { runWithLoading } = require('../../utils/loading')
Page({
data: {
isLoggedIn: false,
loading: false,
savingProfile: false,
updatingPassword: false,
countdown: 0,
userInfo: null,
defaultAvatar: DEFAULT_AVATAR,
form: {
nickname: '',
signature: ''
},
passwordForm: {
verificationCode: '',
password: ''
}
},
onShow() {
this.loadSettings()
},
async loadSettings() {
const isLoggedIn = auth.isLoggedIn()
this.setData({
isLoggedIn,
loading: isLoggedIn
})
if (!isLoggedIn) {
this.setData({
userInfo: null,
loading: false
})
return
}
try {
const userInfo = await userApi.getUserInfo()
getApp().refreshUserInfo(userInfo)
this.setData({
userInfo,
'form.nickname': userInfo.nickname || '',
'form.signature': userInfo.signature || ''
})
} catch (error) {
wx.showToast({
title: error.message || '设置页加载失败',
icon: 'none'
})
} finally {
this.setData({
loading: false
})
}
},
handleBack() {
navigation.goBack('/pages/profile/index')
},
handleOpenAuth() {
navigation.openAuth('/pages/settings/index')
},
handleFormInput(event) {
const field = event.currentTarget.dataset.field
this.setData({
[`form.${field}`]: event.detail.value
})
},
handlePasswordInput(event) {
const field = event.currentTarget.dataset.field
this.setData({
[`passwordForm.${field}`]: event.detail.value
})
},
async handleSaveProfile() {
if (!this.data.form.nickname.trim()) {
wx.showToast({
title: '请输入昵称',
icon: 'none'
})
return
}
this.setData({
savingProfile: true
})
try {
await runWithLoading(() => userApi.updateUserInfo({
nickname: this.data.form.nickname.trim(),
signature: this.data.form.signature.trim()
}))
wx.showToast({
title: '资料已更新',
icon: 'none'
})
this.loadSettings()
} catch (error) {
wx.showToast({
title: error.message || '资料更新失败',
icon: 'none'
})
} finally {
this.setData({
savingProfile: false
})
}
},
startCountdown() {
this.setData({
countdown: 60
})
const timer = setInterval(() => {
const next = this.data.countdown - 1
this.setData({
countdown: next
})
if (next <= 0) {
clearInterval(timer)
}
}, 1000)
},
async handleSendPasswordCode() {
if (this.data.countdown > 0) {
return
}
const userInfo = this.data.userInfo
if (!userInfo || !userInfo.phone) {
wx.showToast({
title: '当前账号未绑定手机号',
icon: 'none'
})
return
}
try {
await runWithLoading(() => authApi.sendVerificationCode({
phone: userInfo.phone
}))
wx.showToast({
title: '验证码已发送',
icon: 'none'
})
this.startCountdown()
} catch (error) {
wx.showToast({
title: error.message || '验证码发送失败',
icon: 'none'
})
}
},
async handleUpdatePassword() {
if (!this.data.passwordForm.verificationCode.trim()) {
wx.showToast({
title: '请输入验证码',
icon: 'none'
})
return
}
if (!this.data.passwordForm.password || this.data.passwordForm.password.length < 6) {
wx.showToast({
title: '新密码至少 6 位',
icon: 'none'
})
return
}
this.setData({
updatingPassword: true
})
try {
await runWithLoading(() => userApi.updatePassword({
password: this.data.passwordForm.password,
verificationCode: this.data.passwordForm.verificationCode.trim()
}))
auth.setNeedSetPassword(false)
wx.showToast({
title: '密码已更新',
icon: 'none'
})
this.setData({
passwordForm: {
verificationCode: '',
password: ''
}
})
} catch (error) {
wx.showToast({
title: error.message || '密码更新失败',
icon: 'none'
})
} finally {
this.setData({
updatingPassword: false
})
}
},
async handleLogout() {
const confirmed = await new Promise(resolve => {
wx.showModal({
title: '退出登录',
content: '退出后需要重新登录才能查看订单和继续下单。',
success: res => resolve(Boolean(res.confirm))
})
})
if (!confirmed) {
return
}
try {
await runWithLoading(() => authApi.logout())
} catch (error) {}
getApp().clearUserSession()
wx.showToast({
title: '已退出登录',
icon: 'none'
})
wx.switchTab({
url: '/pages/home/index'
})
}
})
+5
View File
@@ -0,0 +1,5 @@
{
"usingComponents": {
"navigation-bar": "/components/navigation-bar/navigation-bar"
}
}
+68
View File
@@ -0,0 +1,68 @@
<view class="settings-page-root">
<navigation-bar title="设置中心" color="#2d2430" background="#fff7f8" bindback="handleBack"></navigation-bar>
<scroll-view class="settings-scroll" scroll-y enable-flex enhanced show-scrollbar="false">
<view class="page-shell settings-page-shell">
<view class="page-content">
<view wx:if="{{!isLoggedIn}}" class="page-card empty-card">
<text class="empty-title">登录后进入设置中心</text>
<text class="empty-desc">这里可以修改昵称、个性签名和登录密码。</text>
<view class="ghost-btn" bindtap="handleOpenAuth">去登录</view>
</view>
<block wx:elif="{{userInfo}}">
<view class="page-hero settings-hero">
<text class="hero-kicker">个人设置</text>
<text class="hero-title">维护你的资料与登录信息</text>
<text class="hero-desc">资料会同步到小程序端展示区域,密码更新后下次登录立即生效。</text>
</view>
<view class="page-card settings-card">
<view class="section-title">个人资料</view>
<view class="profile-preview">
<image class="avatar" src="{{userInfo.avatar || defaultAvatar}}" mode="aspectFill"></image>
<view class="profile-preview-copy">
<view class="preview-name">{{userInfo.nickname || 'Yumi 用户'}}</view>
<view class="preview-phone">{{userInfo.phone || '未绑定手机号'}}</view>
</view>
</view>
<view class="field-block">
<text class="field-label">昵称</text>
<input class="field-input" placeholder="请输入昵称" placeholder-class="field-placeholder" value="{{form.nickname}}" data-field="nickname" bindinput="handleFormInput"></input>
</view>
<view class="field-block">
<text class="field-label">个性签名</text>
<textarea class="field-textarea" placeholder="写一句想让客人认识你的话" placeholder-class="field-placeholder" value="{{form.signature}}" data-field="signature" bindinput="handleFormInput"></textarea>
</view>
<view class="primary-btn save-btn" bindtap="handleSaveProfile">{{savingProfile ? '保存中...' : '保存资料'}}</view>
</view>
<view class="page-card settings-card password-card">
<view class="section-title">登录密码</view>
<view class="section-subtitle">向已绑定手机号发送验证码后更新登录密码。</view>
<view class="field-block">
<text class="field-label">验证码</text>
<view class="code-row">
<input class="field-input code-input" type="number" placeholder="请输入验证码" placeholder-class="field-placeholder" value="{{passwordForm.verificationCode}}" data-field="verificationCode" bindinput="handlePasswordInput"></input>
<view class="code-btn {{countdown > 0 ? 'disabled' : ''}}" bindtap="handleSendPasswordCode">{{countdown > 0 ? countdown + 's' : '发送验证码'}}</view>
</view>
</view>
<view class="field-block">
<text class="field-label">新密码</text>
<input class="field-input" password placeholder="请输入新密码" placeholder-class="field-placeholder" value="{{passwordForm.password}}" data-field="password" bindinput="handlePasswordInput"></input>
</view>
<view class="secondary-btn save-btn" bindtap="handleUpdatePassword">{{updatingPassword ? '更新中...' : '更新密码'}}</view>
</view>
<view class="logout-btn" bindtap="handleLogout">退出登录</view>
</block>
</view>
</view>
</scroll-view>
</view>
+111
View File
@@ -0,0 +1,111 @@
.settings-page-root {
height: 100vh;
display: flex;
flex-direction: column;
overflow: hidden;
}
.settings-scroll {
flex: 1;
min-height: 0;
}
.settings-page-shell {
min-height: 100%;
}
.settings-hero {
margin-bottom: 20rpx;
}
.settings-card + .settings-card {
margin-top: 20rpx;
}
.settings-card {
padding: 28rpx;
}
.profile-preview {
display: flex;
align-items: center;
gap: 18rpx;
margin-top: 22rpx;
}
.avatar {
width: 110rpx;
height: 110rpx;
border-radius: 50%;
background: #f7edf1;
}
.profile-preview-copy {
flex: 1;
}
.preview-name {
font-size: 32rpx;
font-weight: 700;
color: #2d2430;
}
.preview-phone {
margin-top: 10rpx;
font-size: 24rpx;
color: #8d7a84;
}
.field-block {
margin-top: 20rpx;
}
.save-btn {
margin-top: 26rpx;
}
.password-card {
margin-top: 20rpx;
}
.code-row {
display: flex;
align-items: center;
gap: 14rpx;
}
.code-input {
flex: 1;
}
.code-btn {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 180rpx;
height: 92rpx;
padding: 0 18rpx;
border-radius: 24rpx;
background: #fde8ef;
color: #c6597d;
font-size: 24rpx;
font-weight: 700;
}
.code-btn.disabled {
background: #f3e7eb;
color: #a998a0;
}
.logout-btn {
display: flex;
align-items: center;
justify-content: center;
height: 92rpx;
margin-top: 24rpx;
border-radius: 999rpx;
background: #fff1f5;
color: #d5536f;
font-size: 28rpx;
font-weight: 700;
}
+98
View File
@@ -0,0 +1,98 @@
const shopApi = require('../../api/shop')
const navigation = require('../../utils/navigation')
const { resolveImageList } = require('../../utils/file')
const { DEFAULT_SHOP_IMAGE } = require('../../utils/config')
Page({
data: {
loading: true,
loadError: '',
shopId: '',
returnTo: '/pages/home/index',
shopInfo: null,
shopImages: []
},
onLoad(options) {
this.setData({
shopId: options && options.id ? options.id : '',
returnTo: options && options.returnTo ? decodeURIComponent(options.returnTo) : '/pages/home/index'
})
this.loadShopDetail()
},
async onPullDownRefresh() {
await this.loadShopDetail()
wx.stopPullDownRefresh()
},
async loadShopDetail() {
if (!this.data.shopId) {
this.setData({
loading: false,
loadError: '门店 ID 不存在'
})
return
}
this.setData({
loading: true,
loadError: ''
})
try {
const shopInfo = await shopApi.getShopById(this.data.shopId)
const shopImages = await resolveImageList(shopInfo.imageFileIds || shopInfo.coverImageFileId, DEFAULT_SHOP_IMAGE)
this.setData({
shopInfo,
shopImages
})
} catch (error) {
this.setData({
loadError: error.message || '门店详情加载失败'
})
} finally {
this.setData({
loading: false
})
}
},
handleBack() {
navigation.goBack(this.data.returnTo || '/pages/home/index')
},
handlePreviewImage(event) {
const url = event.currentTarget.dataset.url
if (!url) {
return
}
wx.previewImage({
current: url,
urls: this.data.shopImages
})
},
handleCopyName() {
const shopInfo = this.data.shopInfo
if (!shopInfo || !shopInfo.shopName) {
return
}
wx.setClipboardData({
data: shopInfo.shopName
})
},
handleCopyAddress() {
const shopInfo = this.data.shopInfo
if (!shopInfo || !shopInfo.address) {
return
}
wx.setClipboardData({
data: shopInfo.address
})
}
})
@@ -0,0 +1,5 @@
{
"usingComponents": {
"navigation-bar": "/components/navigation-bar/navigation-bar"
}
}
@@ -0,0 +1,74 @@
<navigation-bar title="{{shopInfo ? shopInfo.shopName : '门店详情'}}" color="#ffffff" background="transparent" bindback="handleBack"></navigation-bar>
<view class="page-shell shop-page">
<view class="shop-hero">
<image wx:if="{{shopImages.length}}" class="shop-hero-image" src="{{shopImages[0]}}" mode="aspectFill"></image>
<view class="shop-hero-mask"></view>
</view>
<view wx:if="{{loadError}}" class="page-content shop-content">
<view class="page-card empty-card">
<text class="empty-title">暂时无法查看门店详情</text>
<text class="empty-desc">{{loadError}}</text>
<view class="ghost-btn" bindtap="handleBack">返回上一页</view>
</view>
</view>
<view wx:elif="{{shopInfo}}" class="page-content shop-content">
<view class="page-card shop-card">
<view class="section-kicker">门店详情</view>
<view class="shop-title">{{shopInfo.shopName}}</view>
<view class="shop-address" bindtap="handleCopyAddress">{{shopInfo.address || '门店地址待补充'}}</view>
<view class="summary-strip shop-summary">
<view class="summary-metric">
<text class="summary-label">营业时间</text>
<text class="summary-value shop-summary-value">{{shopInfo.businessHours || '待补充'}}</text>
<text class="summary-note">以到店服务时间为准</text>
</view>
<view class="summary-metric">
<text class="summary-label">环境图片</text>
<text class="summary-value shop-summary-value">{{shopImages.length ? shopImages.length : 0}} 张</text>
<text class="summary-note">支持点击放大查看</text>
</view>
</view>
<view class="detail-group">
<view class="detail-label">营业时间</view>
<view class="detail-value">{{shopInfo.businessHours || '待补充'}}</view>
</view>
<view class="detail-group">
<view class="detail-label">门店介绍</view>
<view class="detail-value">{{shopInfo.description || '门店介绍待补充'}}</view>
</view>
<view class="copy-row">
<view class="ghost-btn" bindtap="handleCopyName">复制门店名</view>
<view class="ghost-btn" bindtap="handleCopyAddress">复制地址</view>
</view>
</view>
<view class="section-block">
<view class="section-head">
<view class="section-copy">
<text class="section-kicker">实景展示</text>
<text class="section-title">门店环境图</text>
<text class="section-subtitle">点击图片可以放大查看,更直观地感受门店氛围。</text>
</view>
</view>
<view class="gallery-list">
<image
wx:for="{{shopImages}}"
wx:key="*this"
class="gallery-image"
src="{{item}}"
mode="aspectFill"
data-url="{{item}}"
bindtap="handlePreviewImage"
></image>
</view>
</view>
</view>
</view>
@@ -0,0 +1,91 @@
.shop-page {
background: linear-gradient(180deg, #f4dbe3 0%, #fff8fa 220rpx, #fffdfc 100%);
}
.shop-hero {
position: fixed;
top: 0;
left: 0;
right: 0;
height: 320rpx;
background: linear-gradient(135deg, #c6597d 0%, #8d4763 100%);
}
.shop-hero-image {
width: 100%;
height: 100%;
}
.shop-hero-mask {
position: absolute;
inset: 0;
background: linear-gradient(180deg, rgba(34, 21, 27, 0.12), rgba(34, 21, 27, 0.42));
}
.shop-content {
position: relative;
z-index: 1;
padding-top: 160rpx;
}
.shop-card {
padding: 30rpx;
}
.shop-title {
font-size: 42rpx;
font-weight: 700;
line-height: 1.4;
color: #2d2430;
}
.shop-address {
margin-top: 16rpx;
font-size: 26rpx;
color: #8d7a84;
line-height: 1.7;
}
.shop-summary {
margin-top: 24rpx;
}
.shop-summary-value {
font-size: 26rpx;
line-height: 1.6;
}
.detail-group {
margin-top: 24rpx;
}
.detail-label {
font-size: 24rpx;
color: #8d7a84;
}
.detail-value {
margin-top: 12rpx;
font-size: 28rpx;
color: #2d2430;
line-height: 1.8;
}
.copy-row {
display: flex;
gap: 16rpx;
margin-top: 26rpx;
}
.gallery-list {
display: flex;
flex-wrap: wrap;
gap: 18rpx;
}
.gallery-image {
width: calc(50% - 9rpx);
height: 240rpx;
border-radius: 24rpx;
background: #f6edf1;
}
+97
View File
@@ -0,0 +1,97 @@
const wishlistApi = require('../../api/wishlist')
const auth = require('../../utils/auth')
const navigation = require('../../utils/navigation')
const { buildProductCard } = require('../../utils/product')
const { runWithLoading } = require('../../utils/loading')
Page({
data: {
loading: false,
isLoggedIn: false,
wishlist: []
},
onShow() {
this.loadWishlist()
},
async loadWishlist() {
const isLoggedIn = auth.isLoggedIn()
this.setData({
isLoggedIn,
loading: isLoggedIn
})
if (!isLoggedIn) {
this.setData({
wishlist: [],
loading: false
})
return
}
try {
const wishlist = await wishlistApi.getWishlist()
const list = Array.isArray(wishlist) ? wishlist : []
const cards = await Promise.all(list.map(async item => ({
id: item.id,
productId: item.productId,
productCard: await buildProductCard(item.product || {})
})))
this.setData({
wishlist: cards
})
} catch (error) {
this.setData({
wishlist: []
})
wx.showToast({
title: error.message || '收藏列表加载失败',
icon: 'none'
})
} finally {
this.setData({
loading: false
})
}
},
handleOpenAuth() {
navigation.openAuth('/pages/wishlist/index')
},
handleProductSelect(event) {
const product = event.detail || {}
if (!product.id) {
return
}
navigation.navigate('/pages/product-detail/index', {
id: product.id
})
},
async handleRemove(event) {
const productId = event.currentTarget.dataset.productId
if (!productId) {
return
}
try {
await runWithLoading(() => wishlistApi.removeFromWishlist(productId))
wx.showToast({
title: '已取消收藏',
icon: 'none'
})
this.loadWishlist()
} catch (error) {
wx.showToast({
title: error.message || '取消收藏失败',
icon: 'none'
})
}
},
handleBack() {
navigation.goBack('/pages/profile/index')
}
})
+6
View File
@@ -0,0 +1,6 @@
{
"usingComponents": {
"navigation-bar": "/components/navigation-bar/navigation-bar",
"product-card": "/components/product-card/product-card"
}
}
+34
View File
@@ -0,0 +1,34 @@
<navigation-bar title="我的收藏" color="#2d2430" background="#fff7f8" bindback="handleBack"></navigation-bar>
<view class="page-shell wishlist-page">
<view class="page-content">
<view wx:if="{{!isLoggedIn}}" class="page-card empty-card">
<text class="empty-title">登录后查看收藏</text>
<text class="empty-desc">你收藏过的作品会保存在这里,方便之后快速回看。</text>
<view class="ghost-btn" bindtap="handleOpenAuth">去登录</view>
</view>
<block wx:elif="{{wishlist.length}}">
<view class="page-hero wishlist-hero">
<text class="hero-kicker">收藏夹</text>
<text class="hero-title">已收藏 {{wishlist.length}} 个作品</text>
<text class="hero-desc">遇到喜欢的款式先放进收藏,之后再决定是否预约会更从容。</text>
</view>
<view wx:for="{{wishlist}}" wx:key="id" class="wishlist-item">
<product-card item="{{item.productCard}}" bindselect="handleProductSelect"></product-card>
<view class="wishlist-action" data-product-id="{{item.productId}}" bindtap="handleRemove">取消收藏</view>
</view>
</block>
<view wx:elif="{{loading}}" class="page-card empty-card">
<text class="empty-title">正在加载收藏内容</text>
</view>
<view wx:else class="page-card empty-card">
<text class="empty-title">你还没有收藏作品</text>
<text class="empty-desc">遇到喜欢的款式先收藏,之后再决定要不要预约。</text>
<view class="ghost-btn" bindtap="handleBack">去逛作品</view>
</view>
</view>
</view>
+20
View File
@@ -0,0 +1,20 @@
.wishlist-hero {
margin-bottom: 20rpx;
}
.wishlist-item + .wishlist-item {
margin-top: 22rpx;
}
.wishlist-action {
display: flex;
align-items: center;
justify-content: center;
height: 74rpx;
margin-top: 12rpx;
border-radius: 20rpx;
background: #fff1f5;
color: #c6597d;
font-size: 26rpx;
font-weight: 600;
}