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

Page({
  data: {
    article: null,
    formatDate: ''
  },
  onLoad: function (options) {
    this.articleManager = new ArticleManager();

    // 如果有指定文章ID，则显示该文章
    if (options.id) {
      this.loadArticle(options.id);
    } else {
      // 否则显示最新文章
      const latestArticle = this.articleManager.getLatestArticle();
      if (latestArticle) {
        this.loadArticle(latestArticle.id);
      }
    }
  },
  // 加载指定ID的文章
  loadArticle: function(id) {
    const article = this.articleManager.getArticleById(id);
    if (article) {      // 格式化日期
      const date = new Date(article.createTime);
      const formattedDate = formatDate(date);      this.setData({
        article: article,
        formatDate: formattedDate
      });
    }  },

  // 分享功能
  onShareAppMessage: function () {
    if (this.data.article) {
      return {
        title: this.data.article.title,
        path: `/pages/article/article?id=${this.data.article.id}`
      };
    }
    return {
      title: '精选文章',
      path: '/pages/article/article'
    };
  }
})