// custom-tab-bar/index.js
const app = getApp();

const roleCfg = {
  normal: {
    name: '点单老板',
    defaultPage: '/pages/index/index',
    tabList: [
      { pagePath: 'pages/index/index', text: '商城', iconPath: '/images/zhuye.png', selectedIconPath: '/images/zhuye.png' },
      { pagePath: 'pages/fenlei/fenlei', text: '分类', iconPath: '/images/fenlei.png', selectedIconPath: '/images/fenlei.png' },
      { pagePath: 'pages/xiaoxi/xiaoxi', text: '消息', iconPath: '/images/xiaoxi.png', selectedIconPath: '/images/xiaoxi.png' },
      { pagePath: 'pages/wode/wode', text: '我的', iconPath: '/images/wode.png', selectedIconPath: '/images/wode.png' }
    ]
  },
  dashou: {
    name: '打手',
    defaultPage: '/pages/jiedan/jiedan',
    tabList: [
      { pagePath: 'pages/jiedan/jiedan', text: '接单池', iconPath: '/images/jiedanchi.png', selectedIconPath: '/images/jiedanchi.png' },
      { pagePath: 'pages/dashoudingdan/dashoudingdan', text: '订单', iconPath: '/images/dingdan.png', selectedIconPath: '/images/dingdan.png' },
      { pagePath: 'pages/xiaoxi/xiaoxi', text: '消息', iconPath: '/images/xiaoxi.png', selectedIconPath: '/images/xiaoxi.png' },
      { pagePath: 'pages/dashouduan/dashouduan', text: '我的', iconPath: '/images/wode.png', selectedIconPath: '/images/wode.png' }
    ]
  },
  shangjia: {
    name: '商家',
    defaultPage: 'pages/sjdingdan/sjdingdan',
    tabList: [
      { pagePath: 'pages/sjdingdan/sjdingdan', text: '订单', iconPath: '/images/dingdan.png', selectedIconPath: '/images/dingdan.png' },
      { pagePath: 'pages/xiaoxi/xiaoxi', text: '消息', iconPath: '/images/xiaoxi.png', selectedIconPath: '/images/xiaoxi.png' },
      { pagePath: 'pages/shangjiaduan/shangjiaduan', text: '我的', iconPath: '/images/wode.png', selectedIconPath: '/images/wode.png' }
    ]
  },
  guanshi: {
    name: '管事',
    defaultPage: '/pages/guanshiduan/guanshiduan',
    tabList: [
      { pagePath: 'pages/xiaoxi/xiaoxi', text: '消息', iconPath: '/images/xiaoxi.png', selectedIconPath: '/images/xiaoxi.png' },
      { pagePath: 'pages/guanshiduan/guanshiduan', text: '我的', iconPath: '/images/wode.png', selectedIconPath: '/images/wode.png' }
    ]
  },
  zuzhang: {
    name: '组长',
    defaultPage: '/pages/zuzhangduan/zuzhangduan',
    tabList: [
      { pagePath: 'pages/xiaoxi/xiaoxi', text: '消息', iconPath: '/images/xiaoxi.png', selectedIconPath: '/images/xiaoxi.png' },
      { pagePath: 'pages/zuzhangduan/zuzhangduan', text: '我的', iconPath: '/images/wode.png', selectedIconPath: '/images/wode.png' }
    ]
  },
  kaoheguan: {
    name: '考核官',
    defaultPage: '/pages/kaoheguan/kaoheguan',
    tabList: [
      { pagePath: 'pages/xiaoxi/xiaoxi', text: '消息', iconPath: '/images/xiaoxi.png', selectedIconPath: '/images/xiaoxi.png' },
      { pagePath: 'pages/kaoheguan/kaoheguan', text: '我的', iconPath: '/images/wode.png', selectedIconPath: '/images/wode.png' }
    ]
  }
};

