<template>
<div class="horizontal-navbar">
    <logo v-if="showLogo" :collapse="isCollapse" class="navbar-logo" />
    <el-scrollbar class="scrollbar-wrapper">
      <el-menu
        :default-active="activeMenu"
        mode="horizontal"
        :background-color="getMenuBackground"
        :text-color="getMenuTextColor"
        :active-text-color="'#fff'"
        :unique-opened="false"
        :ellipsis="false"
      >
        <sidebar-item
          v-for="(route, index) in menuShowData"
          :key="route.id || route.path + index"
          :item="route"
          :base-path="route.path"
          @parent-click="handleParentClick"
          @no-children-click="handleNoChildrenClick"
        />
      </el-menu>
    </el-scrollbar>

  

    <div class="right-menu">
      <!-- 这里可以放用户信息、设置按钮等 -->
       <header-search id="header-search" class="right-menu-item" />


        <el-dropdown style="margin-left: 20px;" @command="handleCommand" class="avatar-container right-menu-item hover-effect" trigger="hover">
          <div class="avatar-wrapper">
            <div class="user-avatar"  style="background-color: #69a6cb;"></div>
            <div class="user-nickname" style="position: absolute;text-align:center;width: 30px;"> {{ user.realname || '' }} </div>
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <!-- <router-link to="/user/profile">
                <el-dropdown-item>个人中心</el-dropdown-item>
              </router-link> -->
              <el-dropdown-item command="logout">
                <span>退出登录</span>
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
    </div>
  </div>
      <!-- 子菜单容器 -->

    <div v-if="submenuItems.length > 0" class="submenu-container">
      <div class="submenu-wrapper">
        <template v-for="(child, index) in submenuItems" :key="child.path + index">
          <div v-if="!child.hidden" class="submenu-item" :class="[child.fullPath === route.fullPath ? 'active-submenu-item' : '']" @click="remberChild(child)">
            <app-link :to="child.fullPath"> 
              <div class="submenu-link" >
                <svg-icon :icon-class="child.meta.icon" />
                <span>{{ child.meta.title }}</span>
              </div>
            </app-link>
          </div>
        </template>
      </div>
    </div>

</template>

<script setup>
import { isExternal } from '@/utils/validate'
import { ElMessageBox } from 'element-plus'
import HeaderSearch from '@/components/HeaderSearch'
import Logo from './Logo'
import SidebarItem from './SidebarItem'
import AppLink from './Link'
import variables from '@/assets/styles/variables.module.scss'
import useAppStore from '@/store/modules/app'
import useSettingsStore from '@/store/modules/settings'
import useUserStore from '@/store/modules/user'
import usePermissionStore from '@/store/modules/permission'
import { ref, computed,onMounted } from 'vue'
import { getNormalPath } from '@/utils/ruoyi'
import { useRoute,useRouter } from 'vue-router'
import { emitter } from '@/utils/eventBus'
const route = useRoute()
const router = useRouter()
const submenuItems = ref([])
const appStore = useAppStore()
const userStore = useUserStore()
const settingsStore = useSettingsStore()
const permissionStore = usePermissionStore()
watch(() => submenuItems.value.length, (newVal) => {
  document.documentElement.style.setProperty(
    '--submenu-height', 
    newVal > 0 ? '50px' : '0px'
  );
}, { immediate: true });

// 转换接口数据为组件需要的格式
const processedRouters = computed(() => {
  return permissionStore.sidebarRouters
})
const user = JSON.parse(sessionStorage.getItem('userInfo')).user??{}
// 菜单类型获取
const navType = computed(() => {
  const navStatus = appStore.navStatus
  const type = navStatus.type === 'project' ? '2' : '1'
  return type
})
onMounted(() => { 

  if(sessionStorage.getItem('subMenuPath')){
      submenuItems.value = sessionStorage.getItem('submenuItems') ? JSON.parse(sessionStorage.getItem('submenuItems')) : []
  }else{
      submenuItems.value = []

  }
  emitter.on('event-name', () => {
    submenuItems.value = []
  })
})

const isProject = computed(() => {
  return route.fullPath === '/project/Project'
})

function handleParentClick(children) {
  
  submenuItems.value = children
}
function remberChild(child) {
   console.log('child',child)
   sessionStorage.setItem('subMenuPath', JSON.stringify(child.fullPath))
   sessionStorage.setItem('submenuItems', JSON.stringify(submenuItems.value))
}
function handleNoChildrenClick() {
  sessionStorage.removeItem('subMenuPath')
  submenuItems.value = []
  sessionStorage.removeItem('submenuItems')
}
const activeMenuItem = ref(null)
function handleChild(child) { 
 
}

