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

Page({
  data: {
    articles: [],
    categories: [],
    activeCategory: null,
    page: 1,
    hasMore: true,
    loading: false,
    error: null
  },

  onLoad() {
    this.loadCategories()
    this.loadArticles()
  },

  onBack() {
    wx.navigateBack()
  },

  onArticleTap(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/academy/detail/detail?id=${id}`
    })
  },

  async loadCategories() {
    try {
      const res = await api.happySchool.getCategories()
      console.log('[happy-school] 分类响应:', res)
      
      if (res.success && res.data) {
        let categories = []
        
        if (res.data.length > 0 && res.data[0].id !== null) {
          categories = [
            { id: null, name: '全部' },
            ...res.data.map(cat => ({
              id: cat.id,
              name: cat.name
            }))
          ]
        } else {
          categories = res.data.map(cat => ({
            id: cat.id,
            name: cat.name
          }))
        }
        
        this.setData({ categories })
      }
    } catch (err) {
      console.error('[happy-school] 加载分类失败:', err)
    }
  },

  async loadArticles(reset = true) {
    if (this.data.loading) return
    if (!reset && !this.data.hasMore) return

    this.setData({ loading: true, error: null })
    const page = reset ? 1 : this.data.page + 1

    try {
      const params = {
        page,
        limit: 20
      }

      if (this.data.activeCategory) {
        params.categoryId = this.data.activeCategory
      }

      console.log('[happy-school] 请求文章列表:', params)
      const res = await api.happySchool.getArticles(params)
      console.log('[happy-school] 文章响应:', res)

      if (res.success && res.data) {
        let list = []
        
        if (Array.isArray(res.data)) {
          list = res.data
        } else if (res.data.data && Array.isArray(res.data.data)) {
          list = res.data.data
        } else if (res.data.list && Array.isArray(res.data.list)) {
          list = res.data.list
        }

        const articles = list.map(item => ({
          id: item.id,
          title: item.title,
          summary: item.summary || '',
          cover: this.processImageUrl(item.coverImage),
          date: this.formatDate(item.publishTime),
          views: item.readCount || 0,
          categoryName: item.categoryName || ''
        }))

        this.setData({
          articles: reset ? articles : [...this.data.articles, ...articles],
          page,
          hasMore: articles.length >= params.limit,
          loading: false
        })
      } else {
        this.setData({ 
          loading: false,
          error: res.error || '加载失败'
        })
      }
    } catch (err) {
      console.error('[happy-school] 加载文章失败:', err)
      this.setData({ 
        loading: false,
        error: err.message || '加载失败'
      })
    }
  },

  onCategoryTap(e) {
    const categoryId = e.currentTarget.dataset.id
    if (categoryId === this.data.activeCategory) return

    this.setData({
      activeCategory: categoryId,
      page: 1,
      hasMore: true,
      articles: []
    })
    this.loadArticles(true)
  },

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

  onReachBottom() {
    this.loadArticles(false)
  }
})
