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

Page({
  data: {
    article: null,
    loading: false
  },

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

  onBack() {
    wx.navigateBack()
  },

  async loadArticle(id) {
    this.setData({ loading: true })
    
    try {
      const res = await api.happySchool.getArticleDetail(id)
      console.log('[academy-detail] 文章详情响应:', res)
      
      if (res.success && res.data) {
        const article = res.data
        this.setData({
          article: {
            id: article.id,
            title: article.title,
            cover: this.processImageUrl(article.coverImage),
            content: article.content,
            date: this.formatDate(article.publishTime),
            author: article.author || '心伴康养',
            views: article.readCount || 0
          }
        })
      }
    } catch (err) {
      console.error('[academy-detail] 加载文章详情失败:', err)
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
    } finally {
      this.setData({ loading: false })
    }
  },

  processImageUrl(url) {
    if (!url) return ''
    if (url.startsWith('http://') || url.startsWith('https://')) {
      return url
    }
    return 'https://ai-c.maimanji.com' + (url.startsWith('/') ? '' : '/') + url
  },

  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}`
  }
})
