// 认证相关工具函数

const LOGIN_FORM_KEY = 'loginForm';
const TENANT_ID_KEY = 'tenantId';
const TENANT_NAME_KEY = 'tenantName';
const TOKEN_KEY = 'token';
const USER_ID_KEY = 'userId';
const ACCESS_TOKEN_KEY = 'ACCESS_TOKEN';
const REFRESH_TOKEN_KEY = 'REFRESH_TOKEN';
const USER_KEY = 'user';
const ROLE_ROUTERS_KEY = 'roleRouters';
const LANG_KEY = 'lang';
const IS_DARK_KEY = 'isDark';
const HM_LVT_KEY = 'Hm_lvt_a1ff8825baa73c3a78eb96aa40325abc';

// 登录表单缓存类型
export interface LoginFormCache {
  username?: string;
  password?: string;
  tenantName?: string;
  rememberMe?: boolean;
}

// 设置登录表单缓存
export const setLoginForm = (form: LoginFormCache) => {
  localStorage.setItem(LOGIN_FORM_KEY, JSON.stringify(form));
};

// 获取登录表单缓存
export const getLoginForm = (): LoginFormCache | null => {
  const form = localStorage.getItem(LOGIN_FORM_KEY);
  return form ? JSON.parse(form) : null;
};

// 移除登录表单缓存
export const removeLoginForm = () => {
  localStorage.removeItem(LOGIN_FORM_KEY);
};

// 设置租户ID
export const setTenantId = (tenantId: string | number) => {
  localStorage.setItem(TENANT_ID_KEY, String(tenantId));
};

// 获取租户ID
export const getTenantId = (): string | null => {
  return localStorage.getItem(TENANT_ID_KEY);
};

// 移除租户ID
export const removeTenantId = () => {
  localStorage.removeItem(TENANT_ID_KEY);
};

// 设置租户名称（用于水印等展示）
export const setTenantName = (tenantName: string) => {
  localStorage.setItem(TENANT_NAME_KEY, tenantName);
};

// 获取租户名称
export const getTenantName = (): string | null => {
  return localStorage.getItem(TENANT_NAME_KEY);
};

// 移除租户名称
export const removeTenantName = () => {
  localStorage.removeItem(TENANT_NAME_KEY);
};

// 设置Token（兼容多种格式）
export const setToken = (tokenData: { accessToken?: string; token?: string } | string) => {
  if (typeof tokenData === 'string') {
    localStorage.setItem(TOKEN_KEY, tokenData);
  } else {
    const token = tokenData.accessToken || tokenData.token || '';
    localStorage.setItem(TOKEN_KEY, token);
  }
};

// 获取Token
export const getToken = (): string | null => {
  return localStorage.getItem(TOKEN_KEY);
};

// 移除Token
export const removeToken = () => {
  localStorage.removeItem(TOKEN_KEY);
};

// 设置用户ID
export const setUserId = (userId: string) => {
  localStorage.setItem(USER_ID_KEY, userId);
};

// 获取用户ID
export const getUserId = (): string | null => {
  return localStorage.getItem(USER_ID_KEY);
};

// 移除用户ID
export const removeUserId = () => {
  localStorage.removeItem(USER_ID_KEY);
};

// 设置ACCESS_TOKEN
export const setAccessToken = (token: string) => {
  localStorage.setItem(ACCESS_TOKEN_KEY, token);
};

// 获取ACCESS_TOKEN
export const getAccessToken = (): string | null => {
  return localStorage.getItem(ACCESS_TOKEN_KEY);
};

// 移除ACCESS_TOKEN
export const removeAccessToken = () => {
  localStorage.removeItem(ACCESS_TOKEN_KEY);
};

// 设置REFRESH_TOKEN
export const setRefreshToken = (token: string) => {
  localStorage.setItem(REFRESH_TOKEN_KEY, token);
};

// 获取REFRESH_TOKEN
export const getRefreshToken = (): string | null => {
  return localStorage.getItem(REFRESH_TOKEN_KEY);
};

// 移除REFRESH_TOKEN
export const removeRefreshToken = () => {
  localStorage.removeItem(REFRESH_TOKEN_KEY);
};

// 设置用户信息
export const setUser = (user: any) => {
  localStorage.setItem(USER_KEY, JSON.stringify(user));
};

// 获取用户信息
export const getUser = (): any | null => {
  const user = localStorage.getItem(USER_KEY);
  return user ? JSON.parse(user) : null;
};

// 移除用户信息
export const removeUser = () => {
  localStorage.removeItem(USER_KEY);
};

// 设置角色路由
export const setRoleRouters = (routers: any) => {
  localStorage.setItem(ROLE_ROUTERS_KEY, JSON.stringify(routers));
};

