<template>
  <div :class="{ 'has-logo': showLogo }" :style="{ backgroundColor: '#292C38' }">
    <!-- <logo v-if="showLogo" :collapse="isCollapse" /> -->
    <el-scrollbar wrap-class="scrollbar-wrapper">
      <el-menu
        class="sidebar"
        :default-active="activeMenu"
        :default-openeds="openedMenus"
        @select="handleMenuClick"
        @open="handleSubMenuOpen"
        @close="handleSubMenuClose"
        background-color="#292C38"
        text-color="#96A0B5"
        active-text-color="#fff"
        :unique-opened="true"
      >
        <!-- 一级菜单项 -->
        <template v-for="(route, index) in sidebarRouters" :key="route && route.path ? route.path + index : index">
          <!-- 跳过隐藏的菜单 -->
          <template v-if="route && !route.hidden">
            <!-- 普通菜单项（没有子菜单或子菜单为空） -->
            <el-menu-item v-if="!route.children || route.children.length === 0" :index="route.path || ''">
              <el-icon><svg-icon :icon-class="route.meta?.icon || ''" /></el-icon>
              <span>{{ route.meta?.title || '未命名菜单' }}</span>
            </el-menu-item>
            
            <!-- 带子菜单的菜单项 -->
            <el-sub-menu v-else :index="route.path || ''" :class="{'is-active': isParentActive(route)}">
              <template #title>
                <el-icon><svg-icon :icon-class="route.meta?.icon || ''" /></el-icon>
                <span class="menu-title">{{ route.meta?.title || '未命名菜单' }}</span>
              </template>
              
              <!-- 自定义子菜单 -->
              <div class="submenu-container">
                <div class="timeline">
                  <!-- 子菜单项 -->
                  <template v-for="(subItem, subIndex) in route.children" :key="subItem && subItem.path ? subItem.path : subIndex">
                    <!-- 跳过隐藏的子菜单 -->
                    <template v-if="subItem && !subItem.hidden">
                      <!-- 第一行：竖线 -->
                      <div class="timeline-line" v-if="subIndex === 0"></div>
                      
                      <!-- 圆点和文字 -->
                      <div class="timeline-item">
                        <div class="timeline-dot" :class="{ 'active': activeSubmenu === getFullPath(route.path, subItem.path) }"></div>
                        <div class="timeline-content" 
                            :class="{ 'active': activeSubmenu === getFullPath(route.path, subItem.path) }"
                            @click="handleSubmenuClick(subItem.path || '', route.path || '')">
                          {{ subItem.meta?.title || '未命名菜单' }}
                        </div>
                      </div>
                      
                      <!-- 最后一项之外的每一项后面都有竖线 -->
                      <div class="timeline-line" v-if="subIndex < route.children.length - 1"></div>
                    </template>
                  </template>
                </div>
              </div>
            </el-sub-menu>
          </template>
        </template>
      </el-menu>
    </el-scrollbar>
  </div>
</template>

<script setup>
import Logo from './Logo'
import SidebarItem from './SidebarItem'
import variables from '@/assets/styles/variables.module.scss'
import useAppStore from '@/store/modules/app'
import useSettingsStore from '@/store/modules/settings'
import usePermissionStore from '@/store/modules/permission'

const route = useRoute();
const router = useRouter();
const appStore = useAppStore()
const settingsStore = useSettingsStore()
const permissionStore = usePermissionStore()

const sidebarRouters = computed(() => {
  console.log('侧边栏路由数据:', permissionStore.sidebarRouters);
  return permissionStore.sidebarRouters;
});
const showLogo = computed(() => settingsStore.sidebarLogo);
const sideTheme = computed(() => settingsStore.sideTheme);
const theme = computed(() => settingsStore.theme);
const isCollapse = computed(() => !appStore.sidebar.opened);

// 当前激活的子菜单
const activeSubmenu = ref('');
// 当前打开的菜单列表
const openedMenus = ref([]);

// 从localStorage获取已保存的打开菜单
const getOpenedMenusFromStorage = () => {
  const openedMenusStr = localStorage.getItem('openedMenus');
  return openedMenusStr ? JSON.parse(openedMenusStr) : [];
};

