// utils/chat-core.js - 最终角标稳定版
import GoEasy from '../static/lib/goeasy-2.13.24.esm.min';
import { jianquanxian } from './imAuth/jianquanxian';

let _convListener = null;
let _privateListener = null;
let _groupListener = null;
let _notificationHandler = null;

function initGlobalMessageSystem(app) {
  app.ensureConnection = () => ensureConnection(app);
  app.loadConversations = () => loadConversations(app);
  app.disconnectGoEasy = () => disconnectGoEasy(app);
  app.switchRoleAndReconnect = (newRole) => switchRoleAndReconnect(app, newRole);
  app.updateUnreadCount = (count) => updateTabBarBadge(app, count || 0);

  try {
    const muted = wx.getStorageSync('notificationMuted');
    if (muted !== undefined) app.globalData.messageManager.notificationMuted = muted;
  } catch(e) {}

  initAppStateListener(app);
  initNetworkListener(app);
  ensureConnection(app);
}

function getCurrentUserId() {
  return (wx.goEasy && wx.goEasy.im && wx.goEasy.im.userId) || null;
}

async function ensureConnection(app) {
  const role = app.globalData.currentRole || 'normal';
  const uid = wx.getStorageSync('uid');
  if (!uid) return;

  const prefixMap = { normal: 'Boss', dashou: 'Ds', shangjia: 'Sj', guanshi: 'Gs', zuzhang: 'Zz', kaoheguan: 'Kh' };
  const prefix = prefixMap[role] || 'Boss';
  const targetUserId = prefix + uid;

  const status = wx.goEasy.getConnectionStatus ? wx.goEasy.getConnectionStatus() : 'disconnected';
  if (status === 'connected' || status === 'reconnected') {
    const currentUserId = getCurrentUserId();
    if (currentUserId === targetUserId) {
      registerGlobalListeners(app);
      await subscribeAllGroups(app);
      loadConversations(app);
      registerNotification(app);
      // 强制立即更新一次角标，避免切后台后不显示
      setTimeout(() => { loadConversations(app); }, 500);
      return;
    } else {
      wx.goEasy.disconnect();
    }
  }
  connectGoEasy(app, targetUserId, role);
}

function connectGoEasy(app, userId, identityType) {
  const currentUser = app.globalData.currentUser || {
    id: wx.getStorageSync('uid'),
    name: '用户' + (wx.getStorageSync('uid') || '').substring(0, 6),
    avatar: app.globalData.ossImageUrl + app.globalData.morentouxiang
  };
  wx.goEasy.connect({
    id: userId,
    data: {
      name: currentUser.name,
      avatar: currentUser.avatar || (app.globalData.ossImageUrl + app.globalData.morentouxiang),
      identityType: identityType
    },
    onSuccess: async () => {
      wx.setStorageSync('savedGoEasyConnection', JSON.stringify({
        userId, identityType, lastConnectTime: Date.now(), status: 'connected'
      }));
      registerGlobalListeners(app);
      await subscribeAllGroups(app);
      loadConversations(app);
      registerNotification(app);
    },
    onFailed: (error) => {
      console.error('GoEasy连接失败', error);
      if (error.code === 408) {
        registerGlobalListeners(app);
        loadConversations(app);
        registerNotification(app);
      } else {
        wx.showToast({ title: '连接失败，请重试', icon: 'none' });
      }
    }
  });
}

function subscribeAllGroups(app) {
  return new Promise((resolve) => {
    if (!wx.goEasy || !wx.goEasy.im) return resolve();
    wx.goEasy.im.latestConversations({
      onSuccess: (result) => {
        const conversations = result?.content?.conversations || result?.conversations || [];
        const groupIds = conversations.filter(c => c.type === 'group' && c.groupId).map(c => c.groupId);
        if (groupIds.length && wx.goEasy.im.subscribeGroup) {
          wx.goEasy.im.subscribeGroup({
            groupIds: groupIds,
            onSuccess: () => resolve(),
            onFailed: () => resolve()
          });
        } else {
          resolve();
        }
      },
      onFailed: () => resolve()
    });
  });
}

function registerGlobalListeners(app) {
  if (!wx.goEasy || !wx.goEasy.im) return;
  if (_convListener) {
    wx.goEasy.im.off(wx.GoEasy.IM_EVENT.CONVERSATIONS_UPDATED, _convListener);
  }
  if (_privateListener) {
    wx.goEasy.im.off(wx.GoEasy.IM_EVENT.PRIVATE_MESSAGE_RECEIVED, _privateListener);
  }
  if (_groupListener) {
    wx.goEasy.im.off(wx.GoEasy.IM_EVENT.GROUP_MESSAGE_RECEIVED, _groupListener);
  }

  _convListener = (result) => {
    const unreadTotal = result.unreadTotal || 0;
    updateTabBarBadge(app, unreadTotal);
    app.emitEvent('conversationsUpdated', result);
  };
  wx.goEasy.im.on(wx.GoEasy.IM_EVENT.CONVERSATIONS_UPDATED, _convListener);

  _privateListener = () => { loadConversations(app); };
  wx.goEasy.im.on(wx.GoEasy.IM_EVENT.PRIVATE_MESSAGE_RECEIVED, _privateListener);

  _groupListener = () => { loadConversations(app); };
  wx.goEasy.im.on(wx.GoEasy.IM_EVENT.GROUP_MESSAGE_RECEIVED, _groupListener);
}

