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

const PLATFORM_INVITE_CODE = '0000008RffVgKHMj7kQC'

Page({
  data: {
    isDashou: false,
    isLoading: false,
    inviteCode: '',
    uid: '',
    touxiang: '',
    avatarUrl: '',
    dashouNicheng: '',
    zhanghaoStatus: '',
    yongjin: '',
    zonge: '',
    yajin: '',
    chenghao: '',
    jinfen: '',
    clumber: [],
    chengjiaoliang: '',
    zaixianZhuangtai: 0,
    lastRefreshTime: 0,
    canRefresh: true,
    isAutoRegistering: false,
    inviterCache: null,
    // 🆕 称号标签列表（从独立接口获取）
    chenghaoList: []
  },

  onLoad(options) {
    if (options.scene) {
      try {
        const scene = decodeURIComponent(options.scene);
        options.inviteCode = scene;
      } catch (e) {
        console.error('scene解码失败', e);
      }
    }
    this.checkDashouStatus();
    const { inviteCode } = options || {};
    if (inviteCode) {
      this.setData({ inviteCode: inviteCode });
      setTimeout(() => {
        this.handleInviteCodeWithLoginCheck(inviteCode);
      }, 500);
    }
    const app = getApp();
    if (!app.globalData.hasShownPopupOnColdStart) {
      app.globalData.hasShownPopupOnColdStart = true;
      setTimeout(() => {
        popupService.checkAndShow(this, 'dashouduan');
      }, 300);
    }
  },

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

  onShow() {
    // 从缓存读取邀请人信息
    const inviterCache = wx.getStorageSync('inviterCache') || null;
    this.setData({ inviterCache });

    this.registerNotificationComponent();
    this.checkAndRedirectToJinpai();
    if (this.data.isDashou) {
      setTimeout(() => {
        this.refreshDashouInfo();
        this.fetchChenghaoList();   // 🆕 获取标签
      }, 300);
    }
    const pages = getCurrentPages();
    const currentPage = pages[pages.length - 1];
    const options = currentPage.options || {};
    if (options.inviteCode && this.data.isDashou === false) {
      const { inviteCode } = options;
      setTimeout(() => {
        this.handleInviteCodeWithLoginCheck(inviteCode);
      }, 300);
    }
  },

  // ==================== 🆕 获取称号标签列表 ====================
  async fetchChenghaoList() {
    try {
      const res = await request({
        url: '/dengji/dsbqhq',
        method: 'POST'
      });
      if (res && res.data.code === 0 && res.data.data) {
        const list = res.data.data.chenghao_list || [];
        this.setData({ chenghaoList: list });
        // 可选：也存入全局，方便其他页面使用
        const app = getApp();
        app.globalData.chenghaoList = list;
      } else {
        this.setData({ chenghaoList: [] });
      }
    } catch (e) {
      console.error('获取称号标签失败', e);
      // 失败不影响主流程
    }
  },
  // ========================================================

  // 联系邀请人（保持不变）
  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.connectForCurrentRole) app.connectForCurrentRole();
        }

        const param = {
          toUserId: 'Gs' + inviter.uid,
          toName: inviter.nicheng || '邀请人',
          toAvatar: fullAvatar
        };
        wx.navigateTo({
          url: '/pages/liaotian/liaotian?data=' + encodeURIComponent(JSON.stringify(param))
        });
      } else {
        wx.showToast({ title: res?.data?.msg || '获取失败', icon: 'none' });
      }
    } catch (e) {
      wx.showToast({ title: '网络错误', icon: 'none' });
    } finally {
      wx.hideLoading();
    }
  },

  handleInviteCodeWithLoginCheck(inviteCode) {
    const that = this;
    const token = wx.getStorageSync('token');
    const uid = wx.getStorageSync('uid');
    if (!token || !uid) {
      this.loginAndRegisterWithInviteCode(inviteCode);
    } else {
      if (!that.data.isDashou) {
        wx.showLoading({ title: '自动注册中...', mask: true });
        that.setData({ isAutoRegistering: true });
        that.onRegister();
      } else {
        wx.showToast({ title: '您已是打手', icon: 'success', duration: 2000 });
      }
    }
  },

  loginAndRegisterWithInviteCode(inviteCode) {
    const that = this;
    wx.showLoading({ title: '登录注册中...', mask: true });
    wx.login({
      success: (loginRes) => {
        if (loginRes.code) {
          that.callLoginRegisterApi(loginRes.code, inviteCode);
        } else {
          wx.hideLoading();
          wx.showToast({ title: '微信登录失败', icon: 'none' });
        }
      },
      fail: () => {
        wx.hideLoading();
        console.error('微信登录失败');
        wx.reLaunch({ url: '/pages/gerenzhongxin/gerenzhongxin' });
      }
    });
  },

  callLoginRegisterApi(code, inviteCode) {
    const that = this;
    const app = getApp();
    const apiBaseUrl = app.globalData.apiBaseUrl;
    if (!apiBaseUrl) {
      wx.hideLoading();
      wx.showToast({ title: '服务器配置错误', icon: 'none' });
      return;
    }
    wx.request({
      url: apiBaseUrl + '/yonghu/wdlyhdl',
      method: 'POST',
      data: { code: code, inviteCode: inviteCode },
      header: { 'content-type': 'application/json' },
      success: (res) => {
        if (res.statusCode === 200 && res.data && res.data.code === 0 && res.data.data) {
          const userData = res.data.data;
          if (userData.token) wx.setStorageSync('token', userData.token);
          const identityFields = ['nicheng', 'uid', 'touxiang', 'dashoustatus', 'guanshistatus', 'shangjiastatus', 'zuzhangstatus'];
          identityFields.forEach(field => {
            if (userData[field] !== undefined) {
              wx.setStorageSync(field, userData[field]);
              app.globalData[field] = userData[field];
            }
          });
          const groupFields = ['dashouqun', 'dashouqunid', 'guanshiqun', 'guanshiqunid'];
          groupFields.forEach(field => {
            if (userData[field] !== undefined) {
              wx.setStorageSync(field, userData[field]);
              app.globalData[field] = userData[field];
            }
          });
          if (userData.dashounicheng || userData.yongjin) {
            const updateData = {
              dashouNicheng: userData.dashounicheng || '',
              zhanghaoStatus: userData.zhanghaostatus || '',
              yongjin: userData.yongjin || '0.00',
              zonge: userData.zonge || '0.00',
              yajin: userData.yajin || '0.00',
              chenghao: userData.chenghao || '',
              jinfen: userData.jifen || userData.jinfen || '0',
              clumber: userData.clumber || [],
              chengjiaoliang: userData.chengjiaoliang || '0',
              zaixianZhuangtai: userData.zaixianzhuangtai || 0,
              dashouzhuangtai: userData.dashouzhuangtai || '',
              // 🔥 不再从这里取 chenghaoList，单独调用 fetchChenghaoList
            };
            Object.assign(app.globalData, updateData);
          }
          that.setData({
            isDashou: true,
            uid: userData.uid || '',
            touxiang: userData.touxiang || '',
            isAutoRegistering: false
            // 不设置 chenghaoList，稍后在 onShow 中自动获取
          });
          that.loadAvatar();
          that.getDashouInfo();
          that.switchToDashouRole();
          wx.hideLoading();
          wx.showToast({ title: '登录注册成功！', icon: 'success', duration: 2000 });
        } else {
          wx.hideLoading();
          wx.showToast({ title: (res.data && res.data.msg) || '登录注册失败', icon: 'none' });
        }
      },
      fail: () => {
        wx.hideLoading();
        wx.showToast({ title: '网络请求失败', icon: 'none' });
      }
    });
  },

  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()
      };
    }
  },

  checkDashouStatus() {
    try {
      const dashoustatus = wx.getStorageSync('dashoustatus');
      const uid = wx.getStorageSync('uid');
      const touxiang = wx.getStorageSync('touxiang');
      if (dashoustatus === 1) {
        this.setData({ isDashou: true, uid: uid || '', touxiang: touxiang || '' });
        this.loadAvatar();
        this.checkGlobalData();
      } else {
        this.setData({ isDashou: false });
      }
    } catch (error) {
      console.error('读取缓存失败:', error);
      this.setData({ isDashou: false });
    }
  },

  loadAvatar() {
    const app = getApp();
    const { ossImageUrl = '', morentouxiang = 'avatar/default.jpg' } = app.globalData || {};
    const { touxiang } = this.data;
    let avatarUrl = '';
    if (touxiang) {
      avatarUrl = ossImageUrl + (touxiang.startsWith('/') ? touxiang : '/' + touxiang);
    } else {
      avatarUrl = ossImageUrl + (morentouxiang.startsWith('/') ? morentouxiang : '/' + morentouxiang);
    }
    this.setData({ avatarUrl });
  },

  checkGlobalData() {
    const app = getApp();
    const globalData = app.globalData || {};
    const needRefresh = !globalData.dashouNicheng || globalData.dashouNicheng === '' || !globalData.yongjin;
    if (needRefresh) {
      this.getDashouInfo();
    } else {
      this.setDataFromGlobalData();
    }
  },

  setDataFromGlobalData() {
    const app = getApp();
    const {
      dashouNicheng = '', zhanghaoStatus = '', yongjin = '0.00', zonge = '0.00',
      yajin = '0.00', chenghao = '', jinfen = '0', clumber = [],
      chengjiaoliang = '0', zaixianZhuangtai = 0
      // 🔥 chenghaoList 不再从全局取，避免旧数据干扰
    } = app.globalData || {};
    this.setData({
      dashouNicheng, zhanghaoStatus, yongjin, zonge, yajin,
      chenghao, jinfen,
      clumber: Array.isArray(clumber) ? clumber : [],
      chengjiaoliang,
      zaixianZhuangtai: zaixianZhuangtai === 1 ? 1 : 0
    });
  },

  async getDashouInfo() {
    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 app = getApp();
        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',
          clumber: data.clumber || [],
          chengjiaoliang: data.chengjiaoliang || '0',
          zaixianZhuangtai: data.zaixianzhuangtai || 0,
          dashouzhuangtai: data.dashouzhuangtai || '',
          // 🔥 不再包含 chenghaoList
        };
        Object.assign(app.globalData, updateData);
        if (data.dashoustatus !== undefined) {
          wx.setStorageSync('dashoustatus', data.dashoustatus);
          app.globalData.dashoustatus = data.dashoustatus;
        }
        if (data.guanshistatus !== undefined) {
          wx.setStorageSync('guanshistatus', data.guanshistatus);
          app.globalData.guanshistatus = data.guanshistatus;
        }
        this.setData({ ...updateData, isLoading: false });
        if (this.data.isAutoRegistering) {
          this.setData({ isAutoRegistering: false });
          wx.showToast({ title: '注册成功！', icon: 'success', duration: 2000 });
        } else {
          wx.showToast({ title: '信息已更新', icon: 'success', duration: 1500 });
        }
        this.handleJinpaiStatus(data.chenghao);
      }
    } catch (error) {
      console.error('获取打手信息失败:', error);
      this.setData({ isLoading: false, isAutoRegistering: false });
      wx.showToast({ title: '获取信息失败', icon: 'error', duration: 2000 });
    }
  },

  refreshDashouInfo() {
    const now = Date.now();
    if (!this.data.canRefresh || (now - this.data.lastRefreshTime < 3000)) return;
    this.setData({ lastRefreshTime: now, canRefresh: false });
    this.getDashouInfo();
    this.fetchChenghaoList();   // 🆕 同时刷新标签
    setTimeout(() => this.setData({ canRefresh: true }), 3000);
  },

  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/dashouzhuce',
        method: 'POST',
        data: { inviteCode: inviteCode }
      });
      if (res && res.data.code == 200) {
        const data = res.data.data;
        const app = getApp();
        const identityFields = ['dashoustatus', 'guanshistatus', 'shangjiastatus', 'zuzhangstatus'];
        identityFields.forEach(field => {
          if (data[field] !== undefined) {
            wx.setStorageSync(field, data[field]);
            app.globalData[field] = data[field];
          }
        });
        if (data.dashoustatus === undefined) {
          wx.setStorageSync('dashoustatus', 1);
          app.globalData.dashoustatus = 1;
        }
        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.jinfen || '0',
          clumber: data.clumber || [],
          chengjiaoliang: data.chengjiaoliang || '0',
          zaixianZhuangtai: data.zaixianzhuangtai || 0,
          dashouzhuangtai: data.dashouzhuangtai || '',
          // chenghaoList 不从这取
        };
        Object.assign(app.globalData, updateData);
        this.setData({
          isDashou: true,
          ...updateData,
          isLoading: false,
          isAutoRegistering: false
        });
        this.loadAvatar();
        if (this.data.isAutoRegistering || !wx.getStorageSync('token')) {
          this.switchToDashouRole();
        }
        wx.showToast({ title: '注册成功！', icon: 'success', duration: 2000 });
        this.handleJinpaiStatus(data.chenghao);
      } else {
        this.setData({ isLoading: false, isAutoRegistering: false });
        wx.showToast({ title: (res.data && res.data.message) || '注册失败', icon: 'error', duration: 2000 });
      }
    } catch (error) {
      console.error('注册失败:', error);
      this.setData({ isLoading: false, isAutoRegistering: false });
      wx.showToast({ title: error.message || '注册失败', icon: 'error', duration: 2000 });
    }
  },

  switchToDashouRole() {
    const app = getApp();
    app.globalData.currentRole = 'dashou';
    wx.setStorageSync('currentRole', 'dashou');
    const tabBar = this.getTabBar();
    if (tabBar && tabBar.refresh) tabBar.refresh();
    if (app.connectForCurrentRole) {
      app.connectForCurrentRole();
    } else if (app.ensureConnection) {
      app.ensureConnection();
    }
  },

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

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

  goToWithdraw() { wx.navigateTo({ url: '/pages/tixian/tixian' }) },
  goToReceiveOrder() { wx.navigateTo({ url: '/pages/jiedan/jiedan' }) },
  goToMyOrders() { wx.navigateTo({ url: '/pages/dashoudingdan/dashoudingdan' }) },
  goToMyPunishment() { wx.navigateTo({ url: '/pages/cfss/cfss/cfss' }) },
  goToRecharge() { wx.navigateTo({ url: '/pages/dashouchongzhi/dashouchongzhi' }) },
  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' });
  },

  quickRegisterAsPlatform() {
    const that = this;
    wx.showModal({
      title: '提示',
      content: '使用此功能后，您将不属于任何管事，确认注册吗？',
      success: (res) => {
        if (res.confirm) {
          that.setData({ inviteCode: PLATFORM_INVITE_CODE });
          that.onRegister();
        }
      }
    });
  },

  checkAndRedirectToJinpai() {
    const isJinpai = wx.getStorageSync('isJinpai');
    if (isJinpai === 1) {
      wx.redirectTo({ url: '/pages/jinpaids/jinpaids' });
    }
  },

  handleJinpaiStatus(chenghao) {
    const isJinpai = (chenghao === '金牌选手') ? 1 : 0;
    wx.setStorageSync('isJinpai', isJinpai);
    if (isJinpai) {
      wx.redirectTo({ url: '/pages/jinpaids/jinpaids' });
    }
  }
})