function resolvePath(routePath, routeQuery) {
  // 您的路径解析逻辑
  if (isExternal(routePath)) {
    return routePath
  }
  if (routeQuery) {
    let query = JSON.parse(routeQuery)
    return { path: getNormalPath(routePath), query: query }
  }
  return getNormalPath(routePath)
}

// 菜单显示数据
const menuShowData = computed(() => {
  const list = processedRouters.value.filter(item => {
    if (navType.value === '1') {
      if (navType.value === item.type || !item.type) {
        return true
      } else {
        return false
      }
    } else {
      if (navType.value === item.type) {
        return true
      } else {
        return false
      }
    }
  })
  return list
})

const showLogo = computed(() => settingsStore.sidebarLogo)
const sideTheme = computed(() => settingsStore.sideTheme)
const theme = computed(() => settingsStore.theme)
const isCollapse = computed(() => !appStore.sidebar.opened)

// 获取菜单背景色
const getMenuBackground = computed(() => {
  return 'rgba(33, 103, 217, 1)'
  // if (settingsStore.isDark) {
  //   return 'var(--sidebar-bg)'
  // }
  // return sideTheme.value === 'theme-dark' ? variables.menuBg : variables.menuLightBg
})

// 获取菜单文字颜色
const getMenuTextColor = computed(() => {
  if (settingsStore.isDark) {
    return 'var(--sidebar-text)'
  }
  return sideTheme.value === 'theme-dark' ? variables.menuText : variables.menuLightText
})

const activeMenu = computed(() => {
  const { meta, path } = route
  if (meta.activeMenu) {
    return meta.activeMenu
  }
  return path
})

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


const emits = defineEmits(['setLayout'])
function setLayout() {
  emits('setLayout')
}

function logout() {
  ElMessageBox.confirm('确定注销并退出系统吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    userStore.logOut().then(() => {
      // location.href = '/index'
      appStore.signOut('logout')
      appStore.setNavStatus({type: 'manage'})
      appStore.setQueryData({
        projectId: ''
      })
       window.location.replace(`${import.meta.env.BASE_URL}`)

    })
  }).catch(() => { })
}

</script>

<style lang="scss" scoped>
.horizontal-navbar {
  background: rgba(33, 103, 217, 1);
  display: flex;
  align-items: center;
  height: var(--navbar-height);
  box-shadow: 0px 2px 4px  rgba(0, 0, 0, 0.25);
  .navbar-logo {
    flex-shrink: 0;
    height: 80px;
    width: 300px;
    display: flex;
    align-items: center;
    justify-content: center;
    position: absolute;
    top: 0;
    left: 0;
  }
  
  .scrollbar-wrapper {
    margin: 0 300px;
    flex: 1;
    overflow: hidden;
    // padding-right: 83px;
    display: flex;
    justify-content: center;
    :deep(.el-scrollbar__view) {
      height: 100%;
      
    }
    
    .el-menu {
      border-bottom: none;
      height: 100%;
      
      &--horizontal {
        white-space: nowrap;
      }
    }
  }
  
  .right-menu {
    position: absolute;
    top: 0;
    right: 0;
    height: 80px;
    display: flex;
    align-items: center;
}
  }



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

      .avatar-wrapper {
        // margin-top: 10px;
        right: 5px;
        position: relative;

        .user-avatar {
          cursor: pointer;
          width: 30px;
          height: 30px;
          border-radius: 50%;
        }

        .user-nickname{
          position: relative;
          // left: 5px;
          bottom: 10px;
          font-size: 10px;
          font-weight: bold;
        }

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

  .submenu-container {
    // position: absolute;
    // left: 0;
    // top: 80px;
    width: 100%;
    height: 50px;
    .submenu-wrapper {
      height: 100%;
      background: rgba(255, 255, 255, 1);
      display: flex;
      justify-content: center;
      align-items: center;
      .submenu-item {
        margin-left: 66px;
        &:first-child {
          margin-left: 0;
        }
        &:hover {
          color: rgba(33, 103, 217, 1);
          cursor: pointer;
        }
      }
      .active-submenu-item {
         color: rgba(33, 103, 217, 1);
          cursor: pointer;
      }
    }
  }
    /* 过渡效果 */
.slide-fade-enter-active {
  transition: all 0.3s ease-out;
}

.slide-fade-leave-active {
  transition: all 0.2s cubic-bezier(1, 0.5, 0.8, 1);
}

.slide-fade-enter-from,
.slide-fade-leave-to {
  transform: translateY(-20px);
  opacity: 0;
}

</style>