<template>
  <div class="allmain">
    <div class="tip">
      <div class="tip1">无人灭火机器人数字孪生后台管理系统</div>
      <div class="tip2">国际花园小区</div>
      <div class="avatar-container" v-if="useAppStore.isCurUserLogin">
        <el-dropdown> 
          <el-avatar shape="square" size="large" src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"/>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="toSatffManage">人员管理</el-dropdown-item>
              <el-dropdown-item @click="curUserLogout">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
    <div class="main">
      <div class="left">
        <div class="left1">
          <div v-for="(item, index) in menuList" :key="index" class="menu-item-container">
            <div  class="menu-wrapper">
              <div 
                class="submenu-title" 
                :class="isActive(item) ? 'active' : ''"
                @click="toggleSubMenu(index)">
                <el-icon class="menu_left-icon" >
                  <img :src="item.icon" alt="">
                </el-icon>
                <span class="menu-text">{{ item.name }}</span>
                
                <el-icon class="arrow-icon" :class="openMenus[index] ? 'rotate' : ''">
                  <ArrowRight />
                </el-icon>
              </div>
              
              <transition name="submenu-slide">
                <div v-if="openMenus[index]" class="submenu-list">
                  <div 
                    class="submenu-item" 
                    @click="handleSubMenuClick(child)" 
                    :class="isSubMenuActive(child) ? 'active' : ''" 
                    v-for="(child, childIndex) in item.children"
                    :key="childIndex"
                  >
                    {{ child.name }}
                  </div>
                </div>
              </transition>
            </div>
          </div>
        </div>
      </div>
      <div class="right">
        <!-- 面包屑导航 -->
        <div class="breadcrumb-container">
          <el-breadcrumb separator=">">
            <el-breadcrumb-item v-for="(crumb, index) in breadcrumbs" :key="index" 
              @click="handleBreadcrumbClick(index)">
              {{ crumb.name }}
            </el-breadcrumb-item>
          </el-breadcrumb>
        </div>
        
        <!-- 标签页 -->
        <div class="tabs-container">
          <el-tabs 
            v-model="activeTabKey" 
            type="card" 
            closable 
            @tab-remove="removeTab"
            @tab-click="handleTabClick"
            class="custom-tabs"
          >
            <el-tab-pane 
              v-for="tab in tabs" 
              :key="tab.key" 
              :label="tab.label"
              :name="tab.key"

            >
            </el-tab-pane>
          </el-tabs>
        </div>
        
        <div class="right-content">
          <router-view v-slot="{ Component, route }" :key="$route.fullPath">
            <keep-alive>
              <component v-if="!route.meta.link" :is="Component" :key="route.path"/>
            </keep-alive>
          </router-view>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import useAppStore from '../store/module/app';
import { getToken, removeToken } from '../utils/auth';
import { pa } from 'element-plus/es/locales.mjs';

const router = useRouter();
const route = useRoute();
const useAppStoreInstance = useAppStore();

// 1.（根据菜单结构）

const menuList = ref([
  { 
    name: '仪表盘', 
    id: 'dashboard', 
    path: '/analySisPage', 
    icon: new URL('../static/image/huo.png', import.meta.url).href,
    children:[
      { name: '分析页', id: 'analysis', path: '/analysisPage' },
      { name: '工作台', id: 'workbench', path: '/workBenchPage'},

    ]
  },
  { 
    name: '系统管理', 
    id: 'system', 
    path: '/userManage', 
    icon: new URL('../static/image/huo.png', import.meta.url).href,
    children: [
      { name: '用户管理', id: 'user', path: '/usermanage' },
     
    ]
  },
  { 
    name: '建筑管理', 
    id: 'building', 
    path: '/areaBuildmanage', 
    icon: new URL('../static/image/huo.png', import.meta.url).href,
    children: [
      { name: '区域建筑管理', id: 'areaBuilding', path: '/areabuildmanage' },
    
    ]
  },
  { 
    name: '无人机管理', 
    id: 'drone', 
    path: '/uavDispatch', 
    icon: new URL('../static/image/huo.png', import.meta.url).href,
    children: [
      { name: '无人机调度', id: 'droneDispatch', path: '/uavdispatch' },
      { name: '无人机监控', id: 'droneMonitor', path: '/drone/monitor' }
    ]
  },
  { 
    name: '火情管理', 
    id: 'fire', 
    path: '/fireSurveillance', 
    icon: new URL('../static/image/huo.png', import.meta.url).href,
    children: [
      { name: '当前火情', id: 'fireMonitor', path: '/firesurveillance' },
      { name: '历史火情', id: 'fireHistory', path: '/historyfire' }
    ]
  },

]);

