<script setup lang="ts">
import { useRoute, useRouter } from 'vue-router'

const route = useRoute()
const router = useRouter()

const isCollapse = defineModel<boolean>()
const menuList = [
  {
    index: '1',
    label: 'Dashboard',
    icon: 'icon_data_fill_b',
    path: '/dashboard'
  },
  // {
  //   index: '2',
  //   label: 'Quote',
  //   icon: 'icon_quote__fill_b',
  //   path: '/booking/detail'
  // },
  {
    index: '3',
    label: 'Booking',
    icon: 'icon_booking__fill_b',
    path: '/booking'
  },
  {
    index: '4',
    label: 'Tracking',
    icon: 'icon_tracking__fill_b',
    path: '/tracking'
  },
  // {
  //   index: '5',
  //   label: 'Report',
  //   icon: 'icon_report__fill_b',
  //   path: '/tracking/detail'
  // },
  {
    index: '6',
    label: 'System Management',
    icon: 'icon_system__management_fill_b',
    path: '/test5',
    type: 'list',
    children: [
      // {
      //   index: '5-1',
      //   label: 'Account Management',
      //   path: '/public-tracking'
      // },
      // {
      //   index: '5-2',
      //   label: 'Permission Management',
      //   path: '/public-tracking/detail'
      // },
      // {
      //   index: '5-3',
      //   label: 'System Configuration',
      //   path: '/login'
      // },
      {
        index: '5-4',
        label: 'Operation Log',
        path: '/Operationlog'
      }
    ]
  }
]

//监听窗口大小
const handler = () => {
  return (() => {
    let screenWidth = document.body.clientWidth
    let screenHeight = document.body.clientHeight
    if (screenWidth < 1400) {
      isCollapse.value = true
    } else {
      isCollapse.value = false
    }
  })()
}
const listeningWindow = () => {
  window.addEventListener('resize', handler)
}

const unListeningWindow = () => {
  window.removeEventListener('resize', handler)
}

watchEffect(() => {
  listeningWindow()
})

onUnmounted(() => {
  unListeningWindow()
})

const activeMenu = ref()
activeMenu.value = (route.meta?.activeMenu as string) || route.path

const getAllMenuPaths = (menuList: any) => {
  let paths: any = []
  menuList.forEach((item: any) => {
    paths.push(item.path) // 添加主菜单路径
    if (item.children && item.children.length > 0) {
      // 递归添加子菜单路径
      paths = paths.concat(getAllMenuPaths(item.children))
    }
  })
  return paths
}
// 获取所有菜单项的路径（包括子菜单）
const menuPaths = getAllMenuPaths(menuList)

// 未登录白名单
const whiteList = ['/login', '/public-tracking', '/public-tracking/detail']

// 判断是否允许跳转
const isAllowJump = (path: any) => {
  // 判断是否登录
  if (!whiteList.includes(path) && !localStorage.getItem('token')) {
    ElMessage.warning('Please log in to use this feature.')
    activeMenu.value = route.path // 保持选中状态不变
    return false
  }
  return true
}
// 路由后置守卫
router.afterEach(() => {
  activeMenu.value = (route.meta?.activeMenu as string) || route.path
})

// 路由跳转函数
const changeRouter = (path: any) => {
  let toPath = path
  if (path === '/tracking' && !localStorage.getItem('token')) {
    toPath = '/public-tracking'
  }

  // 如果允许跳转，执行跳转
  if (isAllowJump(toPath)) {
    router.push(toPath)
  } else {
    // 如果不允许跳转，保持当前 activeMenu 不变
    nextTick(() => {
      activeMenu.value = (route.meta?.activeMenu as string) || route.path // 确保菜单栏选中状态为当前路径
    })
  }
}

const handleCollapseClick = () => {
  isCollapse.value = !isCollapse.value
}
const menuRef = ref()
</script>

<template>
  <el-menu
    ref="menuRef"
    class="layout-menu"
    @select="changeRouter"
    :default-active="activeMenu"
    :collapse="isCollapse"
  >
    <template v-for="item in menuList" :key="item.index">
      <el-menu-item
        :class="{ 'clear-active-style': route.path === '/login' }"
        v-if="item.type !== 'list'"
        :index="item.path"
      >
        <span class="font_family" :class="[`icon-${item.icon}`]"></span>
        <template #title>{{ item.label }}</template>
      </el-menu-item>
      <el-sub-menu v-else :index="item.path">
        <template #title>
          <div class="font_family" style="font-size: 16px" :class="[`icon-${item.icon}`]"></div>
          <span>{{ item.label }}</span>
        </template>
        <template v-for="childrenItem in item.children" :key="childrenItem.index">
          <el-menu-item :index="childrenItem.path">{{ childrenItem.label }}</el-menu-item>
        </template>
      </el-sub-menu>
    </template>
  </el-menu>
  <div class="collapse-icon">
    <div @click="handleCollapseClick">
      <span
        :style="{ transform: isCollapse ? 'rotate(0deg)' : 'rotate(180deg)' }"
        class="font_family icon-icon_menu_collapse_b"
      ></span>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.layout-menu {
  height: calc(100% - 120px);
  border-bottom: 1px solid var(--color-border);
  border-right: none;
  .font_family {
    margin-left: 4px;
    margin-right: 8px;
  }
}
.collapse-icon {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  height: 56px;
  padding-right: 10px;
  div {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 42px;
    height: 100%;
    cursor: pointer;
  }
}
.el-menu-item.is-active {
  background-color: var(--color-mune-active-bg);
  color: var(--color-theme);
  font-weight: 700;
}
.el-menu-item {
  height: 40px;
  margin: 0 12px 2px;
  padding-left: 8px !important;
  border-radius: 6px;
  &:hover {
    background-color: var(--color-mune-active-bg);
  }
  :deep(.el-menu-tooltip__trigger) {
    padding-left: 8px;
  }
}
li.clear-active-style {
  background-color: transparent !important;
  color: var(--color-neutral-1) !important;
  font-weight: normal !important;
}

:deep(.el-sub-menu__title) {
  height: 40px;
  margin: 0 12px;
  padding-left: 8px !important;
  line-height: 40px;
  &:hover {
    background-color: var(--color-mune-active-bg);
  }
}
.el-sub-menu {
  margin-bottom: 2px;
  .el-menu-item {
    padding-left: 36px !important;
  }
}
</style>
