<template>
  <header class="layout-header">
    <!-- 左侧：Logo、系统名称和菜单收缩按钮 -->
    <div class="header-left">
      <div class="logo-section">
        <img src="@/assets/images/logo.png" alt="logo" class="logo-img" />
        <!-- <span class="system-name"  v-if="!isSmallScreen">Admin System</span> -->
      </div>
    </div>
    <!-- 菜单收缩按钮 - 在标题右边（仅在大屏幕显示） -->
    <el-button
      v-if="!isSmallScreen"
      class="collapse-btn"
      :icon="sidebarCollapsed ? Expand : Fold"
      @click="toggleSidebar"
      text
    />
    <!-- 中间：面包屑导航和搜索框（仅在大屏幕显示） -->
    <div v-if="!isSmallScreen" class="header-center">
      <Breadcrumb />
    </div>

    <!-- 右侧：功能按钮和用户信息 -->
    <div class="header-right">
      <!-- 菜单搜索 -->
      <div class="menu-search-wrapper" :class="{ 'is-small': isSmallScreen }">
        <el-input
          v-model="searchQuery"
          placeholder="搜索菜单..."
          class="menu-search-input"
          clearable
          @focus="handleSearchFocus"
          @blur="handleSearchBlur"
          @input="handleSearchInput"
          @keydown.enter="handleSearchEnter"
          @keydown.up.prevent="navigateResults(-1)"
          @keydown.down.prevent="navigateResults(1)"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <!-- 搜索结果下拉 -->
        <div v-show="searchVisible && searchResults.length > 0" class="search-results-dropdown">
          <div
            v-for="(item, index) in searchResults"
            :key="item.path"
            class="search-result-item"
            :class="{ 'is-active': activeIndex === index }"
            @click="handleResultClick(item)"
            @mouseenter="activeIndex = index"
          >
            <el-icon v-if="item.icon" class="result-icon"><component :is="item.icon" /></el-icon>
            <span class="result-label">{{ item.label }}</span>
          </div>
        </div>
        <!-- 无结果提示 -->
        <div v-show="searchVisible && searchQuery && !searchResults.length" class="search-empty">
          <el-icon><Search /></el-icon>
          <span>未找到匹配的菜单</span>
        </div>
      </div>

      <!-- 全屏 -->
      <el-tooltip :content="isFullscreen ? '退出全屏' : '全屏'">
        <el-button :icon="isFullscreen ? Crop : FullScreen" text @click="toggleFullscreen" />
      </el-tooltip>

      <!-- 语言选择 -->
      <LanguageSelect v-model="languageStore.lang" 
      v-if="!isSmallScreen" @change="languageStore.changeLang" />

      <!-- 用户信息下拉菜单 -->
      <el-dropdown @command="handleCommand" class="user-dropdown">
        <div class="user-info">
          <el-avatar :size="28" class="user-avatar">
            <el-icon  :size="16"><User /></el-icon>
          </el-avatar>
          <span class="username">{{ activeUserName }}</span>
          <el-icon class="dropdown-icon"><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 command="password">
              <el-icon><Lock /></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>
  </header>
</template>

<script setup lang="ts">
import { computed, ref, onMounted, onUnmounted } from 'vue'
import {
  FullScreen,
  Crop,
  User,
  Lock,
  SwitchButton,
  ArrowDown,
  Fold,
  Expand,
  Search
} from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/modules/user'
import { useLanguageStore } from '@/stores/modules/language'
import LanguageSelect from '@/components/LanguageSelect/index.vue'
import Breadcrumb from './Breadcrumb.vue'
import { getStorage } from '@/utils/storage'

defineProps<{
  isSmallScreen?: boolean
}>()

const emit = defineEmits(['toggle-sidebar'])

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

// 侧边栏收缩状态
const sidebarCollapsed = ref(false)

// 切换侧边栏
const toggleSidebar = () => {
  sidebarCollapsed.value = !sidebarCollapsed.value
  emit('toggle-sidebar', sidebarCollapsed.value)
}