const openMenus = ref([]);
const breadcrumbs = ref([]);
const tabs = ref([]);
const activeTabKey = ref('');

// --------------------------
// 2. 工具函数
// --------------------------
const getMenuNameByPath = (path) => {
  for (const item of router.options.routes[4].children) {
    if (item.path === path) {
      return item.meta.title;
    } else if (item.children && item.children.length) {
      const matchedChild = item.children.find(child => child.path === path);
      if (matchedChild) {
        return matchedChild.meta.title;
      }
    }
  }

  for (const item of menuList.value) {
    if (item.path === path) {
      return item.name;
    } else if (item.children && item.children.length) {
      const matchedChild = item.children.find(child => child.path === path);
      if (matchedChild) {
        return matchedChild.name;
      }
    }
  }
  return '未知页面';
};


// 3. 核心函数
const addTab = () => {
  const path = route.path;
  const existingTabIndex = tabs.value.findIndex(tab => tab.key === path);
  
  const  preTabs = ref(tabs.value);
  console.log("existingTabIndexpath----------------12121----------",preTabs,"----------",path,'----------',tabs.value)
  if (existingTabIndex === -1) {
    // console.log("existingTabIndexpath--------------------------",tabs.value)
    tabs.value.push({
      key: path,
      label: getMenuNameByPath(path),
      path: path
    });
  }else {
    tabs.value=preTabs.value;
  }

  activeTabKey.value = path;
  console.log("existingTabIndexpath---------56555555555555555555-----------------",activeTabKey.value)
};

const saveMenuState = () => {
  const menuState = {
    openMenus: openMenus.value
  };
  localStorage.setItem('menuState', JSON.stringify(menuState));
};

const updateMenuActiveState = () => {
  useAppStoreInstance.num = route.path;
  
  const currentPath = route.path;
  menuList.value.forEach((item, index) => {
    if (item.children && item.children.length) {
      const hasActiveChild = item.children.some(child => child.path === currentPath);
      if (hasActiveChild) {
        openMenus.value[index] = true;
      }
    }
  });
};


// 检查路径是否存在
function isPathInMenu(path) {
  // 扁平化所有菜单项
  const flattenMenu = (menus) => {
    return menus.reduce((acc, item) => {
      acc.push(item.path);
      if (item.children) {
        acc.push(...flattenMenu(item.children));
      }
      return acc;
    }, []);
  };

  const allPaths = flattenMenu(menuList.value);
  return allPaths.includes(path);
}
const updateBreadcrumbs = () => {
  const path = route.path;
  const crumbs = [];
  
  crumbs.push({ name: '首页', path: '/' });
  let preCrumbsDate = breadcrumbs.value;
  // if (path === '/') {
    
  // }
  if (isPathInMenu(path)) {
      menuList.value.forEach(mainItem => {
      if (mainItem.path === path) {
        crumbs.push({ name: mainItem.name, path: mainItem.path });
      } else if (mainItem.children && mainItem.children.length) {
        const matchedChild = mainItem.children.find(child => child.path === path);
        if (matchedChild) {
          crumbs.push({ name: mainItem.name, path: mainItem.path });
          crumbs.push({ name: matchedChild.name, path: matchedChild.path });
        }
      }
    });
    breadcrumbs.value = crumbs;
  }else {
    // 匹配不到时，返回首页
    breadcrumbs.value = preCrumbsDate
    console.log('匹配不到时，返回首页',breadcrumbs.value.length)
    // useAppStoreInstance.num = 
  }

  
};

const initTabs = () => {
  const initialTab = {
    key: route.path,
    label: getMenuNameByPath(route.path),
    path: route.path
  };
  console.log("初始化标签页",initialTab);
  tabs.value = [initialTab];
  activeTabKey.value = route.path;
};

// --------------------------
// 4. 生命周期钩子
// --------------------------
onMounted(() => {
  menuList.value.forEach((item, index) => {
    if (item.children && item.children.length) {
      openMenus.value[index] = false;
    }
    
    const savedState = localStorage.getItem('menuState');
    if (savedState) {
      const parsedState = JSON.parse(savedState);
      openMenus.value = parsedState.openMenus || openMenus.value;
    }
  });
  
  initTabs();
  updateBreadcrumbs();
  updateMenuActiveState();
});

