import { clearPrimaryRole } from './primary-role';
import { getLocalImUserId } from './im-user.js';
import { applyStaffFromLoginData, isStaffMode, restoreStaffContextAfterAuth, clearStaffSession } from './staff-api.js';
export function isWechatLoginSuccess(body) {
  if (!body) return false;
  const code = Number(body.code);
  return code === 0 || code === 200;
}

const SESSION_STATUS_KEYS = ['dashoustatus', 'guanshistatus', 'shangjiastatus', 'zuzhangstatus', 'kaoheguanstatus'];

/** 读取 token（Storage 优先，globalData 兜底并回写 Storage） */
export function getSessionToken(app) {
  app = app || getApp();
  let token = wx.getStorageSync('token') || app.globalData.token || '';
  if (token && !wx.getStorageSync('token')) {
    wx.setStorageSync('token', token);
  }
  return token;
}

export function isUserLoggedIn(app) {
  return !!getSessionToken(app);
}

/** 从 Storage / globalData 汇总展示用用户信息（兼容其他端注册后 nick 未落盘） */
export function getUserProfileForDisplay(app) {
  app = app || getApp();
  const token = getSessionToken(app);
  const uid = wx.getStorageSync('uid') || app.globalData.uid || '';
  let nick = wx.getStorageSync('nicheng') || app.globalData.nicheng || '';
  if (!nick && app.globalData.dashouNicheng) {
    nick = app.globalData.dashouNicheng;
  }
  const tx = wx.getStorageSync('touxiang') || '';
  const def = app.globalData.morentouxiang || '';
  const oss = app.globalData.ossImageUrl || '';
  let avatarUrl = '';
  if (tx) {
    avatarUrl = tx.startsWith('http') ? tx : oss + tx;
  } else if (def) {
    avatarUrl = def.startsWith('http') ? def : oss + def;
  }
  return {
    nick,
    uid,
    avatarUrl,
    isLoggedIn: !!token,
  };
}

/** 其他端登录/注册成功后，把 globalData 里已有字段补写回 Storage */
export function backfillUserProfileCache(app) {
  app = app || getApp();
  if (!isUserLoggedIn()) return;
  const profile = getUserProfileForDisplay(app);
  if (profile.nick && !wx.getStorageSync('nicheng')) {
    wx.setStorageSync('nicheng', profile.nick);
    app.globalData.nicheng = profile.nick;
  }
  if (profile.uid && !wx.getStorageSync('uid')) {
    wx.setStorageSync('uid', profile.uid);
  }
}

export function applyWechatLoginData(data, page) {
  if (!data || typeof data !== 'object') return;
  const app = getApp();
  syncProfileFields(data);
  if (data.token) {
    wx.setStorageSync('token', data.token);
  }
  syncRoleStatuses(data);
  syncGroupFields(data);
  if (data.zuzhangstatus !== undefined) {
    wx.setStorageSync('zuzhangstatus', data.zuzhangstatus);
    app.globalData.zuzhangstatus = data.zuzhangstatus;
  }
  if (data.kaoheguanstatus !== undefined) {
    wx.setStorageSync('kaoheguanstatus', data.kaoheguanstatus);
    app.globalData.kaoheguanstatus = data.kaoheguanstatus;
  }
  if (data.dingdantiaoshu) {
    app.globalData.dingdanTiaoshu = {
      daifuwu: data.dingdantiaoshu.daifuwu || 0,
      fuwuzhong: data.dingdantiaoshu.fuwuzhong || 0,
      yiwancheng: data.dingdantiaoshu.yiwancheng || 0,
      yituikuan: data.dingdantiaoshu.yituikuan || 0,
    };
  }
  if (data.isJinpai !== undefined) {
    wx.setStorageSync('isJinpai', Number(data.isJinpai));
  }

  applyStaffFromLoginData(data);

  const targetPage = page || _getCurrentPage();
  refreshTabBar(targetPage);
  restoreStaffContextAfterAuth().finally(() => {
    refreshTabBar(targetPage);
    if (app.emitEvent) {
      app.emitEvent('staffContextChanged', {});
    }
  });
}

function _getCurrentPage() {
  const pages = getCurrentPages();
  return pages.length ? pages[pages.length - 1] : null;
}

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

export function isCenterPageActive(page, dataFlag, statusKey) {
  return page.data[dataFlag] || isRoleStatusActive(wx.getStorageSync(statusKey)) || isStaffMode();
}

export function syncRoleStatuses(data) {
  if (!data || typeof data !== 'object') return;
  const app = getApp();
  const roleFields = ['dashoustatus', 'guanshistatus', 'shangjiastatus', 'zuzhangstatus', 'kaoheguanstatus'];
  roleFields.forEach((field) => {
    if (Object.prototype.hasOwnProperty.call(data, field)) {
      const val = Number(data[field]);
      const normalized = Number.isNaN(val) ? 0 : val;
      wx.setStorageSync(field, normalized);
      app.globalData[field] = normalized;
    }
  });
}

