/** IM 用户 ID：三端连接 + 管事/组长/考核官统一走打手 Ds 前缀 */
import { getPrimaryRole } from './primary-role.js';
import { resolveAvatarUrl } from './avatar.js';
import { ensureRoleOnCenterPage } from './role-tab-bar.js';

/** 联系对象前缀：管事/组长/考核官已废弃独立前缀，统一 Ds */
const PEER_PREFIX = {
  boss: 'Boss',
  normal: 'Boss',
  dashou: 'Ds',
  shangjia: 'Sj',
  guanshi: 'Ds',
  zuzhang: 'Ds',
  kaoheguan: 'Ds',
};

export function getImPrefixForRole(role) {
  return PEER_PREFIX[role] || 'Ds';
}

/** 当前端连接 GoEasy 用的 userId */
export function getLocalImUserId(app) {
  app = app || getApp();
  const uid = wx.getStorageSync('uid') || '';
  if (!uid) return '';
  const primary = getPrimaryRole(app);
  if (primary === 'dashou') return 'Ds' + uid;
  if (primary === 'shangjia') return 'Sj' + uid;
  return 'Boss' + uid;
}

export function getLocalImIdentity(app) {
  app = app || getApp();
  return getPrimaryRole(app) || 'normal';
}

export function buildPeerImUserId(uid, role = 'dashou') {
  if (!uid) return '';
  return getImPrefixForRole(role) + uid;
}

/** 联系邀请人/管事/组长：统一 Ds 前缀 */
export function buildGuanshiPeerId(uid) {
  return buildDashouPeerId(uid);
}

export function buildDashouPeerId(uid) {
  return buildPeerImUserId(uid, 'dashou');
}

export function buildInviterPeerId(uid) {
  return buildDashouPeerId(uid);
}

export function ensureDashouImReady(page) {
  const app = getApp();
  ensureRoleOnCenterPage(page, 'dashou');
  if (app.ensureConnection) app.ensureConnection();
}

export function openPrivateChat(page, { toUserId, toName, toAvatar, delay = 350 }) {
  ensureDashouImReady(page);
  const avatar = resolveAvatarUrl(toAvatar);
  const param = {
    toUserId,
    toName: toName || '用户',
    toAvatar: avatar,
  };
  return new Promise((resolve) => {
    setTimeout(() => {
      wx.navigateTo({
        url: '/pages/chat/chat?data=' + encodeURIComponent(JSON.stringify(param)),
        fail: () => wx.showToast({ title: '打开聊天失败', icon: 'none' }),
        complete: resolve,
      });
    }, delay);
  });
}