// 初始化打开的菜单列表
openedMenus.value = getOpenedMenusFromStorage();

// 保存打开的菜单到localStorage
const saveOpenedMenusToStorage = (menus) => {
  localStorage.setItem('openedMenus', JSON.stringify(menus));
};

// 处理子菜单打开事件
const handleSubMenuOpen = (index) => {
  if (!openedMenus.value.includes(index)) {
    openedMenus.value.push(index);
    saveOpenedMenusToStorage(openedMenus.value);
  }
};

// 处理子菜单关闭事件
const handleSubMenuClose = (index) => {
  const idx = openedMenus.value.indexOf(index);
  if (idx !== -1) {
    openedMenus.value.splice(idx, 1);
    saveOpenedMenusToStorage(openedMenus.value);
  }
};

const activeMenu = computed(() => {
  const { meta, path } = route;
  // if set path, the sidebar will highlight the path you set
  if (meta.activeMenu) {
    return meta.activeMenu;
  }
  return path;
})

// 处理菜单点击事件
function handleMenuClick(key) {
  // 如果是一级菜单且没有子菜单，直接导航
  const item = findMenuItemByKey(key);
  if (item && (!item.children || item.children.length === 0)) {
    if (isExternal(key)) {
      window.open(key, "_blank");
    } else {
      router.push(key);
    }
  }
}

// 处理子菜单点击事件
function handleSubmenuClick(subKey, parentKey) {
  const fullPath = getFullPath(parentKey, subKey);
  activeSubmenu.value = fullPath;
  
  // 确保父菜单被添加到打开列表中
  if (parentKey && !openedMenus.value.includes(parentKey)) {
    openedMenus.value.push(parentKey);
    saveOpenedMenusToStorage(openedMenus.value);
  }
  
  if (isExternal(subKey)) {
    window.open(subKey, "_blank");
  } else {
    router.push(fullPath);
  }
}

// 获取完整路径
function getFullPath(parentPath, childPath) {
  if (isExternal(childPath)) {
    return childPath;
  }
  if (isExternal(parentPath)) {
    return parentPath;
  }
  return getNormalPath(parentPath + '/' + childPath);
}

// 判断是否为外部链接
function isExternal(path) {
  return /^(https?:|mailto:|tel:)/.test(path);
}

// 获取正常路径
function getNormalPath(p) {
  if (p.length === 0 || !p || p == 'undefined') {
    return p;
  }
  let res = p.replace('//', '/');
  if (res[res.length - 1] === '/') {
    return res.slice(0, res.length - 1);
  }
  return res;
}

// 根据key查找菜单项
function findMenuItemByKey(key) {
  if (!key || !sidebarRouters.value) return null;
  
  for (const item of sidebarRouters.value) {
    if (item && item.path === key) {
      return item;
    }
    if (item && item.children && item.children.length > 0) {
      for (const subItem of item.children) {
        if (subItem && subItem.path === key) {
          return subItem;
        }
      }
    }
  }
  return null;
}

// 查找当前路径所属的父菜单
function findParentMenuByPath(path) {
  if (!path || !sidebarRouters.value) return null;
  
  for (const item of sidebarRouters.value) {
    if (item && item.children && item.children.length > 0) {
      for (const subItem of item.children) {
        if (subItem && getFullPath(item.path, subItem.path) === path) {
          return item.path;
        }
      }
    }
  }
  return null;
}

// 判断父菜单是否应该高亮
const isParentActive = (route) => {
  if (!route || !route.children) return false;
  const currentPath = activeSubmenu.value;
  return route.children.some(child => {
    const fullPath = getFullPath(route.path, child.path);
    return currentPath === fullPath;
  });
};

