const api = require('../../../utils/api')

Page({
  data: {
    notice: null,
    loading: true,
    error: null
  },

  onLoad(options) {
    const id = options.id
    if (id) {
      this.loadNoticeDetail(id)
    }
  },

  onBack() {
    wx.navigateBack()
  },

  async loadNoticeDetail(id) {
    this.setData({ loading: true, error: null })
    
    try {
      const res = await api.common.getNotices()
      console.log('[notice-detail] 公告列表响应:', res)
      
      if (res.success && res.data) {
        const noticeList = res.data.filter(item => String(item.id) === String(id))
        
        if (noticeList.length > 0) {
          const item = noticeList[0]
          this.setData({
            notice: {
              id: item.id,
              content: item.content,
              linkType: item.linkType || 'none',
              linkValue: item.linkValue || '',
              createdAt: this.formatDate(item.createdAt)
            }
          })
        } else {
          this.setData({ error: '公告不存在' })
        }
      } else {
        this.setData({ error: res.error || '加载失败' })
      }
    } catch (err) {
      console.error('[notice-detail] 加载公告详情失败:', err)
      this.setData({ error: err.message || '加载失败' })
    } finally {
      this.setData({ loading: false })
    }
  },

  formatDate(dateStr) {
    if (!dateStr) return ''
    const date = new Date(dateStr)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    return `${year}-${month}-${day}`
  }
})