// 获取角色路由
export const getRoleRouters = (): any | null => {
  const routers = localStorage.getItem(ROLE_ROUTERS_KEY);
  return routers ? JSON.parse(routers) : null;
};

// 移除角色路由
export const removeRoleRouters = () => {
  localStorage.removeItem(ROLE_ROUTERS_KEY);
};

// 设置语言
export const setLang = (lang: string) => {
  localStorage.setItem(LANG_KEY, lang);
};

// 获取语言
export const getLang = (): string | null => {
  return localStorage.getItem(LANG_KEY);
};

// 移除语言
export const removeLang = () => {
  localStorage.removeItem(LANG_KEY);
};

// 设置暗色模式
export const setIsDark = (isDark: boolean) => {
  localStorage.setItem(IS_DARK_KEY, String(isDark));
};

// 获取暗色模式
export const getIsDark = (): boolean => {
  const isDark = localStorage.getItem(IS_DARK_KEY);
  return isDark === 'true';
};

// 移除暗色模式
export const removeIsDark = () => {
  localStorage.removeItem(IS_DARK_KEY);
};

// 设置Hm_lvt cookie值
export const setHmLvt = (value: string) => {
  localStorage.setItem(HM_LVT_KEY, value);
};

// 获取Hm_lvt cookie值
export const getHmLvt = (): string | null => {
  return localStorage.getItem(HM_LVT_KEY);
};

// 移除Hm_lvt cookie值
export const removeHmLvt = () => {
  localStorage.removeItem(HM_LVT_KEY);
};

// 清除所有认证信息
export const clearAuth = () => {
  removeToken();
  removeTenantId();
  removeTenantName();
  removeUserId();
  removeLoginForm();
  removeAccessToken();
  removeRefreshToken();
  removeUser();
  removeRoleRouters();
  removeHmLvt();
  // 清除所有菜单相关的 sessionStorage
  sessionStorage.removeItem('lastActiveMenu');
  sessionStorage.removeItem('navigateToMenu');
  sessionStorage.removeItem('cabinetDetailSource');
  // 清除权限信息
  try {
    const { clearPermissionInfo } = require('./permission');
    clearPermissionInfo();
  } catch (e) {
    // 如果权限模块未加载，忽略错误
  }
};

// Token定期检测和刷新
let tokenCheckInterval: NodeJS.Timeout | null = null;
let isChecking = false; // 防止并发检测

export const startTokenCheck = (intervalSeconds: number = 30) => {
  console.log(`[TokenCheck] 启动token检测，间隔: ${intervalSeconds}秒`);
  
  // 如果已经有定时器在运行，先清除
  if (tokenCheckInterval) {
    console.log('[TokenCheck] 清除旧的定时器');
    stopTokenCheck();
  }

  // 立即执行一次检测
  console.log('[TokenCheck] 立即执行一次检测');
  checkTokenAndRefresh();

  // 设置定时器
  tokenCheckInterval = setInterval(() => {
    console.log(`[TokenCheck] 定时器触发，执行检测 (间隔: ${intervalSeconds}秒)`);
    checkTokenAndRefresh();
  }, intervalSeconds * 1000);
  
  console.log(`[TokenCheck] 定时器已设置，ID: ${tokenCheckInterval}`);
};

export const stopTokenCheck = () => {
  if (tokenCheckInterval) {
    clearInterval(tokenCheckInterval);
    tokenCheckInterval = null;
  }
};

