// pages/profile/article-detail/article-detail.ts
import { EmployeeService } from '../../../services/employee';

Page({
  data: {
    articleId: 0,
    productName: '',
    article: {
      title: '',
      content: '',
      topic: '',
      publishLink: '',  // 小红书链接
      images: [] as Array<{
        id: number;
        image_url: string;
        image_thumb_url: string;
        sort_order: number;
        keywords_name: string;
      }>,
      tags: [] as string[]
    },
    loading: true
  },

  onLoad(options: any) {
    if (options.id) {
      this.setData({
        articleId: parseInt(options.id)
      });
      this.loadArticleDetail();
    }
  },

  async loadArticleDetail() {
    try {
      // 调用专门的详情API
      const response = await EmployeeService.getPublishRecordDetail(this.data.articleId);
      
      console.log('=== 详情响应 ===', response);
      console.log('response.data:', response.data);
      
      if (response.code === 200 && response.data) {
        console.log('product_name:', response.data.product_name);
        console.log('title:', response.data.title);
        console.log('content:', response.data.content);
        console.log('images:', response.data.images);
        console.log('tags:', response.data.tags);
        console.log('topic:', response.data.topic);
        
        this.setData({
          productName: response.data.product_name || '未知商品',
          article: {
            title: response.data.title || '',
            content: response.data.content || '',
            topic: response.data.topic || '',
            publishLink: response.data.publish_link || '',  // 获取小红书链接
            images: response.data.images || [],  // 获取图片列表
            tags: response.data.tags || []  // 获取标签列表
          },
          loading: false
        });
        
        console.log('=== 设置后的数据 ===');
        console.log('productName:', this.data.productName);
        console.log('article:', this.data.article);
      } else {
        throw new Error(response.message || '加载失败');
      }
    } catch (error: any) {
      console.error('加载文章详情失败:', error);
      this.setData({ loading: false });
      
      wx.showToast({
        title: error.message || '加载失败',
        icon: 'none'
      });
      
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },

  // 分享链接（自动复制）
  shareArticle() {
    const publishLink = this.data.article.publishLink;
    
    if (!publishLink) {
      wx.showToast({
        title: '暂无发布链接',
        icon: 'none'
      });
      return;
    }

    // 复制到剪贴板
    wx.setClipboardData({
      data: publishLink,
      success: () => {
        wx.showToast({
          title: '链接已复制',
          icon: 'success',
          duration: 2000
        });
      },
      fail: () => {
        wx.showToast({
          title: '复制失败',
          icon: 'none'
        });
      }
    });
  }
});
