// 客户端认证工具函数

// 获取存储的 Token
export function getToken() {
  if (typeof window === 'undefined') return null;
  return localStorage.getItem('token');
}

// 设置 Token
export function setToken(token) {
  localStorage.setItem('token', token);
}

// 清除 Token
export function clearToken() {
  localStorage.removeItem('token');
  localStorage.removeItem('user');
}

// 获取存储的用户信息
export function getUser() {
  if (typeof window === 'undefined') return null;
  const user = localStorage.getItem('user');
  return user ? JSON.parse(user) : null;
}

// 设置用户信息
export function setUser(user) {
  localStorage.setItem('user', JSON.stringify(user));
}

// 带认证的 fetch 请求
export async function authFetch(url, options = {}) {
  const token = getToken();
  const headers = {
    ...options.headers,
  };
  
  if (token) {
    headers['Authorization'] = `Bearer ${token}`;
  }
  
  // 如果不是 FormData，设置 Content-Type
  if (!(options.body instanceof FormData)) {
    headers['Content-Type'] = 'application/json';
  }

  const response = await fetch(url, {
    ...options,
    headers,
  });

  // 401 未授权，跳转登录
  if (response.status === 401) {
    clearToken();
    if (typeof window !== 'undefined') {
      window.location.href = '/login';
    }
    throw new Error('未登录或登录已过期');
  }

  return response;
}

// 角色中文名称映射
export const ROLE_NAMES = {
  admin: '系统管理员',
  employee: '员工',
  supervisor: '部门主管',
  finance: '财务部',
  secretary: '秘书长',
};

// 状态中文名称映射
export const STATUS_NAMES = {
  draft: '草稿',
  pending_supervisor: '待初审',
  pending_finance: '待财务审核',
  pending_secretary: '待终审',
  approved: '已通过',
  rejected: '已驳回',
};

// 状态颜色映射
export const STATUS_COLORS = {
  draft: '#6b7280',
  pending_supervisor: '#3b82f6',
  pending_finance: '#f59e0b',
  pending_secretary: '#8b5cf6',
  approved: '#10b981',
  rejected: '#ef4444',
};
