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

Page({
  data: {
    productId: 0, // 产品ID
    productName: '', // 产品名称
    productImage: '', // 产品图片
    allCopies: [] as any[], // 所有文案
    currentIndex: 0, // 当前显示的文案索引
    currentCopy: null as any, // 当前显示的文案
    loading: false,
    claiming: false, // 领取中
    publishing: false // 发布中
  },

  onLoad(options: any) {
    // 检查登录状态和Token
    const token = wx.getStorageSync('token');
    if (!token) {
      wx.showModal({
        title: '未登录',
        content: '请先登录后再查看文案',
        confirmText: '去登录',
        success: (res) => {
          if (res.confirm) {
            wx.redirectTo({
              url: '/pages/login/login'
            });
          } else {
            wx.navigateBack();
          }
        }
      });
      return;
    }

    // 检查小红书绑定状态
    this.checkXHSBinding().then(isBound => {
      if (!isBound) {
        wx.showModal({
          title: '未绑定小红书',
          content: '查看文案前需要先绑定小红书账号',
          confirmText: '去绑定',
          success: (res) => {
            if (res.confirm) {
              wx.redirectTo({
                url: '/pages/profile/social-binding/social-binding'
              });
            } else {
              wx.navigateBack();
            }
          }
        });
        return;
      }

      // 获取产品ID参数
      if (options.productId) {
        this.setData({
          productId: parseInt(options.productId)
        });
      }

      this.loadCopies();
    });
  },

  // 检查小红书绑定状态
  async checkXHSBinding(): Promise<boolean> {
    try {
      const response = await EmployeeService.getProfile();
      if (response.code === 200 && response.data) {
        return response.data.is_bound_xhs === 1;
      }
      return false;
    } catch (error) {
      console.error('检查绑定状态失败:', error);
      return false;
    }
  },

  onShow() {
    // 每次显示页面时刷新数据
    if (this.data.productId) {
      this.loadCopies();
    }
  },

  // 加载文案列表
  async loadCopies() {
    const productId = this.data.productId;
    
    if (!productId) {
      wx.showToast({
        title: '请先选择产品',
        icon: 'none'
      });
      return;
    }

    this.setData({ loading: true });

    try {
      // 从后端API获取可领取文案
      const response = await EmployeeService.getAvailableCopies(productId);
      
      console.log('===== 文案列表响应 =====');
      console.log('response:', response);
      
      if (response.code === 200 && response.data) {
        const copies = response.data.copies || [];
        const product = response.data.product || {};

        console.log('文案数量:', copies.length);
        if (copies.length > 0) {
          console.log('第一篇文案:', copies[0]);
          console.log('图片数量:', (copies[0].images && copies[0].images.length) || 0);
          console.log('标签数量:', (copies[0].tags && copies[0].tags.length) || 0);
        }

        this.setData({
          allCopies: copies,
          productName: product.name || '',
          productImage: product.image || '',
          currentIndex: 0,
          currentCopy: copies.length > 0 ? copies[0] : null,
          loading: false
        });

        console.log('setData后的 currentCopy:', this.data.currentCopy);

        if (copies.length === 0) {
          wx.showToast({
            title: '暂无可领取文案',
            icon: 'none'
          });
        }
      }
    } catch (error) {
      console.error('加载文案失败:', error);
      this.setData({ loading: false });
      wx.showToast({
        title: '加载文案失败',
        icon: 'none'
      });
    }
  },

  // 换一个文案
  changeArticle() {
    if (this.data.claiming || this.data.publishing) return;
    
    const { allCopies, currentIndex } = this.data;
    
    if (allCopies.length === 0) {
      wx.showToast({
        title: '暂无更多文案',
        icon: 'none'
      });
      return;
    }

    // 切换到下一个文案
    const nextIndex = (currentIndex + 1) % allCopies.length;
    
    this.setData({
      currentIndex: nextIndex,
      currentCopy: allCopies[nextIndex]
    });

    wx.showToast({
      title: `${nextIndex + 1}/${allCopies.length}`,
      icon: 'none',
      duration: 1000
    });
  },

  // 一键发布（先领取，再发布）
  async publishArticle() {
    if (!this.data.currentCopy) {
      wx.showToast({
        title: '请先选择文案',
        icon: 'none'
      });
      return;
    }

    wx.showModal({
      title: '确认发布',
      content: '确定要领取并发布这篇文案吗？',
      confirmText: '发布',
      confirmColor: '#07c160',
      success: async (res) => {
        if (res.confirm) {
          await this.claimAndPublish();
        }
      }
    });
  },

  // 领取并发布
  async claimAndPublish() {
    this.setData({ claiming: true });

    try {
      // 1. 先领取文案
      const claimResponse = await EmployeeService.claimCopy(
        this.data.currentCopy.id,
        this.data.productId
      );

      if (claimResponse.code !== 200) {
        throw new Error(claimResponse.message || '领取失败');
      }

      const claimId = (claimResponse.data && claimResponse.data.claim_id) || null;
      const copyData = (claimResponse.data && claimResponse.data.copy) || null;

      this.setData({ claiming: false, publishing: true });

      // 2. 再发布
      const publishResponse = await EmployeeService.publish({
        copy_id: this.data.currentCopy.id,
        title: (copyData && copyData.title) || this.data.currentCopy.title,
        content: (copyData && copyData.content) || this.data.currentCopy.content,
        publish_link: '',
        xhs_note_id: ''
      });

      if (publishResponse.code === 200) {
        wx.showToast({
          title: '发布成功',
          icon: 'success',
          duration: 2000
        });

        this.setData({ publishing: false });

        // 2秒后返回
        setTimeout(() => {
          wx.navigateBack();
        }, 2000);
      } else {
        throw new Error(publishResponse.message || '发布失败');
      }
    } catch (error: any) {
      console.error('发布失败:', error);
      
      this.setData({ 
        claiming: false,
        publishing: false 
      });
      
      wx.showToast({
        title: error.message || '操作失败',
        icon: 'none'
      });
    }
  },

  // 返回上一页
  goBack() {
    wx.navigateBack();
  },

  goToProfile() {
    wx.redirectTo({
      url: '/pages/profile/profile'
    });
  },

  // 分享功能
  onShareAppMessage() {
    const currentCopy = this.data.currentCopy;
    return {
      title: currentCopy ? currentCopy.title : '精彩种草文案',
      path: `/pages/articles/articles?productId=${this.data.productId}`,
      imageUrl: this.data.productImage || '' // 使用产品图片作为分享封面
    };
  },

  // 分享到朋友圈
  onShareTimeline() {
    return {
      title: `${this.data.productName} - 精彩种草文案`,
      imageUrl: this.data.productImage || ''
    };
  }
});
