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,
    detail: {}
  },
  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 countText = sc.maxCount ? `${sc.currentCount || 0}/${sc.maxCount}` : '不限'
        this.setData({
          loaded: true,
          detail: {
            ...sc,
            coverUrl: meta.coverUrl,
            relatedPage: meta.relatedPage || sc.relatedPage,
            timeText: formatTime(sc.startTime, sc.endTime),
            countText,
            registerButtonText: sc.registerButtonText || (sc.registerable ? '报名' : '暂不可报名')
          }
        })
      })
    }
  },
  methods: {
    onRegister() {
      const detail = this.data.detail
      if (!detail || !detail.activityId) return
      this._modelCtx.sendFollowUpMessage({
        content: [
          { type: 'text', text: `我要报名：${detail.title}` },
          { type: 'api/call', data: { name: 'prepareActivityRegistration', arguments: { activityId: detail.activityId } } }
        ]
      })
    },
    onOpenPage() {
      const url = this.data.detail.relatedPage
      if (url && this._viewCtx && this._viewCtx.openDetailPage) {
        this._viewCtx.openDetailPage({ url })
      }
    }
  }
})
