You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

442 lines
12 KiB

const API = require('../../utils/api.js');
Page({
data: {
hotTopics: [],
posts: [],
loading: false,
hasMore: true,
page: 1,
pageSize: 10
},
onLoad() {
this.loadHotTopics();
this.loadPosts();
},
onShow() {
this.setData({
page: 1,
hasMore: true,
posts: []
});
this.loadPosts();
},
onReachBottom() {
if (this.data.hasMore && !this.data.loading) {
this.loadPosts();
}
},
onPullDownRefresh() {
this.setData({
page: 1,
hasMore: true,
posts: []
});
this.loadHotTopics();
this.loadPosts();
wx.stopPullDownRefresh();
},
loadHotTopics() {
API.getHotTopics().then(res => {
if (res.data && res.data.length > 0) {
this.setData({
hotTopics: res.data
});
} else {
// 使用默认热门话题
this.setData({
hotTopics: [
{ id: 1, name: '今天你吃蛋了么?', count: 123 },
{ id: 2, name: '日常分享', count: 456 },
{ id: 3, name: '鸡蛋行情', count: 789 },
{ id: 4, name: '养殖经验', count: 321 },
{ id: 5, name: '美食分享', count: 654 }
]
});
}
}).catch(err => {
console.error('加载热门话题失败:', err);
// 出错时使用默认热门话题
this.setData({
hotTopics: [
{ id: 1, name: '今天你吃蛋了么?', count: 123 },
{ id: 2, name: '日常分享', count: 456 },
{ id: 3, name: '鸡蛋行情', count: 789 },
{ id: 4, name: '养殖经验', count: 321 },
{ id: 5, name: '美食分享', count: 654 }
]
});
});
},
loadPosts() {
if (this.data.loading) {
return;
}
this.setData({
loading: true
});
// 获取用户信息
const userInfo = wx.getStorageSync('userInfo');
const phoneNumber = userInfo?.phoneNumber || wx.getStorageSync('phoneNumber');
const userId = wx.getStorageSync('userId') || userInfo?.userId;
// 构建请求参数
const params = {
page: this.data.page,
pageSize: this.data.pageSize
};
// 只有当电话号码存在时才传递,避免传递空值
if (phoneNumber) {
params.phone = phoneNumber;
}
// 传递userId参数,用于后端过滤动态
if (userId) {
params.userId = userId;
}
API.getPosts(params).then(res => {
console.log('后端返回的完整响应:', res);
// 正确处理后端返回的响应格式
let newPosts = res.data && res.data.posts ? res.data.posts : [];
console.log('后端返回的动态数量:', newPosts.length);
console.log('后端返回的动态数据:', newPosts);
// 处理images字段,确保它是一个数组,并添加username字段
newPosts = newPosts.map(post => {
if (post.images) {
// 如果images是字符串,尝试解析为JSON数组
if (typeof post.images === 'string') {
try {
post.images = JSON.parse(post.images);
// 确保解析后是数组
if (!Array.isArray(post.images)) {
post.images = [];
}
} catch (e) {
// 解析失败,设置为空数组
post.images = [];
}
} else if (!Array.isArray(post.images)) {
// 如果不是字符串也不是数组,设置为空数组
post.images = [];
}
} else {
// 如果images不存在,设置为空数组
post.images = [];
}
// 添加username字段(使用phone的前几位作为用户名)
if (!post.username) {
if (post.phone) {
// 隐藏手机号中间部分
post.username = post.phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
} else {
post.username = '用户' + post.user_id?.substring(0, 6) || '未知用户';
}
}
// 添加time字段用于显示时间
if (!post.time && post.created_at) {
const date = new Date(post.created_at);
post.time = date.toLocaleString('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit'
});
}
// 确保topic字段存在
if (post.topic) {
console.log('动态话题:', post.topic);
}
// 为了兼容前端模板,添加user对象
if (!post.user) {
post.user = {
avatar: post.avatar_url || '',
nickname: post.username
};
}
// 为了兼容前端模板,添加image字段(使用images数组的第一个元素)
if (!post.image && post.images && post.images.length > 0) {
post.image = post.images[0];
}
// 为了兼容前端模板,添加like_count和comment_count字段
if (post.likes !== undefined && post.like_count === undefined) {
post.like_count = post.likes;
}
if (post.comments !== undefined && post.comment_count === undefined) {
post.comment_count = post.comments;
}
return post;
});
// 根据status字段过滤动态:0仅自己可见,1所有人可见,2仅自己可见
newPosts = newPosts.filter(post => {
// 如果status为1,所有人可见
if (post.status === 1) {
return true;
}
// 如果status为0或2,仅自己可见
if (post.status === 0 || post.status === 2) {
// 检查是否是当前用户的动态
return post.user_id === userId;
}
// 默认显示
return true;
});
// 如果是第一页且没有数据,使用默认动态数据
if (this.data.page === 1 && (!newPosts || newPosts.length === 0)) {
newPosts = [
{
id: 1,
user_id: '1',
content: '今天的鸡蛋质量真好,客户都很满意!',
images: [],
likes: 12,
comments: 3,
created_at: new Date().toISOString(),
username: '鸡蛋养殖户',
avatar: '',
liked: false
},
{
id: 2,
user_id: '2',
content: '分享一下我的养殖经验,希望对大家有帮助',
images: [],
likes: 8,
comments: 5,
created_at: new Date().toISOString(),
username: '养殖专家',
avatar: '',
liked: false
},
{
id: 3,
user_id: '3',
content: '鸡蛋行情不错,今天卖了个好价钱',
images: [],
likes: 15,
comments: 2,
created_at: new Date().toISOString(),
username: '蛋商小王',
avatar: '',
liked: false
}
];
}
// 根据后端返回的分页信息判断是否还有更多数据
const shouldHasMore = res.data && res.data.pagination ?
this.data.page < res.data.pagination.totalPages :
this.data.page < 3;
this.setData({
posts: this.data.page === 1 ? newPosts : [...this.data.posts, ...newPosts],
loading: false,
hasMore: shouldHasMore,
page: this.data.page + 1
});
}).catch(err => {
console.error('加载动态失败:', err);
// 出错时使用默认动态数据
if (this.data.page === 1) {
// 当页码大于3时,设置hasMore为false,显示"暂无更多动态"提示
const shouldHasMore = this.data.page < 3;
this.setData({
posts: [
{
id: 1,
user_id: '1',
content: '今天的鸡蛋质量真好,客户都很满意!',
images: [],
likes: 12,
comments: 3,
created_at: new Date().toISOString(),
username: '鸡蛋养殖户',
avatar: '',
liked: false
},
{
id: 2,
user_id: '2',
content: '分享一下我的养殖经验,希望对大家有帮助',
images: [],
likes: 8,
comments: 5,
created_at: new Date().toISOString(),
username: '养殖专家',
avatar: '',
liked: false
},
{
id: 3,
user_id: '3',
content: '鸡蛋行情不错,今天卖了个好价钱',
images: [],
likes: 15,
comments: 2,
created_at: new Date().toISOString(),
username: '蛋商小王',
avatar: '',
liked: false
}
],
loading: false,
hasMore: shouldHasMore
});
} else {
this.setData({
loading: false
});
}
});
},
viewTopic(e) {
const topic = e.currentTarget.dataset.topic;
wx.navigateTo({
url: `/pages/eggbar/topic-detail?id=${topic.id}`
});
},
viewPost(e) {
const post = e.currentTarget.dataset.post;
wx.navigateTo({
url: `/pages/eggbar/post-detail?id=${post.id}`
});
},
likePost(e) {
const postId = e.currentTarget.dataset.id;
// 获取用户电话号码
const userInfo = wx.getStorageSync('userInfo');
const phoneNumber = userInfo?.phoneNumber || wx.getStorageSync('phoneNumber');
if (!phoneNumber) {
wx.showToast({
title: '请先登录获取电话号码',
icon: 'none'
});
return;
}
// 前端临时更新状态
const posts = this.data.posts.map(post => {
if (post.id === postId) {
return {
...post,
liked: !post.liked,
likes: post.liked ? post.likes - 1 : post.likes + 1
};
}
return post;
});
this.setData({ posts });
// 调用API
API.likePost(postId, phoneNumber).then(res => {
console.log('点赞成功:', res);
wx.showToast({
title: res.message || '操作成功',
icon: 'success'
});
}).catch(err => {
console.error('点赞失败:', err);
// 恢复原始状态
const originalPosts = this.data.posts.map(post => {
if (post.id === postId) {
return {
...post,
liked: !post.liked,
likes: post.liked ? post.likes + 1 : post.likes - 1
};
}
return post;
});
this.setData({ posts: originalPosts });
wx.showToast({
title: '操作失败,请重试',
icon: 'none'
});
});
},
commentPost(e) {
const postId = e.currentTarget.dataset.id;
wx.navigateTo({
url: `/pages/eggbar/post-detail?id=${postId}&focusComment=true`
});
},
sharePost(e) {
const postId = e.currentTarget.dataset.id;
wx.showShareMenu({
withShareTicket: true,
success: () => {
console.log('分享成功');
}
});
},
// 预览图片
previewImage(e) {
const images = e.currentTarget.dataset.images;
const currentIndex = parseInt(e.currentTarget.dataset.current);
console.log('预览图片:', {
images,
currentIndex,
current: images[currentIndex]
});
wx.previewImage({
current: images[currentIndex],
urls: images,
success: function(res) {
console.log('预览图片成功:', res);
},
fail: function(err) {
console.error('预览图片失败:', err);
}
});
},
createPost() {
wx.navigateTo({
url: '/pages/eggbar/create-post'
});
},
onShareAppMessage() {
return {
title: '蛋吧 - 鸡蛋行业交流社区',
path: '/pages/eggbar/eggbar',
imageUrl: '/images/eggbar-share.jpg'
};
}
});