<template>
  <el-header class="navbar">
    <div class="navbar-left">
      <span style="font-size: 16px; color: #606266;">{{ $route.meta?.title || '通用型流程审批系统' }}</span>
    </div>
    <div class="navbar-right">
      <el-badge :value="todoCountValue" :hidden="todoCountValue === 0" class="todo-badge" @click="goTodo">
        <el-icon :size="20" style="cursor: pointer; color: #606266;"><Bell /></el-icon>
      </el-badge>
      <el-dropdown @command="handleCommand">
        <span class="user-info">
          <el-avatar :size="32" :src="userStore.userInfo?.avatar" />
          <span class="username">{{ userStore.userInfo?.realName || userStore.userInfo?.username }}</span>
          <el-icon><ArrowDown /></el-icon>
        </span>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item command="profile">个人中心</el-dropdown-item>
            <el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
  </el-header>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user-store'
import { ArrowDown, Bell } from '@element-plus/icons-vue'
import { ElMessageBox } from 'element-plus'
import { todoCount } from '@/api/flow/task'

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

const todoCountValue = ref(0)
let timer: ReturnType<typeof setInterval> | null = null
let todoInitialized = false

async function loadTodoCount() {
  try {
    const count = await todoCount()
    todoCountValue.value = Number(count) || 0
  } catch {
    // ignore
  }
}

function goTodo() {
  router.push('/approval/todo')
}

function handleCommand(command: string) {
  if (command === 'logout') {
    ElMessageBox.confirm('确认退出登录吗？', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      await userStore.logoutAction()
      router.push('/login')
    })
  } else if (command === 'profile') {
    router.push('/profile')
  }
}

onMounted(() => {
  if (!todoInitialized) {
    loadTodoCount()
    todoInitialized = true
  }
  if (!timer) {
    timer = setInterval(loadTodoCount, 30000)
  }
})

onUnmounted(() => {
  if (timer) {
    clearInterval(timer)
    timer = null
  }
  todoInitialized = false
})
</script>

<style scoped>
.navbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #fff;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}
.navbar-right {
  display: flex;
  align-items: center;
  gap: 20px;
}
.todo-badge {
  cursor: pointer;
  line-height: 1;
}
.user-info {
  display: flex;
  align-items: center;
  cursor: pointer;
  gap: 8px;
}
.username {
  font-size: 14px;
  color: #606266;
}
</style>
