<template>
  <view class="header">
    <view class="header-left">
      <!-- 移动端菜单切换按钮(CSS 控制显隐) -->
      <view class="menu-toggle mobile-only" @click="onToggleSubSider">
        <text class="menu-icon">☰</text>
      </view>

      <!-- Desktop/Tablet Hamburger -->
      <view class="menu-toggle desktop-only" @click="onToggleSubSider">
        <text class="menu-icon">☰</text>
      </view>

      <view class="breadcrumb-container desktop-only">
        <text class="crumb" v-for="(item, index) in breadcrumb" :key="item.id"> 
          {{ item.title }}
          <text v-if="index < breadcrumb.length - 1" class="separator"> / </text>
        </text>
      </view>

      <text class="mobile-title mobile-only">{{ currentTitle }}</text>
    </view>

    <view class="header-right">
      <view class="hbtn" @click="$emit('search')"><text>🔍</text></view>        
      <view v-if="!isMobile" class="hbtn" @click="$emit('refresh')"><text>🔄</text></view>                                                                                  
      <view class="hbtn" @click="$emit('notify')">
        <text>🔔</text>
        <view class="dot" v-if="hasNotification"></view>
      </view>

      <!-- 用户个人中心 / 下拉菜单 -->
      <view class="admin-user-menu"
        @mouseenter="handleUserMenuOver"
        @mouseleave="handleUserMenuLeave"
      >
        <view class="admin-user-trigger" @click="toggleUserMenu">
          <text class="user-name">{{ userName }}</text>
          <text class="user-arrow">▼</text>
        </view>

        <view v-if="showUserMenu" class="admin-user-dropdown">
          <view class="admin-user-dropdown-item" @click.stop="goToUserCenter">
            <text class="admin-user-dropdown-text">个人中心</text>
          </view>
          <view class="admin-user-dropdown-item" @click.stop="handleLogout">
            <text class="admin-user-dropdown-text">退出登录</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="uts">
import { ref, computed } from 'vue'
import {
  toggleSubSider,
  layoutMode,
  isOverlayVisible,
  isMobileMenuOpen,
  openRoute
} from '@/layouts/admin/store/adminNavStore.uts'
import { state, logout } from '@/utils/store.uts'
import { clearAdminRoleCache, getCurrentAdminRole } from '@/layouts/admin/utils/role.uts'

const showUserMenu = ref(false)
const userName = computed((): string => {
  if (state.userProfile?.username != null && state.userProfile!.username != '') return state.userProfile!.username as string
  if (state.authUser != null) {
      if (state.authUser!.getString('email') != null && state.authUser!.getString('email') != '') return state.authUser!.getString('email') as string
      if (state.authUser!.getString('phone') != null && state.authUser!.getString('phone') != '') return state.authUser!.getString('phone') as string
      if (state.authUser!.getString('id') != null && state.authUser!.getString('id') != '') return (state.authUser!.getString('id') as string).substring(0, 8)
  }
  return '未知用户'
})

let hideMenuTimer: number | null = null

function handleUserMenuOver(e: any) {
  // #ifdef H5
  if (hideMenuTimer !== null) {
    clearTimeout(hideMenuTimer as number)
    hideMenuTimer = null
  }
  showUserMenu.value = true
  // #endif
}

function handleUserMenuLeave(e: any) {
  // #ifdef H5
  if (hideMenuTimer !== null) {
    clearTimeout(hideMenuTimer as number)
  }
  hideMenuTimer = setTimeout(() => {
    showUserMenu.value = false
    hideMenuTimer = null
  }, 150) as number
  // #endif
}

function toggleUserMenu(e: any) {
  if (e && typeof e.stopPropagation === 'function') {
    e.stopPropagation()
  }
  showUserMenu.value = !showUserMenu.value
}

function goToUserCenter(e: any) {
  if (e && typeof e.stopPropagation === 'function') {
    e.stopPropagation()
  }
  showUserMenu.value = false
  openRoute('home_user_center')
}