function loadConversations(app) {
  if (!getCurrentUserId()) return;
  wx.goEasy.im.latestConversations({
    onSuccess: (result) => {
      const unreadTotal = result.unreadTotal || 0;
      updateTabBarBadge(app, unreadTotal);
      app.emitEvent('conversationsUpdated', result);
      subscribeAllGroups(app);
    },
    onFailed: (err) => console.error('加载会话失败', err)
  });
}

function updateTabBarBadge(app, unreadCount) {
  const badgeText = unreadCount > 0 ? (unreadCount > 99 ? '99+' : String(unreadCount)) : '';
  app.globalData.messageManager.unreadTotal = unreadCount;
  app.emitEvent('tabBarBadgeChanged', { badgeText, showRedDot: unreadCount > 0 });
  // 直接更新组件，确保角标立即显示
  try {
    const pages = getCurrentPages();
    if (pages.length) {
      const tabBar = pages[pages.length-1].selectComponent('#custom-tab-bar');
      if (tabBar && tabBar.setData) tabBar.setData({ badgeText });
      // 兼容 getTabBar 方式
      const page = pages[pages.length-1];
      if (page.getTabBar) {
        const tabBarInstance = page.getTabBar();
        if (tabBarInstance && tabBarInstance.setData) tabBarInstance.setData({ badgeText });
      }
    }
  } catch(e) {}
  wx.setStorageSync('messageUnreadTotal', unreadCount);
}

function registerNotification(app) {
  if (!wx.goEasy || !wx.goEasy.im) return;
  if (_notificationHandler) {
    wx.goEasy.im.off(wx.GoEasy.IM_EVENT.PRIVATE_MESSAGE_RECEIVED, _notificationHandler);
    wx.goEasy.im.off(wx.GoEasy.IM_EVENT.GROUP_MESSAGE_RECEIVED, _notificationHandler);
  }
  _notificationHandler = (message) => {
    if (app.globalData.messageManager.notificationMuted) return;
    const pages = getCurrentPages();
    if (pages.length) {
      const curPage = pages[pages.length - 1];
      if (curPage.route === 'pages/liaotian/liaotian' || curPage.route === 'pages/qunliaotian/qunliaotian') return;
    }
    const senderName = message.senderData?.name || (message.senderId || '用户');
    let content = '';
    if (message.type === 'text') content = message.payload?.text || '[文本]';
    else if (message.type === 'image') content = '[图片]';
    else if (message.type === 'audio') content = '[语音]';
    else content = '[新消息]';
    if (app.globalData.globalNotification && app.globalData.globalNotification.show) {
      app.globalData.globalNotification.show({
        senderName, content, message,
        notificationType: message.groupId ? 'group' : 'private',
        groupId: message.groupId, orderId: message.orderId
      });
    } else {
      wx.showToast({ title: `${senderName}: ${content}`, icon: 'none', duration: 2000 });
    }
  };
  wx.goEasy.im.on(wx.GoEasy.IM_EVENT.PRIVATE_MESSAGE_RECEIVED, _notificationHandler);
  wx.goEasy.im.on(wx.GoEasy.IM_EVENT.GROUP_MESSAGE_RECEIVED, _notificationHandler);
}

function disconnectGoEasy(app) {
  if (_convListener) {
    wx.goEasy.im.off(wx.GoEasy.IM_EVENT.CONVERSATIONS_UPDATED, _convListener);
    _convListener = null;
  }
  if (_privateListener) {
    wx.goEasy.im.off(wx.GoEasy.IM_EVENT.PRIVATE_MESSAGE_RECEIVED, _privateListener);
    _privateListener = null;
  }
  if (_groupListener) {
    wx.goEasy.im.off(wx.GoEasy.IM_EVENT.GROUP_MESSAGE_RECEIVED, _groupListener);
    _groupListener = null;
  }
  if (_notificationHandler) {
    wx.goEasy.im.off(wx.GoEasy.IM_EVENT.PRIVATE_MESSAGE_RECEIVED, _notificationHandler);
    wx.goEasy.im.off(wx.GoEasy.IM_EVENT.GROUP_MESSAGE_RECEIVED, _notificationHandler);
    _notificationHandler = null;
  }
  wx.goEasy.disconnect({ onSuccess: () => {}, onFailed: () => {} });
  wx.removeStorageSync('savedGoEasyConnection');
}

async function switchRoleAndReconnect(app, newRole) {
  await disconnectGoEasy(app);
  app.globalData.currentRole = newRole;
  wx.setStorageSync('currentRole', newRole);
  ensureConnection(app);
  return true;
}

function initAppStateListener(app) {
  let isActive = true;
  wx.onAppShow(() => {
    if (!isActive) return;
    const status = wx.goEasy.getConnectionStatus ? wx.goEasy.getConnectionStatus() : 'disconnected';
    if (status !== 'connected' && status !== 'reconnected') {
      ensureConnection(app);
    } else {
      // 连接存在但可能角标未更新，强制拉取并更新
      loadConversations(app);
      // 额外确保角标组件刷新
      setTimeout(() => {
        const unread = app.globalData.messageManager.unreadTotal || 0;
        updateTabBarBadge(app, unread);
      }, 500);
    }
  });
  wx.onAppHide(() => {});
}

function initNetworkListener(app) {
  wx.onNetworkStatusChange((res) => {
    if (res.isConnected) {
      setTimeout(() => {
        ensureConnection(app);
      }, 1000);
    }
  });
}

module.exports = { initGlobalMessageSystem };