// pages/jinpaids/jinpaids.js
import request from '../../utils/request.js'
import popupService from '../../services/popupService.js'

const app = getApp()

Page({
  data: {
    // OSS地址
    ossImageUrl: '',
    
    // 图标路径
    icons: {
      jinpai: '',
      refresh: '',
      copy: '',
      qiangdan: '',
      chongzhi: '',
      dingdan: '',
      chufa: '',
      paihang: '',
      xiugai: '',
      tixian: '',
      rightArrow: ''
    },
    
    // 用户基本信息
    uid: '',
    touxiang: '',
    avatarUrl: '',
    dashouNicheng: '',
    
    // 打手核心数据
    chenghao: '',
    yongjin: '0.00',
    zonge: '0.00',
    yajin: '0.00',
    jinfen: '0',
    chengjiaoliang: '0',
    zaixianZhuangtai: 0,
    dashouzhuangtai: '',
    clumber: [],
    
    // 金牌专属数据
    jiedanZongliang: '0',
    jinriJiedan: '0.00',
    zuijinTixian: '0.00',
    
    // 页面状态
    isLoading: false,
    lastRefreshTime: 0,
    canRefresh: true,
    
    // 计算数据
    chengjiaoRate: '0%',
    chengjiaoAngle: 0,
    tixianProgress: 0,

    // 邀请人缓存（管事）
    inviterCache: null,
    chenghaoList: []  // 新增
  },

  onLoad() {
    const ossUrl = app.globalData.ossImageUrl || ''
    const iconBase = 'beijing/tubiao/'
    
    this.setData({
      ossImageUrl: ossUrl,
      'icons.jinpai': ossUrl + iconBase + 'jinpai.png',
      'icons.refresh': ossUrl + iconBase + 'shuaxin.png',
      'icons.copy': ossUrl + iconBase + 'fuzhi.png',
      'icons.qiangdan': ossUrl + iconBase + 'qiangdan.png',
      'icons.chongzhi': ossUrl + iconBase + 'chongzhi.png',
      'icons.dingdan': ossUrl + iconBase + 'dingdan.png',
      'icons.chufa': ossUrl + iconBase + 'chufa.png',
      'icons.paihang': ossUrl + iconBase + 'paihang.png',
      'icons.xiugai': ossUrl + iconBase + 'xiugai.png',
      'icons.tixian': ossUrl + iconBase + 'tixian.png',
      'icons.rightArrow': ossUrl + iconBase + 'jiantou.png',
      'icons.guize': ossUrl + iconBase + 'guize.png',
      'icons.kaohe': ossUrl + iconBase + 'kaohe.png',
    })
    
    this.loadUserInfo()
    this.getJinpaiInfo()

    if (!app.globalData.hasShownPopupOnColdStart) {
        app.globalData.hasShownPopupOnColdStart = true;
        setTimeout(() => {
          popupService.checkAndShow(this, 'jinpaids');
        }, 300);
    }
  },

  onHide() {
    const popupComp = this.selectComponent('#popupNotice');
    if (popupComp && popupComp.cleanup) {
      popupComp.cleanup();
    }
  },

  onShow() {
    this.registerNotificationComponent()
    this.refreshJinpaiInfo()
    this.fetchChenghaoList()  // 新增
    const inviterCache = wx.getStorageSync('inviterCache') || null
    this.setData({ inviterCache })
  },

  registerNotificationComponent() {
    const notificationComp = this.selectComponent('#global-notification')
    if (notificationComp && notificationComp.showNotification) {
      app.globalData.globalNotification = {
        show: (data) => notificationComp.showNotification(data),
        hide: () => notificationComp.hideNotification()
      }
    }
  },

  loadUserInfo() {
    const uid = wx.getStorageSync('uid') || ''
    const touxiang = wx.getStorageSync('touxiang') || ''
    const ossUrl = app.globalData.ossImageUrl || ''
    const defaultAvatar = ossUrl + (app.globalData.morentouxiang || 'avatar/default.jpg')
    
    let avatarUrl = defaultAvatar
    if (touxiang) {
      avatarUrl = ossUrl + (touxiang.startsWith('/') ? touxiang : '/' + touxiang)
    }
    
    const dashouNicheng = app.globalData.dashouNicheng || wx.getStorageSync('nicheng') || '金牌选手'
    
    this.setData({ uid, touxiang, avatarUrl, dashouNicheng })
  },

  async getJinpaiInfo() {
    this.setData({ isLoading: true })
    
    try {
      const res = await request({
        url: '/yonghu/dashouxinxi',
        method: 'POST'
      })
      
      if (res && res.data.code === 200) {
        const data = res.data.data
        
        const updateData = {
          dashouNicheng: data.dashounicheng || '',
          zhanghaoStatus: data.zhanghaostatus || '',
          yongjin: data.yongjin || '0.00',
          zonge: data.zonge || '0.00',
          yajin: data.yajin || '0.00',
          chenghao: data.chenghao || '',
          jinfen: data.jifen || '0',
          chengjiaoliang: data.chengjiaoliang || '0',
          zaixianZhuangtai: data.zaixianzhuangtai || 0,
          dashouzhuangtai: data.dashouzhuangtai || '',
          clumber: data.clumber || [],
          jiedanZongliang: data.jiedanZongliang || '0',
          jinriJiedan: data.jinriJiedan || '0.00',
          zuijinTixian: data.zuijinTixian || '0.00',
        }
        
        const jiedanTotal = parseFloat(updateData.jiedanZongliang) || 0
        const chengjiaoTotal = parseFloat(updateData.chengjiaoliang) || 0
        const rateNumber = jiedanTotal > 0 ? (chengjiaoTotal / jiedanTotal) * 100 : 0
        const chengjiaoRate = rateNumber.toFixed(1) + '%'
        const chengjiaoAngle = rateNumber * 3.6
        
        const zuijin = parseFloat(updateData.zuijinTixian) || 0
        const zong = parseFloat(updateData.jinriJiedan) || 0
        const tixianProgress = zong > 0 ? Math.min((zuijin / zong) * 100, 100) : 0
        
        const globalUpdate = {
          dashouNicheng: updateData.dashouNicheng,
          zhanghaoStatus: updateData.zhanghaoStatus,
          yongjin: updateData.yongjin,
          zonge: updateData.zonge,
          yajin: updateData.yajin,
          chenghao: updateData.chenghao,
          jinfen: updateData.jinfen,
          chengjiaoliang: updateData.chengjiaoliang,
          zaixianZhuangtai: updateData.zaixianZhuangtai,
          dashouzhuangtai: updateData.dashouzhuangtai,
          clumber: updateData.clumber,
        }
        Object.assign(app.globalData, globalUpdate)
        
        wx.setStorageSync('nicheng', updateData.dashouNicheng)
        if (data.touxiang) {
          wx.setStorageSync('touxiang', data.touxiang)
        }
        
        this.setData({
          ...updateData,
          chengjiaoRate,
          chengjiaoAngle,
          tixianProgress: Math.round(tixianProgress),
          isLoading: false
        })
        
        this.checkJinpaiAndRedirect(updateData.chenghao)
        
      } else {
        wx.showToast({ title: res?.data?.msg || '获取信息失败', icon: 'none' })
        this.setData({ isLoading: false })
      }
    } catch (error) {
      console.error('获取金牌信息失败:', error)
      wx.showToast({ title: '网络错误', icon: 'none' })
      this.setData({ isLoading: false })
    }
  },

  refreshJinpaiInfo() {
    const now = Date.now()
    const lastTime = this.data.lastRefreshTime
    const canRefresh = this.data.canRefresh
    if (!canRefresh || (now - lastTime < 3000)) return

    
    this.setData({ lastRefreshTime: now, canRefresh: false })
    this.getJinpaiInfo()
    this.fetchChenghaoList()  // 新增
    setTimeout(() => this.setData({ canRefresh: true }), 3000)
  },

  checkJinpaiAndRedirect(chenghao) {
    if (chenghao !== '金牌选手') {
      wx.setStorageSync('isJinpai', 0)
      wx.redirectTo({ url: '/pages/dashouduan/dashouduan' })
    } else {
      wx.setStorageSync('isJinpai', 1)
    }
  },

  // 联系管事（与打手端完全一致，增加容错）
  async contactInviter() {
    wx.showLoading({ title: '获取管事信息...', mask: true })
    try {
      const res = await request({ url: '/yonghu/hqwdyqr', method: 'POST' })
      if (res && res.data.code === 200) {
        const inviter = res.data.data
        const ossImageUrl = getApp().globalData.ossImageUrl || ''
        const fullAvatar = inviter.touxiang
          ? (inviter.touxiang.startsWith('http') ? inviter.touxiang : ossImageUrl + inviter.touxiang)
          : ''

        // 缓存邀请人信息
        const cacheData = {
          uid: inviter.uid,
          nicheng: inviter.nicheng || '',
          avatar: fullAvatar
        }
        wx.setStorageSync('inviterCache', cacheData)
        this.setData({ inviterCache: cacheData })

        // 确保打手身份并连接
        const app = getApp()
        const myUid = wx.getStorageSync('uid')
        
        // 如果当前不是打手身份，则切换并重连
        if (app.globalData.currentRole !== 'dashou') {
          app.globalData.currentRole = 'dashou'
          wx.setStorageSync('currentRole', 'dashou')
          if (app.switchRoleAndReconnect) {
            await app.switchRoleAndReconnect('dashou')
          } else if (app.connectWithIdentity) {
            // 降级方案：直接用打手身份连接
            await app.connectWithIdentity('dashou', 'Ds' + myUid, false)
          }
        } else {
          // 已为打手，确保连接存活
          if (app.connectForCurrentRole) {
            app.connectForCurrentRole()
          } else if (app.ensureConnection) {
            app.ensureConnection()
          }
        }

        // 构造私聊参数
        const param = {
          toUserId: 'Gs' + inviter.uid,
          toName: inviter.nicheng || '管事',
          toAvatar: fullAvatar
        }
        wx.navigateTo({
          url: '/pages/liaotian/liaotian?data=' + encodeURIComponent(JSON.stringify(param)),
          fail: (err) => {
            console.error('跳转私聊失败', err)
            wx.showToast({ title: '打开聊天失败', icon: 'none' })
          }
        })
      } else {
        wx.showToast({ title: res?.data?.msg || '获取失败', icon: 'none' })
      }
    } catch (e) {
      console.error('联系管事出错:', e)
      wx.showToast({ title: '网络错误', icon: 'none' })
    } finally {
      wx.hideLoading()
    }
  },

  copyUid() {
    const { uid } = this.data
    if (!uid) return wx.showToast({ title: 'UID不存在', icon: 'none' })
    wx.setClipboardData({
      data: uid,
      success: () => wx.showToast({ title: '已复制UID', icon: 'success' })
    })
  },

  previewAvatar() {
    if (this.data.avatarUrl) wx.previewImage({ urls: [this.data.avatarUrl] })
  },

  goToWithdraw() { wx.navigateTo({ url: '/pages/tixian/tixian' }) },
  goToReceiveOrder() { wx.navigateTo({ url: '/pages/jiedan/jiedan' }) },
  goToRecharge() { wx.navigateTo({ url: '/pages/dashouchongzhi/dashouchongzhi' }) },
  goToMyOrders() { wx.navigateTo({ url: '/pages/dashoudingdan/dashoudingdan' }) },
  goToMyPunishment() { wx.navigateTo({ url: '/pages/cfss/cfss/cfss' }) },
  goToRanking() { wx.navigateTo({ url: '/pages/dashoupaihang/dashoupaihang' }) },
  goToModifyInfo() { wx.navigateTo({ url: '/pages/dashouxiugai/dashouxiugai' }) },
  goToRules() { wx.navigateTo({ url: '/pages/dashouguize/dashouguize' }) },
  // 跳转到考核金牌
goToKaohe() {
    wx.navigateTo({ url: '/pages/kaohe_jinpai/kaohe_jinpai' });
  },

  async fetchChenghaoList() {
    try {
        const res = await request({
            url: '/dengji/dsbqhq',
            method: 'POST'
        });
        if (res && res.data.code === 0 && res.data.data) {
            this.setData({ chenghaoList: res.data.data.chenghao_list || [] });
        }
    } catch (e) {
        console.error('获取称号标签失败', e);
    }
},
})