/** 三端固定：normal | dashou | shangjia，认证后不可回退 */

import { isStaffMode } from './staff-api.js';
import { ensurePhoneAuth } from './phone-auth.js';

const VALID = ['normal', 'dashou', 'shangjia'];
const LEGACY_CENTER_ROLES = ['guanshi', 'zuzhang', 'kaoheguan'];

/** 旧版管事/组长/考核官主端标识 → 统一回落打手 Tab */
export function migrateLegacyCenterRole(app) {
  app = app || getApp();
  const cur = wx.getStorageSync('currentRole') || app.globalData.currentRole || '';
  const pri = wx.getStorageSync('primaryRole') || '';
  const isLegacy = LEGACY_CENTER_ROLES.includes(cur) || LEGACY_CENTER_ROLES.includes(pri);
  if (!isLegacy) return false;

  const hasDashouSide =
    isRoleStatusActive(wx.getStorageSync('dashoustatus'))
    || isRoleStatusActive(wx.getStorageSync('guanshistatus'))
    || isRoleStatusActive(wx.getStorageSync('zuzhangstatus'))
    || isRoleStatusActive(wx.getStorageSync('kaoheguanstatus'));

  if (hasDashouSide) {
    lockPrimaryRole('dashou', app);
    return true;
  }
  return false;
}

export function isRoleStatusActive(status) {
  return Number(status) === 1;
}

/** 读取主端（兼容旧 currentRole / 管事组长落地页） */
export function getPrimaryRole(app) {
  app = app || getApp();
  const stored = wx.getStorageSync('primaryRole');
  if (VALID.includes(stored)) {
    return stored;
  }
  const legacy = wx.getStorageSync('currentRole') || app.globalData.currentRole || 'normal';
  if (legacy === 'dashou' || legacy === 'shangjia') {
    return legacy;
  }
  if (legacy === 'guanshi' || legacy === 'zuzhang' || legacy === 'kaoheguan') {
    if (isRoleStatusActive(wx.getStorageSync('dashoustatus'))) {
      return 'dashou';
    }
    if (isRoleStatusActive(wx.getStorageSync('shangjiastatus'))) {
      return 'shangjia';
    }
  }
  if (isRoleStatusActive(wx.getStorageSync('dashoustatus'))) {
    return 'dashou';
  }
  if (isRoleStatusActive(wx.getStorageSync('shangjiastatus'))) {
    return 'shangjia';
  }
  if (isStaffMode()) {
    return 'shangjia';
  }
  return 'normal';
}

/** 锁定主端并同步 TabBar 角色 */
export function lockPrimaryRole(role, app) {
  if (!VALID.includes(role)) return;
  app = app || getApp();
  wx.setStorageSync('primaryRole', role);
  wx.setStorageSync('currentRole', role);
  app.globalData.primaryRole = role;
  app.globalData.currentRole = role;
  if (app.emitEvent) {
    app.emitEvent('currentRoleChanged', { role });
  }
}

/** TabBar / IM 使用的有效角色（仅三端） */
export function getTabRole(app) {
  return getPrimaryRole(app);
}

export function clearPrimaryRole(app) {
  app = app || getApp();
  wx.removeStorageSync('primaryRole');
  lockPrimaryRole('normal', app);
}

export const PRIMARY_DEFAULT_PAGES = {
  normal: '/pages/mine/mine',
  dashou: '/pages/accept-order/accept-order',
  shangjia: '/pages/merchant-home/merchant-home',
};

/** 锁定主端并跳转到该端默认首页，同时建立 IM 长连接 */
function finishEnterLockedRole(role, app) {
  app = app || getApp();
  lockPrimaryRole(role, app);
  wx.reLaunch({ url: PRIMARY_DEFAULT_PAGES[role] });
  setTimeout(() => {
    if (app.switchRoleAndReconnect) {
      app.switchRoleAndReconnect(role).catch(() => {
        if (app.connectForCurrentRole) app.connectForCurrentRole();
      });
    } else if (app.connectForCurrentRole) {
      app.connectForCurrentRole();
    }
  }, 600);
  return true;
}

export function enterLockedRole(role, app) {
  if (!VALID.includes(role) || role === 'normal') return false;
  if (role === 'dashou' || role === 'shangjia') {
    ensurePhoneAuth({ redirect: true, role }).then((ok) => {
      if (ok) finishEnterLockedRole(role, app);
    });
    return true;
  }
  return finishEnterLockedRole(role, app);
}
