hongjli
2025-06-05 05e55761058e2089e81fb93dd4000dc3f42f40b3
src/components/layout/Navbar.tsx
@@ -2,9 +2,11 @@
import Link from 'next/link';
import Image from 'next/image';
import { useState, useEffect } from 'react';
import { useState, useEffect, useRef } from 'react';
import { useUserStore } from '@/store/userStore';
import { getUserInfo } from '@/services/userService';
import { useRouter } from 'next/navigation';
import ApiService from '@/utils/api';
const Navbar = () => {
  const [isMenuOpen, setIsMenuOpen] = useState(false);
@@ -12,7 +14,10 @@
  const [activeMenu, setActiveMenu] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [showUserDropdown, setShowUserDropdown] = useState(false);
  const { userInfo, token, setUserInfo } = useUserStore();
  const router = useRouter();
  const dropdownRef = useRef<HTMLDivElement>(null);
  // 监听滚动事件,为导航栏添加滚动效果
  useEffect(() => {
@@ -31,8 +36,13 @@
  // 获取用户信息
  useEffect(() => {
    const fetchUserInfo = async () => {
      if (!token) return;
      // 检查localStorage中是否有token
      const storedToken = localStorage.getItem('token');
      if (!storedToken) {
        useUserStore.getState().clearUserInfo();
        return;
      }
      setIsLoading(true);
      setError(null);
      
@@ -43,21 +53,85 @@
        } else {
          console.error('获取用户信息失败:', response.message);
          setError(response.message || '获取用户信息失败');
          // 如果是认证相关错误,清除用户信息
          // 如果是认证相关错误,清除用户信息和token
          if (response.code === 401) {
            useUserStore.getState().clearUserInfo();
            localStorage.removeItem('token');
          }
        }
      } catch (err) {
        console.error('获取用户信息出错:', err);
        setError('获取用户信息失败');
        // 发生错误时也清除token和用户信息
        localStorage.removeItem('token');
        useUserStore.getState().clearUserInfo();
      } finally {
        setIsLoading(false);
      }
    };
    fetchUserInfo();
  }, [token, setUserInfo]);
  }, []); // 组件挂载时执行一次
  // 点击外部关闭下拉菜单
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setShowUserDropdown(false);
      }
    };
    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, []);
  const handleNavigation = async (path: string, e: React.MouseEvent) => {
    e.preventDefault();
    // 检查localStorage中是否有token
    const storedToken = localStorage.getItem('token');
    if (!storedToken) {
      window.location.href = '/login';
      return;
    }
    try {
      const response = await getUserInfo();
      if (response.code === 200 && response.data) {
        setUserInfo(response.data);
        window.location.href = path;
      } else {
        if (response.code === 401) {
          localStorage.removeItem('token');
          useUserStore.getState().clearUserInfo();
        }
        window.location.href = '/login';
      }
    } catch (err) {
      console.error('验证用户信息失败:', err);
      localStorage.removeItem('token');
      useUserStore.getState().clearUserInfo();
      window.location.href = '/login';
    }
  };
  const handleLogout = async () => {
    try {
      const response = await ApiService.post('/users/logout', {});
      if (response.code === 200) {
        // 清除本地存储的token和用户信息
        localStorage.removeItem('token');
        useUserStore.getState().clearUserInfo();
        window.location.href = '/'; // 改为跳转到首页
      } else {
        console.error('退出登录失败:', response.message);
      }
    } catch (err) {
      console.error('退出登录出错:', err);
    }
  };
  return (
    <nav 
@@ -196,6 +270,7 @@
            <a 
              href="/ai-scene" 
              className="relative px-2 lg:px-3 py-2 text-sm font-medium"
              onClick={(e) => handleNavigation('/ai-scene', e)}
              onMouseEnter={() => setActiveMenu('ai-scene')}
              onMouseLeave={() => setActiveMenu('')}
            >
@@ -207,6 +282,7 @@
            <a 
              href="/chatroom" 
              className="relative px-2 lg:px-3 py-2 text-sm font-medium"
              onClick={(e) => handleNavigation('/chatroom', e)}
              onMouseEnter={() => setActiveMenu('chatroom')}
              onMouseLeave={() => setActiveMenu('')}
            >
@@ -214,10 +290,11 @@
              <span className={`absolute bottom-0 left-0 h-[2px] bg-gradient-to-r from-[#6ADBFF] to-transparent
                transition-all duration-300 ${activeMenu === 'chatroom' ? 'w-full' : 'w-0'}`}></span>
            </a>
            <a 
              href="/training" 
              className="relative px-2 lg:px-3 py-2 text-sm font-medium"
              onClick={(e) => handleNavigation('/training', e)}
              onMouseEnter={() => setActiveMenu('training')}
              onMouseLeave={() => setActiveMenu('')}
            >
@@ -228,12 +305,91 @@
            
            {userInfo ? (
              // 用户信息显示
              <div className="relative">
                <div className="relative overflow-hidden flex items-center justify-center px-4 lg:px-7 py-2">
              <div className="relative" ref={dropdownRef}>
                <div
                  className="relative overflow-hidden flex items-center justify-center px-4 lg:px-7 py-2 cursor-pointer group"
                  onClick={() => setShowUserDropdown(!showUserDropdown)}
                >
                  {/* 添加悬停背景效果 */}
                  <div className="absolute inset-0 bg-[#1E2B63]/0 group-hover:bg-[#1E2B63]/30 rounded-full transition-all duration-300"></div>
                  {/* 用户图标 */}
                  <svg
                    className="w-5 h-5 text-[#6ADBFF] group-hover:text-[#FF6A88] transition-colors duration-300 mr-2"
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                  >
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
                  </svg>
                  <span className="relative z-10 bg-gradient-to-r from-[#6ADBFF] via-[#FF6A88] to-[#F5A800] bg-clip-text text-transparent font-medium">
                    {isLoading ? '加载中...' : userInfo.nickname}
                  </span>
                  {/* 箭头图标 */}
                  <svg
                    className={`ml-2 h-4 w-4 text-[#6ADBFF] transition-all duration-300 transform ${
                      showUserDropdown ? 'rotate-180 text-[#FF6A88]' : ''
                    } group-hover:text-[#FF6A88]`}
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                  >
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                  </svg>
                  {/* 添加光晕效果 */}
                  <div className="absolute inset-0 -z-10">
                    <div className="absolute inset-0 bg-gradient-to-r from-[#6ADBFF]/0 via-[#6ADBFF]/5 to-[#6ADBFF]/0 opacity-0 group-hover:opacity-100 transition-opacity duration-300 rounded-full"></div>
                  </div>
                </div>
                {/* 下拉菜单 */}
                {showUserDropdown && (
                  <div className="absolute right-0 mt-2 w-48 rounded-xl shadow-lg overflow-hidden animate-fadeIn">
                    {/* 菜单背景 */}
                    <div className="backdrop-blur-xl bg-gradient-to-b from-[#1E2B63]/95 to-[#0A1033]/95 border border-[#6ADBFF]/20">
                      {/* 顶部装饰 */}
                      <div className="h-[1px] w-full bg-gradient-to-r from-transparent via-[#6ADBFF]/50 to-transparent"></div>
                      <div className="py-2">
                        <button
                          onClick={handleLogout}
                          className="w-full text-left px-5 py-3 text-sm text-white hover:bg-[#6ADBFF]/10 transition-all duration-300 flex items-center group relative overflow-hidden cursor-pointer"
                        >
                          {/* 悬停背景动画 */}
                          <div className="absolute inset-0 bg-gradient-to-r from-[#6ADBFF]/0 via-[#6ADBFF]/5 to-[#6ADBFF]/0 translate-x-[-100%] group-hover:translate-x-[100%] transition-transform duration-1000"></div>
                          {/* 图标容器 */}
                          <div className="relative">
                            <div className="absolute -inset-1 bg-gradient-to-r from-[#6ADBFF]/0 via-[#6ADBFF]/10 to-[#6ADBFF]/0 rounded-full blur-sm opacity-0 group-hover:opacity-100 transition-opacity duration-300"></div>
                            <svg
                              className="relative z-10 mr-3 h-5 w-5 text-[#6ADBFF] group-hover:text-[#FF6A88] transition-colors duration-300"
                              fill="none"
                              stroke="currentColor"
                              viewBox="0 0 24 24"
                            >
                              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1" />
                            </svg>
                          </div>
                          {/* 文字 */}
                          <span className="relative z-10 font-medium group-hover:text-[#FF6A88] transition-colors duration-300">
                            退出登录
                          </span>
                          {/* 右侧指示器 */}
                          <div className="absolute right-0 top-[10%] bottom-[10%] w-[2px] bg-gradient-to-b from-[#6ADBFF] to-[#FF6A88] transform scale-y-0 group-hover:scale-y-100 transition-transform duration-300"></div>
                        </button>
                      </div>
                      {/* 底部装饰 */}
                      <div className="h-[1px] w-full bg-gradient-to-r from-transparent via-[#6ADBFF]/50 to-transparent"></div>
                    </div>
                  </div>
                )}
                {error && (
                  <div className="absolute top-full mt-2 left-0 right-0 px-4 py-2 bg-red-500/90 text-white text-sm rounded-md">
                    {error}
@@ -309,24 +465,24 @@
          border-t border-[#6ADBFF]/10">
          <a 
            href="/ai-scene" 
            className="block px-4 py-3 text-white border-l-2 border-transparent hover:border-[#6ADBFF]
              hover:bg-[#3B4888]/20 rounded-r-md transition-all duration-200 cursor-pointer"
            onClick={(e) => handleNavigation('/ai-scene', e)}
            className="block px-4 py-3 text-white border-l-2 border-transparent hover:border-[#6ADBFF] hover:bg-[#3B4888]/20 rounded-r-md transition-all duration-200 cursor-pointer"
          >
            AI场景模拟
          </a>
          
          <a 
            href="/chatroom" 
            className="block px-4 py-3 text-white border-l-2 border-transparent hover:border-[#6ADBFF]
              hover:bg-[#3B4888]/20 rounded-r-md transition-all duration-200 cursor-pointer"
            onClick={(e) => handleNavigation('/chatroom', e)}
            className="block px-4 py-3 text-white border-l-2 border-transparent hover:border-[#6ADBFF] hover:bg-[#3B4888]/20 rounded-r-md transition-all duration-200 cursor-pointer"
          >
            聊天室
          </a>
          
          <a 
            href="/training" 
            className="block px-4 py-3 text-white border-l-2 border-transparent hover:border-[#6ADBFF]
              hover:bg-[#3B4888]/20 rounded-r-md transition-all duration-200 cursor-pointer"
            onClick={(e) => handleNavigation('/training', e)}
            className="block px-4 py-3 text-white border-l-2 border-transparent hover:border-[#6ADBFF] hover:bg-[#3B4888]/20 rounded-r-md transition-all duration-200 cursor-pointer"
          >
            训练场
          </a>
@@ -358,9 +514,4 @@
  );
};
export default Navbar;
// 添加到CSS文件中的全局样式
// .hover:shadow-glow:hover {
//   box-shadow: 0 0 15px rgba(255, 65, 108, 0.5);
// }
export default Navbar;