// index.js
const { ArticleManager } = require('../../models/articleManager');
const { formatDate } = require('../../utils/util');

Page({
  data: {
    bannerList: [
      { imageUrl: 'https://www.meetstarry.com/banner1.png', title: '1' },
      { imageUrl: 'https://www.meetstarry.com/banner2.png', title: '2' },
      { imageUrl: 'https://www.meetstarry.com/banner3.png', title: '3' }
    ],
    article: null,
    formatDate: ''
  },

  onLoad() {
    // 实例化文章管理器
    this.articleManager = new ArticleManager();
    
    // 获取最新的一篇文章
    const latestArticle = this.articleManager.getLatestArticle();
    if (latestArticle) {
      // 格式化日期
      const date = new Date(latestArticle.createTime);
      const formattedDate = formatDate(date);
      
      this.setData({
        article: latestArticle,
        formatDate: formattedDate
      });
    }
  },
  
  /**
   * 图片加载错误处理
   */
  onImageError(e) {
    const index = e.currentTarget.dataset.index;
    const app = getApp();
    const defaultImage = app.globalData.imageManager ? app.globalData.imageManager.defaultImage : 'https://www.meetstarry.com/default.png';
    
    // 处理轮播图错误
    if (typeof index !== 'undefined') {
      const key = `bannerList[${index}].imageUrl`;
      this.setData({
        [key]: defaultImage
      });
    }
  },
  
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: '精选文章',
      path: '/pages/index/index'
    };
  }
})
