function formatTime(startTime, endTime) {
  if (!startTime) return ''
  const start = String(startTime).replace('T', ' ').slice(0, 16)
  const end = endTime ? String(endTime).replace('T', ' ').slice(11, 16) : ''
  return end ? `${start}-${end}` : start
}

Component({
  data: {
    loaded: false,
    title: '活动',
    items: [],
    total: 0,
    relatedPage: '/pages/events/index'
  },
  lifetimes: {
    created() {
      this._modelCtx = wx.modelContext.getContext(this)
      this._viewCtx = wx.modelContext.getViewContext(this)
      const { NotificationType } = wx.modelContext
      this._modelCtx.on(NotificationType.Result, (data) => {
        const result = data && data.result ? data.result : {}
        const sc = result.structuredContent || {}
        const meta = result._meta || {}
        const rawItems = meta.viewItems || sc.items || []
        const items = rawItems.map((item) => ({
          ...item,
          timeText: item.timeText || formatTime(item.startTime, item.endTime),
          registerButtonText: item.registerButtonText || (item.registerable ? '可报名' : '查看详情')
        }))
        this.setData({
          loaded: true,
          title: sc.listType === 'registered' ? '我的报名' : '为你找到这些活动',
          items,
          total: sc.total || items.length,
          relatedPage: meta.relatedPage || '/pages/events/index'
        })
      })
    }
  },
  methods: {
    onTapItem(e) {
      const item = this.data.items[e.currentTarget.dataset.index]
      if (!item || !item.activityId) return
      this._modelCtx.sendFollowUpMessage({
        content: [
          { type: 'text', text: `查看活动：${item.title}` },
          { type: 'api/call', data: { name: 'getActivityDetail', arguments: { activityId: item.activityId } } }
        ]
      })
    },
    onTapRegister(e) {
      const item = this.data.items[e.currentTarget.dataset.index]
      if (!item || !item.activityId) return
      this._modelCtx.sendFollowUpMessage({
        content: [
          { type: 'text', text: `报名活动：${item.title}` },
          { type: 'api/call', data: { name: 'prepareActivityRegistration', arguments: { activityId: item.activityId } } }
        ]
      })
    },
    onOpenList() {
      if (this._viewCtx && this._viewCtx.openDetailPage) {
        this._viewCtx.openDetailPage({ url: this.data.relatedPage })
      }
    }
  }
})