function handleLogout(e: any) {
  if (e && typeof e.stopPropagation === 'function') {
    e.stopPropagation()
  }
  showUserMenu.value = false
  uni.showModal({
    title: '提示',
    content: '确定要退出登录吗？',
    success: (res) => {
      if (res.confirm) {
        logout()
        clearAdminRoleCache()
        uni.removeStorageSync('token')
        // Force the layout cleanup to wait for the dialog to disappear 
        setTimeout(() => {
          uni.reLaunch({
            url: '/pages/user/login'
          })
        }, 300)
      }
    }
  })
}

const props = defineProps<{
  breadcrumb: Array<{id: string, title: string}>
  hasNotification: boolean
  isMobile: boolean
}>()

defineEmits<{
  (e:'search'): void
  (e:'refresh'): void
  (e:'notify'): void
  (e:'toggle-mobile-menu'): void
}>()

function onToggleSubSider(): void {
  if (layoutMode.value === 'desktop') {
    toggleSubSider()
  } else if (layoutMode.value === 'tablet') {
    isOverlayVisible.value = !isOverlayVisible.value
  } else {
    isMobileMenuOpen.value = !isMobileMenuOpen.value
  }
}

const currentTitle = computed((): string => {
  if (props.breadcrumb.length > 0) {
    return props.breadcrumb[props.breadcrumb.length - 1].title
  }
  return '管理后台'
})
</script>

<style>
.header {
  overflow: visible;
  position: relative;
  z-index: 1001;
  height: 56px;
  background: #fff;
  border-bottom: 1px solid #eef2f7;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
}

.header-left {
  display: flex;
  flex-direction: row;
  align-items: center;
}

.menu-toggle {
  margin-right: 12px;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.menu-icon {
  font-size: 20px;
  color: #333;
}

.mobile-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.breadcrumb-container {
  display: flex;
  flex-direction: row;
  align-items: center;
}

.crumb {
  color: #374151;
  font-size: 14px;
}

/* 响应式控制 */
.mobile-only {
  display: none;
}

@media screen and (max-width: 768px) {
  .desktop-only {
    display: none !important;
  }
  .mobile-only {
    display: flex !important;
  }
  .header-right {
    gap: 5px;
  }
}

.separator {
  color: #d1d5db;
  margin: 0 8px;
}

.header-right {
  overflow: visible;
  position: relative;
  z-index: 100;
  pointer-events: auto;
  display: flex;
  flex-direction: row;
  align-items: center;
  gap: 10px;
  height: 100%;
}

.hbtn {
  width: 34px;
  height: 34px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f6f7fb;
  position: relative;
  cursor: pointer;
}

.dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #ff4d4f;
  position: absolute;
  top: 6px;
  right: 6px;
}

/* 后台用户菜单部分 */
.admin-user-menu {
  position: relative;
  display: flex;
  flex-direction: row;
  align-items: center;
  height: 100%; /* 和 header 高度一致，确保悬停不中断 */
  overflow: visible;
}

.admin-user-trigger {
  display: flex;
  flex-direction: row;
  align-items: center;
  cursor: pointer;
  padding: 0 10px;
  height: 100%;
}

.user-name {
  font-size: 14px;
  color: #333;
}

.user-arrow {
  font-size: 12px;
  color: #666;
  margin-left: 4px;
}

.admin-user-dropdown {
  position: absolute;
  top: 56px;
  right: 0;
  min-width: 120px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 6px 18px rgba(0,0,0,0.08);
  z-index: 10000;
  overflow: visible;
  display: flex;
  flex-direction: column;
  padding: 5px 0;
}

.admin-user-dropdown-item {
  height: 40px;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  padding: 0 20px;
}

.admin-user-dropdown-text {
  font-size: 14px;
  color: #333;
  line-height: 40px;
}

/* #ifdef H5 */
.admin-user-dropdown-item:hover {
  background-color: #f5f7fa;
}
.admin-user-dropdown-item:hover .admin-user-dropdown-text {
  color: #1890ff;
}
/* #endif */

</style>
