Codex Assistant
昨天 58d9f460b2f8c34430285115e2557d18333c5cab
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
// pages/index/index.js
const app = getApp()
const utils = require('../../lib/utils.js')
 
Page({
  data: {
    // 轮播图数据
    banners: [],
    // 赛事列表
    activities: [],
    // 加载状态
    loading: true,
    // 是否还有更多数据
    hasMore: true,
    // 当前页码
    currentPage: 1,
    // 每页数量
    pageSize: 10,
    // 搜索关键词
    searchKeyword: '',
    // 筛选条件
    filterStatus: 'all', // all, upcoming, ongoing, ended
    // 轮播图当前索引
    currentBannerIndex: 0
  },
 
  onLoad(options) {
    console.log('首页加载')
    this.loadBanners()
    this.loadActivities()
  },
 
  onShow() {
    console.log('首页显示')
    // 统一系统导航栏标题
    try { wx.setNavigationBarTitle({ title: '蓉易创' }) } catch (e) {}
    // 检查登录状态
    if (!app.globalData.token) {
      app.login()
    }
    // 初始化自定义 tabbar
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().init();
    }
  },
 
  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.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)
    })
  },
 
  // 加载赛事列表
  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': 2,     // 进行中  
        'ended': 3        // 已结束
      }
      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: stateFilter
    }).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 })
  },
 
 
  // 格式化日期
  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
  }
})