import { useAuthStore } from '@/store/modules/auth';

interface RouteGuardOptions {
  requireAuth?: boolean;
  redirectUrl?: string;
}

/**
 * 路由守卫 - 检查登录状态
 */
export const checkAuth = async (options: RouteGuardOptions = {}): Promise<boolean> => {
  const { requireAuth = true, redirectUrl = '/pages/login/login' } = options;
  
  if (!requireAuth) {
    return true;
  }

  const authStore = useAuthStore();
  console.log(authStore,"authStore");
  
  // 如果没有token，直接跳转到登录页
  if (!authStore.token) {
    uni.reLaunch({
      url: redirectUrl
    });
    return false;
  }

  // 检查token有效性
  try {
    const isValid = await authStore.checkToken();
    if (!isValid) {
      uni.reLaunch({
        url: redirectUrl
      });
      return false;
    }
    return true;
  } catch (error) {
    console.error('Token check failed:', error);
    uni.reLaunch({
      url: redirectUrl
    });
    return false;
  }
};

/**
 * 页面跳转前的路由守卫
 */
export const routeGuard = async (url: string, options: RouteGuardOptions = {}): Promise<void> => {
  const isAuthenticated = await checkAuth(options);
  console.log(isAuthenticated,'isAuthenticated');
  
  if (isAuthenticated) {
    uni.navigateTo({
      url
    });
  }
};

/**
 * 带认证检查的页面跳转
 */
export const navigateWithAuth = (url: string, options: RouteGuardOptions = {}): void => {
  routeGuard(url, options);
};

/**
 * 自动登录检查
 */
export const autoLogin = async (): Promise<boolean> => {
  const authStore = useAuthStore();
  console.log(authStore,'自动登录检查');
  if (!authStore.token) {
    return false;
  }

  try {
    const isValid = await authStore.checkToken();
    return isValid;
  } catch (error) {
    console.error('Auto login failed:', error);
    return false;
  }
};

/**
 * 登出并跳转到登录页
 */
export const logoutAndRedirect = async (redirectUrl: string = '/pages/login/login'): Promise<void> => {
  const authStore = useAuthStore();
  await authStore.logout();
  console.log('登出并跳转到登录页');
  
  uni.reLaunch({
    url: redirectUrl
  });
};
