Files
zt-closet-wxmini-frontend/miniprogram/pages/outfit-detail/outfit-detail.ts
T
2026-09-15 16:01:59 +08:00

409 lines
14 KiB
TypeScript

import { request, AUTH_EXPIRED_CODES } from '../../utils/request'
import { OutfitItem, ClothesItem } from '../../types/models'
import { IsPublic } from '../../utils/config'
import { navScroll } from '../../utils/nav'
import { logger } from '../../utils/logger'
// 日志模块名
const LOG = 'outfit-detail'
// 接收者打开「分享者额度不足」链接后的自动返回倒计时(秒)
const SHARE_FAIL_BACK_SECONDS = 10
Page({
data: {
uuid: '',
// 仅显式 owner=1 视为属主:无参数链接(如微信默认分享路径)安全降级为非属主视角
isOwner: false,
outfit: {} as OutfitItem,
clothes: [] as ClothesItem[],
isLiked: false,
likeCount: 0,
isCollected: false,
loading: true,
// 页面状态:normal 正常;quota 接收者命中「分享者额度不足」;invalid 加载失败
pageState: 'normal' as 'normal' | 'quota' | 'invalid',
invalidTitle: '',
invalidDesc: '',
needLogin: false,
countdown: SHARE_FAIL_BACK_SECONDS,
// 滚动收缩:由 utils/nav.ts 的共享 handler 驱动
navScrolled: false,
// v2 玻璃弹层
tipVisible: false,
tipTitle: '',
tipText: '',
tipButtons: [{ text: '我知道了', value: 'ok', type: 'main' }],
pubVisible: false,
pubButtons: [
{ text: '取消', value: '' },
{ text: '确认公开', value: 'ok', type: 'main' },
],
delVisible: false,
delButtons: [
{ text: '取消', value: '' },
{ text: '确认删除', value: 'ok', type: 'main' },
],
moreVisible: false,
moreItems: [
{ text: '编辑穿搭', value: 'edit' },
{ text: '删除穿搭', value: 'delete' },
],
// 额度不足引导:v2 玻璃弹窗
quotaVisible: false,
quotaTitle: '',
quotaText: '',
quotaButtons: [
{ text: '取消', value: '' },
{ text: '去购买', value: 'ok', type: 'main' },
],
},
// scroll-view 滚动 → 导航收缩为玻璃小标题
onNavScroll: navScroll,
onLoad(query: Record<string, string>) {
const uuid = query.uuid || ''
const isOwner = query.owner === '1'
logger.debug(LOG, 'onLoad, uuid=', uuid, 'isOwner=', isOwner, 'shareFail=', query.share_fail)
this.setData({ uuid, isOwner })
// 分享者额度不足时分享出去的链接:不请求后端(也不依赖登录),直接进入提示态
if (query.share_fail === 'quota') {
this.showShareFailQuota()
return
}
if (!uuid) {
logger.warn(LOG, 'onLoad 缺少 uuid 参数')
this.setInvalid('链接不完整', '缺少穿搭标识,无法打开')
return
}
this.fetchDetail()
},
// 接收者命中「分享者额度不足」:弹提醒 + 倒计时后返回「我的」页
showShareFailQuota() {
this.setData({
pageState: 'quota',
loading: false,
countdown: SHARE_FAIL_BACK_SECONDS,
tipVisible: true,
tipTitle: '提示',
tipText: '给您分享的好友额度不足哦',
})
this.startBackCountdown()
},
onTipConfirm() {
this.setData({ tipVisible: false })
},
startBackCountdown() {
this.clearBackTimer()
;(this as any).backTimer = setInterval(() => {
const next = this.data.countdown - 1
if (next > 0) {
this.setData({ countdown: next })
return
}
this.clearBackTimer()
this.onBackProfile()
}, 1000)
},
clearBackTimer() {
const timer = (this as any).backTimer
if (timer) {
clearInterval(timer)
;(this as any).backTimer = null
}
},
onBackProfile() {
logger.info(LOG, '额度不足提示结束,返回「我的」页')
wx.switchTab({
url: '/pages/profile/profile',
fail: (e) => logger.warn(LOG, 'switchTab 我的失败, err=', e && e.errMsg),
})
},
onBackHome() {
wx.switchTab({
url: '/pages/wardrobe/wardrobe',
fail: (e) => logger.warn(LOG, 'switchTab 衣橱失败, err=', e && e.errMsg),
})
},
onGoLogin() {
// 透传视角参数:属主登录失效后重登,仍回到属主视角
const owner = this.data.isOwner ? '1' : '0'
const redirect = `/pages/outfit-detail/outfit-detail?uuid=${this.data.uuid}&owner=${owner}`
const loginUrl = `/pages/login/login?redirect=${encodeURIComponent(redirect)}`
wx.navigateTo({
url: loginUrl,
fail: () => {
wx.redirectTo({
url: loginUrl,
fail: () => wx.switchTab({ url: '/pages/profile/profile' }),
})
},
})
},
setInvalid(title: string, desc: string, needLogin = false) {
this.setData({
loading: false,
pageState: 'invalid',
invalidTitle: title,
invalidDesc: desc,
needLogin,
})
},
async fetchDetail() {
let outfit: OutfitItem
try {
outfit = await request<OutfitItem>({ url: `/outfit/${this.data.uuid}`, showError: false })
} catch (e: any) {
const code = e && e.code
logger.warn(LOG, '穿搭详情加载失败, code=', code)
if (AUTH_EXPIRED_CODES.indexOf(code) >= 0) {
// 未登录:给「去登录」出口,登录成功后回到本页
this.setInvalid('请先登录', '登录后即可查看该穿搭', true)
} else if (code === 40004 || code === 40000) {
// 他人未公开 / 已删除:不暴露具体原因,统一提示内容不可见
this.setInvalid('内容不可见', '该穿搭可能已被删除或未公开')
} else {
this.setInvalid('加载失败', '请稍后重试')
}
return
}
logger.debug(LOG, '穿搭详情加载成功, 单品数=', outfit.items && outfit.items.length)
this.setData({ outfit, loading: false })
// 封面与衣物缩略图直接使用穿搭明细里的抠图(processed_image),
// 避免非属主逐件请求 /clothes/:uuid 被拒(50005)导致图片与名称全部丢失。
const baseClothes = (outfit.items || []).map(
(it) => ({ clothes_uuid: it.clothes_uuid, processed_image: it.processed_image }) as ClothesItem,
)
this.setData({ clothes: baseClothes })
// 属主可进一步拉取衣物详情补充名称;非属主无权限,跳过。
if (this.data.isOwner) {
const clothes = await Promise.all(
(outfit.items || []).map(async (it) => {
try {
return await request<ClothesItem>({ url: `/clothes/${it.clothes_uuid}`, showError: false })
} catch (e: any) {
logger.warn(LOG, '单品详情拉取失败, uuid=', it.clothes_uuid, 'code=', e && e.code)
return { clothes_uuid: it.clothes_uuid, processed_image: it.processed_image } as ClothesItem
}
})
)
this.setData({ clothes })
}
// 点赞状态:失败静默保持默认,不影响详情展示
request<{ is_liked: boolean; like_count: number }>({
url: `/like/${this.data.uuid}`,
showError: false,
})
.then((like) => this.setData({ isLiked: like.is_liked, likeCount: like.like_count }))
.catch((e: any) => logger.warn(LOG, '点赞状态拉取失败(保持默认), code=', e && e.code))
// 收藏状态:调用后端 /collect/:targetUUID 初始化,失败静默保持未收藏
request<{ is_collected: boolean; collect_count: number }>({
url: `/collect/${this.data.uuid}`,
showError: false,
})
.then((collect) => this.setData({ isCollected: collect.is_collected }))
.catch((e: any) => logger.warn(LOG, '收藏状态拉取失败(保持未收藏), code=', e && e.code))
},
onLike() {
const action = this.data.isLiked ? 2 : 1
request({ url: '/like', method: 'POST', data: { target_uuid: this.data.uuid, action } })
.then(() => {
logger.debug(LOG, '点赞操作成功, action=', action)
this.setData({
isLiked: action === 1,
likeCount: this.data.likeCount + (action === 1 ? 1 : -1),
})
})
.catch((e: any) => logger.warn(LOG, '点赞操作失败, action=', action, 'code=', e && e.code))
},
onCollect() {
const action = this.data.isCollected ? 2 : 1
request({ url: '/collect', method: 'POST', data: { target_uuid: this.data.uuid, action } })
.then(() => this.setData({ isCollected: action === 1 }))
.catch((e: any) => logger.warn(LOG, '收藏操作失败, action=', action, 'code=', e && e.code))
},
onTogglePublic() {
const isPublic = this.data.outfit.is_public === IsPublic.PUBLIC
if (isPublic) {
this.doPublic(IsPublic.PRIVATE)
} else {
this.setData({ pubVisible: true })
}
},
onPubCancel() {
this.setData({ pubVisible: false })
},
onPubConfirm(e: WechatMiniprogram.CustomEvent) {
this.setData({ pubVisible: false })
if (e.detail.value !== 'ok') return
this.doPublic(IsPublic.PUBLIC)
},
doPublic(isPublic: number) {
// 后端 OutfitPublicRequest.OutfitUUID 为必填(binding required),请求体需携带
request({
url: `/outfit/${this.data.uuid}/public`,
method: 'PUT',
data: { outfit_uuid: this.data.uuid, is_public: isPublic },
})
.then(() => {
logger.info(LOG, '公开状态变更成功, isPublic=', isPublic)
this.setData({ 'outfit.is_public': isPublic })
wx.showToast({ title: isPublic === IsPublic.PUBLIC ? '已公开' : '已取消公开', icon: 'none' })
})
.catch((e: any) => {
logger.warn(LOG, '公开状态变更失败, code=', e && e.code)
// 社区分享额度不足(后端已回滚为私有):弹窗引导购买
if (e && e.code === 80000) {
this.setData({
quotaVisible: true,
quotaTitle: '社区分享额度不足',
quotaText: '购买额度包后可公开到社区',
})
}
})
},
onMore() {
this.setData({ moreVisible: true })
},
onMoreCancel() {
this.setData({ moreVisible: false })
},
onMoreSelect(e: WechatMiniprogram.CustomEvent) {
this.setData({ moreVisible: false })
const value = e.detail.value
if (value === 'edit') this.onEdit()
else if (value === 'delete') this.onDelete()
},
onEdit() {
wx.navigateTo({
url: `/pages/outfit-edit/outfit-edit?uuid=${this.data.uuid}`,
fail: (e) => logger.warn(LOG, 'navigateTo 编辑穿搭失败, err=', e && e.errMsg),
})
},
onDelete() {
this.setData({ delVisible: true })
},
onDelCancel() {
this.setData({ delVisible: false })
},
onDelConfirm(e: WechatMiniprogram.CustomEvent) {
this.setData({ delVisible: false })
if (e.detail.value !== 'ok') return
request({ url: `/outfit/${this.data.uuid}`, method: 'DELETE' })
.then(() => {
logger.info(LOG, '穿搭删除成功')
wx.showToast({ title: '已删除', icon: 'success' })
setTimeout(
() =>
wx.navigateBack({
fail: (e2) => logger.warn(LOG, 'navigateBack 失败, err=', e2 && e2.errMsg),
}),
500,
)
})
.catch((e2: any) => logger.warn(LOG, '穿搭删除失败, code=', e2 && e2.code))
},
onItemTap(e: WechatMiniprogram.TouchEvent) {
const uuid = e.currentTarget.dataset.uuid as string
// 非属主无权读取衣物详情(50005),点击仅提示;属主正常跳转。
if (!this.data.isOwner) {
logger.debug(LOG, '非属主点击衣物,仅可查看穿搭, uuid=', uuid)
wx.showToast({ title: '仅可查看穿搭', icon: 'none' })
return
}
wx.navigateTo({
url: `/pages/clothes-detail/clothes-detail?uuid=${uuid}`,
fail: (err) => logger.warn(LOG, 'navigateTo 单品详情失败, err=', err && err.errMsg),
})
},
// 分享采用微信官方「同步返回 + promise 字段」异步分享模式(基础库 2.12.0+):
// 同步返回兜底链接(3 秒内未 resolve 时生效),promise resolve 后以结果为准。
// 非属主不创建分享记录(对他人穿搭创建会被拒),直接转发普通详情链接。
onShareAppMessage(): any {
const name = this.data.outfit.outfit_name || '我的穿搭'
const fallback = `/pages/outfit-detail/outfit-detail?uuid=${this.data.uuid}&owner=0`
if (!this.data.isOwner) {
return { title: name, path: fallback }
}
const promise = request<{ share_uuid: string }>({
url: '/outfit-share',
method: 'POST',
data: { outfit_uuid: this.data.uuid },
showError: false,
})
.then((res) => {
logger.info(LOG, '穿搭分享创建成功, share_uuid=', res.share_uuid)
return {
title: name,
path: `/pages/outfit-share-detail/outfit-share-detail?uuid=${res.share_uuid}`,
}
})
.catch((e: any) => {
logger.warn(LOG, '穿搭分享创建失败, code=', e && e.code)
if (e && e.code === 80000) {
// 额度不足:提示去购买,链接指向「额度不足」提示页(接收者侧提示后自动返回)
this.setData({
quotaVisible: true,
quotaTitle: '分享额度不足',
quotaText: '购买额度包后可继续分享',
})
return { title: name, path: `${fallback}&share_fail=quota` }
}
// 其他失败:回退普通详情链接(接收者侧展示通用「内容不可见」空态)
return { title: name, path: fallback }
})
return { title: name, path: fallback, promise }
},
onQuotaCancel() {
this.setData({ quotaVisible: false })
},
onQuotaConfirm(e: WechatMiniprogram.CustomEvent) {
this.setData({ quotaVisible: false })
if (e.detail.value !== 'ok') return
wx.navigateTo({
url: '/pages/mall/mall',
fail: (err) => logger.warn(LOG, 'navigateTo 商城失败, err=', err && err.errMsg),
})
},
onUnload() {
this.clearBackTimer()
},
})