import { Post } from '../../types/index' import { formatTime, formatCount, getAvatarGradient } from '../../utils/format' import { api } from '../../utils/api' Component({ properties: { post: { type: Object, value: null, }, }, data: { avatarGradient: '', timeText: '', likeCount: 0, imageGridClass: 'post-img-grid-0', }, observers: { post(val: Post) { if (!val) return this.setData({ avatarGradient: getAvatarGradient(val.authorId || ''), timeText: formatTime(val.createdAt), likeCount: typeof val.likeCount === 'number' ? val.likeCount : 0, imageGridClass: this.getImageGridClass(val.images), }) }, }, methods: { getImageGridClass(images?: string[]) { if (!Array.isArray(images)) return 'post-img-grid-0' return `post-img-grid-${images.length > 3 ? 'multi' : images.length}` }, onCardTap() { const post = this.data.post as Post if (!post) return wx.navigateTo({ url: `/pages/post-detail/post-detail?id=${post._id}` }) }, onAuthorTap() { const post = this.data.post as Post if (!post?.authorId) return wx.navigateTo({ url: `/pages/pet-detail/pet-detail?userId=${post.authorId}` }) }, onImageTap(e: WechatMiniprogram.CustomEvent) { const post = this.data.post as Post if (!post?.images?.length) return wx.previewImage({ current: post.images[e.currentTarget.dataset.idx as number], urls: post.images, }) }, async onLike() { const post = this.data.post as Post if (!post) return const wasLiked = post.isLiked const prevCount = this.data.likeCount this.setData({ 'post.isLiked': !wasLiked, likeCount: wasLiked ? prevCount - 1 : prevCount + 1, }) try { const res = await api.likePost(post._id) this.setData({ likeCount: res.count, 'post.isLiked': res.liked }) this.triggerEvent('likeChange', { postId: post._id, liked: res.liked, count: res.count }) } catch { this.setData({ 'post.isLiked': wasLiked, likeCount: prevCount }) wx.showToast({ title: '操作失败', icon: 'none' }) } }, onComment() { const post = this.data.post as Post if (!post) return wx.navigateTo({ url: `/pages/post-detail/post-detail?id=${post._id}&focus=comment` }) }, onShare() { wx.showShareMenu({ withShareTicket: true, menus: ['shareAppMessage', 'shareTimeline'] }) }, }, })