<template>
  <div class="navbar">
    <hamburger id="hamburger-container" :is-active="appStore.sidebar.opened" class="hamburger-container" @toggleClick="toggleSideBar" />
    <breadcrumb v-if="!settingsStore.topNav" id="breadcrumb-container" class="breadcrumb-container" />
    <top-nav v-if="settingsStore.topNav" id="topmenu-container" class="topmenu-container" />

    <div class="right-menu">
      <template v-if="appStore.device !== 'mobile'">
        <header-search id="header-search" class="right-menu-item" />

        <screenfull id="screenfull" class="right-menu-item hover-effect" />

        <!-- 消息中心 -->
        <el-tooltip content="消息中心" effect="dark" placement="bottom">
          <div class="right-menu-item hover-effect message-center" @click="goMessage">
            <el-badge :value="unreadCount" :hidden="unreadCount === 0" :max="99">
              <el-icon :size="18"><ChatDotRound /></el-icon>
            </el-badge>
          </div>
        </el-tooltip>
      </template>

      <el-dropdown @command="handleCommand" class="avatar-container right-menu-item hover-effect" trigger="hover">
        <div class="avatar-wrapper">
          <img :src="userStore.avatar" class="user-avatar" />
          <span class="user-nickname"> {{ userStore.nickName }} </span>
        </div>
        <template #dropdown>
          <el-dropdown-menu>
            <router-link to="/user/profile">
              <el-dropdown-item>个人中心</el-dropdown-item>
            </router-link>
            <el-dropdown-item command="setLayout" v-if="settingsStore.showSettings">
                <span>布局设置</span>
              </el-dropdown-item>
            <el-dropdown-item divided command="logout">
              <span>退出登录</span>
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessageBox } from 'element-plus'
import { ChatDotRound } from '@element-plus/icons-vue'
import Breadcrumb from '@/components/Breadcrumb'
import TopNav from '@/components/TopNav'
import Hamburger from '@/components/Hamburger'
import Screenfull from '@/components/Screenfull'
import HeaderSearch from '@/components/HeaderSearch'
import useAppStore from '@/store/modules/app'
import useUserStore from '@/store/modules/user'
import useSettingsStore from '@/store/modules/settings'
import wsService from '@/utils/websocket'

const router = useRouter()
const appStore = useAppStore()
const userStore = useUserStore()
const settingsStore = useSettingsStore()

// 未读消息数
const unreadCount = ref(0)

// 跳转消息中心
function goMessage() {
  router.push('/message')
}

// WebSocket 事件处理
onMounted(() => {
  console.log('[Navbar] 初始化 WebSocket 连接...')
  // 建立 WebSocket 连接
  wsService.connect()
  
  // 监听连接状态
  wsService.on('connected', () => {
    console.log('[Navbar] WebSocket 已连接')
  })
  
  wsService.on('disconnected', () => {
    console.log('[Navbar] WebSocket 已断开')
  })
  
  // 监听未读数更新
  wsService.on('unread_count', (count) => {
    console.log('[Navbar] 未读数更新:', count)
    unreadCount.value = count
  })
  
  // 监听新消息
  wsService.on('new_message', (payload) => {
    console.log('[Navbar] 收到新消息:', payload)
    unreadCount.value++
  })
  
  // 监听新通知
  wsService.on('new_notification', (payload) => {
    console.log('[Navbar] 收到新通知:', payload)
    unreadCount.value++
  })
  
  // 监听系统通知
  wsService.on('system_notification', (payload) => {
    console.log('[Navbar] 收到系统通知:', payload)
    unreadCount.value++
  })
})

onUnmounted(() => {
  // 断开 WebSocket 连接
  wsService.disconnect()
})

function toggleSideBar() {
  appStore.toggleSideBar()
}

function handleCommand(command) {
  switch (command) {
    case "setLayout":
      setLayout()
      break
    case "logout":
      logout()
      break
    default:
      break
  }
}

function logout() {
  ElMessageBox.confirm('确定注销并退出系统吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    userStore.logOut().then(() => {
      location.href = '/index'
    })
  }).catch(() => { })
}