// 用户信息 - 使用 userStore 的响应式数据
const activeUserName = computed(() => userStore.userInfo?.username || '-')

// ==================== 菜单搜索功能 ====================
interface SearchMenuItem {
  label: string
  path: string
  icon?: string
}

const searchQuery = ref('')
const searchVisible = ref(false)
const searchResults = ref<SearchMenuItem[]>([])
const activeIndex = ref(-1)

// 从 storage 获取菜单列表
const getMenuList = (): any[] => {
  return getStorage('menusInfo') || []
}

// 扁平化菜单（只获取没有子菜单的菜单项，即叶子菜单）
const flattenMenu = (menus: any[], result: SearchMenuItem[] = []): SearchMenuItem[] => {
  menus.forEach(menu => {
    // 只有没有子菜单的菜单项才添加到搜索结果
    if (menu.name && menu.path && (!menu.son || menu.son.length === 0)) {
      result.push({
        label: menu.name,
        path: menu.path,
        icon: menu.icon
      })
    }
    // 递归处理子菜单
    if (menu.son && menu.son.length > 0) {
      flattenMenu(menu.son, result)
    }
  })
  return result
}

// 搜索菜单
const performSearch = (query: string) => {
  if (!query.trim()) {
    searchResults.value = []
    return
  }
  
  const allMenus = flattenMenu(getMenuList())
  const lowerQuery = query.toLowerCase()
  
  searchResults.value = allMenus.filter(menu =>
    menu.label.toLowerCase().includes(lowerQuery)
  ).slice(0, 10) // 最多显示10条
  
  activeIndex.value = searchResults.value.length > 0 ? 0 : -1
}

// 搜索输入处理
const handleSearchInput = () => {
  performSearch(searchQuery.value)
  searchVisible.value = true
}

// 搜索框获得焦点
const handleSearchFocus = () => {
  if (searchQuery.value) {
    searchVisible.value = true
  }
}

// 搜索框失去焦点
const handleSearchBlur = () => {
  // 延迟关闭，以便点击结果
  setTimeout(() => {
    searchVisible.value = false
  }, 200)
}

// 回车键处理
const handleSearchEnter = () => {
  if (activeIndex.value >= 0 && searchResults.value[activeIndex.value]) {
    handleResultClick(searchResults.value[activeIndex.value])
  }
}

// 点击搜索结果
const handleResultClick = (item: SearchMenuItem) => {
  searchQuery.value = ''
  searchVisible.value = false
  router.push(item.path)
}

// 上下键导航搜索结果
const navigateResults = (direction: number) => {
  if (searchResults.value.length === 0) return
  
  activeIndex.value += direction
  if (activeIndex.value < 0) {
    activeIndex.value = searchResults.value.length - 1
  } else if (activeIndex.value >= searchResults.value.length) {
    activeIndex.value = 0
  }
}

// 全屏相关
const isFullscreen = ref(false)
const toggleFullscreen = () => {
  if (!document.fullscreenElement) {
    document.documentElement.requestFullscreen()
    isFullscreen.value = true
  } else {
    if (document.exitFullscreen) {
      document.exitFullscreen()
      isFullscreen.value = false
    }
  }
}

// 监听全屏变化
onMounted(() => {
  document.addEventListener('fullscreenchange', () => {
    isFullscreen.value = !!document.fullscreenElement
  })
})

// 用户操作
const handleCommand = (command: string) => {
  switch (command) {
    case 'profile':
      router.push('/profile/personal-center')
      break
    case 'password':
      router.push('/user/change-password')
      break
    case 'logout':
      handleLogout()
      break
  }
}

// 退出登录
const handleLogout = () => {
  ElMessageBox.confirm('确定要退出登录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const deviceNo = getStorage('device_no') as string
    userStore.logout({ device_no: String(deviceNo) })
  }).catch(() => {
    // 取消退出
  })
}
</script>

