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

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

export const IM_ROLE_PREFIX = {
  normal: 'Boss',
  dashou: 'Ds',
  shangjia: 'Sj',
  guanshi: 'Ds',
  zuzhang: 'Ds',
  kaoheguan: 'Ds',
};

import { getDefaultAvatarUrl } from './avatar.js';

export function getDefaultAvatar(app) {
  return getDefaultAvatarUrl(app || getApp());
}

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

export function getImUserIdForRole(role, uid) {
  if (!uid) return '';
  const prefix = getImPrefixForRole(role);
  return prefix + uid;
}

/** 当前端连接 GoEasy 用的 userId（子客服仍用 Sj） */
export function getLocalImUserId(app) {
  app = app || getApp();
  const uid = wx.getStorageSync('uid') || '';
  if (!uid) return '';
  if (isStaffMode()) return 'Sj' + uid;
  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();
  if (isStaffMode()) return 'shangjia';
  return getPrimaryRole(app) || 'normal';
}

export function getFreshImUser(app, role, uid) {
  const effectiveRole = isStaffMode() ? 'shangjia' : role;
  const id = getImUserIdForRole(effectiveRole, uid);
  const touxiang = wx.getStorageSync('touxiang') || '';
  const avatar = resolveAvatarUrl(touxiang, app);
  const name = app.globalData.currentUser?.name || `用户${(uid || '').slice(-6)}`;
  return { id, name, avatar };
}

export function persistGroupMeta(app, groupId, meta) {
  if (!groupId || !meta) return;
  if (!app.globalData.groupInfoMap) app.globalData.groupInfoMap = {};
  app.globalData.groupInfoMap[groupId] = { ...app.globalData.groupInfoMap[groupId], ...meta };
  try {
    const cache = wx.getStorageSync('pairGroupMetaCache') || {};
    cache[groupId] = app.globalData.groupInfoMap[groupId];
    wx.setStorageSync('pairGroupMetaCache', cache);
  } catch (e) {}
}

export function loadGroupMetaCache(app) {
  try {
    const cache = wx.getStorageSync('pairGroupMetaCache') || {};
    if (!app.globalData.groupInfoMap) app.globalData.groupInfoMap = {};
    Object.assign(app.globalData.groupInfoMap, cache);
  } catch (e) {}
}

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

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);
  });
}
