peng
2025-11-07 f64693c0da5483d8670220bf3a5bf89a32e94a20
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
// pages/index/index.js
const app = getApp()
const utils = require('../../lib/utils.js')
 
Page({
  data: {
    // 轮播图数据
    banners: [],
    // 赛事列表
    activities: [],
    // 最新新闻列表
    latestNews: [],
    // 加载状态
    loading: true,
    // 是否还有更多数据
    hasMore: true,
    // 当前页码
    currentPage: 1,
    // 每页数量
    pageSize: 10,
    // 搜索关键词
    searchKeyword: '',
    // 筛选条件
    filterStatus: 'all', // all, upcoming, ongoing, ended
    // 轮播图当前索引
    currentBannerIndex: 0,
    // 分享相关数据
    shareActivityId: null,
    shareActivityName: null
  },
 
  onLoad(options) {
    console.log('首页加载')
  },
 
  onShow() {
    console.log('首页显示')
    // 统一系统导航栏标题
    try { wx.setNavigationBarTitle({ title: '蓉e创' }) } catch (e) {}
    // 检查登录状态
    if (!app.globalData.token) {
      app.login()
    }
    // 初始化自定义 tabbar
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().init();
    }
    // 加载数据
    this.loadBanners()
    this.loadLatestNews()
    this.loadActivities()
  },
 
  onPullDownRefresh() {
    console.log('下拉刷新')
    this.refreshData()
  },
 
  onReachBottom() {
    console.log('上拉加载更多')
    if (this.data.hasMore && !this.data.loading) {
      this.loadMoreActivities()
    }
  },
 
  // 刷新数据
  refreshData() {
    this.setData({
      currentPage: 1,
      hasMore: true,
      activities: []
    })
    
    Promise.all([
      this.loadBanners(),
      this.loadLatestNews(),
      this.loadActivities()
    ]).finally(() => {
      wx.stopPullDownRefresh()
    })
  },
 
  // 加载轮播图
  loadBanners() {
    return app.graphqlRequest(`
      query getBanners {
        banners: carouselPlayList {
          id
          title
          content
          coverImage {
            id
            name
            path
            fullUrl
            fullThumbUrl
            mediaType
          }
          images {
            id
            name
            path
            fullUrl
            fullThumbUrl
            mediaType
          }
          videos {
            id
            name
            path
            fullUrl
            fullThumbUrl
            mediaType
          }
        }
      }
    `).then(data => {
      if (data.banners) {
        // 处理轮播图数据,合并图片和视频
        const processedBanners = data.banners.map(banner => {
          const mediaFiles = []
          
          // 添加图片
          if (banner.images && banner.images.length > 0) {
            banner.images.forEach(image => {
              mediaFiles.push({
                ...image,
                type: 'image',
                url: image.fullUrl,
                thumbUrl: image.fullThumbUrl
              })
            })
          }
          
          // 添加视频
          if (banner.videos && banner.videos.length > 0) {
            banner.videos.forEach(video => {
              mediaFiles.push({
                ...video,
                type: 'video',
                url: video.fullUrl,
                thumbUrl: video.fullThumbUrl
              })
            })
          }
          
          // 如果没有媒体文件,使用封面图片
          if (mediaFiles.length === 0 && banner.coverImage) {
            mediaFiles.push({
              ...banner.coverImage,
              type: 'image',
              url: banner.coverImage.fullUrl,
              thumbUrl: banner.coverImage.fullThumbUrl
            });
          }
          
          return {
            ...banner,
            mediaFiles
          }
        })
        
        this.setData({
          banners: processedBanners
        })
      }
    }).catch(err => {
      console.error('加载轮播图失败:', err)
    })
  },
 
  // 加载最新新闻(只加载前3条)
  loadLatestNews() {
    return app.graphqlRequest(`
      query getPublishedNewsList($page: Int!, $size: Int!) {
        publishedNewsList(page: $page, size: $size) {
          content {
            id
            title
            summary
            coverImage
            author
            viewCount
            createTime
          }
          totalElements
          page
          size
        }
      }
    `, {
      page: 1,
      size: 3
    }).then(data => {
      if (data.publishedNewsList) {
        // 格式化时间显示
        const latestNews = data.publishedNewsList.content.map(news => {
          if (news.createTime) {
            news.createTime = utils.formatDate(news.createTime, 'YYYY-MM-DD HH:mm:ss');
          }
          return news;
        });
        
        this.setData({
          latestNews: latestNews
        })
      }
    }).catch(err => {
      console.error('加载最新新闻失败:', err)
    })
  },
 
  // 加载赛事列表
  loadActivities(isLoadMore = false) {
    this.setData({ loading: true })
    
    const { currentPage, pageSize, searchKeyword, filterStatus } = this.data
    
    // 名称搜索条件
    const nameFilter = searchKeyword || ""
    
    // 状态筛选条件:将前端的筛选状态转换为后端的state参数
    let stateFilter = null
    if (filterStatus !== 'all') {
      // 根据filterStatus映射到对应的state值
      const stateMapping = {
        'upcoming': 1,    // 即将开始 -> 发布状态
        'ongoing': 1,     // 进行中 -> 发布状态  
        'ended': 2        // 已结束 -> 关闭状态
      }
      stateFilter = stateMapping[filterStatus]
    }
    
    return app.graphqlRequest(`
      query getActivities($page: Int!, $size: Int!, $name: String, $state: Int) {
        activities(page: $page, size: $size, name: $name, state: $state) {
          content {
            id
            name
            description
            coverImage {
              id
              name
              path
              fullUrl
              fullThumbUrl
              mediaType
            }
            signupDeadline
            matchTime
            address
            playerMax
            state
            stateName
            playerCount
          }
          totalElements
          page
          size
        }
      }
    `, {
      page: currentPage,
      size: pageSize,
      name: nameFilter,
      state: 1
    }).then(data => {
      if (data.activities) {
        let newActivities = data.activities.content
        // 调试:输出报名截止原始值
        try {
          console.log('活动原始报名截止:', newActivities.map(a => ({ id: a.id, name: a.name, signupDeadline: a.signupDeadline })))
        } catch (e) {}
        
        // 为每个活动添加名称文字
        // newActivities = newActivities.map(activity => ({
        //   ...activity,
        //   nameText: (activity.name || '活动').substring(0, 2)
        // }))
        
        // 合并数据:只有在真正的加载更多时才追加,其他情况都是全量替换
        const mergedActivities = isLoadMore && this.data.activities.length > 0
          ? [...this.data.activities, ...newActivities]
          : newActivities
        
        this.setData({
          activities: mergedActivities,
          hasMore: data.activities.totalElements > (currentPage * pageSize) && newActivities.length > 0,
          loading: false
        })
      }
    }).catch(err => {
      console.error('加载赛事列表失败:', err)
      utils.showError('加载失败,请重试')
      this.setData({ loading: false })
    })
  },
 
  // 加载更多赛事
  loadMoreActivities() {
    this.setData({
      currentPage: this.data.currentPage + 1
    })
    this.loadActivities(true) // 传入true表示这是加载更多
  },
 
  // 轮播图切换
  onBannerChange(e) {
    this.setData({
      currentBannerIndex: e.detail.current
    })
  },
 
  // 点击轮播图
  onBannerTap(e) {
    const index = e.currentTarget.dataset.index
    const banner = this.data.banners[index]
    if (!banner) return
    
    // 检查是否有媒体文件
    if (banner.mediaFiles && banner.mediaFiles.length > 0) {
      const firstMedia = banner.mediaFiles[0]
      
      if (firstMedia.type === 'video') {
        // 播放视频
        wx.navigateTo({
          url: `/pages/video/video?url=${encodeURIComponent(firstMedia.url)}&title=${encodeURIComponent(banner.title)}`
        })
      } else if (firstMedia.type === 'image') {
        // 显示图片,如果有多个媒体文件,显示所有图片
        const imageUrls = banner.mediaFiles
          .filter(media => media.type === 'image')
          .map(img => img.url)
        
        if (imageUrls.length > 0) {
          wx.previewImage({
            urls: imageUrls,
            current: firstMedia.url
          })
        }
      }
    }
    // 如果没有媒体文件,检查是否有封面图
    else if (banner.coverImage && banner.coverImage.fullUrl) {
      wx.previewImage({
        urls: [banner.coverImage.fullUrl],
        current: banner.coverImage.fullUrl
      })
    }
  },
 
  // 搜索输入
  onSearchInput(e) {
    const keyword = e.detail.value
    this.setData({ searchKeyword: keyword })
    
    // 防抖搜索
    clearTimeout(this.searchTimer)
    this.searchTimer = setTimeout(() => {
      this.refreshData()
    }, 500)
  },
 
  // 搜索提交
  onSearchSubmit(e) {
    const keyword = e.detail.value
    this.setData({ searchKeyword: keyword })
    this.refreshData()
  },
 
  // 清空搜索
  onSearchClear() {
    this.setData({ searchKeyword: '' })
    this.refreshData()
  },
 
  // 筛选状态切换
  onFilterChange(e) {
    const status = e.currentTarget.dataset.status
    this.setData({ filterStatus: status })
    this.refreshData()
  },
 
  // 跳转到赛事详情
  goToActivityDetail(activityId) {
    utils.navigateTo('/pages/activity/detail', { id: activityId })
  },
 
  // 跳转到新闻详情
  goToNewsDetail(e) {
    const newsId = e.currentTarget.dataset.id
    if (newsId) {
      wx.navigateTo({
        url: `/pages/news/detail?id=${newsId}`
      })
    }
  },
 
  // 跳转到新闻列表
  goToNewsList() {
    wx.navigateTo({
      url: '/pages/news/list'
    })
  },
 
  // 格式化日期
  formatDate(date) {
    return utils.formatDate(date, 'MM-DD HH:mm')
  },
 
  // 设计稿需要的 YYYY-MM-DD(强兼容:直接截取前10位,避免 JSCore 日期解析差异)
  formatDateYYYYMMDD(date) {
    if (!date && date !== 0) return '—'
    // 字符串:优先匹配 YYYY-MM-DD 直接返回,避免解析
    if (typeof date === 'string') {
      const m = date.match(/^(\d{4}-\d{2}-\d{2})/)
      if (m) return m[1]
    }
    // 数值:时间戳(秒/毫秒)兜底
    if (typeof date === 'number') {
      const ts = date > 1e12 ? date : date * 1000
      const d = new Date(ts)
      if (!isNaN(d.getTime())) {
        const y = d.getFullYear()
        const m = String(d.getMonth() + 1).padStart(2, '0')
        const day = String(d.getDate()).padStart(2, '0')
        return `${y}-${m}-${day}`
      }
    }
    // 其他情况走工具函数兜底
    const v = utils.formatDate(date, 'YYYY-MM-DD')
    return v && typeof v === 'string' && v.trim() ? v : '—'
  },
  onTest(e){
    const activityId = e.currentTarget.dataset.id
    const xid = e.currentTarget.dataset.xid;
    const idx = e.currentTarget.dataset.idx;
    
    // 简化的调试信息
    console.log('点击活动详情 - ID:', activityId, '名称:', xid, '索引:', idx)
    
    if (activityId) {
      this.goToActivityDetail(activityId)
    }
  },
  // 点击"详情"按钮(与卡片点击一致)
  onActivityDetailTap(e) {
    const activityId = e.currentTarget.dataset.id
    const xid = e.currentTarget.dataset.xid;
    const idx = e.currentTarget.dataset.idx;
    
    // 简化的调试信息
    console.log('点击活动详情 - ID:', activityId, '名称:', xid, '索引:', idx)
    
    if (activityId) {
      this.goToActivityDetail(activityId)
    }
  },
 
  // 获取状态文本
  getStatusText(state) {
    const statusMap = {
      'DRAFT': '草稿',
      'PUBLISHED': '已发布',
      'SIGNUP': '报名中',
      'SIGNUP_END': '报名结束',
      'PLAYING': '进行中',
      'ENDED': '已结束',
      'CANCELLED': '已取消'
    }
    return statusMap[state] || state
  },
 
  // 获取状态样式类
  getStatusClass(state) {
    const classMap = {
      'DRAFT': 'text-muted',
      'PUBLISHED': 'text-primary',
      'SIGNUP': 'text-success',      // 报名中
      'SIGNUP_END': 'text-warning',  // 报名结束
      'PLAYING': 'text-primary',     // 进行中
      'ENDED': 'text-muted',         // 已结束
      'CANCELLED': 'text-danger'     // 已取消
    }
    return classMap[state] || 'text-muted'
  },
 
  // 计算报名进度
  getRegistrationProgress(current, max) {
    if (!max || max <= 0) return 0
    return Math.min((current / max) * 100, 100)
  },
 
  // 判断是否可以报名
  canRegister(activity) {
    const now = new Date()
    const signupDeadline = new Date(activity.signupDeadline)
    
    return now <= signupDeadline && 
           activity.state === 'SIGNUP' &&
           activity.playerCount < activity.playerMax
  },
 
  // 分享单个比赛
  onShareActivity(e) {
    const { id, name } = e.currentTarget.dataset
    
    // 显示分享选项
    wx.showActionSheet({
      itemList: ['分享给朋友', '生成分享海报'],
      success: (res) => {
        if (res.tapIndex === 0) {
          // 分享给朋友
          this.shareToFriend(id, name)
        } else if (res.tapIndex === 1) {
          // 生成分享海报
          this.generateSharePoster(id, name)
        }
      },
      fail: (res) => {
        console.log('用户取消分享')
      }
    })
  },
 
  // 分享给朋友
  shareToFriend(activityId, activityName) {
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    })
    
    // 设置当前要分享的活动信息
    this.setData({
      shareActivityId: activityId,
      shareActivityName: activityName
    })
    
    // 触发分享
    wx.updateShareMenu({
      withShareTicket: true,
      isUpdatableMessage: true,
      activityId: 'share_activity_' + activityId,
      templateInfo: {
        parameterList: [{
          name: 'activity_name',
          value: activityName
        }]
      }
    })
    
    wx.showToast({
      title: '请点击右上角分享',
      icon: 'none',
      duration: 2000
    })
  },
 
  // 生成分享海报
  generateSharePoster(activityId, activityName) {
    wx.showLoading({
      title: '生成海报中...'
    })
    
    // 这里可以调用后端API生成分享海报
    // 或者使用canvas在前端生成
    setTimeout(() => {
      wx.hideLoading()
      wx.showToast({
        title: '海报生成功能开发中',
        icon: 'none',
        duration: 2000
      })
    }, 1500)
  },
 
  // 页面分享功能 - 分享给朋友
  onShareAppMessage(res) {
    console.log('分享给朋友', res)
    
    // 如果是从比赛卡片分享
    if (this.data.shareActivityId && this.data.shareActivityName) {
      const shareData = {
        title: `${this.data.shareActivityName} - 蓉e创比赛平台`,
        path: `/pages/activity/detail?id=${this.data.shareActivityId}`,
        imageUrl: '', // 可以设置分享图片
        success: (res) => {
          console.log('分享成功', res)
        },
        fail: (res) => {
          console.log('分享失败', res)
        }
      }
      return shareData
    }
    
    // 默认分享
    return {
      title: '蓉e创比赛平台',
      path: '/pages/index/index',
      imageUrl: '',
      success: (res) => {
        console.log('分享成功', res)
      },
      fail: (res) => {
        console.log('分享失败', res)
      }
    }
  },
 
  // 页面分享功能 - 分享到朋友圈
  onShareTimeline() {
    return {
      title: '蓉e创比赛平台',
      query: '',
      imageUrl: ''
    }
  }
})