<style scoped lang="scss">
.layout-header {
  height: 50px;
  background: #fff;
  border-bottom: 1px solid var(--el-border-color-light);
  display: flex;
  justify-content: space-between;
  align-items: center; 
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;

  .header-left {
    display: flex;
    align-items: center;
    padding: 0 16px;
    height: 100%;
    box-sizing: border-box;
    width: 200px;
    flex-shrink: 0;
    
    .logo-section {
      display: flex;
      align-items: center;
      height: 100%;
      gap: 8px;
      width: 100%;
        padding: 4px 0 ;
      overflow: hidden;
      
      .logo-img {
        height: 90%;
        object-fit: cover;
        width: 100%;
        flex-shrink: 0;
      }

      .system-name {
        font-size: 12px;
        font-weight: 600;
        color: var(--el-text-color-primary);
        white-space: nowrap;
        // overflow: hidden;
        // text-overflow: ellipsis;
        flex: 1;
      }

      .collapse-btn {
        padding: 4px 8px;
        color: var(--el-text-color-regular);
        flex-shrink: 0;
        margin-left: auto;
        
        &:hover {
          color: var(--el-color-primary);
        }
      }
    }
  }
  
  .header-center {
    flex: 1;
    display: flex;
    // justify-content: center;
    padding: 0 20px;
  }

  .header-right {
    display: flex;
    align-items: center;
    gap: 8px;
    min-width: 200px;
    justify-content: flex-end;

    // 菜单搜索样式
    .menu-search-wrapper {
      position: relative;
      flex-shrink: 0;

      .menu-search-input {
        width: 180px;
        transition: none;

        &:hover,
        &:focus-within {
          width: 240px;
        }

        :deep(.el-input__wrapper) {
          padding-left: 8px;
          padding-right: 8px;
        }
      }

      // 小屏幕时搜索框样式
      &.is-small {
        .menu-search-input {
          width: 120px;

          &:hover,
          &:focus-within {
            width: 140px;
          }
        }
      }

      .search-results-dropdown {
        position: absolute;
        top: calc(100% + 4px);
        left: 0;
        min-width: 240px;
        background: var(--el-bg-color);
        border: 1px solid var(--el-border-color-light);
        border-radius: 8px;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        max-height: 320px;
        overflow-y: auto;
        z-index: 2000;

        .search-result-item {
          display: flex;
          align-items: center;
          gap: 8px;
          padding: 10px 12px;
          cursor: pointer;
          transition: background 0.2s;
          border-bottom: 1px solid var(--el-border-color-lighter);

          &:last-child {
            border-bottom: none;
          }

          &:hover,
          &.is-active {
            background: var(--el-fill-color-light);
          }

          .result-icon {
            color: var(--el-text-color-regular);
            font-size: 14px;
          }

          .result-label {
            flex: 1;
            font-size: 13px;
            color: var(--el-text-color-primary);
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
        }
      }

      .search-empty {
        position: absolute;
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 8px;
        padding: 16px;
        color: var(--el-text-color-regular);
        font-size: 13px;
        background: var(--el-bg-color);
        border: 1px solid var(--el-border-color-light);
        border-radius: 8px;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      }
    }

    .el-button {
      padding: 4px 8px;
      color: var(--el-text-color-regular);

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

    .user-dropdown {
      cursor: pointer;

      .user-info {
        display: flex;
        align-items: center;
        gap: 6px;
        padding: 2px 8px;
        border-radius: 4px;
        transition: background 0.3s;

        &:hover {
          background: var(--el-fill-color-light);
        }

        .user-avatar {
          background: var(--el-color-primary);
        }

        .username {
          font-size: 13px;
          color: var(--el-text-color-primary);
          max-width: 80px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .dropdown-icon {
          font-size: 12px;
          color: var(--el-text-color-regular);
        }
      }
    }
  }
}

// 暗色模式适配
:deep(.dark) {
  .layout-header {
    background: var(--el-bg-color);
    border-bottom-color: var(--el-border-color-darker);
  }
}
</style>
