<template>
    <div>
      <div class="lefts">
        <el-row class="tac">
          <el-col :span="12">
            <el-menu


            
              class="el-menu-vertical-demo"
           
              :default-active="activeItemIndex"
              :default-openeds="openedMenus"
              :unique-opened="true"

              :active-text-color="activeColor">
              <!-- 动态渲染菜单 -->
              <el-submenu 
                v-for="menu in menuData" 
                :key="menu.index" 
                :index="menu.index"
                :class="{ 'active-menu': activeMenu === menu.index }">
                <template slot="title">
                  <div>
                    <i :class="menu.icon"></i>
                    <span>{{ menu.title }}</span>
                  </div>
                </template>
                
                <div class="submenu-content">
                  <el-menu-item-group 
                    v-for="group in menu.groups" 
                    :key="group.title || group.items[0].index">
                    <template v-if="group.title" slot="title">{{ group.title }}</template>
                 
                    <el-menu-item 
                     v-for="(item, $index) in group.items"
                      :key="item.index" 
                      :index="item.index"
                         @click="setActiveItem(item,item.index)"
                      >
                      <div class="shu" :style="{ height: $index  === group.items.length - 1 ? '16px' : '40px' }"></div>
                      <div 
                        class="yuan" 
                        :style="{ backgroundColor: activeItemIndex === item.index ? '#5165f7' : '#ebebeb' }" 
                    ></div>
                     {{ item.name }}
                    </el-menu-item>
                  </el-menu-item-group>
                </div>
              </el-submenu>
            </el-menu>
          </el-col>
        </el-row>
      </div>
    </div>
  </template>
  
  <script>
  export default {
   
    data() {
      return {
        activeItemIndex: null,
      activeMenu: '0',
      activeColor: '#409EFF',
      openedMenus:[],
     
        menuData: [
        {
            index: '0',
            title: '企业总览',
            icon: 'el-icon-location',
            groups: [
              {
                items: [
                  { index: '0-1', name: '企业概况',
                   route: '/home',
                   children:[
                     {
                        name: "数据概览",
                        route: '/home'
                      }, {
                        name: "资料检索",
                        route: '/home/dataretrieval'
                      },
                      { 
                        name: "企业信息",
                        route: '/home/corporateInformation'
                      },
                     
                    ] 
                   },
                 
                ]
              },
             

            ]
          },
          {
            index: '1',
            title: '资源资料',
            icon: 'el-icon-location',
            groups: [
              {
                items: [
                  { 
                    index: '1-1', name: '财务概览',
                    route: '/operate',
                    children:[
                     {
                        name: "经营情况",
                        route: '/operate'
                      }, {
                        name: "年度审计情况",
                        route: '/annual'
                      },
                      { 
                        name: "专项审计情况",
                        route: '/special'
                      },
                      { 
                        name: "企业所得税纳税情况",
                        route: '/paytaxes'
                      }
                    ] 
                },
                  { index: '1-2', name: '人力资源',
                  route:'/organization',
                  children:[
                     {
                        name: "组织架构",
                        route: '/organization'
                      }, {
                        name: "职工管理",
                        route: '/employee'
                      },
                      {
                        name: "科技专家",
                        route: '/technology'
                      },
                    ] 
                },
                  { index: '1-3', name: '成果管理',
                  route:'/knowledge',
                  children:[
                     {
                        name: "知识产权",
                        route: '/knowledge'
                      }, {
                        name: "论文管理",
                        route: '/paper'
                      },
                      {
                        name: "标准制定",
                        route: '/standard'
                      },
                    ] 
                 },
                  { index: '1-4', name: '资质荣誉',
                  route:'/enterprise',
                  children:[
                     {
                        name: "企业资质",
                        route: '/enterprise'
                      }, {
                        name: "企业荣誉",
                        route: '/corporatehonors'
                      },
                     
                    ] 
                   },
                  { index: '1-5', name: '制度文件',
                  route:'/systemnotice',
                   children:[
                     {
                        name: "制度通知",
                        route: '/systemnotice'
                      }
                     
                    ] 
                   },
                   { index: '1-6', name: '合同登记',
                  route:'/contract',
                   children:[
                     {
                        name: "合同登记",
                        route: '/contract'
                      }
                     
                    ] 
                   },
                  { index: '1-7', name: '校企合作',
                  route:'/Schoolenterprise',
                   children:[
                     {
                        name: "校企合作",
                        route: '/Schoolenterprise'
                      }
                     
                    ] 
                   },
               
                ]
              },
             

            ]
          },
          {
            index: '2',
            title: '研发项目',
            icon: 'el-icon-menu',
            groups: [
              {
                items: [
                  { index: '2-1', name: '项目管理',
                  route:'/projecthours',
                   children:[
                     {
                        name: "项目情况",
                        route: '/projecthours'
                      }
                     
                    ] 
                   },
                  { index: '2-2', name: '工时管理' ,
                  route:'/examstatus',
                   children:[
                     {
                        name: "考情管理",
                        route: '/examstatus'
                      },
                      {
                        name: "人员降薪",
                        route: '/personnel'
                      },
                      {
                        name: "项目工时",
                        route: '/projecthours'
                      }
                    ] 
                  }
                ]
              }
            ]
          },
          {
            index: '3',
            title: '经营项目',
            icon: 'el-icon-document',
            groups: [
              {
                items: [
                  { index: '3-1',	name: '经营项目',
                  route:'/productService',
                   children:[
                     {
                        name: "产品服务",
                        route: '/productService'
                      },
                      {
                        name: "销售情况",
                        route: '/salesperformance'
                      },
                     
                    ] 
                   }
                ]
              }
            ]
          },
          {
            index: '4',
            title: '审核中心',
            icon: 'el-icon-document',
            groups: [
              {
                items: [
                  { index: '4-1',	name: '审核管理',
                  route:'/myreview',
                   children:[
                     {
                        name: "我的审核",
                        route: '/myreview'
                      },
                      {
                        name: "我的提交",
                        route: '/mysubmission'
                      },
                      {
                        name: "权限节点",
                        route: '/permissionnode'
                      },
                    ] 
                   }
                ]
              }
            ]
          },
          {
            index: '5',
            title: '高企认定',
            icon: 'el-icon-document',
            groups: [
              {
                items: [
                  { index: '5-1',	name: '申报管理',
                  route:'/declarationmanagement',
                   children:[
                     {
                        name: "申报情况",
                        route: '/declarationmanagement'
                      }
                     
                    ] 
                   }
                ]
              }
            ]
          },
          {
            index: '6',
            title: '专精特新',
            icon: 'el-icon-document',
            groups: [
              {
                items: [
                  { index: '6-1',	name: '申报管理',
                  route:'/specialized',
                   children:[
                     {
                        name: "申报管理",
                        route: '/specialized'
                      }
                     
                    ] 
                   }
                ]
              }
            ]
          },
          {
            index: '7',
            title: '加计扣除',
            icon: 'el-icon-document',
            groups: [
              {
                items: [
                  { index: '7-1',	name: '申报管理',
                  route:'/declarationstatus',
                   children:[
                     {
                        name: "申报情况",
                        route: '/declarationstatus'
                      },
                      {
                        name: "研发支出辅助账",
                        route: '/rds'
                      }
                     
                    ] 
                   }
                ]
                 
              }
            ]
          },
          {
            index: '8',
            title: '科创汇',
            icon: 'el-icon-document',
            groups: [
              {
                items: [
                  { index: '8-1',	name: '通知公告',
                  route:'/follow',
                   children:[
                     {
                        name: "关注",
                        route: '/follow'
                      },
                      { name: '全部',
                        route: '/government'
                       }
                     
                    ] 
                   },
                  { index: '8-2',	name: '政府网站',
                  route:'/home/government/address',
                   children:[
                     {
                        name: "地址管理",
                        route: '/home/government/address'
                      }
                     
                    ] 
                   },
                 
                ]
              }
            ]
          },
          {
            index: '9',
            title: '系统管理',
            icon: 'el-icon-document',
            groups: [
              {
                items: [
                  { index: '9-1',	name: '权限管理',
                  route:'/role',
                   children:[
                     {
                        name: "用户管理",
                        route: '/role'
                      },
                      { name: '角色管理',
                        route: '/user'
                       }
                     
                    ] 
                   },
                  { index: '9-2',	name: '系统日志',
                  route:'/userbehavior',
                   children:[
                     {
                        name: "用户行为",
                        route: '/userbehavior'
                      },
                      { name: '运行日志',
                        route: '/operationlog'
                       }
                     
                    ] 
                   },
                  { index: '9-3',	name: '配置管理',
                  route:'/dictionary',
                   children:[
                     {
                        name: "数据字典",
                        route: '/dictionary'
                      },
                      { name: '菜单管理',
                        route: '/menu'
                       },
                       { name: '系统配置',
                        route: '/systemconfiguration'
                       }
                     
                    ] 
                   }
                ]
              }
            ]
          }
        ]
      }
    },
    methods: {
      
      restoreMenuState() {
  if (!this.activeItemIndex) {
    const savedIndex = localStorage.getItem('activeItemIndex');
    const savedMenu = localStorage.getItem('activeMenu');
    if (savedIndex) {
      this.activeItemIndex = savedIndex;
      this.activeMenu = savedMenu || savedIndex.split('-')[0];
    }
  }
},


    handleStorageChange(event) {
      if (event.key === 'activeItemIndex') {
        this.activeItemIndex = event.newValue
        this.activeMenu = event.newValue.split('-')[0]
      }
    },


// 统一的方法
setActiveItem(item, index) {
  // 更新当前激活的菜单项
  this.activeItemIndex = index;
    this.activeMenu = index.split('-')[0];
    
    // 确保当前菜单是展开状态（防抖避免频繁操作）
    if (!this.openedMenus.includes(this.activeMenu)) {
      this.openedMenus = [this.activeMenu];
    }

  
  // 存储到 localStorage
  localStorage.setItem('activeItemIndex', index);
  localStorage.setItem('activeMenu', this.activeMenu);
  const normalizedRoute = this.normalizeRoute(item.route);
  localStorage.setItem('lastRoute', normalizedRoute);  // 存储当前路由
  
  // 触发路由跳转（如果路由变更）
  if (normalizedRoute && this.$route.path !== normalizedRoute) {
    this.$router.push(normalizedRoute);
  }
  
  // 传递给父组件（如有需要）
  this.$emit('headerDate', item);
},
    
    // 匹配当前路由对应的菜单项
    matchRouteWithMenu(currentPath) {
  let matchedItem = null;
  
  // 处理 /home 和 /home/ 路由，统一转换为 /home/ 进行匹配
  let normalizedPath = currentPath;
  if (currentPath === '/home') {
    normalizedPath = '/home/';
  }
  
  // 深度遍历菜单数据
  outerLoop:
  for (const menu of this.menuData) {
    for (const group of menu.groups) {
      for (const item of group.items) {
        // 标准化路由路径进行匹配
        const itemRoute = this.normalizeRoute(item.route);
        const normalizedItemRoute = itemRoute === '/home' ? '/home/' : itemRoute;
        
        // 匹配主路由（支持 /home 和 /home/ 两种格式）
        // 特别处理：当路由是 /home 或 /home/ 时，匹配 route 为 / 的菜单项
        if (normalizedItemRoute === normalizedPath || 
            (normalizedPath === '/home/' && item.route === '/')) {
          matchedItem = item;
          break outerLoop;
        }
        // 匹配子路由
        if (item.children) {
          const matchedChild = item.children.find(child => {
            const childRoute = this.normalizeRoute(child.route);
            const normalizedChildRoute = childRoute === '/home' ? '/home/' : childRoute;
            // 特别处理：当路由是 /home 或 /home/ 时，匹配 route 为 / 的子菜单项
            return normalizedChildRoute === normalizedPath || 
                   (normalizedPath === '/home/' && child.route === '/');
          });
          if (matchedChild) {
            matchedItem = item;
            break outerLoop;
          }
        }
      }
    }
  }
  
  // 更新状态
  if (matchedItem) {
    this.activeItemIndex = matchedItem.index;
    this.activeMenu = matchedItem.index.split('-')[0];
    localStorage.setItem('activeItemIndex', matchedItem.index);
    localStorage.setItem('activeMenu', this.activeMenu);
    // 更新 lastRoute 为当前路由
    localStorage.setItem('lastRoute', normalizedPath);
  }
},
normalizeRoute(route) {
  if (!route) return '/home'
  if (route === '/') return '/home'
  if (route.startsWith('/home')) return route
  return '/home' + (route.startsWith('/') ? route : '/' + route)
}


   
    },
// sidebar.vue
watch: {
  $route: {
      immediate: true,
      handler(newVal) {
      this.matchRouteWithMenu(newVal.path);
    }

  }
},
mounted() {
  // 如果当前路由是 /home 或 /home/，不恢复 lastRoute，直接匹配菜单
  const currentPath = this.$route.path;
  if (currentPath === '/home' || currentPath === '/home/') {
    // 直接匹配当前路由对应的菜单
    this.matchRouteWithMenu(currentPath);
    return;
  }
  
  // 从localStorage恢复路由（仅当不是 /home 或 /home/ 时）
  const lastRoute = localStorage.getItem('lastRoute')
  if (lastRoute) {
    const normalizedRoute = this.normalizeRoute(lastRoute)
    // 如果 lastRoute 是 /home 或 /home/，不恢复，使用当前路由
    if (normalizedRoute && normalizedRoute !== '/home' && normalizedRoute !== '/home/' && this.$route.path !== normalizedRoute) {
      this.$router.push(normalizedRoute)
    }
  }
},
created() {
  // 如果当前路由是 /home 或 /home/，优先匹配路由，不恢复 localStorage 状态
  const currentPath = this.$route.path;
  if (currentPath === '/home' || currentPath === '/home/') {
    // 直接匹配当前路由对应的菜单
    this.matchRouteWithMenu(currentPath);
    window.addEventListener('storage', this.handleStorageChange);
    return;
  }
  
  // 优先从localStorage恢复状态（仅当不是 /home 或 /home/ 时）
  const savedIndex = localStorage.getItem('activeItemIndex');
  const savedMenu = localStorage.getItem('activeMenu');
  const savedOpened = JSON.parse(localStorage.getItem('openedMenus') || '[]');

  if (savedIndex) {
    this.activeItemIndex = savedIndex;
    this.activeMenu = savedMenu || savedIndex.split('-')[0];
    this.openedMenus = savedOpened;
  }

  // 再匹配路由（确保路由优先级更高）
  this.matchRouteWithMenu(this.$route.path);
  
  // 如果路由未匹配但localStorage有数据，则使用存储的数据
  if (!this.activeItemIndex && savedIndex) {
    this.activeItemIndex = savedIndex;
    this.activeMenu = savedMenu;
    this.openedMenus = savedOpened;
  }
  
  window.addEventListener('storage', this.handleStorageChange);
},

  beforeDestroy() {
    // 移除事件监听
    window.removeEventListener('storage', this.handleStorageChange)
  },

  }
  </script>
  
  <style scoped>
  .shu{
    width: 3px;
    height: 40px;
    background: #ebebeb;
    position: absolute;
    left: 28px;
  }

  .yuan{
    width: 6px;
    height: 6px;
    background-color: #ebebeb;
    border-radius: 50%;
    z-index: 99;
    position: absolute;
    top: 16px;
    left: 26px;
  }
 :deep .el-menu-item.is-active{
    color: #5165f7  !important;
}
  /* 调整整体间距 */
