|
|
import http from '../../../utils/api'const baseUrl = require('../../../utils/baseUrl')
Page({ data: { // 帖子列表相关
posts: [], baseUrl: baseUrl, loading: false, searchLoading: false, initialLoading: true, loadingMore: false, refreshing: false, hasMore: true, page: 1, pageSize: 10, searchKeyword: '', lastSearchKeyword: '', // 新增:记录上次搜索关键词
scrollTop: 0, showBackToTop: false, scrollThreshold: 300,
// 发布帖子相关
showPostModal: false, postTitle: '', postContent: '', postImages: [], isSubmitting: false },
onLoad: function () { this.loadPosts(true); },
onShow: function () { // 每次显示页面时刷新数据
this.refreshData(); },
// 加载帖子列表
loadPosts: function (reset = false) { // 防止重复请求
if (reset) { this.setData({ page: 1, hasMore: true, loading: true, searchLoading: !!this.data.searchKeyword }); } else if (this.data.loadingMore) { return; }
this.setData({ loading: reset || this.data.page === 1, loadingMore: !reset && this.data.page > 1 });
// 准备请求参数
const params = { page: this.data.page, pageSize: this.data.pageSize };
// 如果有搜索关键词,添加搜索参数
const searchKeyword = this.data.searchKeyword.trim(); if (searchKeyword) { params.searchKey = searchKeyword; }
// 记录当前搜索关键词
this.setData({ lastSearchKeyword: searchKeyword });
// 调用接口获取数据
http.forumList({ data: params, success: (res) => { if (res.code === 200) { let postsData = res.rows || []; // 处理图片字段(分割字符串为数组)
postsData = postsData.map(item => { if (item.images && typeof item.images === 'string') { item.images = item.images.split(',').filter(img => img.trim() !== ''); } else { item.images = []; } return item; });
if (reset) { this.setData({ posts: postsData, loading: false, searchLoading: false, initialLoading: false, hasMore: postsData.length === this.data.pageSize }); } else { this.setData({ posts: [...this.data.posts, ...postsData], loading: false, initialLoading: false, loadingMore: false, hasMore: postsData.length === this.data.pageSize }); } } else { wx.showToast({ title: res.msg || '加载失败', icon: 'none' }); this.setData({ loading: false, searchLoading: false, initialLoading: false, loadingMore: false }); }
if (this.data.refreshing) { wx.stopPullDownRefresh(); this.setData({ refreshing: false }); } }, fail: (err) => { wx.showToast({ title: '网络错误', icon: 'none' }); this.setData({ loading: false, searchLoading: false, initialLoading: false, loadingMore: false, refreshing: false }); } }); },
// 下拉刷新
onRefresh: function () { this.setData({ refreshing: true }); this.loadPosts(true); },
// 加载更多
loadMore: function () { if (!this.data.hasMore || this.data.loadingMore) return;
this.setData({ page: this.data.page + 1 }, () => { this.loadPosts(); }); },
// 搜索输入(防抖)
onSearchInput: function (e) { const keyword = e.detail.value; this.setData({ searchKeyword: keyword });
// 防抖搜索
clearTimeout(this.searchTimer); // 如果输入框为空,立即重置搜索
if (!keyword.trim()) { this.setData({ searchKeyword: '' }); // 清空搜索时立即重新加载数据
this.loadPosts(true); return; } this.searchTimer = setTimeout(() => { // 只有当有搜索词且与上次不同时才搜索
if (keyword.trim() && keyword.trim() !== this.data.lastSearchKeyword) { this.loadPosts(true); } }, 500); },
// 搜索确认
onSearchConfirm: function (e) { const keyword = e.detail.value.trim(); this.setData({ searchKeyword: keyword }); // 如果搜索词为空,加载所有帖子
if (!keyword) { this.loadPosts(true); } else { // 只有当搜索词与上次不同时才搜索
if (keyword !== this.data.lastSearchKeyword) { this.loadPosts(true); } } },
// 清空搜索 - 优化版
clearSearch: function () { // 如果当前已经有搜索词,才执行清空操作
if (this.data.searchKeyword) { this.setData({ searchKeyword: '' }, () => { // 清空后立即加载所有帖子
this.loadPosts(true); }); } },
// 跳转到详情页
goToDetail: function (e) { const postId = e.currentTarget.dataset.id; wx.navigateTo({ url: `/pagesB/pages/onlineAsk/onlineAsk?id=${postId}` }); },
// 图片预览功能
previewImage: function (e) { const postIndex = e.currentTarget.dataset.postindex; const imageIndex = e.currentTarget.dataset.imageindex; const post = this.data.posts[postIndex]; if (!post || !post.images || post.images.length === 0) return; // 构建完整的图片URL数组
const urls = post.images.map(img => this.data.baseUrl + img); wx.previewImage({ current: urls[imageIndex], // 当前显示图片的链接
urls: urls // 需要预览的图片链接列表
}); },
// 显示发布模态框
createPost: function () { // 检查登录状态(如果需要)
// 这里可以添加登录检查逻辑
this.setData({ showPostModal: true }); },
// 隐藏发布模态框
hidePostModal: function () { if (this.data.isSubmitting) return; this.setData({ showPostModal: false, postTitle: '', postContent: '', postImages: [] }); },
// 阻止事件冒泡
stopPropagation: function () {},
// 标题输入
onPostTitleInput: function (e) { this.setData({ postTitle: e.detail.value }); },
// 内容输入
onPostContentInput: function (e) { this.setData({ postContent: e.detail.value }); },
// 选择图片
chooseImage: function () { const remaining = 3 - this.data.postImages.length; if (remaining <= 0) { wx.showToast({ title: '最多上传3张图片', icon: 'none' }); return; }
wx.chooseMedia({ count: remaining, mediaType: ['image'], sizeType: ['compressed'], sourceType: ['album', 'camera'], success: (res) => { const tempFiles = res.tempFiles; const newImages = tempFiles.map(file => file.tempFilePath); const postImages = [...this.data.postImages, ...newImages];
this.setData({ postImages: postImages.slice(0, 3) // 确保不超过3张
}); }, fail: (err) => { console.error('选择图片失败:', err); } }); },
// 移除图片
removeImage: function (e) { const index = e.currentTarget.dataset.index; const postImages = [...this.data.postImages]; postImages.splice(index, 1); this.setData({ postImages }); },
// 提交帖子
submitPost: function () { const { postTitle, postContent, postImages } = this.data;
// 验证输入
if (!postTitle.trim()) { wx.showToast({ title: '请输入标题', icon: 'none' }); return; }
if (!postContent.trim()) { wx.showToast({ title: '请输入内容', icon: 'none' }); return; }
this.setData({ isSubmitting: true });
// 如果有图片,先上传图片
const uploadPromises = postImages.map(imagePath => { return new Promise((resolve, reject) => { wx.uploadFile({ url: baseUrl+'/common/upload', header: { 'Authorization': 'Bearer ' + wx.getStorageSync('token') }, filePath: imagePath, name: 'file', success: (res) => { const data = JSON.parse(res.data); console.log(data); if (data.code === 200) { resolve(data.fileName); // 假设返回的图片路径在data.url中
} else { reject(new Error('图片上传失败')); } }, fail: (err) => { reject(err); } }); }); });
// 处理图片上传
Promise.all(uploadPromises) .then((imageUrls) => { // 所有图片上传成功,提交帖子数据
const postData = { title: postTitle, content: postContent, images: imageUrls.join(',') // 将图片URL用逗号拼接
};
return http.forumAdd({ data: postData, success:res=>{ console.log(1111,res); if (res.code === 200) { // 发布成功
this.setData({ showPostModal: false, postTitle: '', postContent: '', postImages: [], isSubmitting: false }); wx.showToast({ title: '发布成功', icon: 'success', duration: 2000 }); // 刷新帖子列表
setTimeout(() => { this.loadPosts(true); }, 500); } else { throw new Error(res.msg || '发布失败'); } } }); }) },
// 滚动事件监听
onScroll: function (e) { const scrollTop = e.detail.scrollTop; const showBackToTop = scrollTop > this.data.scrollThreshold; if (showBackToTop !== this.data.showBackToTop) { this.setData({ scrollTop: scrollTop, showBackToTop: showBackToTop }); } },
// 返回顶部
backToTop: function () { this.setData({ showBackToTop: false });
wx.pageScrollTo({ scrollTop: 0, duration: 400, success: () => { this.setData({ scrollTop: 0 }); }, fail: (err) => { console.log('滚动失败:', err); this.setData({ scrollTop: 0 }); } }); },
// 刷新数据
refreshData: function () { const pages = getCurrentPages(); const currentPage = pages[pages.length - 1]; if (currentPage.data && currentPage.data.refresh) { this.loadPosts(true); currentPage.setData({ refresh: false }); } },
onPullDownRefresh: function () { this.onRefresh(); },
onReachBottom: function () { this.loadMore(); }});
|