// pages/my/my.js
const app = getApp()

Page({
  data: {
    userInfo: {},
    userStats: {
      readChapters: 0,
      readMinutes: 0,
      bookmarks: 0
    },
    earnings: {
      total: '0.00',
      available: '0.00',
      withdrawn: '0.00'
    },
    referralData: {
      totalUsers: 0,
      totalOrders: 0,
      commissionRate: 90
    },
    menuBadges: {
      orders: 0
    },
    showPoster: false
  },

  onLoad(options) {
    // 检查是否有tab参数
    if (options.tab === 'referral') {
      // 自动展开分销中心
      this.setData({ expandReferral: true })
    }
  },

  onShow() {
    this.loadUserInfo()
    this.loadUserStats()
    this.loadEarnings()
    this.loadReferralData()
  },

  // 加载用户信息
  loadUserInfo() {
    const userInfo = app.getUserInfo()
    
    if (userInfo) {
      this.setData({ userInfo })
    } else {
      // 未登录状态
      this.setData({
        userInfo: {
          avatar: '',
          nickname: '点击登录',
          id: '',
          inviteCode: ''
        }
      })
    }
  },

  // 加载用户统计
  loadUserStats() {
    const token = wx.getStorageSync('token')
    if (!token) return

    wx.request({
      url: `${app.globalData.apiBase}/user/stats`,
      header: {
        'Authorization': `Bearer ${token}`
      },
      success: (res) => {
        if (res.statusCode === 200) {
          this.setData({
            userStats: res.data.stats
          })
        }
      },
      fail: () => {
        // 使用缓存数据
        const cached = wx.getStorageSync('userStats')
        if (cached) {
          this.setData({ userStats: cached })
        }
      }
    })
  },

  // 加载收益数据
  loadEarnings() {
    const token = wx.getStorageSync('token')
    if (!token) return

    wx.request({
      url: `${app.globalData.apiBase}/referral/earnings`,
      header: {
        'Authorization': `Bearer ${token}`
      },
      success: (res) => {
        if (res.statusCode === 200) {
          this.setData({
            earnings: {
              total: res.data.total || '0.00',
              available: res.data.available || '0.00',
              withdrawn: res.data.withdrawn || '0.00'
            }
          })
        }
      }
    })
  },

  // 加载推广数据
  loadReferralData() {
    const token = wx.getStorageSync('token')
    if (!token) return

    wx.request({
      url: `${app.globalData.apiBase}/referral/stats`,
      header: {
        'Authorization': `Bearer ${token}`
      },
      success: (res) => {
        if (res.statusCode === 200) {
          this.setData({
            referralData: res.data
          })
        }
      }
    })
  },

  // 编辑资料
  editProfile() {
    const userInfo = this.data.userInfo
    
    if (!userInfo.id) {
      // 未登录，执行登录
      this.doLogin()
      return
    }

    wx.navigateTo({
      url: '/pages/profile/edit'
    })
  },

  // 执行登录
  doLogin() {
    wx.showLoading({ title: '登录中...', mask: true })
    
    app.wxLogin((success, user) => {
      wx.hideLoading()
      
      if (success) {
        wx.showToast({
          title: '登录成功',
          icon: 'success'
        })
        this.setData({ userInfo: user })
        this.loadUserStats()
        this.loadEarnings()
        this.loadReferralData()
      } else {
        wx.showToast({
          title: '登录失败',
          icon: 'none'
        })
      }
    })
  },

  // 生成推广海报
  generatePoster() {
    const userInfo = this.data.userInfo
    
    if (!userInfo.id) {
      this.showLoginModal()
      return
    }

    this.setData({ showPoster: true })
    
    wx.showLoading({ title: '生成中...', mask: true })
    
    // 使用Canvas绘制海报
    setTimeout(() => {
      this.drawPoster()
      wx.hideLoading()
    }, 500)
  },

  // 绘制海报
  drawPoster() {
    const ctx = wx.createCanvasContext('posterCanvas')
    const userInfo = this.data.userInfo
    
    // 背景
    ctx.setFillStyle('#000000')
    ctx.fillRect(0, 0, 375, 500)
    
    // 渐变背景
    const gradient = ctx.createLinearGradient(0, 0, 0, 500)
    gradient.addColorStop(0, 'rgba(255, 77, 79, 0.3)')
    gradient.addColorStop(1, 'rgba(0, 0, 0, 0)')
    ctx.setFillStyle(gradient)
    ctx.fillRect(0, 0, 375, 500)
    
    // 标题
    ctx.setFontSize(32)
    ctx.setFillStyle('#FFFFFF')
    ctx.setTextAlign('center')
    ctx.fillText('Soul派对·创业实验', 187.5, 60)
    
    // 邀请码
    ctx.setFontSize(48)
    ctx.setFillStyle('#FF4D4F')
    ctx.fillText(userInfo.inviteCode || 'XXXXXX', 187.5, 250)
    
    // 提示文字
    ctx.setFontSize(24)
    ctx.setFillStyle('rgba(255, 255, 255, 0.8)')
    ctx.fillText('使用此邀请码购买，双方都有佣金！', 187.5, 320)
    
    // 二维码占位
    ctx.setStrokeStyle('#FFFFFF')
    ctx.strokeRect(137.5, 360, 100, 100)
    ctx.setFontSize(16)
    ctx.setFillStyle('rgba(255, 255, 255, 0.5)')
    ctx.fillText('扫码阅读', 187.5, 420)
    
    ctx.draw()
  },

  // 关闭海报
  closePoster() {
    this.setData({ showPoster: false })
  },

  // 阻止冒泡
  stopPropagation() {},

  // 保存海报
  savePoster() {
    wx.canvasToTempFilePath({
      canvasId: 'posterCanvas',
      success: (res) => {
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: () => {
            wx.showToast({
              title: '保存成功',
              icon: 'success'
            })
            this.closePoster()
          },
          fail: () => {
            wx.showToast({
              title: '保存失败',
              icon: 'none'
            })
          }
        })
      }
    })
  },

  // 提现
  withdraw() {
    const earnings = this.data.earnings
    const available = parseFloat(earnings.available)
    
    if (available < 1) {
      wx.showToast({
        title: '可提现金额不足1元',
        icon: 'none'
      })
      return
    }

    wx.navigateTo({
      url: `/pages/withdraw/withdraw?amount=${available}`
    })
  },

  // 复制邀请码
  copyInviteCode() {
    const inviteCode = this.data.userInfo.inviteCode
    
    if (!inviteCode) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
      return
    }

    wx.setClipboardData({
      data: inviteCode,
      success: () => {
        wx.showToast({
          title: '已复制邀请码',
          icon: 'success'
        })
      }
    })
  },

  // 查看推荐列表
  viewReferrals() {
    wx.navigateTo({
      url: '/pages/referral/list'
    })
  },

  // 查看订单列表
  viewOrders() {
    wx.navigateTo({
      url: '/pages/referral/orders'
    })
  },

  // 查看佣金明细
  viewCommission() {
    wx.navigateTo({
      url: '/pages/referral/commission'
    })
  },

  // 我的订单
  goToOrders() {
    wx.navigateTo({
      url: '/pages/orders/list'
    })
  },

  // 阅读历史
  goToReadHistory() {
    wx.navigateTo({
      url: '/pages/history/read'
    })
  },

  // 阅读时长
  goToReadTime() {
    wx.showToast({
      title: '功能开发中',
      icon: 'none'
    })
  },

  // 书签
  goToBookmarks() {
    wx.navigateTo({
      url: '/pages/bookmarks/list'
    })
  },

  // 阅读笔记
  goToNotes() {
    wx.navigateTo({
      url: '/pages/notes/list'
    })
  },

  // 设置
  goToSettings() {
    wx.navigateTo({
      url: '/pages/settings/index'
    })
  },

  // 联系客服
  contactSupport() {
    wx.showToast({
      title: '客服功能开发中',
      icon: 'none'
    })
  },

  // 关于我们
  about() {
    wx.navigateTo({
      url: '/pages/about/index'
    })
  },

  // 退出登录
  logout() {
    wx.showModal({
      title: '提示',
      content: '确定要退出登录吗？',
      success: (res) => {
        if (res.confirm) {
          wx.removeStorageSync('token')
          wx.removeStorageSync('userInfo')
          app.globalData.userInfo = null
          
          this.setData({
            userInfo: {
              avatar: '',
              nickname: '点击登录',
              id: '',
              inviteCode: ''
            },
            earnings: {
              total: '0.00',
              available: '0.00',
              withdrawn: '0.00'
            },
            referralData: {
              totalUsers: 0,
              totalOrders: 0,
              commissionRate: 90
            }
          })
          
          wx.showToast({
            title: '已退出登录',
            icon: 'success'
          })
        }
      }
    })
  },

  // 显示登录弹窗
  showLoginModal() {
    wx.showModal({
      title: '需要登录',
      content: '请先登录账号',
      confirmText: '立即登录',
      success: (res) => {
        if (res.confirm) {
          this.doLogin()
        }
      }
    })
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadUserInfo()
    this.loadUserStats()
    this.loadEarnings()
    this.loadReferralData()
    
    setTimeout(() => {
      wx.stopPullDownRefresh()
    }, 1000)
  }
})
