<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="useAppStoreInstance.userInfo.avatar ? useAppStoreInstance.userInfo.avatar : useAppStoreInstance.showavatarUrl" />
          <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">
              {{ 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 { nextTick, onMounted, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import useAppStore from '../store/module/app';
import { getToken, removeToken } from '../utils/auth';


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

// 菜单结构
const menuList = ref([
  {
    name: '仪表盘',
    id: 'dashboard',
    path: '/analySisPage',
    icon: new URL('../static/image/huo.png', import.meta.url).href,
    children: [
      { name: '分析页', id: 'analysis', path: '/dashboard/analysis' },
      { name: '工作台', id: 'workbench', path: '/dashboard/workbench' },
    ]
  },
  {
    name: '系统管理',
    id: 'system',
    path: '/userManage',
    icon: new URL('../static/image/huo.png', import.meta.url).href,
    children: [
      { name: '用户管理', id: 'user', path: '/systemmanage/staffManage' },
    ]
  },
  {
    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: '/uavshowdate' },
      { name: '无人机监控', id: 'droneMonitor', path: '/uavshowdate/uavmanage' }
    ]
  },
  {
    name: '火情管理',
    id: 'fire',
    path: '/fireSurveillance',
    icon: new URL('../static/image/huo.png', import.meta.url).href,
    children: [

      { name: '当前火情', id: 'fireHistory', path: '/areafiremanage/historyfire' },
      { name: '上报记录', id: 'fireRecord', path: '/areafiremanage/firerecord' },
      { name: '历史火情', id: 'fireMonitor', path: '/areafiremanage/firesurveillance' },
    ]
  },
]);

const openMenus = ref([]);
const breadcrumbs = ref([]);
const tabs = ref([]);
const activeTabKey = ref('');
const lastValidMenuPath = ref('/areafiremanage/historyfire'); // 记录最后一个有效的菜单路径

// 获取菜单项名称
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 '未知页面';
};

// 检查路径是否在菜单中
const isPathInMenu = (path) => {
  for (const item of menuList.value) {
    if (item.path === path) return true;
    if (item.children && item.children.some(c => c.path === path)) return true;
  }
  return false;
};

// 获取当前有效路径
const getCurrentValidPath = () => {
  return isPathInMenu(route.path) ? route.path : lastValidMenuPath.value;
};

// 更新菜单激活状态
const updateMenuActiveState = () => {
  const currentPath = getCurrentValidPath();
  useAppStoreInstance.num = currentPath;

  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;
      }
    }
  });

  if (isPathInMenu(route.path)) {
    lastValidMenuPath.value = route.path;
  }
};

// 检查菜单项是否激活
const isActive = (item) => {
  const currentPath = getCurrentValidPath();
  if (currentPath === item.path) return true;
  if (item.children && item.children.length) {
    return item.children.some(child => child.path === currentPath);
  }
  return false;
};

// 检查子菜单项是否激活
const isSubMenuActive = (child) => {
  const currentPath = getCurrentValidPath();
  return currentPath === child.path;
};

// 更新面包屑导航
const updateBreadcrumbs = () => {
  const path = getCurrentValidPath();
  const crumbs = [{ name: '首页', path: '/' }];

  for (const item of menuList.value) {
    if (item.path === path) {
      crumbs.push({ name: item.name, path: item.path });
      break;
    }
    if (item.children && item.children.length) {
      const child = item.children.find(c => c.path === path);
      if (child) {
        crumbs.push({ name: item.name, path: item.path });
        crumbs.push({ name: child.name, path: child.path });
        break;
      }
    }
  }

  breadcrumbs.value = crumbs;
};

// 添加标签页
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 initTabs = () => {
  const initialPath = isPathInMenu(route.path) ? route.path : lastValidMenuPath.value;
  tabs.value = [{
    key: initialPath,
    label: getMenuNameByPath(initialPath),
    path: initialPath
  }];
  activeTabKey.value = initialPath;
};

// 保存菜单状态
const saveMenuState = () => {
  console.log('保存菜单状态', router.options.history.state.back)
  if (router.options.history.state.back !== null) {
    const menuState = {
      openMenus: openMenus.value,
      lastValidMenuPath: isPathInMenu(router.options.history.state.back) ? router.options.history.state.back : (localStorage.getItem('lastValidMenuPath')),
    };
    localStorage.setItem('menuState', JSON.stringify(menuState));
  }
};

// 移除标签页
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.paneName);
  if (tabItem) {
    router.push(tabItem.path);
  }
};

// 切换子菜单展开状态
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 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 noremoveItemFn = (data) => {
  const valueToKeep = localStorage.getItem(data);
  console.log("sdsadadddddd", valueToKeep)
  localStorage.clear();
  if (valueToKeep !== null) {
    localStorage.setItem(data, valueToKeep);
  }
};
// 用户退出
const curUserLogout = () => {
  removeToken();
  router.push('/login');
  useAppStoreInstance.isCurUserLogin = false;
  noremoveItemFn('rememberedAccount');
};



const showavatarUrl = ref('https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png');

// 初始化
onMounted(() => {
  nextTick(() => {
    useAppStoreInstance.initavatarUrlFn()
  })


  // 初始化菜单展开状态
  menuList.value.forEach((_, index) => {
    openMenus.value[index] = false;
  });

  // 从本地存储恢复状态
  const savedState = localStorage.getItem('menuState');
  if (savedState) {
    try {
      const parsedState = JSON.parse(savedState);
      openMenus.value = parsedState.openMenus || openMenus.value;
      lastValidMenuPath.value = parsedState.lastValidMenuPath || '/areafiremanage/historyfire';
    } catch (e) {
      console.error('Failed to parse menu state', e);
    }
  }
  // console.log("currentDisplayPath.value--------------------------",isPathInMenu(route.path))
  if (!isPathInMenu(route.path)) {
    console.log("currentDisplayPath.value--------------------------", isPathInMenu(route.path), getCurrentValidPath(), JSON.parse(localStorage.getItem('menuState')).lastValidMenuPath)
    router.replace(JSON.parse(localStorage.getItem('menuState')).lastValidMenuPath);
  }
  // console.log("currentDisplayPath.value--------------------------",isPathInMenu(route.path),getCurrentValidPath())
  initTabs();
  updateBreadcrumbs();
  updateMenuActiveState();

});

// 监听路由变化
watch(route, () => {
  useAppStoreInstance.initavatarUrlFn()
  updateMenuActiveState();
  updateBreadcrumbs();
  addTab();
  saveMenuState();
}, { immediate: true });
</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>