export function syncProfileFields(data) {
  if (!data || typeof data !== 'object') return;
  const app = getApp();
  ['nicheng', 'uid', 'touxiang', 'token'].forEach((field) => {
    if (data[field] !== undefined && data[field] !== null) {
      wx.setStorageSync(field, data[field]);
      app.globalData[field] = data[field];
    }
  });
}

/** 清除缓存：清空登录与身份，回到点单端「我的」 */
export function clearCacheAndEnterNormal(page) {
  resetGuestSession(page, { skipPageReset: true });
  wx.reLaunch({ url: '/pages/mine/mine' });
}

/** 清除缓存并重置为点单端（不跳转，供当前已在点单端时使用） */
export function resetGuestSession(page, options = {}) {
  const app = getApp();
  const configKey = app.CONFIG_CACHE_KEY || 'app_dynamic_config';
  let configCache = null;
  try {
    configCache = wx.getStorageSync(configKey);
  } catch (e) {}

  wx.clearStorageSync();

  clearStaffSession();

  if (configCache && typeof configCache === 'object') {
    wx.setStorageSync(configKey, configCache);
  }

  clearPrimaryRole(app);
  app.globalData.token = '';
  app.globalData.nicheng = '';
  app.globalData.uid = '';
  app.globalData.loginPromise = null;
  app.globalData.currentUser = null;
  app.globalData.dashouNicheng = '';
  app.globalData.dingdanTiaoshu = { daifuwu: 0, fuwuzhong: 0, yiwancheng: 0, yituikuan: 0 };
  app.globalData.dashouqun = '';
  app.globalData.dashouqunid = '';
  app.globalData.guanshiqun = '';
  app.globalData.guanshiqunid = '';
  SESSION_STATUS_KEYS.forEach((key) => {
    app.globalData[key] = 0;
  });
  app.globalData.shangpinleixing = [];
  app.globalData.shangpinzhuanqu = [];
  app.globalData.shangpinliebiao = [];

  app.emitEvent('currentRoleChanged', { role: 'normal' });
  refreshTabBar(page);

  if (!options.skipPageReset && page && page.setData) {
    page.setData({
      avatarUrl: '',
      userNicheng: '',
      userUid: '',
      showLoginBtn: true,
      orderCounts: { daifuwu: 0, fuwuzhong: 0, yiwancheng: 0, yituikuan: 0 },
      dashouCertified: false,
      shangjiaCertified: false,
    });
  }
}

export function syncGroupFields(data) {
  if (!data || typeof data !== 'object') return;
  const app = getApp();
  ['dashouqun', 'dashouqunid', 'guanshiqun', 'guanshiqunid'].forEach((field) => {
    if (data[field] !== undefined) {
      wx.setStorageSync(field, data[field]);
      app.globalData[field] = data[field];
    }
  });
}

export function refreshTabBar(page) {
  const tryRefresh = () => {
    const tabBar = page.getTabBar && page.getTabBar();
    if (tabBar && tabBar.refresh) tabBar.refresh();
  };
  tryRefresh();
  [50, 150, 300, 500, 800].forEach((delay) => setTimeout(tryRefresh, delay));
}

export function setRoleAndRefreshTabBar(page, role) {
  const app = getApp();
  if (app.setCurrentRole) {
    app.setCurrentRole(role);
  } else {
    app.globalData.currentRole = role;
    wx.setStorageSync('currentRole', role);
    app.emitEvent('currentRoleChanged', { role });
  }
  refreshTabBar(page);
}

export function reconnectForRole(role) {
  const app = getApp();
  if (!wx.getStorageSync('uid')) return;

  const targetUserId = getLocalImUserId(app);
  if (!targetUserId) return;

  const status = wx.goEasy?.getConnectionStatus?.() || 'disconnected';
  const currentUserId = wx.goEasy?.im?.userId || '';
  const connected = status === 'connected' || status === 'reconnected';

  if (connected && currentUserId === targetUserId) {
    if (app.loadConversations) app.loadConversations();
    if (app.ensureConnection) app.ensureConnection();
    return;
  }

  if (app.switchRoleAndReconnect) {
    app.switchRoleAndReconnect(role).catch(() => {
      if (app.ensureConnection) app.ensureConnection();
    });
  } else if (app.connectForCurrentRole) {
    app.connectForCurrentRole();
  } else if (app.ensureConnection) {
    app.ensureConnection();
  }
}

export function ensureRoleOnCenterPage(page, role) {
  setRoleAndRefreshTabBar(page, role);
  reconnectForRole(role);
}