// 检测token并刷新
const checkTokenAndRefresh = async () => {
  console.log('[TokenCheck] checkTokenAndRefresh 被调用');
  
  // 如果正在检测中，跳过
  if (isChecking) {
    console.log('[TokenCheck] 正在检测中，跳过本次调用');
    return;
  }

  // 如果没有refreshToken，不需要检测
  const refreshToken = getRefreshToken();
  if (!refreshToken) {
    console.log('[TokenCheck] 没有refreshToken，跳过检测');
    return;
  }

  console.log('[TokenCheck] 开始检测token...');
  isChecking = true;

  try {
    // 动态导入loginApi和axios，避免循环依赖
    const { loginApi } = await import('../api/Login');
    const axios = (await import('axios')).default;
    const { env } = await import('./env');
    
    // 直接使用axios调用，绕过拦截器，获取原始响应
    const baseURL = env.baseUrl ? `${env.baseUrl}/admin-api` : '/admin-api';
    const token = getAccessToken() || getToken();
    
    if (!token) {
      // 如果没有token，直接尝试刷新
      console.log('[TokenCheck] 未找到accessToken，尝试刷新token...');
      await refreshTokenIfNeeded(refreshToken);
      return;
    }
    
    // 使用一个轻量级的接口来检测token是否有效
    // 优先使用get-unread-count，如果失败则尝试其他接口
    const testUrls = [
      `${baseURL}/system/notify-message/get-unread-count`,
      `${baseURL}/system/auth/get-permission-info`,
    ];
    
    let tokenExpired = false;
    let lastError: any = null;
    
    // 尝试每个检测接口
    for (const url of testUrls) {
      try {
        console.log(`[TokenCheck] 调用检测接口: ${url}`);
        
        const response = await axios.get(url, {
          headers: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json',
          },
          validateStatus: (status) => {
            // 接受所有状态码，包括401，以便我们能够检测到登录状态失效
            return status >= 200 && status < 500;
          },
          timeout: 5000, // 5秒超时
        });
        
        console.log(`[TokenCheck] 接口响应: status=${response.status}, code=${response.data?.code}`);
        
        // 检查响应数据，如果code是401或HTTP状态码是401，说明token失效
        const responseData = response.data;
        const isExpired = 
          response.status === 401 || 
          (responseData && (responseData.code === 401 || responseData.msg === '账号未登录'));
        
        if (isExpired) {
          tokenExpired = true;
          console.log('[TokenCheck] 检测到token失效');
          break;
        } else {
          // token有效，不需要继续检测
          console.log('[TokenCheck] Token有效，无需刷新');
          return;
        }
      } catch (error: any) {
        console.log(`[TokenCheck] 接口调用异常:`, error?.message || error);
        lastError = error;
        
        // 检查错误响应，如果是401，说明token失效
        const isExpired = 
          error?.response?.status === 401 ||
          (error?.response?.data && (
            error.response.data.code === 401 || 
            error.response.data.msg === '账号未登录'
          ));
        
        if (isExpired) {
          tokenExpired = true;
          console.log('[TokenCheck] 检测到token失效（通过错误响应）');
          break;
        }
        // 如果是网络错误等其他错误，继续尝试下一个接口
      }
    }
    
    // 如果检测到token失效，立即刷新
    if (tokenExpired) {
      console.log('[TokenCheck] 开始刷新token...');
      await refreshTokenIfNeeded(refreshToken);
    } else if (lastError) {
      // 所有接口都失败，但不是401错误，可能是网络问题
      console.log('[TokenCheck] Token检测接口调用失败:', lastError?.message || lastError, '但不退出登录');
    }
  } catch (error: any) {
    console.log(`[TokenCheck] 检测过程异常:`, error?.message || error);
  } finally {
    isChecking = false;
    console.log('[TokenCheck] 检测完成');
  }
};

// 刷新token的辅助函数
const refreshTokenIfNeeded = async (refreshToken: string) => {
  try {
    console.log('[TokenCheck] 开始调用refreshToken接口...');
    const { loginApi } = await import('../api/Login');
    
    // 使用原生axios调用，绕过拦截器，避免循环
    const axios = (await import('axios')).default;
    const { env } = await import('./env');
    const baseURL = env.baseUrl ? `${env.baseUrl}/admin-api` : '/admin-api';
    
    const response = await axios.post(
      `${baseURL}/system/auth/refresh-token?refreshToken=${encodeURIComponent(refreshToken)}`,
      {},
      {
        headers: {
          'Content-Type': 'application/json',
        },
        validateStatus: (status) => status < 500, // 接受所有非5xx状态码
      }
    );
    
    // 处理返回数据格式：{code: 0, data: {accessToken, refreshToken, ...}, msg: ""}
    const responseData = response.data;
    let tokenData;
    
    if (responseData?.code === 0 && responseData?.data) {
      // 标准格式：{code: 0, data: {...}}
      tokenData = responseData.data;
    } else if (responseData?.code === 200 && responseData?.data) {
      // 兼容格式：{code: 200, data: {...}}
      tokenData = responseData.data;
    } else if (responseData?.data) {
      // 兼容格式：{data: {...}}
      tokenData = responseData.data;
    } else if (responseData?.accessToken || responseData?.token) {
      // 直接是token数据对象
      tokenData = responseData;
    } else {
      // 可能是直接返回的数据
      tokenData = responseData;
    }
    
    const newAccessToken = tokenData?.accessToken || tokenData?.token;
    const newRefreshToken = tokenData?.refreshToken;

    if (newAccessToken) {
      // 更新token
      setToken({ accessToken: newAccessToken, token: newAccessToken });
      setAccessToken(newAccessToken);
      if (newRefreshToken) {
        setRefreshToken(newRefreshToken);
      }
      console.log('[TokenCheck] Token刷新成功，新token已保存');
    } else {
      console.warn('[TokenCheck] 刷新token失败：未返回新token，但不退出登录');
      // 即使刷新失败，也不退出登录，继续保留当前页面
    }
  } catch (refreshError: any) {
    console.warn('[TokenCheck] 刷新token失败:', refreshError?.message || refreshError, '但不退出登录，继续保留当前页面');
    // 即使刷新失败，也不退出登录，继续保留当前页面
  }
};