// 初始化时设置当前激活的子菜单和展开的菜单
onMounted(() => {
  // 确保从localStorage加载已保存的菜单状态
  openedMenus.value = getOpenedMenusFromStorage();
  
  const currentPath = route.path;
  if (currentPath) {
    activeSubmenu.value = currentPath;
    
    // 获取当前路径的父菜单
    const parentMenu = findParentMenuByPath(currentPath);
    if (parentMenu) {
      // 确保当前路径的父菜单被添加到打开列表中
      if (!openedMenus.value.includes(parentMenu)) {
        openedMenus.value.push(parentMenu);
        saveOpenedMenusToStorage(openedMenus.value);
      }
    }
  }
});

// 监听路由变化，更新激活的子菜单和展开的菜单
watch(() => route.path, (newPath) => {
  if (newPath) {
    activeSubmenu.value = newPath;
    
    // 获取当前路径的父菜单
    const parentMenu = findParentMenuByPath(newPath);
    if (parentMenu && !openedMenus.value.includes(parentMenu)) {
      openedMenus.value.push(parentMenu);
      saveOpenedMenusToStorage(openedMenus.value);
    }
  }
});

// 监听侧边栏路由变化，确保路由更新时组件能正确刷新
watch(() => permissionStore.sidebarRouters, (newRoutes) => {
  if (newRoutes && newRoutes.length > 0) {
    // 延迟执行，确保DOM更新完成
    nextTick(() => {
      // 当前路由路径
      const currentPath = route.path;
      if (currentPath) {
        activeSubmenu.value = currentPath;
        
        // 获取当前路径的父菜单
        const parentMenu = findParentMenuByPath(currentPath);
        if (parentMenu && !openedMenus.value.includes(parentMenu)) {
          openedMenus.value.push(parentMenu);
          saveOpenedMenusToStorage(openedMenus.value);
        }
      }
    });
  }
}, { deep: true });
</script>

<style scoped>
/* 左侧导航栏样式 */
.sidebar {
  width: 220px;
  height: 100%;
  border-right: none;
}

/* 菜单标题样式，避免与箭头重合 */
.menu-title {
  width: 100%;
  display: inline-block;
}

:deep(.el-sub-menu .el-sub-menu__icon-arrow) {
  font-size: 12px;
  /* 移除导致重叠的样式 */
  width: inherit;
}

/* 自定义子菜单样式 */
.submenu-container {
  padding: 5px 0;
  background-color: #292C38; /* 与父菜单背景色保持一致 */
}

/* 修复 Element Plus 子菜单样式 */
:deep(.el-menu--inline) {
  background-color: #292C38 !important;
  padding: 0 !important;
}

.timeline {
  display: flex;
  flex-direction: column;
  position: relative;
  padding-left: 50px;
}

.timeline::before {
  display: none; /* 移除贯穿整个timeline的竖线 */
}

.timeline-line {
  display: block; /* 恢复显示分段线条 */
  width: 1px;
  height: 20px;
  background-color: rgba(255, 255, 255, 0.15);
  margin-left: 3px;
}

.timeline-item {
  position: relative;
  display: flex;
  align-items: center;
  height: 40px;
  cursor: pointer;
  padding-left: 15px;
  width: 100%;
}

.timeline-dot {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.3);
  margin-right: 12px;
  flex-shrink: 0;
  position: relative;
  left: -15px; /* 调整圆点位置，使其与竖线对齐 */
}

.timeline-content {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.65);
  margin-left: -15px; /* 补偿圆点的位置调整 */
}

/* 子菜单选中状态 */
.timeline-content.active {
  color: #ffffff;
}

.timeline-dot.active {
  background-color: #1890ff;
}

/* 父菜单激活状态样式 */
:deep(.el-sub-menu__title.is-active) {
  background-color: #343744 !important;
  border-radius: 10px!important;

}

:deep(.el-sub-menu.is-active .el-sub-menu__title) {
  background-color: #343744 !important;
  border-radius: 10px!important;
  
}

/* 确保子菜单容器背景色与父菜单一致 */
:deep(.el-menu--inline) {
  background-color: #292C38 !important;
  border-radius: 10px!important;
}

/* 父菜单hover效果 */
:deep(.el-sub-menu .el-sub-menu__title:hover) {
  background-color: #343744 !important;
  border-radius: 10px!important;
}
</style>
