communicate.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. Page({
  2. data: {
  3. showComment: false,
  4. currentCommentId: '',
  5. commentContent: '',
  6. showPreview: false, // 控制预览模态框显示
  7. previewImages: [], // 预览图片数组
  8. previewIndex: 0 , // 当前预览索引
  9. tabs: [
  10. { id: 'recommend', name: '推荐' },
  11. { id: 'notes', name: '研学笔记' },
  12. { id: 'reports', name: '实践报告' },
  13. { id: 'experience', name: '考察心得' }
  14. ],
  15. activeTab: 'recommend',
  16. scrollLeft: 0,
  17. tabHeight: 44,
  18. // 卡片数据
  19. allData: {
  20. recommend: [],
  21. notes: [],
  22. reports: [],
  23. experience: []
  24. },
  25. currentData: [],
  26. pageSize: 10,
  27. currentPage: {
  28. recommend: 1,
  29. notes: 1,
  30. reports: 1,
  31. experience: 1
  32. },
  33. hasMore: {
  34. recommend: true,
  35. notes: true,
  36. reports: true,
  37. experience: true
  38. },
  39. loading: false,
  40. needRefresh:false
  41. },
  42. onLoad() {
  43. // 绑定方法确保上下文正确
  44. this.addNewCard = this.addNewCard.bind(this);
  45. this.onNewPublish = this.onNewPublish.bind(this);
  46. // 初始化数据
  47. this.initData();
  48. setTimeout(() => {
  49. this.checkPendingPublish();
  50. }, 300);
  51. // 加载数据
  52. this.loadAllTabData();
  53. this.checkPendingPublish();
  54. },
  55. initData() {
  56. this.setData({
  57. allData: {
  58. recommend: [],
  59. notes: [],
  60. reports: [],
  61. experience: []
  62. },
  63. currentData: []
  64. });
  65. },
  66. loadAllTabData() {
  67. ['recommend', 'notes', 'reports', 'experience'].forEach(tab => {
  68. this.loadTabData(tab);
  69. });
  70. },
  71. loadTabData(tabId, page = 1) {
  72. if (this.data.loading) return;
  73. this.setData({ loading: true });
  74. setTimeout(() => {
  75. const mockData = this.generateMockData(tabId, page);
  76. const newData = page === 1 ? mockData : [...this.data.allData[tabId], ...mockData];
  77. this.setData({
  78. [`allData.${tabId}`]: newData,
  79. currentData: this.data.activeTab === tabId ? newData : this.data.currentData,
  80. loading: false
  81. });
  82. if (page === 1) {
  83. wx.pageScrollTo({ scrollTop: 0, duration: 300 });
  84. }
  85. }, 800);
  86. },
  87. // 切换Tab
  88. switchTab(e) {
  89. const tabId = e.currentTarget.dataset.id;
  90. if (this.data.activeTab === tabId) return;
  91. this.setData({
  92. activeTab: tabId,
  93. currentData: this.data.allData[tabId] || []
  94. });
  95. // 如果当前Tab没有数据,则加载
  96. if (this.data.allData[tabId].length === 0) {
  97. this.loadTabData(tabId);
  98. }
  99. },
  100. // 加载Tab数据
  101. loadTabData(tabId, page = 1) {
  102. if (this.data.loading) return;
  103. this.setData({ loading: true });
  104. // 模拟API请求
  105. setTimeout(() => {
  106. // 模拟数据
  107. const mockData = this.generateMockData(tabId, page);
  108. // 更新数据
  109. const newData = page === 1
  110. ? mockData
  111. : [...this.data.allData[tabId], ...mockData];
  112. this.setData({
  113. [`allData.${tabId}`]: newData,
  114. currentData: newData,
  115. [`currentPage.${tabId}`]: page,
  116. [`hasMore.${tabId}`]: mockData.length >= this.data.pageSize,
  117. loading: false
  118. });
  119. // 如果是第一页,滚动到顶部
  120. if (page === 1) {
  121. wx.pageScrollTo({
  122. scrollTop: 0,
  123. duration: 300
  124. });
  125. }
  126. }, 800);
  127. },
  128. // 生成模拟数据
  129. generateMockData(tabId, page) {
  130. const data = [];
  131. const count = page === 3 ? 5 : this.data.pageSize; // 模拟最后一页数据不足
  132. for (let i = 0; i < count; i++) {
  133. data.push({
  134. id: `${tabId}_${page}_${i}`,
  135. images: this.generateMockImages(), // 必须包含有效图片数组
  136. user: {
  137. avatar: 'https://randomuser.me/api/portraits/thumb/men/' + (Math.floor(Math.random() * 100)) + '.jpg',
  138. name: ['张', '王', '李', '赵', '钱'][Math.floor(Math.random() * 5)] + '同学'
  139. },
  140. createTime: `${Math.floor(Math.random() * 12) + 1}小时前`,
  141. title: `${this.getTabTitle(tabId)} ${page * this.data.pageSize + i + 1}`,
  142. content: `这是${this.getTabTitle(tabId)}的内容示例,这里可以展示用户发布的具体内容。${tabId}内容区域可以展示多种形式的内容卡片。`,
  143. images: this.generateMockImages(),
  144. likeCount: Math.floor(Math.random() * 100),
  145. commentCount: Math.floor(Math.random() * 50),
  146. collectCount: Math.floor(Math.random() * 30)
  147. });
  148. }
  149. return data;
  150. },
  151. // 生成模拟图片
  152. generateMockImages() {
  153. const count = Math.min(4, Math.floor(Math.random() * 4) + 1); // 1-4张
  154. return Array.from({length: count}, (_, i) =>
  155. `https://picsum.photos/300/200?random=${Date.now()}_${i}`
  156. );
  157. },
  158. // 获取Tab标题
  159. getTabTitle(tabId) {
  160. const tab = this.data.tabs.find(item => item.id === tabId);
  161. return tab ? tab.name : '';
  162. },
  163. // 上拉加载更多
  164. onReachBottom() {
  165. const { activeTab, currentPage, hasMore } = this.data;
  166. if (!hasMore[activeTab] || this.data.loading) return;
  167. this.loadTabData(activeTab, currentPage[activeTab] + 1);
  168. },
  169. // 下拉刷新
  170. onPullDownRefresh() {
  171. this.loadTabData(this.data.activeTab, 1);
  172. wx.stopPullDownRefresh();
  173. },
  174. navigateToPublish() {
  175. wx.navigateTo({
  176. url: '/pages/publish/publish'
  177. });
  178. },
  179. onNewPublish(newCard) {
  180. console.log('收到新发布卡片:', newCard);
  181. if (this.addNewCard && typeof this.addNewCard === 'function') {
  182. this.addNewCard(newCard, newCard.type);
  183. } else {
  184. console.error('addNewCard方法不可用');
  185. // 降级处理:使用全局数据
  186. getApp().globalData.lastPublishedCard = newCard;
  187. }
  188. },
  189. // 检查待处理的发布
  190. checkPendingPublish() {
  191. const app = getApp();
  192. // 1. 检查全局数据(不删除原有数据)
  193. if (app.globalData?.lastPublishedCard) {
  194. this.addNewCard(app.globalData.lastPublishedCard,
  195. app.globalData.lastPublishedCard.type);
  196. // 不清空,避免影响其他页面
  197. }
  198. // 2. 检查本地存储
  199. try {
  200. const storedCard = wx.getStorageSync('lastPublishedCard');
  201. if (storedCard) {
  202. this.addNewCard(storedCard, storedCard.type);
  203. wx.removeStorageSync('lastPublishedCard');
  204. }
  205. } catch (e) {
  206. console.error('读取本地存储失败:', e);
  207. }
  208. },
  209. addNewCard(newCard, cardType) {
  210. const targetType = this.getTargetType(cardType);
  211. const { allData, activeTab } = this.data;
  212. // 深度拷贝原有数据
  213. const updatedAllData = JSON.parse(JSON.stringify(allData));
  214. // 合并新数据
  215. updatedAllData[targetType] = [newCard, ...(updatedAllData[targetType] || [])];
  216. updatedAllData.recommend = [newCard, ...(updatedAllData.recommend || [])];
  217. this.setData({
  218. allData: updatedAllData,
  219. currentData: activeTab === 'recommend' || activeTab === targetType
  220. ? [newCard, ...this.data.currentData]
  221. : this.data.currentData
  222. }, () => {
  223. wx.pageScrollTo({ scrollTop: 0 });
  224. console.log('数据合并完成', this.data.allData);
  225. });
  226. },
  227. getTargetType(cardType) {
  228. return cardType === '实践报告' ? 'reports' :
  229. cardType === '考察心得' ? 'experience' : 'notes';
  230. },
  231. onShow() {
  232. const app = getApp();
  233. // 处理全局待发布卡片
  234. if (app.globalData.pendingCard) {
  235. this.addNewCard(app.globalData.pendingCard.card, app.globalData.pendingCard.type);
  236. app.globalData.pendingCard = null;
  237. }
  238. // 处理刷新标记
  239. if (this.data.needRefresh) {
  240. this.loadTabData(this.data.activeTab, 1);
  241. this.setData({ needRefresh: false });
  242. }
  243. },
  244. checkPendingPublish() {
  245. const app = getApp();
  246. // 1. 检查全局数据
  247. if (app.globalData?.lastPublishedCard) {
  248. console.log('处理全局数据中的待发布卡片');
  249. this.addNewCard(app.globalData.lastPublishedCard, app.globalData.lastPublishedCard.type);
  250. app.globalData.lastPublishedCard = null;
  251. return; // 处理完就返回,避免重复处理
  252. }
  253. // 2. 检查本地存储
  254. try {
  255. const storedCard = wx.getStorageSync('lastPublishedCard');
  256. if (storedCard) {
  257. console.log('处理本地存储中的待发布卡片');
  258. this.addNewCard(storedCard, storedCard.type);
  259. wx.removeStorageSync('lastPublishedCard');
  260. }
  261. } catch (e) {
  262. console.error('读取本地存储失败:', e);
  263. }
  264. },
  265. // 添加 loadInitialData 方法(如果确实需要)
  266. loadInitialData() {
  267. // 这里可以放一些初始化数据的逻辑
  268. console.log('执行初始化数据加载');
  269. },
  270. // 点赞处理
  271. handleLike(e) {
  272. const cardId = e.currentTarget.dataset.id;
  273. this.updateCardData(cardId, (item) => ({
  274. isLiked: !item.isLiked,
  275. likeCount: item.isLiked ? item.likeCount - 1 : item.likeCount + 1
  276. }));
  277. },
  278. // 收藏处理
  279. handleCollect(e) {
  280. const cardId = e.currentTarget.dataset.id;
  281. this.updateCardData(cardId, (item) => ({
  282. isCollected: !item.isCollected,
  283. collectCount: item.isCollected ? item.collectCount - 1 : item.collectCount + 1
  284. }));
  285. },
  286. // 通用数据更新方法
  287. updateCardData(cardId, updateFn) {
  288. const { allData, currentData, activeTab } = this.data;
  289. // 深拷贝数据
  290. const newAllData = JSON.parse(JSON.stringify(allData));
  291. let newCurrentData = [...currentData];
  292. // 更新所有分类中的数据
  293. Object.keys(newAllData).forEach(tab => {
  294. newAllData[tab] = newAllData[tab].map(item => {
  295. if (item.id === cardId) {
  296. return { ...item, ...updateFn(item) };
  297. }
  298. return item;
  299. });
  300. });
  301. // 更新当前显示数据
  302. newCurrentData = newCurrentData.map(item => {
  303. if (item.id === cardId) {
  304. return { ...item, ...updateFn(item) };
  305. }
  306. return item;
  307. });
  308. this.setData({
  309. allData: newAllData,
  310. currentData: newCurrentData
  311. });
  312. },
  313. // 图片预览功能(增强版)
  314. previewImage(e) {
  315. const { urls, index } = e.currentTarget.dataset;
  316. wx.previewImage({
  317. current: urls[index], // 当前点击图片url
  318. urls: urls, // 所有图片url列表
  319. success: () => {
  320. this.setData({
  321. showPreview: true,
  322. previewImages: urls,
  323. previewIndex: index
  324. });
  325. },
  326. fail: (err) => {
  327. console.error('预览失败:', err);
  328. wx.showToast({ title: '预览失败', icon: 'none' });
  329. }
  330. });
  331. },
  332. // 关闭预览
  333. closePreview() {
  334. this.setData({ showPreview: false });
  335. },
  336. // 图片预览功能
  337. previewImage(e) {
  338. // 多重保障获取图片数组
  339. const urls = e.currentTarget.dataset.urls ||
  340. this.data.currentData.find(
  341. item => item.images &&
  342. item.images.includes(e.currentTarget.dataset.current)
  343. )?.images || [];
  344. const current = e.currentTarget.dataset.current;
  345. if (!urls.length) {
  346. console.error('无效图片参数:', {
  347. dataset: e.currentTarget.dataset,
  348. currentData: this.data.currentData
  349. });
  350. wx.showToast({ title: '暂无可预览图片', icon: 'none' });
  351. return;
  352. }
  353. wx.previewImage({
  354. current: current,
  355. urls: urls,
  356. fail: (err) => {
  357. console.error('预览失败:', err);
  358. wx.showToast({ title: '预览失败', icon: 'none' });
  359. }
  360. });
  361. },
  362. // 关闭预览
  363. closePreview() {
  364. this.setData({ showPreview: false });
  365. },
  366. });