watch(route, () => {
  updateMenuActiveState();
  updateBreadcrumbs();
  addTab();
  saveMenuState();
}, { immediate: true });

// --------------------------
// 5. 其他辅助函数
// --------------------------
const removeTab = (key) => {
  const index = tabs.value.findIndex(tab => tab.key === key);
  
  if (index === -1) return;
  
  if (key === activeTabKey.value) {
    const newIndex = index > 0 ? index - 1 : index + 1;
    if (tabs.value[newIndex]) {
      router.push(tabs.value[newIndex].path);
    }
  }
  
  tabs.value.splice(index, 1);
};

const handleTabClick = (tab) => {
  const tabItem = tabs.value.find(item => item.key === tab.name);
  console.log(tab,tab.props.name,"-------999999999999999999-------------");
  router.push(tab.props.name);

};

const toggleSubMenu = (index) => {
  openMenus.value[index] = !openMenus.value[index];
  saveMenuState();
};

const handleSubMenuClick = (child) => {
  useAppStoreInstance.num = child.path;
  
  localStorage.setItem('menu', child.path);
  router.push(child.path);
};

const menuclick = (item) => {
  if (!item.children || !item.children.length) {
    useAppStoreInstance.num = item.id;
    localStorage.setItem('menu', item.id);
    router.push(item.path);
  }
};

const isActive = (item) => {
  if (route.path === item.path) return true;
  
  if (item.children && item.children.length) {
    return item.children.some(child => child.path === route.path);
  }
  
  return false;
};

const isSubMenuActive = (child) => {
  return route.path === child.path;
};

const handleBreadcrumbClick = (index) => {
  if (index < breadcrumbs.value.length - 1) {
    const crumb = breadcrumbs.value[index];
    router.push(crumb.path);
  }
};

const toSatffManage = () => {
  router.push({ path: '/staff' });
  useAppStoreInstance.num = '/staff';
};

const curUserLogout = () => {
  removeToken();
  router.push('/login');
  useAppStoreInstance.isCurUserLogin = false;
};
</script>



<style scoped>
/* CSS美化重点：增强视觉层次、添加深度感、优化动画效果 */
.allmain {
  width: 100vw;
  min-width: 1024px;
  height: 100vh;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background: #051d39;
  background-image: 
  radial-gradient(circle at 10% 20%, rgba(6, 176, 225, 0.05) 0%, transparent 30%),
  radial-gradient(circle at 90% 80%, rgba(5, 113, 196, 0.05) 0%, transparent 30%);
  color: #ffffff;
  display: flex;
  flex-direction: column;
  font-family: 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
}

.tip {
  width: 100%;
  height: 9vh;
  min-height: 60px;
  background: linear-gradient(90deg, #0a2a4a 0%, #0f3a64 100%);
  display: flex;
  align-items: center;
  position: relative;
  padding: 0 20px;
  flex-shrink: 0;
  z-index: 10;
  box-shadow: 0 2px 15px rgba(0, 0, 0, 0.3);
  border-bottom: 1px solid rgba(6, 176, 225, 0.15);
}

.tip::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 3px;
  background: linear-gradient(90deg, rgba(6, 176, 225, 0) 0%, rgba(6, 176, 225, 0.8) 50%, rgba(6, 176, 225, 0) 100%);
}

