<script setup lang="ts">
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '@/stores/modules/user'
import { CaretRight } from '@element-plus/icons-vue'

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

const isCollapse = defineModel<boolean>()

const menuList = ref()
watch(
  () => userStore.username,
  () => {
    getMenuList()
  }
)
const getMenuList = () => {
  $api.getMenuList().then((res) => {
    if (res.code === 200) {
      menuList.value = res.data
    }
  })
}
getMenuList()
//监听窗口大小
const handler = () => {
  return (() => {
    let screenWidth = document.body.clientWidth
    if (screenWidth < 1400) {
      isCollapse.value = true
    } else {
      isCollapse.value = false
    }
  })()
}
handler()

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

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

// 判断是否允许跳转
const isAllowJump = (path: any) => {
  // 判断是否登录
  if (!whiteList.includes(path) && !localStorage.getItem('username')) {
    ElMessage.warning({
      message: 'Please log in to use this feature.',
      grouping: true
    })
    if (route.name !== 'Public Tracking') {
      router.push({
        name: 'Login'
      })
    }
    activeMenu.value = route.path // 保持选中状态不变
    return false
  }
  return true
}
// 路由后置守卫
router.afterEach(() => {
  activeMenu.value = (route.meta?.activeMenu as string) || route.path
})
const isVisible = ref(false)
const emits = defineEmits(['changeVisible'])
// 路由跳转函数
const changeRouter = (path: any) => {
  if (sessionStorage.getItem('searchTableQeury')) {
    sessionStorage.removeItem('searchTableQeury')
  }
  if (sessionStorage.getItem('searchTableQeuryTracking')) {
    sessionStorage.removeItem('searchTableQeuryTracking')
  }
  if (sessionStorage.getItem('clickParams')) {
    sessionStorage.removeItem('clickParams')
    sessionStorage.removeItem('reportList')
    sessionStorage.removeItem('tagsList')
  }
  sessionStorage.removeItem('trackingTablePageInfo')
  sessionStorage.removeItem('bookingTablePageInfo')
  isVisible.value = false
  emits('changeVisible', isVisible.value)
  isVisible.value = false
  let toPath = path
  if (path === '/tracking' && !localStorage.getItem('username')) {
    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()

// 友情链接
const activeName = ref('1')
// const blogrollList = ref([
//   {
//     icon: () => import('./images/flag.png'),
//     title: 'Kerry Siam Seaport Web Service',
//     link: 'https://www.kerrysiamseaport.com/'
//   }
// ])

const jumpLink = (link: string) => {
  window.open(link, '_blank')
}
</script>

<template>
  <div class="left-section">
    <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' || route.path === '/reset-password'
          }"
          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="blogroll" :class="{ collapse: isCollapse }">
      <el-collapse v-model="activeName" accordion>
        <el-collapse-item title="REGIONAL SOLUTIONS" name="1" :icon="CaretRight">
          <div class="blogroll-content">
            <div class="blogroll-item" @click="jumpLink('https://www.kerrysiamseaport.com/')">
              <img
                style="height: 16px; width: 16px; margin-right: 4px"
                src="./images/flag.png"
                alt="string"
              />
              <span class="title">Kerry Siam Seaport Web Service</span>
            </div>
          </div>
        </el-collapse-item>
      </el-collapse>
    </div>
    <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>
  </div>
</template>

<style lang="scss" scoped>
.left-section {
  display: flex;
  flex-direction: column;
  height: calc(100% - 64px);
}
.layout-menu {
  flex: 1;
  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;
  & > span {
    color: var(--color-theme);
  }
}
.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;
  & > span {
    color: var(--color-neutral-1) !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;
  }
}

.blogroll {
  position: relative;
  &.collapse {
    display: none;
  }
  :deep(.el-collapse) {
    border-top: none;
    .el-collapse-item__arrow {
      color: #b5b9bf;
      align-self: center;
    }
  }
  :deep(.el-collapse-item__header) {
    align-items: normal;
    position: sticky;
    top: 1px;
    height: 40px;
    line-height: 42px;
    padding: 0 12px;
    overflow: hidden;
    white-space: nowrap;
    font-weight: 700;
  }
}
.blogroll-content {
  max-height: 180px;
  padding: 0 8px;
  overflow: auto;
  .blogroll-item {
    height: 40px;
    margin-top: 4px;
    padding: 0 8px;
    line-height: 40px;
    font-size: 12px;
    cursor: pointer;
    overflow: hidden;
    white-space: nowrap;
    transition: all 0.3s;
    .font_family {
      margin-right: 4px;
    }
    span {
      vertical-align: middle;
    }

    &:hover {
      background-color: var(--color-mune-active-bg);
      border-radius: 6px;
      cursor: pointer;
    }
  }
}
</style>