Component({
  data: {
    selectedIndex: 0,
    tabList: [],
    currentRole: 'normal',
    showRolePicker: false,
    availableRoles: [],
    badgeText: ''
  },
  lifetimes: {
    attached() {
      this.refresh();
      this._badgeListener = (data) => {
        if (data.badgeText !== undefined) {
          this.setData({ badgeText: data.badgeText });
        }
      };
      this._roleListener = () => {
        this.refresh();
      };
      app.on('tabBarBadgeChanged', this._badgeListener);
      app.on('currentRoleChanged', this._roleListener);
    },
    detached() {
      if (this._badgeListener) {
        app.off('tabBarBadgeChanged', this._badgeListener);
      }
      if (this._roleListener) {
        app.off('currentRoleChanged', this._roleListener);
      }
    }
  },
  pageLifetimes: {
    show() {
      this.refresh();
      const globalBadge = app.globalData.messageManager?.tabBarBadgeText || '';
      if (this.data.badgeText !== globalBadge) {
        this.setData({ badgeText: globalBadge });
      }
      this._syncUnreadWithDebounce();
    }
  },
  methods: {
    _syncUnreadWithDebounce() {
      if (this._syncTimer) clearTimeout(this._syncTimer);
      this._syncTimer = setTimeout(() => {
        if (app && app.loadConversations) {
          app.loadConversations();
        }
      }, 300);
    },

    refresh() {
      const token = wx.getStorageSync('token');
      // 未登录时强制点单端，避免清除缓存后 TabBar 仍显示其他身份
      let role = wx.getStorageSync('currentRole') || app.globalData.currentRole || 'normal';
      if (!token) {
        role = 'normal';
        app.globalData.currentRole = 'normal';
        wx.setStorageSync('currentRole', 'normal');
      } else {
        app.globalData.currentRole = role;
      }
      let cfg = roleCfg[role];
      if (!cfg) return;

      // 打手身份下，如果 isJinpai=1，悄悄把“我的”页面换成金牌页面
      if (role === 'dashou') {
        const isJinpai = wx.getStorageSync('isJinpai') === 1;
        if (isJinpai) {
          cfg = {
            ...cfg,
            tabList: cfg.tabList.map(item => {
              if (item.pagePath === 'pages/dashouduan/dashouduan') {
                return { ...item, pagePath: 'pages/jinpaids/jinpaids' };
              }
              return { ...item };
            })
          };
        }
      }

      const list = cfg.tabList.map((v, i) => ({ ...v, index: i }));
      const pages = getCurrentPages();
      const curRoute = pages.length ? pages[pages.length - 1].route : '';
      let idx = list.findIndex(t => t.pagePath === curRoute);
      if (idx === -1) idx = 0;
      const avail = this._getAvail();
      this.setData({ currentRole: role, tabList: list, selectedIndex: idx, availableRoles: avail });
    },

    _getAvail() {
      const token = wx.getStorageSync('token');
      if (!token) {
        return [{ key: 'normal', name: '点单老板' }];
      }
      const isActive = (key) => Number(wx.getStorageSync(key)) === 1;
      const arr = [{ key: 'normal', name: '点单老板' }];
      if (isActive('dashoustatus')) arr.push({ key: 'dashou', name: '打手' });
      if (isActive('shangjiastatus')) arr.push({ key: 'shangjia', name: '商家' });
      if (isActive('guanshistatus')) arr.push({ key: 'guanshi', name: '管事' });
      if (isActive('zuzhangstatus')) arr.push({ key: 'zuzhang', name: '组长' });
      if (isActive('kaoheguanstatus')) arr.push({ key: 'kaoheguan', name: '考核官' });
      return arr;
    },

    toggleRolePicker() {
      this.setData({ showRolePicker: !this.data.showRolePicker });
    },

    async selectRole(e) {
      const newRole = e.currentTarget.dataset.role;
      if (newRole === this.data.currentRole) {
        this.setData({ showRolePicker: false });
        return;
      }

      this.setData({ showRolePicker: false });

      // 1. 立即更新角色并保存
      if (app.setCurrentRole) {
        app.setCurrentRole(newRole);
      } else {
        app.globalData.currentRole = newRole;
        wx.setStorageSync('currentRole', newRole);
        app.emitEvent('currentRoleChanged', { role: newRole });
      }

      // 2. 🔥 确定跳转页面：所有角色都去“我的”页面
      let targetPage = '';
      if (newRole === 'dashou') {
        // 打手需要根据金牌状态决定跳转
        const isJinpai = wx.getStorageSync('isJinpai') === 1;
        targetPage = isJinpai ? '/pages/jinpaids/jinpaids' : '/pages/dashouduan/dashouduan';
      } else {
        // 其他角色直接取 tabList 最后一个页面
        const cfg = roleCfg[newRole];
        if (cfg && cfg.tabList.length > 0) {
          targetPage = '/' + cfg.tabList[cfg.tabList.length - 1].pagePath;
        }
      }

      // 3. 跳转
      if (targetPage) {
        wx.reLaunch({ url: targetPage });
      }

      // 4. 后台异步切换连接
      app.switchRoleAndReconnect(newRole).catch(err => {
        console.error('后台切换连接失败:', err);
      });
    },

    switchTab(e) {
      const path = e.currentTarget.dataset.path;
      const idx = e.currentTarget.dataset.index;
      if (idx === this.data.selectedIndex) return;
      wx.redirectTo({ url: '/' + path });
    }
  }
});