.lefts {
    flex: 1;
    padding: 0 0 8px 0;
    height: 100%;
    background: transparent;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    
}
  
  /* 菜单项间距调整 */
  .el-menu {
    padding: 0 !important;
  }
  .el-menu-item, 
  .el-submenu__title {
    height: 40px !important;
    line-height: 40px !important;
  }
  
  /* 子菜单居中 */
  .submenu-content {
    display: flex;
    flex-direction: column;
    align-items: center;
  }
  .el-menu-item-group {
    width: 100%;
  }
  .el-menu-item {
    text-align: center !important;
    padding: 0 10px !important;
    min-width: auto !important;
  }
  
  /* 激活状态样式（重点修改部分） */
  .el-submenu.active-menu > .el-submenu__title,
.el-submenu.active-menu > .el-submenu__title:hover {
  color: #409EFF !important;
  background-color: red !important;
}
/* 确保子菜单展开时也有高亮 */
.el-submenu.is-opened > .el-submenu__title {
  color: #409EFF !important;
}

  .el-submenu.active-menu .el-icon-arrow-down,
  .el-submenu.is-active .el-icon-arrow-down,
 
  
  /* 分组标题样式 */
  ::v-deep .el-menu-item-group__title {
    padding: 0 !important;
    font-size: 12px !important;
    text-align: center;
  }
  
  /* 菜单宽度调整 */
  .el-menu-vertical-demo {
    width: 222px !important;
  }
  .el-menu--inline {
    padding-left: 0 !important;
  }
  
  /* 调整图标间距 */
  .el-submenu__title i {
    margin-right: 8px !important;
  }
  /* :deep .el-submenu__title {
 
     background: red !important; 
} */
 /* ✅ 正确写法：作用于被选中的 "导航一" */
.el-submenu.active-menu :deep(.el-submenu__title) {
  background: #5165f7 !important;
  color: white !important;
}
.el-submenu.active-menu :deep(.el-submenu__title i) {
  color: white !important; /* 强制图标变白 */
}

  </style>
  