import { useAuthStore } from '@/store/modules/auth';
import { useUserStore } from '@/store/modules/user';
import type { LoginForm } from '@/store/modules/auth';

/**
 * 登录相关工具函数
 */

/**
 * 快速登录
 */
export const quickLogin = async (username: string, password: string): Promise<boolean> => {
  const authStore = useAuthStore();
  
  const loginForm: LoginForm = {
    username,
    password,
    rememberMe: false
  };
  
  return await authStore.login(loginForm);
};

/**
 * 静默登录（使用已保存的凭据）
 */
export const silentLogin = async (): Promise<boolean> => {
  const authStore = useAuthStore();
  
  if (!authStore.token) {
    return false;
  }
  
  try {
    return await authStore.checkToken();
  } catch (error) {
    console.error('Silent login failed:', error);
    return false;
  }
};

/**
 * 安全登出
 */
export const secureLogout = async (): Promise<void> => {
  console.log('安全登出');
  
  const authStore = useAuthStore();
  const userStore = useUserStore();
  
  try {
    // 调用登出API
    await authStore.logout();
    
    // 清除所有缓存数据
    userStore.clearUserInfo();
    
    // 清除其他可能的缓存
    uni.clearStorageSync();
    
    uni.showToast({
      title: '已安全退出',
      icon: 'success'
    });
  } catch (error) {
    console.error('Secure logout failed:', error);
    // 即使API调用失败，也要清除本地数据
    userStore.clearUserInfo();
    uni.clearStorageSync();
  }
};

/**
 * 检查是否需要重新登录
 */
export const checkReloginNeeded = async (): Promise<boolean> => {
  const authStore = useAuthStore();
  
  if (!authStore.token) {
    return true;
  }
  
  try {
    const isValid = await authStore.checkToken();
    return !isValid;
  } catch (error) {
    console.error('Check relogin needed failed:', error);
    return true;
  }
};

/**
 * 带权限检查的页面跳转
 */
export const navigateWithPermission = (url: string, permission?: string): void => {
  const userStore = useUserStore();
  
  if (permission && !userStore.hasPermission(permission)) {
    uni.showToast({
      title: '没有权限访问该页面',
      icon: 'none'
    });
    return;
  }
  
  uni.navigateTo({
    url
  });
};

/**
 * 带角色检查的页面跳转
 */
export const navigateWithRole = (url: string, role?: string): void => {
  const userStore = useUserStore();
  
  if (role && !userStore.hasRole(role)) {
    uni.showToast({
      title: '没有权限访问该页面',
      icon: 'none'
    });
    return;
  }
  
  uni.navigateTo({
    url
  });
};

/**
 * 获取用户头像URL（带默认值）
 */
export const getUserAvatarUrl = (): string => {
  const userStore = useUserStore();
  return userStore.userInfo?.avatar || '/static/logo.png';
};

/**
 * 获取用户显示名称
 */
export const getUserDisplayName = (): string => {
  const userStore = useUserStore();
  if (!userStore.userInfo) {
    return '未登录';
  }
  return userStore.userInfo.nickname || userStore.userInfo.username || '用户';
};

/**
 * 格式化用户角色为显示文本
 */
export const formatUserRoles = (): string => {
  const userStore = useUserStore();
  if (!userStore.userInfo?.roles || userStore.userInfo.roles.length === 0) {
    return '普通用户';
  }
  return userStore.userInfo.roles.join(', ');
};

/**
 * 登录状态检查装饰器（用于方法）
 */
export const requireAuth = (fn: Function) => {
  return async (...args: any[]) => {
    const authStore = useAuthStore();
    
    if (!authStore.isLoggedIn) {
      uni.showModal({
        title: '提示',
        content: '请先登录',
        success: (res) => {
          if (res.confirm) {
            uni.navigateTo({
              url: '/pages/login/login'
            });
          }
        }
      });
      return;
    }
    
    return await fn(...args);
  };
};

/**
 * 权限检查装饰器
 */
export const requirePermission = (permission: string) => {
  return (fn: Function) => {
    return async (...args: any[]) => {
      const userStore = useUserStore();
      
      if (!userStore.hasPermission(permission)) {
        uni.showToast({
          title: '没有权限执行此操作',
          icon: 'none'
        });
        return;
      }
      
      return await fn(...args);
    };
  };
};
