// pages/dashouzhongxin/dashouzhongxin.js
import { createPage, request, isRoleStatusActive, isCenterPageActive, syncRoleStatuses, syncProfileFields, syncGroupFields, ensureRoleOnCenterPage, clearCacheAndEnterNormal, lockPrimaryRole, migrateLegacyCenterRole, enterLockedRole, parseSceneOptions } from '../../utils/base-page.js'
import { resolveAvatarUrl } from '../../utils/avatar.js'
import { openPrivateChat, buildInviterPeerId } from '../../utils/im-user.js'
import { isStaffMode, getStaffContext } from '../../utils/staff-api.js'
import { ensurePhoneAuth } from '../../utils/phone-auth.js'

const PLATFORM_INVITE_CODE = '0000008RffVgKHMj7kQC'

Page(createPage({
  data: {
    // 图片路径对象
    imgUrls: {},

    isDashou: false,
    isGuanshi: false,
    isZuzhang: false,
    isKaoheguan: false,
    isShangjia: false,
    shangjiaCertified: false,
    totalAssets: '0.00',
    assetBreakdown: [],
    pendingAuthList: [],
    showAuthSection: false,
    inviteCode: '',
    guanshiInviteCode: '',
    zuzhangInviteCode: '',
    uid: '',
    touxiang: '',
    avatarUrl: '',
    dashouNicheng: '',
    zhanghaoStatus: '',
    yongjin: '',
    zonge: '',
    yajin: '',
    chenghao: '',
    jinfen: '',
    clumber: [],
    chengjiaoliang: '',
    zaixianZhuangtai: 0,
    isAutoRegistering: false,
    inviterCache: null,
    zuzhangInviterCache: null,
    chenghaoList: [],
    guanshiChenghaoList: [],
    gszhstatus: '',
    yaoqingzongshu: 0,
    fenyongzonge: '0.00',
    fenyongtixian: '0.00',
    yichongzhiDashou: 0,
    zhuanhualv: 0,
    ketixian: '0.00',
    guanshiCount: 0,
    fenhongZonge: '0.00',
    kaoheYue: '0.00',
    kaoheZonge: '0.00',
    shenheZongshu: 0,
    tongguoZongshu: 0,
    pendingShenheCount: 0,
    layoutSparse: false,
    scrollRefreshing: false,
    rankBoardList: [
      { type: 'dashou', name: '接单员榜', sub: '接单成交', icon: '', shapeClass: 'rank-shape-left', themeClass: 'rank-theme-blue' },
      { type: 'guanshi', name: '管事榜', sub: '邀请收入', icon: '', shapeClass: 'rank-shape-right', themeClass: 'rank-theme-gold' },
      { type: 'zuzhang', name: '组长榜', sub: '团队分红', icon: '', shapeClass: 'rank-shape-left', themeClass: 'rank-theme-purple' },
      { type: 'shangjia', name: '商家榜', sub: '派单流水', icon: '', shapeClass: 'rank-shape-right', themeClass: 'rank-theme-orange' },
    ],

    statusBar: 20,
    navBar: 44,
  },

  _buildImgUrls(ossImageUrl) {
    const dsBase = ossImageUrl + 'beijing/dashouduan/';
    const iconBase = ossImageUrl + 'beijing/dashouduan/dashoutubiaobeijing/';
    const gsBase = ossImageUrl + 'beijing/guanshiduan/';
    const khBase = ossImageUrl + 'beijing/kaohe/';
    return {
      pageBg: dsBase + 'page-bg.jpg',
      userCardBg: dsBase + 'user-card-bg.png',
      vipCardBg: dsBase + 'vip-card-bg.jpg',
      assetPanelBg: dsBase + 'asset-panel-bg.png',
      rankHubBg: dsBase + 'rank-hub-bg.png',
      rankTileBg: dsBase + 'rank-tile-bg.png',
      funcPanelBg: dsBase + 'func-panel-bg.png',
      listBg: dsBase + 'list-card-bg.png',
      topBg: iconBase + 'top-bg.jpg',
      cardBg: iconBase + 'card-bg.jpg',
      iconRefresh: gsBase + 'icon-refresh.png',
      iconCopy: gsBase + 'icon-copy.png',
      iconVip: dsBase + 'icon-vip.png',
      iconArrowLight: dsBase + 'icon-arrow-light.png',
      iconSectionAsset: dsBase + 'icon-section-asset.png',
      iconSectionRank: dsBase + 'icon-section-rank.png',
      iconSectionFunc: dsBase + 'icon-section-func.png',
      iconSectionGuanshi: dsBase + 'icon-section-guanshi.png',
      iconSectionZuzhang: dsBase + 'icon-section-zuzhang.png',
      iconSectionKaohe: dsBase + 'icon-section-kaohe.png',
      iconSectionMore: dsBase + 'icon-section-more.png',
      iconRankDashou: dsBase + 'rank-dashou.png',
      iconRankGuanshi: dsBase + 'rank-guanshi.png',
      iconRankZuzhang: dsBase + 'rank-zuzhang.png',
      iconRankShangjia: dsBase + 'rank-shangjia.png',
      iconGame: iconBase + 'icon-game.jpg',
      iconRecharge: iconBase + 'icon-recharge.jpg',
      iconOrders: iconBase + 'icon-orders.jpg',
      iconPunish: iconBase + 'icon-punish.jpg',
      iconRank: iconBase + 'icon-rank.jpg',
      iconInvite: gsBase + 'icon-invite.png',
      iconMedal: iconBase + 'icon-medal.jpg',
      iconEdit: iconBase + 'icon-edit.jpg',
      iconBook: iconBase + 'icon-book.jpg',
      iconArrow: gsBase + 'icon-arrow.png',
      iconSub: gsBase + 'icon-sub.png',
      iconRecord: gsBase + 'icon-record.png',
      iconPoster: gsBase + 'icon-poster.png',
      iconWithdraw: gsBase + 'icon-withdraw.png',
      iconContact: gsBase + 'icon-contact.png',
      avatarDefault: ossImageUrl + 'avatar/default.jpg',
      iconClear: ossImageUrl + 'beijing/tubiao/grzx_qingchu.jpg',
      iconSwitch: '/images/_exit.png',
      iconKefu: ossImageUrl + 'beijing/tubiao/grzx_kefu.jpg',
      iconKuaishou: ossImageUrl + 'beijing/tubiao/grzx_guanzhualong.jpg',
      iconKaoheDafen: khBase + 'daofen.png',
      iconKaoheJilu: khBase + 'jilu.png',
      iconKaoheZhongxin: khBase + 'zhongxin.png',
      iconShangjia: ossImageUrl + 'beijing/tubiao/grzx_shangjia.jpg',
      iconDashouAuth: ossImageUrl + 'beijing/tubiao/grzx_dashou.jpg',
      iconGuanshiAuth: ossImageUrl + 'beijing/tubiao/grzx_guanshi.jpg',
      iconZuzhangAuth: ossImageUrl + 'beijing/tubiao/grzx_zuzhang.jpg',
      kefuBannerBg: dsBase + 'kefu-banner-bg.png',
      totalAssetBg: dsBase + 'total-asset-bg.png',
      authPanelBg: dsBase + 'auth-panel-bg.png',
      bannerVip: 'https://bintao-1308403501.cos.ap-guangzhou.myqcloud.com/uploads/images/20260512123427531240452.png',
      bannerDeposit: 'https://bintao-1308403501.cos.ap-guangzhou.myqcloud.com/uploads/images/202605121234283091d3980.png',
    };
  },

  _applyRankBoardIcons(imgUrls) {
    const iconMap = {
      dashou: imgUrls.iconRankDashou,
      guanshi: imgUrls.iconRankGuanshi,
      zuzhang: imgUrls.iconRankZuzhang,
      shangjia: imgUrls.iconRankShangjia,
    };
    return (this.data.rankBoardList || []).map((item) => ({
      ...item,
      icon: iconMap[item.type] || imgUrls.iconRank,
    }));
  },

  onLoad(options) {
    const app = getApp();
    const sys = wx.getSystemInfoSync();
    const ossImageUrl = app.globalData.ossImageUrl || '';
    const imgUrls = this._buildImgUrls(ossImageUrl);
    this.setData({
      imgUrls,
      rankBoardList: this._applyRankBoardIcons(imgUrls),
      statusBar: sys.statusBarHeight || 20,
      navBar: (sys.statusBarHeight || 20) + 44,
    });
    this.checkRoleStatuses();

    const parsed = parseSceneOptions(options);
    const registerType = parsed.registerType || 'dashou';
    const { inviteCode } = parsed;
    this.checkDashouStatus();
    if (inviteCode) {
      if (registerType === 'guanshi') {
        this.setData({ guanshiInviteCode: inviteCode });
        setTimeout(() => {
          this.handleGuanshiInviteCodeWithLoginCheck(inviteCode);
        }, 500);
      } else {
        this.setData({ inviteCode });
        setTimeout(() => {
          this.handleInviteCodeWithLoginCheck(inviteCode);
        }, 500);
      }
    }
    this.checkColdStartPopup('dashouduan');
  },

  async onShow() {
    const phoneOk = await ensurePhoneAuth({ redirect: true, role: 'dashou' });
    if (!phoneOk) return;

    migrateLegacyCenterRole(getApp());
    lockPrimaryRole('dashou', getApp());
    wx.setStorageSync('isJinpai', 0);
    ensureRoleOnCenterPage(this, 'dashou');

    const inviterCache = wx.getStorageSync('inviterCache') || null;
    const zuzhangInviterCache = wx.getStorageSync('zuzhangInviterCache') || null;
    this.setData({ inviterCache, zuzhangInviterCache });

    this.registerNotificationComponent();
    this.checkRoleStatuses();
    this.applyCachedProfileFromGlobal();
    if (isCenterPageActive(this, 'isDashou', 'dashoustatus')) {
      if (!this.data.isDashou) this.setData({ isDashou: true });
      ensureRoleOnCenterPage(this, 'dashou');
    } else if (isRoleStatusActive(wx.getStorageSync('guanshistatus')) ||
      isRoleStatusActive(wx.getStorageSync('zuzhangstatus')) ||
      isRoleStatusActive(wx.getStorageSync('kaoheguanstatus'))) {
      ensureRoleOnCenterPage(this, 'dashou');
    }
    const pages = getCurrentPages();
    const currentPage = pages[pages.length - 1];
    const options = currentPage.options || {};
    const registerType = options.registerType || 'dashou';
    if (options.inviteCode) {
      if (registerType === 'guanshi' && !isRoleStatusActive(wx.getStorageSync('guanshistatus'))) {
        setTimeout(() => {
          this.handleGuanshiInviteCodeWithLoginCheck(options.inviteCode);
        }, 300);
      } else if (registerType !== 'guanshi' && !isCenterPageActive(this, 'isDashou', 'dashoustatus')) {
        setTimeout(() => {
          this.handleInviteCodeWithLoginCheck(options.inviteCode);
        }, 300);
      }
    }
  },

  checkRoleStatuses() {
    const isDashou = isRoleStatusActive(wx.getStorageSync('dashoustatus'));
    const isGuanshi = isRoleStatusActive(wx.getStorageSync('guanshistatus'));
    const isZuzhang = isRoleStatusActive(wx.getStorageSync('zuzhangstatus'));
    const isKaoheguan = isRoleStatusActive(wx.getStorageSync('kaoheguanstatus'));
    const isShangjia = isRoleStatusActive(wx.getStorageSync('shangjiastatus'));
    const subRoleCount = [isGuanshi, isZuzhang, isKaoheguan].filter(Boolean).length;
    this.setData({
      isDashou, isGuanshi, isZuzhang, isKaoheguan,
      isShangjia,
      shangjiaCertified: isShangjia,
      layoutSparse: subRoleCount === 0,
    }, () => {
      this._updateTotalAssets();
      this._updatePendingAuth();
    });
    if (isDashou) {
      const uid = wx.getStorageSync('uid') || '';
      const touxiang = wx.getStorageSync('touxiang') || '';
      this.setData({ uid, touxiang });
      this.loadAvatar();
    }
  },

  _parseMoney(val) {
    return parseFloat(String(val || '0').replace(/,/g, '')) || 0;
  },

  _updateTotalAssets() {
    const d = this.data;
    const breakdown = [{ label: '接单员佣金', amount: d.yongjin || '0.00' }];
    let total = this._parseMoney(d.yongjin);
    if (d.isGuanshi) {
      total += this._parseMoney(d.fenyongtixian);
      breakdown.push({ label: '管事分成', amount: d.fenyongtixian || '0.00' });
    }
    if (d.isZuzhang) {
      total += this._parseMoney(d.ketixian);
      breakdown.push({ label: '组长余额', amount: d.ketixian || '0.00' });
    }
    if (d.isKaoheguan) {
      total += this._parseMoney(d.kaoheYue);
      breakdown.push({ label: '考核余额', amount: d.kaoheYue || '0.00' });
    }
    this.setData({ totalAssets: total.toFixed(2), assetBreakdown: breakdown });
  },

  /** 打手端：已认证不展示；商家始终第一位 */
  _updatePendingAuth() {
    const d = this.data;
    const img = d.imgUrls || {};
    const list = [];
    list.push({
      type: 'shangjia',
      name: '商家',
      icon: img.iconShangjia,
      tag: d.shangjiaCertified ? '进入商家端' : '去认证',
      done: d.shangjiaCertified,
    });
    list.push({
      type: 'staff',
      name: '商家客服',
      icon: img.iconKefu || img.iconShangjia,
      tag: isStaffMode() ? '进入工作台' : '去入驻',
      done: isStaffMode(),
    });
    if (!d.isGuanshi) {
      list.push({ type: 'guanshi', name: '管事', icon: img.iconGuanshiAuth, tag: '去认证' });
    }
    if (!d.isZuzhang) {
      list.push({ type: 'zuzhang', name: '组长', icon: img.iconZuzhangAuth, tag: '去认证' });
    }
    if (!d.isDashou) {
      list.push({ type: 'dashou', name: '接单员', icon: img.iconDashouAuth, tag: '去认证' });
    }
    this.setData({
      pendingAuthList: list,
      showAuthSection: list.length > 0,
    });
  },

  applyCachedProfileFromGlobal() {
    const app = getApp();
    const g = app.globalData;
    const guanshi = g.guanshi || {};
    const patch = {
      dashouNicheng: g.dashouNicheng || this.data.dashouNicheng || '',
      zhanghaoStatus: g.zhanghaoStatus ?? this.data.zhanghaoStatus,
      yongjin: g.yongjin || this.data.yongjin || '0.00',
      zonge: g.zonge || this.data.zonge || '0.00',
      yajin: g.yajin || this.data.yajin || '0.00',
      chenghao: g.chenghao || this.data.chenghao || '',
      jinfen: g.jinfen || this.data.jinfen || '0',
      clumber: g.clumber || this.data.clumber || [],
      chengjiaoliang: g.chengjiaoliang || this.data.chengjiaoliang || '0',
      zaixianZhuangtai: g.zaixianZhuangtai ?? this.data.zaixianZhuangtai ?? 0,
      dashouzhuangtai: g.dashouzhuangtai ?? this.data.dashouzhuangtai,
      gszhstatus: guanshi.gszhstatus || this.data.gszhstatus || '',
      yaoqingzongshu: guanshi.yaoqingzongshu ?? this.data.yaoqingzongshu ?? 0,
      fenyongzonge: guanshi.fenyongzonge || this.data.fenyongzonge || '0.00',
      fenyongtixian: guanshi.fenyongtixian || this.data.fenyongtixian || '0.00',
    };
    this.setData(patch, () => this._updateTotalAssets());
  },

  async onPullDownRefresh() {
    if (this._pullRefreshing) return;
    this._pullRefreshing = true;
    this.setData({ scrollRefreshing: true });
    try {
      this.checkRoleStatuses();
      await Promise.allSettled([
        this._fetchDashouInfoSilent(),
        this.fetchChenghaoList(),
        this._fetchGuanshiInfoSilent(),
        this.fetchGuanshiChenghaoList(),
        this._fetchZuzhangInfoSilent(),
        this._fetchKaoheguanInfoSilent(),
      ]);
      this.checkRoleStatuses();
      wx.showToast({ title: '已更新', icon: 'success', duration: 1200 });
    } catch (e) {
      wx.showToast({ title: '刷新失败', icon: 'none' });
    } finally {
      this._pullRefreshing = false;
      this.setData({ scrollRefreshing: false });
    }
  },

  async refreshAllInfo(showToast = true) {
    this.throttledRefresh(async () => {
      this.setData({ isLoading: true });
      try {
        this.checkRoleStatuses();
        const results = await Promise.allSettled([
          this._fetchDashouInfoSilent(),
          this.fetchChenghaoList(),
          this._fetchGuanshiInfoSilent(),
          this.fetchGuanshiChenghaoList(),
          this._fetchZuzhangInfoSilent(),
          this._fetchKaoheguanInfoSilent(),
        ]);
        this.checkRoleStatuses();
        const dashouOk = results[0].status === 'fulfilled';
        if (showToast) {
          wx.showToast({
            title: dashouOk ? '刷新成功' : '刷新失败',
            icon: dashouOk ? 'success' : 'none',
            duration: 1500,
          });
        }
      } catch (e) {
        if (showToast) {
          wx.showToast({ title: '刷新失败', icon: 'none' });
        }
      } finally {
        this.setData({ isLoading: false });
      }
    }, 3000);
  },

  refreshDashouInfo() {
    this.refreshAllInfo(true);
  },

  onTapRefresh() {
    this.refreshAllInfo(true);
  },

  async _fetchDashouInfoSilent() {
    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 || '',
      };
      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;
      }
      if (data.zuzhangstatus !== undefined) {
        wx.setStorageSync('zuzhangstatus', data.zuzhangstatus);
        app.globalData.zuzhangstatus = data.zuzhangstatus;
      }
      this.setData({ ...updateData, isLoading: false });
      this._updateTotalAssets();
      return;
    }
    throw new Error('打手信息获取失败');
  },

  async _fetchGuanshiInfoSilent() {
    const res = await request({ url: '/yonghu/guanshixinxi', method: 'POST' });
    if (res && this._isApiSuccess(res.data)) {
      const data = this._extractUserData(res.data);
      if (data.guanshistatus !== undefined) {
        wx.setStorageSync('guanshistatus', data.guanshistatus);
        getApp().globalData.guanshistatus = data.guanshistatus;
      }
      if (!isRoleStatusActive(data.guanshistatus ?? wx.getStorageSync('guanshistatus'))) {
        return;
      }
      const app = getApp();
      if (!app.globalData.guanshi) app.globalData.guanshi = {};
      const updateData = {
        gszhstatus: data.gszhstatus || '',
        yaoqingzongshu: data.yaoqingzongshu || 0,
        fenyongzonge: data.fenyongzonge || '0.00',
        fenyongtixian: data.fenyongtixian || '0.00',
        yichongzhiDashou: data.yichongzhiDashou || 0,
      };
      Object.assign(app.globalData.guanshi, updateData);
      const zhuanhualv = updateData.yaoqingzongshu > 0
        ? (updateData.yichongzhiDashou / updateData.yaoqingzongshu * 100).toFixed(1)
        : 0;
      this.setData({ isGuanshi: true, ...updateData, zhuanhualv });
      this._updateTotalAssets();
      return;
    }
  },

  async _fetchZuzhangInfoSilent() {
    const res = await request({ url: '/yonghu/zuzhangxinxi', method: 'POST' });
    if (res && res.data.code === 200) {
      const data = res.data.data || {};
      if (data.zuzhangstatus !== undefined) {
        wx.setStorageSync('zuzhangstatus', data.zuzhangstatus);
        getApp().globalData.zuzhangstatus = data.zuzhangstatus;
      }
      if (!isRoleStatusActive(data.zuzhangstatus ?? wx.getStorageSync('zuzhangstatus'))) {
        return;
      }
      this.setData({
        isZuzhang: true,
        ketixian: data.ketixian || '0.00',
        guanshiCount: data.guanshiCount || 0,
        fenhongZonge: data.fenhongZonge || '0.00',
      });
      this._updateTotalAssets();
      return;
    }
  },

  async _fetchKaoheguanInfoSilent() {
    const res = await request({ url: '/dengji/khgsx', method: 'POST' });
    if (res && res.data.code === 200) {
      const data = res.data.data || {};
      if (data.zhuangtai === 0 || data.zhuangtai === 2) {
        wx.setStorageSync('kaoheguanstatus', 0);
        getApp().globalData.kaoheguanstatus = 0;
        this.setData({ isKaoheguan: false });
        return;
      }
      wx.setStorageSync('kaoheguanstatus', 1);
      getApp().globalData.kaoheguanstatus = 1;
      const app = getApp();
      if (!app.globalData.kaoheguan) app.globalData.kaoheguan = {};
      Object.assign(app.globalData.kaoheguan, {
        shenhe_zongshu: data.shenhe_zongshu || 0,
        tongguo_zongshu: data.tongguo_zongshu || 0,
        yue: data.yue || '0.00',
        zonge: data.zonge || '0.00',
        pending_shenhe_count: data.pending_shenhe_count || 0,
      });
      this.setData({
        isKaoheguan: true,
        shenheZongshu: data.shenhe_zongshu || 0,
        tongguoZongshu: data.tongguo_zongshu || 0,
        kaoheYue: data.yue || '0.00',
        kaoheZonge: data.zonge || '0.00',
        pendingShenheCount: data.pending_shenhe_count || 0,
      });
      this._updateTotalAssets();
    }
  },

  async fetchGuanshiChenghaoList() {
    try {
      const res = await request({
        url: '/dengji/chenghao',
        method: 'POST',
        data: { role: 'guanshi' },
      });
      if (res && res.data.code === 0 && res.data.data) {
        this.setData({ guanshiChenghaoList: res.data.data.chenghao_list || [] });
      }
    } catch (e) {}
  },

  _isAlreadyGuanshiMsg(msg) {
    if (!msg || typeof msg !== 'string') return false;
    return msg.includes('已是管事') || msg.includes('已经是管事');
  },

  async _applyGuanshiRegisterSuccess(userData, toastMsg) {
    const data = userData || {};
    syncRoleStatuses(data);
    syncProfileFields(data);
    syncGroupFields(data);
    if (data.token) {
      wx.setStorageSync('token', data.token);
      getApp().globalData.token = data.token;
    }
    if (!Object.prototype.hasOwnProperty.call(data, 'guanshistatus') &&
        !isRoleStatusActive(wx.getStorageSync('guanshistatus'))) {
      wx.setStorageSync('guanshistatus', 1);
      getApp().globalData.guanshistatus = 1;
    }
    const app = getApp();
    if (!app.globalData.guanshi) app.globalData.guanshi = {};
    const guanshiData = {
      gszhstatus: data.gszhstatus ?? '',
      yaoqingzongshu: data.yaoqingzongshu ?? 0,
      fenyongzonge: data.fenyongzonge ?? '0.00',
      fenyongtixian: data.fenyongtixian ?? '0.00',
      yichongzhiDashou: data.yichongzhiDashou ?? 0,
    };
    Object.assign(app.globalData.guanshi, guanshiData);
    const zhuanhualv = guanshiData.yaoqingzongshu > 0
      ? (guanshiData.yichongzhiDashou / guanshiData.yaoqingzongshu * 100).toFixed(1)
      : 0;
    this.checkRoleStatuses();
    if (isRoleStatusActive(wx.getStorageSync('dashoustatus'))) {
      this.setData({ isDashou: true, uid: data.uid || wx.getStorageSync('uid') || '' });
      this.loadAvatar();
    }
    this.setData({
      isGuanshi: true,
      ...guanshiData,
      zhuanhualv,
      isLoading: false,
      guanshiInviteCode: '',
    });
    lockPrimaryRole('dashou');
    ensureRoleOnCenterPage(this, 'dashou');
    await this.refreshAllInfo(false);
    wx.hideLoading();
    wx.showToast({ title: toastMsg || '管事注册成功', icon: 'success', duration: 2000 });
  },

  handleGuanshiInviteCodeWithLoginCheck(inviteCode) {
    const token = wx.getStorageSync('token');
    const uid = wx.getStorageSync('uid');
    if (!token || !uid) {
      this.loginAndRegisterGuanshiWithInviteCode(inviteCode);
    } else if (!this.data.isGuanshi) {
      wx.showLoading({ title: '管事注册中...', mask: true });
      this.callGuanshiRegisterApi(inviteCode);
    } else {
      lockPrimaryRole('dashou');
      ensureRoleOnCenterPage(this, 'dashou');
      wx.showToast({ title: '您已是管事', icon: 'success' });
    }
  },

  loginAndRegisterGuanshiWithInviteCode(inviteCode) {
    const that = this;
    wx.showLoading({ title: '登录注册中...', mask: true });
    wx.login({
      success: (loginRes) => {
        if (loginRes.code) {
          that.callGuanshiLoginRegisterApi(loginRes.code, inviteCode);
        } else {
          wx.hideLoading();
          wx.showToast({ title: '微信登录失败', icon: 'none' });
        }
      },
      fail: () => {
        wx.hideLoading();
        wx.showToast({ title: '微信登录失败', icon: 'none' });
      },
    });
  },

  callGuanshiLoginRegisterApi(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/zuzhangyqmzc',
      method: 'POST',
      data: { code, inviteCode },
      header: { 'content-type': 'application/json' },
      success: (res) => {
        const body = res.data || {};
        if (res.statusCode === 200 && that._isApiSuccess(body)) {
          const userData = that._extractUserData(body);
          const toastMsg = that._isAlreadyGuanshiMsg(that._getApiMsg(body))
            ? that._getApiMsg(body)
            : '管事注册成功';
          that._applyGuanshiRegisterSuccess(userData, toastMsg);
        } else if (res.statusCode === 200 && that._isAlreadyGuanshiMsg(that._getApiMsg(body))) {
          that._applyGuanshiRegisterSuccess(that._extractUserData(body), that._getApiMsg(body) || '您已是管事');
        } else {
          wx.hideLoading();
          wx.showToast({ title: that._getApiMsg(body) || '注册失败', icon: 'none' });
        }
      },
      fail: () => {
        wx.hideLoading();
        wx.showToast({ title: '网络请求失败', icon: 'none' });
      },
    });
  },

  async callGuanshiRegisterApi(inviteCode) {
    try {
      const res = await request({
        url: '/yonghu/guanshizhuce',
        method: 'POST',
        data: { inviteCode },
      });
      const body = res?.data || {};
      if (res && this._isApiSuccess(body)) {
        const userData = this._extractUserData(body);
        const toastMsg = this._isAlreadyGuanshiMsg(this._getApiMsg(body))
          ? this._getApiMsg(body)
          : '管事注册成功';
        await this._applyGuanshiRegisterSuccess(userData, toastMsg);
      } else if (this._isAlreadyGuanshiMsg(this._getApiMsg(body))) {
        await this._applyGuanshiRegisterSuccess(this._extractUserData(body), this._getApiMsg(body) || '您已是管事');
      } else {
        wx.hideLoading();
        wx.showToast({ title: this._getApiMsg(body) || '注册失败', icon: 'none' });
      }
    } catch (e) {
      wx.hideLoading();
      wx.showToast({ title: e.message || '注册失败', icon: 'none' });
    }
  },

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

  goToZuzhangWithdraw() {
    wx.navigateTo({ url: `/pages/withdraw/withdraw?from=zuzhang&amount=${this.data.ketixian}` });
  },

  goToInviteUser() { wx.navigateTo({ url: '/pages/invite-fighter/invite-fighter' }); },
  goToMySubordinate() { wx.navigateTo({ url: '/pages/my-fighter/my-fighter' }); },
  goToRechargeRecord() { wx.navigateTo({ url: '/pages/recharge-log/recharge-log' }); },
  goToGuanshiRanking() {
    wx.navigateTo({ url: '/pages/fighter-rank/fighter-rank?type=guanshi' });
  },
  goToPromoPoster() { wx.navigateTo({ url: '/pages/poster/poster' }); },
  goToFenhongJilu() { wx.navigateTo({ url: '/pages/leader-bonus-log/leader-bonus-log' }); },
  goToYaoqingGuanshi() { wx.navigateTo({ url: '/pages/invite-manager/invite-manager' }); },
  goToGuanshiAuthPage() { wx.navigateTo({ url: '/pages/verify/verify?type=guanshi' }); },

  async contactZuzhang() {
    wx.showLoading({ title: '获取组长信息...', mask: true });
    try {
      const res = await request({ url: '/yonghu/guanshi_contact', method: 'POST' });
      if (res && res.data.code === 200 && res.data.data) {
        const inviter = res.data.data;
        const fullAvatar = resolveAvatarUrl(inviter.touxiang);
        const cacheData = { uid: inviter.uid, nicheng: inviter.nicheng || '', avatar: fullAvatar };
        wx.setStorageSync('zuzhangInviterCache', cacheData);
        this.setData({ zuzhangInviterCache: cacheData });
        await openPrivateChat(this, {
          toUserId: buildInviterPeerId(inviter.uid),
          toName: inviter.nicheng || '组长',
          toAvatar: fullAvatar,
        });
      } else {
        wx.showToast({ title: '未绑定邀请人', icon: 'none' });
      }
    } catch (e) {
      wx.showToast({ title: '网络错误', icon: 'none' });
    } finally {
      wx.hideLoading();
    }
  },

  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) {
    }
  },

  // 联系邀请人
  async contactInviter() {
    wx.showLoading({ title: '获取邀请人...', mask: true });
    try {
      const res = await request({ url: '/yonghu/hqwdyqr', method: 'POST' });
      if (res && res.data.code === 200 && res.data.data) {
        const inviter = res.data.data;
        const fullAvatar = resolveAvatarUrl(inviter.touxiang);
        const cacheData = {
          uid: inviter.uid,
          nicheng: inviter.nicheng || '',
          avatar: fullAvatar,
        };
        wx.setStorageSync('inviterCache', cacheData);
        this.setData({ inviterCache: cacheData });
        await openPrivateChat(this, {
          toUserId: buildInviterPeerId(inviter.uid),
          toName: inviter.nicheng || '管事',
          toAvatar: fullAvatar,
        });
      } 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/mine/mine' });
      }
    });
  },

  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;
          syncProfileFields(userData);
          syncRoleStatuses(userData);
          syncGroupFields(userData);
          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 || '',
            };
            Object.assign(app.globalData, updateData);
          }
          that.setData({
            isDashou: true,
            uid: userData.uid || '',
            touxiang: userData.touxiang || '',
            isAutoRegistering: false
          });
          that.loadAvatar();
          that.getDashouInfo();
          that.switchToDashouRole();
          lockPrimaryRole('dashou');
          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' });
      }
    });
  },

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

  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
    } = 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 || '',
        };
        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 });
        this._updateTotalAssets();
        if (this.data.isAutoRegistering) {
          this.setData({ isAutoRegistering: false });
          wx.showToast({ title: '注册成功！', icon: 'success', duration: 2000 });
        } else {
          wx.showToast({ title: '信息已更新', icon: 'success', duration: 1500 });
        }
      }
    } catch (error) {
      console.error('获取打手信息失败:', error);
      this.setData({ isLoading: false, isAutoRegistering: false });
      wx.showToast({ title: '获取信息失败', icon: 'error', duration: 2000 });
    }
  },

  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();
        syncRoleStatuses(data);
        syncProfileFields(data);
        if (data.dashoustatus === undefined && !isRoleStatusActive(wx.getStorageSync('dashoustatus'))) {
          wx.setStorageSync('dashoustatus', 1);
          app.globalData.dashoustatus = 1;
        }
        const identityFields = ['dashoustatus', 'guanshistatus', 'shangjiastatus', 'zuzhangstatus'];
        identityFields.forEach(field => {
          if (data[field] !== undefined) {
            wx.setStorageSync(field, data[field]);
            app.globalData[field] = data[field];
          }
        });
        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 || '',
        };
        Object.assign(app.globalData, updateData);
        this.setData({
          isDashou: true,
          ...updateData,
          isLoading: false,
          isAutoRegistering: false
        });
        this.loadAvatar();
        ensureRoleOnCenterPage(this, 'dashou');
        lockPrimaryRole('dashou');
        wx.showToast({ title: '注册成功！', icon: 'success', duration: 2000 });
      } 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() {
    ensureRoleOnCenterPage(this, 'dashou');
  },

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

  goToWithdraw() { wx.navigateTo({ url: '/pages/withdraw/withdraw' }) },
  goToTotalWithdraw() { this.goToWithdraw(); },

  goToAuth(e) {
    const type = e.currentTarget.dataset.type;
    if (!type || !['dashou', 'shangjia', 'guanshi', 'zuzhang'].includes(type)) return;
    const statusMap = {
      dashou: 'dashoustatus',
      shangjia: 'shangjiastatus',
      guanshi: 'guanshistatus',
      zuzhang: 'zuzhangstatus',
    };
    const statusKey = statusMap[type];
    if (isRoleStatusActive(wx.getStorageSync(statusKey))) {
      if (type === 'shangjia') {
        enterLockedRole('shangjia', getApp());
      }
      return;
    }
    wx.navigateTo({ url: `/pages/verify/verify?type=${type}` });
  },

  onTapAuthItem(e) {
    const type = e.currentTarget.dataset.type;
    if (type === 'staff') {
      if (isStaffMode()) {
        enterLockedRole('shangjia', getApp());
      } else {
        wx.navigateTo({ url: '/pages/staff-join/staff-join' });
      }
      return;
    }
    if (type === 'shangjia') {
      this.onTapShangjiaAuth();
      return;
    }
    this.goToAuth(e);
  },

  enterShangjiaCenter() {
    if (!this.data.shangjiaCertified) {
      wx.navigateTo({ url: '/pages/verify/verify?type=shangjia' });
      return;
    }
    enterLockedRole('shangjia', getApp());
  },

  onTapShangjiaAuth() {
    if (this.data.shangjiaCertified) {
      this.enterShangjiaCenter();
      return;
    }
    wx.navigateTo({ url: '/pages/verify/verify?type=shangjia' });
  },
  goToReceiveOrder() { wx.navigateTo({ url: '/pages/accept-order/accept-order' }) },
  goToMyOrders() { wx.navigateTo({ url: '/pages/fighter-orders/fighter-orders' }) },
  goToMyPunishment() { wx.navigateTo({ url: '/pages/penalty/penalty/penalty' }) },
  goToRecharge() { wx.navigateTo({ url: '/pages/fighter-recharge/fighter-recharge' }) },
  goToRanking(e) {
    const type = e?.currentTarget?.dataset?.type || 'dashou';
    wx.navigateTo({ url: `/pages/fighter-rank/fighter-rank?type=${type}` });
  },
  goToGuanzhuKs() { wx.navigateTo({ url: '/pages/manager-assign/manager-assign' }) },
  goToKaoheDafen() { wx.navigateTo({ url: '/pages/assess-score/assess-score' }) },
  goToKaoheJilu() { wx.navigateTo({ url: '/pages/assess-log/assess-log' }) },
  goToKaoheZhongxin() { wx.navigateTo({ url: '/pages/assess-center/assess-center' }) },
  goToKaoheWithdraw() {
    const yue = this.data.kaoheYue || '0.00';
    wx.navigateTo({ url: `/pages/withdraw/withdraw?amount=${yue}&from=kaoheguan` });
  },
  goToModifyInfo() { wx.navigateTo({ url: '/pages/fighter-edit/fighter-edit' }) },
  goToRules() { wx.navigateTo({ url: '/pages/fighter-rules/fighter-rules' }) },
  goToKaohe() {
    wx.navigateTo({ url: '/pages/assess-gold/assess-gold' });
  },

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

}, { roleConfig: { role: 'dashou', statusKey: 'dashoustatus', dataFlag: 'isDashou', pageId: 'dashouduan', apiUrl: '/yonghu/dashouxinxi' } }))