const emits = defineEmits(['setLayout'])
function setLayout() {
  emits('setLayout')
}
</script>

<style lang='scss' scoped>
.navbar {
  height: 50px;
  overflow: hidden;
  position: relative;
  background: rgba(255, 255, 255, 0.8); // 半透明背景
  backdrop-filter: blur(8px); // 磨砂玻璃效果
  box-shadow: none; // 移除投影
  border-bottom: 1px solid rgba(0,0,0,0.05); // 极淡边框

  .hamburger-container {
    line-height: 46px;
    height: 100%;
    float: left;
    cursor: pointer;
    transition: background 0.3s;
    -webkit-tap-highlight-color: transparent;
    padding: 0 12px; // 增加点击区域
    border-radius: 8px; // 悬停圆角
    margin: 2px 0 0 4px; // 微调位置

    &:hover {
      background: rgba(0, 0, 0, 0.04);
    }
  }

  .breadcrumb-container {
    float: left;
    margin-left: 8px;
  }

  .topmenu-container {
    position: absolute;
    left: 50px;
  }

  .errLog-container {
    display: inline-block;
    vertical-align: top;
  }

  .right-menu {
    float: right;
    height: 100%;
    line-height: 50px;
    display: flex;
    align-items: center; // 垂直居中
    padding-right: 12px;

    &:focus {
      outline: none;
    }

    .right-menu-item {
      display: inline-block;
      padding: 0 8px;
      height: 100%;
      font-size: 16px; // 稍微调小图标
      color: #64748b; // Slate 500
      vertical-align: text-bottom;
      display: flex;
      align-items: center; // 图标垂直居中
      transition: all 0.3s;

      &.hover-effect {
        cursor: pointer;
        transition: background 0.3s;
        border-radius: 6px; // 圆角
        height: 36px; // 限制悬停背景高度
        margin: 0 4px; // 图标间距

        &:hover {
          background: rgba(0, 0, 0, 0.04);
          color: #334155; // Slate 700
        }
      }

      &.theme-switch-wrapper {
        display: flex;
      }

      &.message-center {
        display: flex;
        align-items: center;

        .el-badge {
          display: flex;
          align-items: center;

          :deep(.el-badge__content) {
            top: 0;
            right: 0;
            transform: translateY(-50%) translateX(50%);
          }
        }

        .el-icon {
          color: #64748b;
          transition: color 0.3s;
        }

        &:hover .el-icon {
          color: var(--el-color-primary);
        }
      }
    }

    .avatar-container {
      margin-right: 0px;
      padding-right: 0px;
      margin-left: 8px;

      .avatar-wrapper {
        margin-top: 0; // 移除旧的margin
        position: relative;
        display: flex;
        align-items: center;
        cursor: pointer;
        padding: 4px 8px;
        border-radius: 6px;
        transition: background 0.3s;

        &:hover {
          background: rgba(0,0,0,0.04);
        }

        .user-avatar {
          cursor: pointer;
          width: 32px;
          height: 32px;
          border-radius: 50%;
          border: 1px solid #e2e8f0; // 头像描边
        }

        .user-nickname{
          margin-left: 8px;
          font-size: 14px;
          font-weight: 500;
          color: #334155;
        }

        i {
          cursor: pointer;
          position: absolute;
          right: -20px;
          top: 25px;
          font-size: 12px;
        }
      }
    }
  }
}

// 暗色模式适配
html.dark .navbar {
  background: rgba(15, 23, 42, 0.8); // Slate 900
  border-bottom: 1px solid #1e293b;

  .right-menu .right-menu-item {
    color: #94a3b8; // Slate 400

    &:hover {
      background: rgba(255, 255, 255, 0.05);
      color: #f1f5f9; // Slate 100
    }
  }

  .avatar-container .avatar-wrapper {
    &:hover {
      background: rgba(255, 255, 255, 0.05);
    }

    .user-nickname {
      color: #f1f5f9;
    }

    .user-avatar {
      border-color: #334155;
    }
  }
}
</style>
