// pages/article-detail/article-detail.ts
import { formatDate, getStatusInfo, getChannelInfo, getCoverColor, getCoverIcon } from '../../utils/util'
import { EmployeeService } from '../../services/employee'

Page({
  data: {
    article: {} as any,
    copyId: 0, // 文案ID
    productId: 0, // 产品ID
    showClaimButton: true // 是否显示领取按钮
  },

  onLoad(options: any) {
    const copyId = parseInt(options.id);
    const productId = parseInt(options.productId || '0');
    
    this.setData({
      copyId,
      productId
    });
    
    // 如果有copyId，显示文案详情
    if (copyId) {
      this.setData({
        article: {
          id: copyId,
          title: '正在加载...',
          content: ''
        }
      });
    }
  },

  // 领取文案
  async claimCopy() {
    const { copyId, productId } = this.data;

    if (!copyId || !productId) {
      wx.showToast({
        title: '参数错误',
        icon: 'none'
      });
      return;
    }

    try {
      const response = await EmployeeService.claimCopy(copyId, productId);

      if (response.code === 200 && response.data) {
        wx.showToast({
          title: '领取成功',
          icon: 'success'
        });

        // 隐藏领取按钮
        this.setData({
          showClaimButton: false
        });

        // 延迟后跳转到发布页面，传递领取信息
        setTimeout(() => {
          const copy = response.data!.copy;
          wx.redirectTo({
            url: `/pages/article-generate/article-generate?copyId=${copyId}&claimId=${response.data!.claim_id}&productId=${productId}&productName=${encodeURIComponent(copy.title)}&title=${encodeURIComponent(copy.title)}&content=${encodeURIComponent(copy.content)}`
          });
        }, 1500);
      }
    } catch (error) {
      console.error('领取文案失败:', error);
    }
  },

  // 分享功能
  onShareAppMessage() {
    const article = this.data.article;
    return {
      title: article.title || '精彩种草文案',
      path: `/pages/article-detail/article-detail?id=${this.data.copyId}&productId=${this.data.productId}`,
      imageUrl: '' // 可以设置文章封面图
    };
  },

  // 分享到朋友圈
  onShareTimeline() {
    const article = this.data.article;
    return {
      title: article.title || '精彩种草文案',
      imageUrl: '' // 可以设置文章封面图
    };
  }
});
