// pages/promote/promote.js - 合作推广页面

const api = require('../../utils/api')

Page({
  data: {
    statusBarHeight: 44,
    navBarHeight: 44,
    totalNavHeight: 88,
    showModal: false, // 控制弹窗显示
    // 推广数据
    isDistributor: false,
    referralCode: '',
    commissionStats: {
      totalReferrals: 0,
      commissionBalance: 0,
      totalEarned: 0
    },
    referrals: [], // Recent referrals for grid
    defaultAvatar: 'https://images.unsplash.com/photo-1534528741775-53994a69daeb?w=500&auto=format&fit=crop&q=60',
    loading: false,
    // 分享配置
    shareConfig: null
  },

  onLoad() {
    // Calculat nav bar height
    const systemInfo = wx.getSystemInfoSync()
    const statusBarHeight = systemInfo.statusBarHeight || 44
    const menuButton = wx.getMenuButtonBoundingClientRect()
    const navBarHeight = menuButton.height + (menuButton.top - statusBarHeight) * 2
    const totalNavHeight = statusBarHeight + navBarHeight

    this.setData({
      statusBarHeight,
      navBarHeight,
      totalNavHeight
    })

    this.loadPromotionData()
    this.loadShareConfig()
  },

  /**
   * 加载分享配置
   */
  async loadShareConfig() {
    try {
      const res = await api.promotion.getShareConfig('promote')
      if (res.success && res.data) {
        const util = require('../../utils/util')
        const shareConfig = {
          ...res.data,
          imageUrl: res.data.imageUrl ? util.getFullImageUrl(res.data.imageUrl) : ''
        }
        this.setData({ shareConfig })
      }
    } catch (error) {
      console.error('加载分享配置失败:', error)
    }
  },

  /**
   * 加载推广数据
   */
  async loadPromotionData() {
    this.setData({ loading: true })

    try {
      // 1. Get Stats
      const res = await api.commission.getStats()
      if (res.success && res.data) {
        this.setData({
          commissionStats: {
            totalReferrals: res.data.totalReferrals || 0,
            commissionBalance: (res.data.commissionBalance || 0).toFixed(2),
            totalEarned: res.data.totalCommission || 0,
            // 绑定到 WXML 中的字段
            shareCount: res.data.shareCount || 0,
            registeredCount: res.data.totalReferrals || 0,
            orderCount: res.data.orderCount || 0
          },
          referralCode: res.data.referralCode || '',
          isDistributor: res.data.isDistributor || false
        })
      }

      // 2. Get Referrals Preview (Limit 10 for list)
      const refRes = await api.commission.getReferrals({ page: 1, limit: 10, sortBy: 'time' })
      if (refRes.success && refRes.data) {
        const util = require('../../utils/util')
        const list = (refRes.data.list || refRes.data || []).map(item => {
          let avatar = item.avatar || item.avatarUrl || item.userAvatar;
          if (avatar) {
            avatar = util.getFullImageUrl(avatar);
          }
          const joinedAtRaw = item.boundAt || item.createdAt || '';
          const joinedAt = joinedAtRaw ? util.formatTime(joinedAtRaw, 'YYYY-MM-DD') : '';
          return {
            userId: item.id || item.userId,
            userName: item.nickname || item.userName || item.name || '未知用户',
            userAvatar: avatar || this.data.defaultAvatar,
            level: item.levelText || item.roleName || '普通用户',
            joinedAt: joinedAt,
            referralCount: item.referralCount || 0,
            performance: item.totalContribution || 0
          };
        });
        this.setData({
          referrals: list
        });
      }

      this.setData({ loading: false })
    } catch (error) {
      console.error('加载推广数据失败:', error)
      this.setData({ loading: false })
    }
  },

  onWithdraw() {
    wx.navigateTo({
      url: '/pages/withdraw/withdraw'
    })
  },

  // goToReferrals removed

  /**
   * 返回上一页
   */
  goBack() {
    wx.navigateBack({
      fail: () => {
        // 如果无法返回，跳转到个人中心
        wx.switchTab({ url: '/pages/profile/profile' })
      }
    })
  },

  /**
   * 显示合作推广弹窗
   */
  showPromotionModal() {
    this.setData({ showModal: true })
  },

  /**
   * 关闭合作推广弹窗
   */
  closeModal() {
    this.setData({ showModal: false })
  },

  /**
   * 阻止弹窗内容区域点击事件冒泡
   */
  preventClose() {
    // 空函数，阻止事件冒泡
  },

  /**
   * 申请合作推广
   */
  applyPromotion() {
    if (this.data.isDistributor) {
      wx.showToast({
        title: '您已是分销商',
        icon: 'none',
        duration: 2000
      })
      return
    }

    wx.showModal({
      title: '成为分销商',
      content: '购买身份卡即可成为分销商，推荐好友赚佣金！',
      confirmText: '了解详情',
      cancelText: '暂不需要',
      confirmColor: '#B06AB3',
      success: (res) => {
        if (res.confirm) {
          // 跳转到充值页面购买身份卡
          wx.navigateTo({
            url: '/pages/recharge/recharge'
          })
        }
      }
    })
  },

  /**
   * 跳转到佣金中心
   */
  goToCommission() {
    wx.navigateTo({
      url: '/pages/commission/commission'
    })
  },

  goToPoster() {
    wx.navigateTo({
      url: '/pages/promote-poster/promote-poster'
    })
  },

  /**
   * 预览推广素材
   */
  previewMaterial(e) {
    const { index } = e.currentTarget.dataset
    const material = this.data.materials[index]

    wx.previewImage({
      current: material.image,
      urls: this.data.materials.map(m => m.image)
    })
  },

  /**
   * 下载推广素材
   */
  downloadMaterial(e) {
    const { index } = e.currentTarget.dataset
    const material = this.data.materials[index]

    wx.showLoading({ title: '下载中...' })

    wx.downloadFile({
      url: material.image,
      success: (res) => {
        wx.hideLoading()
        if (res.statusCode === 200) {
          wx.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success: () => {
              wx.showToast({
                title: '已保存到相册',
                icon: 'success'
              })
            },
            fail: () => {
              wx.showToast({
                title: '保存失败',
                icon: 'none'
              })
            }
          })
        }
      },
      fail: () => {
        wx.hideLoading()
        wx.showToast({
          title: '下载失败',
          icon: 'none'
        })
      }
    })
  },

  /**
   * 查看教程详情
   */
  viewTutorial(e) {
    const { index } = e.currentTarget.dataset
    const tutorial = this.data.tutorials[index]

    wx.showModal({
      title: tutorial.title,
      content: tutorial.content,
      showCancel: false,
      confirmText: '知道了'
    })
  },

  /**
   * 复制推荐码
   */
  copyReferralCode() {
    if (!this.data.referralCode) {
      wx.showToast({
        title: '暂无推荐码',
        icon: 'none'
      })
      return
    }

    wx.setClipboardData({
      data: this.data.referralCode,
      success: () => {
        wx.showToast({
          title: '已复制推荐码',
          icon: 'success'
        })
      }
    })
  },

  /**
   * 分享推荐码
   */
  onShareAppMessage() {
    const { referralCode, isDistributor, shareConfig } = this.data
    const referralCodeParam = referralCode ? `?referralCode=${referralCode}` : ''

    // 记录分享行为
    api.promotion.recordShare({
      type: 'app_message',
      page: '/pages/promote/promote',
      referralCode: referralCode
    }).then(() => {
      this.loadPromotionData()
    }).catch(err => console.error('记录分享失败:', err))

    // 如果有分享配置且是分销商，使用配置内容
    if (shareConfig && isDistributor && referralCode) {
      return {
        title: shareConfig.title,
        path: `${shareConfig.path || '/pages/index/index'}${referralCodeParam}`,
        imageUrl: shareConfig.imageUrl
      }
    }

    // 默认分享逻辑
    if (!isDistributor || !referralCode) {
      return {
        title: '心伴AI - 情感陪伴聊天机器人',
        path: '/pages/index/index',
        imageUrl: '/images/share-cover.jpg'
      }
    }

    return {
      title: `我的推荐码：${referralCode}，注册即可享受优惠！`,
      path: `/pages/index/index?referralCode=${referralCode}`,
      imageUrl: '/images/share-commission.png'
    }
  },

  /**
   * 分享到朋友圈
   */
  onShareTimeline() {
    const { referralCode, isDistributor, shareConfig } = this.data
    const query = referralCode ? `referralCode=${referralCode}` : ''

    // 记录分享行为
    api.promotion.recordShare({
      type: 'timeline',
      page: '/pages/promote/promote',
      referralCode: referralCode
    }).then(() => {
      this.loadPromotionData()
    }).catch(err => console.error('记录分享失败:', err))

    // 如果有分享配置且是分销商，使用配置内容
    if (shareConfig && isDistributor && referralCode) {
      return {
        title: shareConfig.title,
        query: query || shareConfig.query,
        imageUrl: shareConfig.imageUrl
      }
    }

    // 默认分享逻辑
    if (!isDistributor || !referralCode) {
      return {
        title: '心伴AI - 情感陪伴聊天机器人',
        imageUrl: '/images/share-cover.jpg'
      }
    }

    return {
      title: `我的推荐码：${referralCode}，注册即可享受优惠！`,
      query: `referralCode=${referralCode}`,
      imageUrl: '/images/share-commission.png'
    }
  }
})
