//  Copyright (c) 2024 Huawei Technologies Co., Ltd.
//  openUBMC is licensed under Mulan PSL v2.
//  You can use this software according to the terms and conditions of the Mulan PSL v2.
//  You may obtain a copy of Mulan PSL v2 at:
//        #  http://license.coscl.org.cn/MulanPSL2
//  THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
//  EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
//  MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
//  See the Mulan PSL v2 for more details.
import useStore from '@/stores';
import { onBeforeRouteUpdate, useRouter } from 'vue-router';
import { ref, computed } from 'vue';

export function useLeftNav(title: string) {
  const $router = useRouter();
  let currentRoute = ref($router.currentRoute.value.fullPath);
  const pageTitle = title;
  const store = useStore();
  const mainMenus = store.state.menu.mainMenu;
  let navList: any = [];
  const pageItem = mainMenus.find((item: any) => {
    return item.label === pageTitle;
  });
  
  if (pageItem?.children) {
    navList = pageItem.children;
  }

  let openLeftNav = ref(true);

  // 点击导航栏
  const changeNav = function (item: any) {
    $router.push(item.router);
    currentRoute.value = item.router;
  };

  // 修改导航栏的展开与收起状态
  const changeLeftNavState = function () {
    openLeftNav.value = !openLeftNav.value;
  };

  const currentPageTitle = ref('');
  // 路由改变修改标题
  onBeforeRouteUpdate((to: any) => {
    currentPageTitle.value = navList.find((item: any) => {
      return to.path.indexOf(item.router) === 0;
    })?.label;
  });
  // 开始调用的时候初始化标题
  currentPageTitle.value = navList.find((item: any) => {
    return currentRoute.value.indexOf(item.router) === 0;
  })?.label;

  return {
    openLeftNav,
    pageTitle,
    currentPageTitle,
    navList,
    currentRoute,
    changeNav,
    changeLeftNavState,
  };
}