// 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 { fetchMyZhidingOrders, processZhidingList, filterZhidingBannerList } from '../../utils/zhiding-order.js'
import { openPrivateChat, buildInviterPeerId } from '../../utils/im-user.js'
import { isStaffMode, getStaffContext } from '../../utils/staff-api.js'
import { ensurePhoneAuth } from '../../utils/phone-auth.js'
import {
  ICON_KEYS,
  resolveMiniappIcon,
  refreshPindaoConfig,
  getPindaoConfig,
  resolvePindaoImages,
  warmupPindaoConfig,
  PINDAO_ICON_FALLBACK,
  defaultIconRel,
  ICON_FOLDER,
} from '../../utils/miniapp-icons.js'
import { getDefaultAvatarUrl } from '../../utils/avatar.js'

const PLATFORM_INVITE_CODE = '0000008RffVgKHMj7kQC'
const app = getApp()

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

    isDashou: false,
    isGuanshi: false,
    isZuzhang: false,
    isKaoheguan: false,
    isShangjia: false,
    shangjiaCertified: false,
    totalAssets: '0.00',
    assetBreakdown: [],
    moreFuncList: [],
    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: [],
    identityTagList: [],
    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,
    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,
    pindaoVisible: false,
    pindaoTitle: '频道',
    pindaoChannelNo: '',
    examEnabled: false,
    examPassed: false,
    pindaoImages: [],

    scrollViewRefreshing: false,
    showRechargeBanners: false,
    showPindaoEntry: true,

    userBg: '',
    qiepianBanner: '',
    ksIcon: '',
    penaltyTipIcon: '',
    followExpanded: false,
    followClass: '',
    pendingPenaltyCount: 0,
    myZhidingList: [],
    myZhidingCount: 0,
    orderNavXym: [],
    tradeNavXym: [],
    inviteNavXym: [],
  },

  _buildImgUrls(ossImageUrl) {
    const app = getApp();
    const icon = (key, fallback) => resolveMiniappIcon(app, key, fallback || defaultIconRel(key));
    return {
      iconRefresh: icon(ICON_KEYS.ICON_REFRESH, 'beijing/guanshiduan/icon-refresh.png'),
      iconCopy: icon(ICON_KEYS.FIGHTER_MINE_COPY, 'beijing/guanshiduan/icon-copy.png'),
      iconEdit: icon(ICON_KEYS.FIGHTER_MINE_EDIT, 'beijing/dashouduan/dashoutubiaobeijing/icon-edit.jpg'),
      iconPunish: icon(ICON_KEYS.FIGHTER_MINE_PUNISH, 'beijing/dashouduan/dashoutubiaobeijing/icon-punish.jpg'),
      iconMedal: icon(ICON_KEYS.FIGHTER_MINE_MEDAL, 'beijing/dashouduan/dashoutubiaobeijing/icon-medal.jpg'),
      iconBook: icon(ICON_KEYS.FIGHTER_MINE_BOOK, 'beijing/dashouduan/dashoutubiaobeijing/icon-book.jpg'),
      iconRank: icon(ICON_KEYS.FIGHTER_MINE_RANK, 'beijing/dashouduan/dashoutubiaobeijing/icon-rank.jpg'),
      iconInvite: icon(ICON_KEYS.FIGHTER_MINE_INVITE, 'beijing/guanshiduan/icon-invite.png'),
      iconContact: icon(ICON_KEYS.FIGHTER_MINE_CONTACT, 'beijing/guanshiduan/icon-contact.png'),
      iconKefu: icon(ICON_KEYS.FIGHTER_MINE_KEFU, 'beijing/tubiao/grzx_kefu.jpg'),
      iconPindao: icon(ICON_KEYS.MINE_PINDAO, PINDAO_ICON_FALLBACK),
      iconKaoheDafen: icon(ICON_KEYS.FIGHTER_MINE_KAOHE_DAFEN, 'beijing/kaohe/daofen.png'),
      iconKaoheJilu: icon(ICON_KEYS.FIGHTER_MINE_KAOHE_JILU, 'beijing/kaohe/jilu.png'),
      iconKaoheZhongxin: icon(ICON_KEYS.FIGHTER_MINE_KAOHE_ZHONGXIN, 'beijing/kaohe/zhongxin.png'),
      iconShangjia: icon(ICON_KEYS.FIGHTER_MINE_SHANGJIA, 'beijing/tubiao/grzx_shangjia.jpg'),
      iconDashouAuth: icon(ICON_KEYS.FIGHTER_MINE_DASHOU_AUTH, 'beijing/tubiao/grzx_dashou.jpg'),
      iconClear: icon(ICON_KEYS.FIGHTER_MINE_CLEAR, 'beijing/tubiao/grzx_qingchu.jpg'),
      iconSwitch: icon(ICON_KEYS.FIGHTER_MINE_SWITCH, `${ICON_FOLDER}/fighter_mine_switch.png`),
      iconRecord: icon(ICON_KEYS.FIGHTER_MINE_RECORD, 'beijing/guanshiduan/icon-record.png'),
      bannerVip: icon(ICON_KEYS.FIGHTER_RECHARGE_MEMBER, `${ICON_FOLDER}/fighter_recharge_member.png`),
      bannerDeposit: icon(ICON_KEYS.FIGHTER_RECHARGE_DEPOSIT, `${ICON_FOLDER}/fighter_recharge_deposit.png`),
      avatarDefault: getDefaultAvatarUrl(app),
    };
  },

  onLoad(options) {
    const app = getApp();
    const sys = wx.getSystemInfoSync();
    const ossImageUrl = app.globalData.ossImageUrl || '';
    const imgUrls = this._buildImgUrls(ossImageUrl);
    const nav = this._buildNavLists(app);
    this.setData({
      imgUrls,
      ...nav,
      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');
    this.syncConfiguredAssets();
  },

  _buildNavLists(app) {
    const icon = (key) => resolveMiniappIcon(app, key, defaultIconRel(key));
    return {
      orderNavXym: [
        { name: '待完成', statusKey: 'jinxingzhong', icon: icon(ICON_KEYS.FIGHTER_ORDER_PENDING), badge: 0, showBadge: false },
        { name: '待结算', statusKey: 'jiesuanzhong', icon: icon(ICON_KEYS.FIGHTER_ORDER_SETTLING), badge: 0, showBadge: false },
        { name: '已完成', statusKey: 'yiwancheng', icon: icon(ICON_KEYS.FIGHTER_ORDER_DONE), badge: 0, showBadge: false },
        { name: '已关闭', statusKey: 'yituikuan', icon: icon(ICON_KEYS.FIGHTER_ORDER_CLOSED), badge: 0, showBadge: false },
      ],
      tradeNavXym: [
        { name: '佣金记录', type: 'commission', icon: icon(ICON_KEYS.FIGHTER_TRADE_COMMISSION) },
        { name: '提现记录', type: 'withdraw', icon: icon(ICON_KEYS.FIGHTER_TRADE_WITHDRAW) },
        { name: '结算记录', type: 'settle', icon: icon(ICON_KEYS.FIGHTER_TRADE_SETTLE) },
        { name: '扣款记录', type: 'deduct', icon: icon(ICON_KEYS.FIGHTER_TRADE_DEDUCT) },
        { name: '充值记录', type: 'recharge', icon: icon(ICON_KEYS.FIGHTER_TRADE_RECHARGE) },
      ],
      inviteNavXym: [
        { name: '我的下级', action: 'subordinate', icon: icon(ICON_KEYS.FIGHTER_INVITE_SUBORDINATE) },
        { name: '推广海报', action: 'poster', icon: icon(ICON_KEYS.FIGHTER_INVITE_POSTER) },
        { name: '邀请码', action: 'inviteCode', icon: icon(ICON_KEYS.FIGHTER_INVITE_CODE) },
      ],
      ksIcon: icon(ICON_KEYS.FIGHTER_KUAISHOU_CASH),
      qiepianBanner: icon(ICON_KEYS.FIGHTER_MINE_QIEPIAN),
      penaltyTipIcon: icon(ICON_KEYS.FIGHTER_MINE_PENALTY_TIP),
    };
  },

  syncConfiguredAssets() {
    const app = getApp();
    const ossImageUrl = app.globalData.ossImageUrl || '';
    const imgUrls = this._buildImgUrls(ossImageUrl);
    const nav = this._buildNavLists(app);
    const bannerVip = imgUrls.bannerVip;
    const bannerDeposit = imgUrls.bannerDeposit;
    this.setData({
      imgUrls,
      ...nav,
      showRechargeBanners: !!(bannerVip || bannerDeposit),
      // showPindaoEntry: ... || this.data.isKaoheguan 临时隐藏考核官
      showPindaoEntry: this.data.isDashou || this.data.isGuanshi || this.data.isZuzhang,
    }, () => {
      this._buildMoreFuncList();
    });
  },

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

    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();
    warmupPindaoConfig(app);
    this.checkRoleStatuses();
    this.syncConfiguredAssets();
    this.loadPenaltyCount();
    if (isCenterPageActive(this, 'isDashou', 'dashoustatus')) {
      if (!this.data.isDashou) this.setData({ isDashou: true });
      ensureRoleOnCenterPage(this, 'dashou');
      this.loadExamStatus();
      this.loadMyZhidingOrders();
    } 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);
      }
    }
    if (app.startImWhenReady) app.startImWhenReady();
  },

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

  /** 更多功能：常用优先，按身份动态展示 */
  _buildMoreFuncList() {
    const d = this.data;
    const img = d.imgUrls || {};
    const list = [];
    const push = (action, name, icon, extra = {}) => {
      list.push({ action, name, icon, ...extra });
    };

    if (d.isZuzhang) {
      push('goToYaoqingGuanshi', '邀请管事', img.iconInvite);
    }
    push('contactInviter', '联系管事', img.iconInvite);
    if (d.isGuanshi) {
      push('contactZuzhang', '联系组长', img.iconContact);
    }
    push('goToKefu', '在线客服', img.iconKefu);
    push('onTapShangjiaAuth', d.shangjiaCertified ? '进入商家端' : '商家认证', img.iconShangjia);
    push('onTapStaffAuth', isStaffMode() ? '商家客服工作台' : '商家客服入驻', img.iconKefu || img.iconShangjia);
    if (d.showPindaoEntry) {
      push('openPindaoModal', '频道', img.iconPindao);
    }

    push('goToMyPunishment', '我的处罚', img.iconPunish);
    // push('goToKaohe', '考核金牌', img.iconMedal); // 临时隐藏，恢复时取消注释
    push('goToDashouExam', '接单考试', img.iconBook);
    push('goToRanking', '总排行榜', img.iconRank, { rankType: 'dashou' });

    // 会员记录 / 分红记录已合并至「佣金记录」页 Tab 切换
    // 临时隐藏考核官入口，恢复时取消注释
    // if (d.isKaoheguan) {
    //   push('goToKaoheDafen', '考核打分', img.iconKaoheDafen);
    //   push('goToKaoheJilu', '考核记录', img.iconKaoheJilu);
    //   push('goToKaoheZhongxin', '考核中心', img.iconKaoheZhongxin);
    // }

    if (!d.isDashou) {
      push('goToAuth', '接单员认证', img.iconDashouAuth, { authType: 'dashou' });
    }

    push('goToRules', '用户规则', img.iconBook);
    push('switchToNormal', '返回点单端', img.iconSwitch);
    push('clearCache', '退出登录', img.iconClear);

    this.setData({ moreFuncList: list });
  },

  onMoreFuncTap(e) {
    const { action, authType, rankType } = e.currentTarget.dataset;
    if (action === 'goToAuth' && authType) {
      this.goToAuth({ currentTarget: { dataset: { type: authType } } });
      return;
    }
    if (action === 'goToRanking') {
      this.goToRanking({ currentTarget: { dataset: { type: rankType || 'dashou' } } });
      return;
    }
    if (action === 'onTapStaffAuth') {
      this.onTapAuthItem({ currentTarget: { dataset: { type: 'staff' } } });
      return;
    }
    if (action === 'onTapShangjiaAuth') {
      this.onTapShangjiaAuth();
      return;
    }
    if (typeof this[action] === 'function') {
      this[action]();
    }
  },

  async refreshAllInfo(showToast = true) {
    if (this._profileRefreshing) return;
    this._profileRefreshing = true;
    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.loadIdentityTags(),
        this.loadMyZhidingOrders(),
      ]);
      this.checkRoleStatuses();
      this.syncConfiguredAssets();
      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._profileRefreshing = false;
      this.setData({ isLoading: false });
    }
  },

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

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

  onPullDownRefresh() {
    this.setData({ scrollViewRefreshing: true });
    Promise.all([
      this.refreshAllInfo(false),
      this.loadExamStatus(),
    ]).finally(() => {
      this.setData({ scrollViewRefreshing: false });
      wx.stopPullDownRefresh();
    });
  },

  async loadIdentityTags() {
    try {
      const res = await request({ url: '/jituan/identity-tag/my-tags', method: 'POST' });
      if (res && res.data && (res.data.code === 0 || res.data.code === 200)) {
        const d = res.data.data || {};
        const merged = [
          ...(d.dashou || []),
          ...(d.zuzhang || []),
          ...(d.guanshi || []),
        ];
        this.setData({ identityTagList: merged });
      }
    } catch (e) {
      /* 静默 */
    }
  },

  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('打手信息获取失败');
  },

  _applyRoleStatusFromApi(field, active) {
    const val = active ? 1 : 0;
    wx.setStorageSync(field, val);
    getApp().globalData[field] = val;
    return val;
  },

  async _fetchGuanshiInfoSilent() {
    const res = await request({ url: '/yonghu/guanshixinxi', method: 'POST' });
    if (res && this._isApiSuccess(res.data)) {
      const data = this._extractUserData(res.data);
      // guanshixinxi 成功即表示已是管事；接口不返回 guanshistatus，不能依赖本地旧缓存
      if (data.guanshistatus !== undefined) {
        this._applyRoleStatusFromApi('guanshistatus', isRoleStatusActive(data.guanshistatus));
      } else {
        this._applyRoleStatusFromApi('guanshistatus', true);
      }
      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;
    }
    this._applyRoleStatusFromApi('guanshistatus', false);
    this.setData({ isGuanshi: false });
  },

  async _fetchZuzhangInfoSilent() {
    const res = await request({ url: '/yonghu/zuzhangxinxi', method: 'POST' });
    if (res && res.data.code === 200) {
      const data = res.data.data || {};
      // zuzhangxinxi 成功即表示已是组长；后台新增组长后本地缓存可能仍为 0
      if (data.zuzhangstatus !== undefined) {
        this._applyRoleStatusFromApi('zuzhangstatus', isRoleStatusActive(data.zuzhangstatus));
      } else {
        this._applyRoleStatusFromApi('zuzhangstatus', true);
      }
      this.setData({
        isZuzhang: true,
        ketixian: data.ketixian || '0.00',
        guanshiCount: data.guanshiCount || 0,
        fenhongZonge: data.fenhongZonge || '0.00',
      });
      this._updateTotalAssets();
      return;
    }
    this._applyRoleStatusFromApi('zuzhangstatus', false);
    this.setData({ isZuzhang: false });
  },

  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?tab=guanshi' }); },
  goToCommissionLog(tab = 'dashou') {
    wx.navigateTo({ url: `/pages/recharge-log/recharge-log?tab=${tab}` });
  },
  goToGuanshiRanking() {
    wx.navigateTo({ url: '/pages/fighter-rank/fighter-rank?type=guanshi' });
  },
  goToPromoPoster() { wx.navigateTo({ url: '/pages/poster/poster' }); },
  goToFenhongJilu() { wx.navigateTo({ url: '/pages/recharge-log/recharge-log?tab=zuzhang' }); },
  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.switchTab({ url: '/pages/accept-order/accept-order' }) },

  async loadMyZhidingOrders() {
    if (!isCenterPageActive(this, 'isDashou', 'dashoustatus')) return;
    try {
      const raw = await fetchMyZhidingOrders();
      const uid = this.data.uid || wx.getStorageSync('uid');
      const list = filterZhidingBannerList(processZhidingList(raw, getApp(), uid));
      this.setData({ myZhidingList: list, myZhidingCount: list.length });
    } catch (e) {
      console.warn('fighter loadMyZhidingOrders', e);
    }
  },

  goToZhidingFromMine() {
    const app = getApp();
    const first = (this.data.myZhidingList || [])[0];
    if (first && first.dingdan_id) {
      app.globalData._acceptOrderHighlight = first.dingdan_id;
    }
    wx.switchTab({
      url: '/pages/accept-order/accept-order',
      fail: () => wx.showToast({ title: '跳转失败', icon: 'none' }),
    });
  },

  goToDashouExam() { wx.navigateTo({ url: '/pages/dashou-exam/dashou-exam' }) },

  goToMyOrders() { wx.switchTab({ url: '/pages/fighter-orders/fighter-orders' }) },

  goToOrdersWithStatus(e) {
    const statusKey = e.currentTarget.dataset.status;
    if (statusKey) {
      getApp().globalData._fighterOrdersStatusKey = statusKey;
    }
    wx.switchTab({ url: '/pages/fighter-orders/fighter-orders' });
  },

  goToAllOrders() {
    getApp().globalData._fighterOrdersStatusKey = 'all';
    wx.switchTab({ url: '/pages/fighter-orders/fighter-orders' });
  },

  goToTradeNav(e) {
    const type = e.currentTarget.dataset.type;
    if (type === 'commission') {
      this.goToCommissionLog('dashou');
      return;
    }
    if (type === 'recharge') {
      if (this.data.isGuanshi) {
        this.goToCommissionLog('guanshi');
      } else {
        this.onComingSoon();
      }
      return;
    }
    if (type === 'withdraw') {
      wx.navigateTo({ url: '/pages/withdraw/withdraw-records' });
      return;
    }
    if (type === 'deduct') {
      wx.navigateTo({ url: '/pages/fighter-ledger/fighter-ledger?type=deduct' });
      return;
    }
    wx.navigateTo({ url: `/pages/fighter-ledger/fighter-ledger?type=${type}` });
  },

  goToWalletDetail() {
    this.goToCommissionLog('dashou');
  },

  onInviteNavTap(e) {
    if (!this.data.isGuanshi) {
      this.goToGuanshiAuthPage();
      return;
    }
    const action = e.currentTarget.dataset.action;
    if (action === 'subordinate') {
      this.goToMySubordinate();
      return;
    }
    if (action === 'poster') {
      this.goToPromoPoster();
      return;
    }
    if (action === 'inviteCode') {
      this.goToInviteUser();
    }
  },

  onComingSoon() {
    wx.showToast({ title: '该功能待开发', icon: 'none' });
  },

  toggleFollowKuaishou() {
    const next = !this.data.followExpanded;
    this.setData({ followExpanded: next, followClass: next ? 'expanded' : '' });
  },

  onQiepianTap() {
    this.onComingSoon();
  },

  async loadPenaltyCount() {
    if (!this.data.isDashou && !this.data.isGuanshi) return;
    try {
      const res = await request({ url: '/yonghu/cffktjhq', method: 'POST' });
      const body = res?.data;
      if (body && (body.code === 200 || body.code === 0) && body.data) {
        const d = body.data;
        const cnt = Number(d.daichuli_fakuan || d.fakuan_wait || d.pending || 0);
        this.setData({ pendingPenaltyCount: cnt > 0 ? cnt : 0 });
      }
    } catch (e) {
      /* ignore */
    }
  },

  goToMyPunishment() { wx.navigateTo({ url: '/pages/penalty/penalty/penalty' }) },

  async loadExamStatus() {
    try {
      const res = await request({ url: '/jituan/dashou-exam/status', method: 'POST' });
      const body = res?.data;
      if (body && (body.code === 200 || body.code === 0) && body.data) {
        const d = body.data;
        this.setData({
          examEnabled: !!d.exam_enabled,
          examPassed: !!d.exam_passed,
        });
      }
    } catch (e) { /* 静默 */ }
  },
  goToRecharge() { wx.navigateTo({ url: '/pages/fighter-recharge/fighter-recharge' }); },
  goToRechargeMember() { wx.navigateTo({ url: '/pages/fighter-recharge/fighter-recharge' }); },
  goToRechargeDeposit() { wx.navigateTo({ url: '/pages/fighter-recharge/fighter-deposit' }); },
  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' });
  },

  openPindaoModal() {
    const app = getApp();
    const cfg = getPindaoConfig(app);
    const images = resolvePindaoImages(app);
    this.setData({
      pindaoVisible: true,
      pindaoTitle: cfg.title || '频道',
      pindaoChannelNo: cfg.channel_no || '',
      pindaoImages: images,
    });
    refreshPindaoConfig(app).then(({ cfg: latest, images: latestImages }) => {
      if (!this.data.pindaoVisible) return;
      this.setData({
        pindaoTitle: latest.title || '频道',
        pindaoChannelNo: latest.channel_no || '',
        pindaoImages: latestImages,
      });
    }).catch(() => {});
  },

  closePindaoModal() {
    this.setData({ pindaoVisible: false });
  },
  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' } }))
