// pages/zuzhangduan/zuzhangduan.js
import request from '../../utils/request.js'

Page({
  data: {
    // 页面状态
    isZuzhang: false,
    isLoading: false,
    
    // 邀请码相关
    inviteCode: '',
    
    // 用户信息
    uid: '',
    nicheng: '',
    avatarUrl: '',
    
    // 组长信息
    ketixian: '0.00',        // 可提现金额
    guanshiCount: 0,         // 邀请的管事数量
    fenhongZonge: '0.00',    // 分红总额
  },

  onLoad() {
    this.checkLoginStatus()
  },

  onShow() {
    this.registerNotificationComponent()
    if (this.data.isZuzhang) {
      this.getZuzhangInfo()
    }
  },

  // 检查登录状态
  checkLoginStatus() {
    const token = wx.getStorageSync('token')
    if (!token) {
      wx.showModal({
        title: '提示',
        content: '您尚未登录，请先登录',
        confirmText: '去登录',
        success: (res) => {
          if (res.confirm) {
            wx.reLaunch({ url: '/pages/gerenzhongxin/gerenzhongxin' })
          }
        }
      })
      return false
    }
    this.checkZuzhangStatus()
    return true
  },

  // 检查组长状态
  checkZuzhangStatus() {
    try {
      const zuzhangstatus = wx.getStorageSync('zuzhangstatus')
      if (zuzhangstatus === 1) {
        this.setData({ isZuzhang: true })
        this.loadUserInfo()
        this.getZuzhangInfo()
      } else {
        this.setData({ isZuzhang: false })
      }
    } catch (error) {
      console.error('读取缓存失败:', error)
      this.setData({ isZuzhang: false })
    }
  },

  // 加载用户信息
  loadUserInfo() {
    const app = getApp()
    const globalData = app.globalData || {}
    
    const touxiang = wx.getStorageSync('touxiang')
    const ossImageUrl = globalData.ossImageUrl || ''
    const morentouxiang = globalData.morentouxiang || 'avatar/default.jpg'
    
    let avatarUrl = ''
    if (touxiang) {
      avatarUrl = ossImageUrl + (touxiang.startsWith('/') ? touxiang : '/' + touxiang)
    } else {
      avatarUrl = ossImageUrl + (morentouxiang.startsWith('/') ? morentouxiang : '/' + morentouxiang)
    }
    
    const uid = wx.getStorageSync('uid') || ''
    const nicheng = wx.getStorageSync('nicheng') || globalData.nicheng || ''
    
    this.setData({ avatarUrl, uid, nicheng })
  },

  // 注册通知组件
  registerNotificationComponent() {
    const app = getApp()
    const notificationComp = this.selectComponent('#global-notification')
    if (notificationComp && notificationComp.showNotification) {
      app.globalData.globalNotification = {
        show: (data) => notificationComp.showNotification(data),
        hide: () => notificationComp.hideNotification()
      }
    }
  },

  // 获取组长信息（刷新）
  async getZuzhangInfo() {
    this.setData({ isLoading: true })
    try {
      const res = await request({
        url: '/yonghu/zuzhangxinxi',
        method: 'POST'
      })
      if (res && res.data.code === 200) {
        const data = res.data.data
        this.setData({
          ketixian: data.ketixian || '0.00',
          guanshiCount: data.guanshiCount || 0,
          fenhongZonge: data.fenhongZonge || '0.00',
          isLoading: false
        })
        wx.showToast({ title: '刷新成功', icon: 'success', duration: 1500 })
      } else {
        throw new Error(res?.data?.msg || '获取信息失败')
      }
    } catch (error) {
      console.error('获取组长信息失败:', error)
      this.setData({ isLoading: false })
      wx.showToast({ title: error.message || '刷新失败', icon: 'none' })
    }
  },

  // 刷新按钮点击
  refreshZuzhangInfo() {
    this.getZuzhangInfo()
  },

  // 邀请码输入
  onInviteCodeInput(e) {
    this.setData({ inviteCode: e.detail.value.trim() })
  },

  // 注册组长
  async onRegister() {
    const { inviteCode } = this.data
    if (!inviteCode) {
      wx.showToast({ title: '请输入邀请码', icon: 'none', duration: 2000 })
      return
    }
    if (inviteCode.length > 100) {
      wx.showToast({ title: '邀请码不能超过100字符', icon: 'none', duration: 2000 })
      return
    }

    this.setData({ isLoading: true })
    try {
      const res = await request({
        url: '/yonghu/zuzhangzhuce',
        method: 'POST',
        data: { inviteCode }
      })
      if (res && res.data.code === 200) {
        wx.setStorageSync('zuzhangstatus', 1)
        const data = res.data.data
        this.setData({
          isZuzhang: true,
          ketixian: data.ketixian || '0.00',
          guanshiCount: data.guanshiCount || 0,
          fenhongZonge: data.fenhongZonge || '0.00',
          isLoading: false
        })
        this.loadUserInfo()
        wx.showToast({ title: '注册成功！', icon: 'success', duration: 2000 })
      } else {
        throw new Error(res?.data?.msg || '注册失败')
      }
    } catch (error) {
      console.error('注册失败:', error)
      this.setData({ isLoading: false })
      wx.showToast({ title: error.message || '注册失败', icon: 'error' })
    }
  },

  // 🔥【修改】跳转到提现页面，传递from=zuzhang参数
  goToWithdraw() {
    const { ketixian } = this.data
    wx.navigateTo({
      url: `/pages/tixian/tixian?from=zuzhang&amount=${ketixian}`
    })
  },

  // 跳转到分红记录页面
  goToFenhongJilu() {
    wx.navigateTo({ url: '/pages/zzfhjilu/zzfhjilu' })
  },

  // 跳转到邀请管事页面
  goToYaoqingGuanshi() {
    wx.navigateTo({ url: '/pages/yqguanshi/yqguanshi' })
  }
})