.tip1 {
  font-weight: bold;
  background: linear-gradient(to bottom, #FFFFFF 40%, #96CBFF 100%);
  background-clip: text;
  -webkit-background-clip: text;
  color: transparent;
  font-size: clamp(24px, 1.2vw, 32px);
  white-space: nowrap;
  margin-right: 20px;
  text-shadow: 0 0 15px rgba(150, 203, 255, 0.3);
  letter-spacing: 0.5px;
}

.tip2 {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(5px);
  padding: 5px 20px;
  height: 36px;
  line-height: 25px;
  font-size: clamp(16px, 1.5vw, 20px);
  white-space: nowrap;
  color: #ffffff;
  text-shadow: 0 0 8px rgba(6, 176, 225, 0.5);
  border-radius: 18px;
  box-shadow: 0 0 10px rgba(6, 176, 225, 0.1);
}

.avatar-container {
  margin-left: auto;
  cursor: pointer;
  margin-right: 10px;
  transition: transform 0.2s ease, box-shadow 0.2s ease;
  border-radius: 8px;
  padding: 2px;
}

.avatar-container:hover {
  transform: scale(1.05);
  box-shadow: 0 0 15px rgba(6, 176, 225, 0.3);
}

.main {
  display: flex;
  flex: 1;
  min-height: 0;
  width: 100%;
  background-color: #ffffff;
}

.left {
  width: 240px;
  min-width: 200px;
  display: flex;
  flex-direction: column;
  flex-shrink: 0;
  /* background: linear-gradient(180deg, #0a2a4a 0%, #0d3053 100%); */
  box-shadow: 2px 0 15px rgba(0, 0, 0, 0.3);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  /* z-index: 5; */
  border-right: 1px solid rgba(6, 176, 225, 0.1);
  color: black;
}

.left1 {
  
  flex: 1;
  overflow-y: auto;
  padding: 15px 0;
  scrollbar-width: thin;
  scrollbar-color: rgba(73, 73, 73, 0.3) transparent;
}

.left1::-webkit-scrollbar {
  width: 6px;
}

.left1::-webkit-scrollbar-track {
  background: transparent;
}

.left1::-webkit-scrollbar-thumb {
  background-color: rgba(6, 176, 225, 0.3);
  border-radius: 3px;
}

.menu-item-container {
  margin-bottom: 8px;
  padding: 0 5px;
}

.menu, .submenu-title {
  height: 56px;
  display: flex;
  align-items: center;
  padding: 0 20px;
  cursor: pointer;
  font-size: clamp(14px, 1.2vw, 16px);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  border-radius: 12px;
  margin: 0 5px;
}

.menu_left-icon img{
  width: 100%;
  height: 100%;
  object-fit: cover;
}


.menu:hover, .submenu-title:hover {
  background: rgba(5, 113, 196, 0.2);
  transform: translateX(3px);
}

.menu.active, .submenu-title.active {
  background: linear-gradient(90deg, rgba(6, 176, 225, 0.25) 0%, rgba(5, 113, 196, 0.4) 100%);
  box-shadow: 0 0 15px rgba(6, 176, 225, 0.25), inset 0 0 10px rgba(6, 176, 225, 0.1);
}

.menu.active::before, .submenu-title.active::before {
  content: '';
  position: absolute;
  left: 0;
  top: 15%;
  height: 70%;
  width: 4px;
  background: linear-gradient(180deg, #06b0e1 0%, #0571c4 100%);
  border-radius: 0 6px 6px 0;
  box-shadow: 0 0 10px rgba(6, 176, 225, 0.5);
}

.menu el-icon, .submenu-title el-icon {
  font-size: 20px;
  margin-right: 12px;
  color: #9ec8e6;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.menu .menu-text, .submenu-title .menu-text {
  color: black;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  flex: 1;
  position: relative;
  z-index: 2;
  padding-left: 10%;
}

.menu.active .menu-text, .submenu-title.active .menu-text {
  color: #ffffff;
  font-weight: 500;
  text-shadow: 0 0 5px rgba(6, 176, 225, 0.5);
}

.menu.active-icon {
  color: #06b0e1;
  filter: drop-shadow(0 0 5px rgba(6, 176, 225, 0.6));
}

.arrow-icon {
  font-size: 18px;
  transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  color: black;
}

.rotate {
  transform: rotate(90deg);
  color: #06b0e1;
}

.submenu-list {
  background: #f1f0f0;

  backdrop-filter: blur(5px);
  /* padding: 5px 0; */
  /* border-left: 2px solid rgba(6, 176, 225, 0.2); */
  /* margin: 0 5px 10px 5px; */
  /* border-radius: 0 12px 12px 0; */
  /* box-shadow: inset 2px 2px rgba(0, 0, 0, 0.2); */
}

.submenu-item {
  height: 42px;
  line-height: 42px;
  padding-left: 40px;
  color: #000000;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  border-radius: 8px;
  margin: 0 5px;
}

.submenu-item:hover {
  background: rgba(5, 113, 196, 0.2);
  color: #e6f7ff;
  padding-left: 45px;
  transform: translateX(3px);
}

.submenu-item.active {
  color: #06b0e1;
  font-weight: 500;
  background: linear-gradient(90deg, rgba(6, 176, 225, 0.1) 0%, rgba(6, 176, 225, 0.05) 100%);
}

.submenu-item.active::before {
  content: '';
  position: absolute;
  left: 25px;
  top: 50%;
  width: 8px;
  height: 8px;
  background: #06b0e1;
  border-radius: 50%;
  transform: translateY(-50%);
  box-shadow: 0 0 10px rgba(6, 176, 225, 0.5);
}

.submenu-slide-enter-from,
.submenu-slide-leave-to {
  max-height: 0;
  opacity: 0;
  transform: translateX(-10px);
}

.submenu-slide-enter-active,
.submenu-slide-leave-active {
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  overflow: hidden;
}

.submenu-slide-enter-to,
.submenu-slide-leave-from {
  max-height: 500px;
  opacity: 1;
  transform: translateX(0);
}

.right {
  flex: 1;
  width: 100%;
  min-width: 0;
  display: flex;
  flex-direction: column;
  background: #ffffff;
  overflow: hidden;
}

.breadcrumb-container {
  color: #000000;
  /* padding-left: 15px; */
  padding: 10px;
  background: #fff;
  border-bottom: 1px solid rgb(180, 178, 178);
}

.el-breadcrumb {
  color: #000000;
}

.el-breadcrumb__item {
  cursor: pointer;
  transition: all 0.2s ease;
  padding: 2px 5px;
  border-radius: 4px;
}

.el-breadcrumb__item:hover:not(.el-breadcrumb__item:last-child) {
  color: #06b0e1;
  background: rgba(6, 176, 225, 0.1);
  text-shadow: 0 0 5px rgba(6, 176, 225, 0.5);
}

.el-breadcrumb__item:last-child {
  color: #ffffff;
  font-weight: 500;
  text-shadow: 0 0 5px rgba(6, 176, 225, 0.3);
}

.el-breadcrumb__separator {
  color: rgba(158, 200, 230, 0.5);
  margin: 0 10px;
}

/* 标签页样式 */
.tabs-container {
  background-color: #ffffff;

  padding: 8px 25px;
}

.custom-tabs .el-tabs__nav-scroll {
  /* padding-bottom: 5px; */
}

.el-tabs__item {
  height: 40px;
  line-height: 40px;
  color: #b3cfe5;
  border-radius: 12px 12px 0 0;
  margin-right: 8px;
  /* border-bottom: none !important; */
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  padding: 0 18px;
}

.el-tabs__item:hover {
  color: #06b0e1;
  background: rgba(6, 176, 225, 0.1);
}

.el-tabs__item.is-active {
  background: linear-gradient(180deg, rgba(10, 30, 56, 0.9) 0%, rgba(10, 30, 56, 0.7) 100%);
  color: #06b0e1;
  font-weight: 500;
  box-shadow: none;
  border-top: 2px solid #06b0e1;
  transform: translateY(2px);
}

.el-tabs__close-btn {
  color: #9ec8e6;
  margin-left: 8px;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
}

.el-tabs__close-btn:hover {
  color: #ffffff;
  background: rgba(6, 176, 225, 0.2);
  transform: rotate(90deg);
}

.right-content {
   overflow: hidden;
   height: 100%;


}



/* 响应式优化 */
@media (max-width: 1200px) {
  .left {
    width: 220px;
  }
  
  .menu, .submenu-title {
    height: 52px;
  }
}

@media (max-width: 992px) {
  .left {
    width: 80px;
  }
  
  .menu-text, .arrow-icon {
    display: none;
  }
  
  .menu, .submenu-title {
    justify-content: center;
    padding: 0;
  }
  
  .menu el-icon, .submenu-title el-icon {
    margin-right: 0;
    font-size: 24px;
  }
  
  .submenu-list {
    display: none;
  }
  
  .tip1 {
    font-size: clamp(20px, 1vw, 28px);
  }
}

@media (max-width: 768px) {
  .allmain {
    min-width: auto;
  }
  
  .main {
    flex-direction: column;
  }
  
  .left {
    width: 100%;
    height: auto;
    flex-direction: row;
    flex-wrap: wrap;
  }
  
  .left1 {
    display: flex;
    flex-wrap: wrap;
    height: auto;
    width: 100%;
    padding: 10px;
  }
  
  .menu-item-container {
    width: 33.33%;
  }
  
  .menu, .submenu-title {
    width: 100%;
    height: 50px;
    justify-content: center;
    padding: 0;
    margin: 5px;
  }
  
  .menu-text {
    display: block;
    font-size: 12px;
  }
  
  .menu el-icon, .submenu-title el-icon {
    margin-right: 5px;
    font-size: 14px;
  }
  
  .arrow-icon {
    display: none;
  }
  
  .submenu-list {
    display: none;
  }
  
  .tabs-container {
    overflow-x: auto;
    /* padding-bottom: 10px; */
  }
}
</style>