<template>
  <div class="top-navbar">
    <div class="navbar-left">
      <el-icon :size="22" color="#ffffff"><Folder /></el-icon>
      <span class="system-title">云文件管理系统</span>
    </div>
    <div class="navbar-right">
      <!-- 消息图标 -->
      <el-badge :value="totalUnread" :hidden="totalUnread === 0" class="msg-badge" :class="{ 'has-unread': totalUnread > 0 }">
        <el-button link class="navbar-icon-btn" @click="openChat">
          <el-icon :size="20" color="#ffffff"><ChatDotRound /></el-icon>
        </el-button>
      </el-badge>

      <!-- 用户头像下拉 -->
      <el-dropdown trigger="click" @command="handleUserCommand">
        <div class="user-info">
          <el-avatar :size="30" :src="userStore.avatar || undefined" style="background:#409eff;font-size:13px">
            {{ (userStore.nickname || userStore.username)?.[0]?.toUpperCase() || 'U' }}
          </el-avatar>
          <span class="username">{{ userStore.nickname || userStore.username }}</span>
          <el-icon :size="12" color="#ffffff"><ArrowDown /></el-icon>
        </div>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item command="profile">
              <el-icon><User /></el-icon> 个人信息
            </el-dropdown-item>
            <el-dropdown-item divided command="logout">
              <el-icon><SwitchButton /></el-icon> 退出系统
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>

    <!-- 聊天弹窗 -->
    <ChatDialog v-model="chatVisible" @unread-change="updateUnread" />

    <!-- 个人信息弹窗 -->
    <ProfileDialog v-model="profileVisible" />
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessageBox, ElMessage } from 'element-plus'
import { Folder, ChatDotRound, ArrowDown, User, SwitchButton } from '@element-plus/icons-vue'
import { useUserStore } from '@/store/user'
import ChatDialog from './ChatDialog.vue'
import ProfileDialog from './ProfileDialog.vue'
import { chatService } from '@/services/chat'
import { getUnreadCount } from '@/api/message'

const router = useRouter()
const userStore = useUserStore()

const chatVisible = ref(false)
const profileVisible = ref(false)
const totalUnread = ref(0)

const updateUnread = () => {
  checkUnread()
}

const openChat = () => {
  chatVisible.value = true
  // 打开聊天时清零未读数
  totalUnread.value = 0
}

// 定期检查未读消息
let pollTimer = null
let wsUnsubscribe = null

const checkUnread = () => {
  getUnreadCount().then(res => {
    totalUnread.value = res.data.count || 0
  }).catch(() => {})
}

onMounted(() => {
  checkUnread()
  pollTimer = setInterval(checkUnread, 30000)
  
  // 监听 WebSocket 消息，增加未读计数
  wsUnsubscribe = chatService.onMessage((data) => {
    if (data.type === 'chat') {
      const isSelf = Number(data.message.fromUserId) === Number(userStore.userId)
      // 只在对方发来消息且聊天窗口未打开时增加未读
      if (!isSelf && !chatVisible.value) {
        totalUnread.value++
      }
    }
  })
})

onUnmounted(() => {
  if (pollTimer) clearInterval(pollTimer)
  if (wsUnsubscribe) wsUnsubscribe()
})

const handleUserCommand = (command) => {
  if (command === 'profile') {
    profileVisible.value = true
  } else if (command === 'logout') {
    ElMessageBox.confirm('确定退出登录吗？', '提示', { type: 'warning' }).then(() => {
      userStore.logout()
      router.push('/login')
    }).catch(() => {})
  }
}
</script>

<style scoped>
.top-navbar {
  height: 50px;
  background: #009688;
  border-bottom: 1px solid #00796b;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  flex-shrink: 0;
}

.navbar-left {
  display: flex;
  align-items: center;
  gap: 10px;
}

.system-title {
  font-size: 16px;
  font-weight: 600;
  color: #ffffff;
}

.navbar-right {
  display: flex;
  align-items: center;
  gap: 16px;
}

.msg-badge :deep(.el-badge__content) {
  transform: scale(0.8);
}

.msg-badge.has-unread :deep(.el-badge__content) {
  animation: flash 1s infinite;
}

@keyframes flash {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.5; }
}

.navbar-icon-btn {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #ffffff;
}

.navbar-icon-btn:hover {
  background: rgba(255, 255, 255, 0.15);
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 20px;
  transition: background 0.2s;
}

.user-info:hover {
  background: rgba(255, 255, 255, 0.15);
}

.username {
  font-size: 14px;
  color: #ffffff;
  max-width: 80px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
