/**
 * IM 用户展示：从本地缓存读取最新头像，空则用默认图
 */
export function getDefaultAvatar(app) {
  const oss = app.globalData.ossImageUrl || '';
  return oss + (app.globalData.morentouxiang || '');
}

export function resolveAvatarUrl(raw, app) {
  const def = getDefaultAvatar(app);
  if (!raw) return def;
  if (raw.startsWith('http')) return raw;
  const oss = app.globalData.ossImageUrl || '';
  return oss + raw.replace(/^\//, '');
}

export function getFreshImUser(app, role, uid) {
  const prefixMap = {
    normal: 'Boss', dashou: 'Ds', shangjia: 'Sj',
    guanshi: 'Gs', zuzhang: 'Zz', kaoheguan: 'Kh',
  };
  const prefix = prefixMap[role] || 'Boss';
  const touxiang = wx.getStorageSync('touxiang') || '';
  const avatar = resolveAvatarUrl(touxiang, app);
  const name = app.globalData.currentUser?.name || `用户${(uid || '').slice(-6)}`;
  return {
    id: prefix + uid,
    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) {}
}
