import type { TabItem } from '@/stores/modules/tabbar';

import { computed, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';

import { useTabbarStore } from '@/stores';

/**
 * Tabbar 操作 Hook
 */
export function useTabbar() {
  const router = useRouter();
  const route = useRoute();
  const tabbarStore = useTabbarStore();

  /**
   * 当前激活的标签页路径
   */
  const currentActive = computed(() => tabbarStore.activeTab);

  /**
   * 标签页列表
   */
  const currentTabs = computed(() => tabbarStore.tabs);

  /**
   * 点击标签页
   */
  const handleClick = (tab: TabItem) => {
    tabbarStore.setActiveTab(tab.path);
    router.push(tab.path);
  };

  /**
   * 关闭标签页
   */
  const handleClose = (path: string) => {
    tabbarStore.closeTab(path);
  };

  /**
   * 固定/取消固定标签页
   */
  const handleUnpin = (tab: TabItem) => {
    tabbarStore.toggleAffixTab(tab.path);
  };

  /**
   * 关闭其他标签页
   */
  const closeOtherTabs = (path?: string) => {
    tabbarStore.closeOtherTabs(path);
  };

  /**
   * 关闭所有标签页
   */
  const closeAllTabs = () => {
    tabbarStore.closeAllTabs();
  };

  /**
   * 关闭右侧标签页
   */
  const closeRightTabs = (path?: string) => {
    tabbarStore.closeRightTabs(path);
  };

  /**
   * 初始化固定标签页
   */
  const initAffixTabs = () => {
    const routes = router.getRoutes();
    tabbarStore.initAffixTabs(routes);
  };

  /**
   * 监听路由变化，自动添加标签页
   */
  watch(
    () => route.path,
    () => {
      if (route.name) {
        tabbarStore.addTab(route);
      }
    },
    { immediate: true },
  );

  /**
   * 初始化固定标签页
   */
  watch(
    () => router.getRoutes(),
    () => {
      initAffixTabs();
    },
    { immediate: true },
  );

  return {
    currentActive,
    currentTabs,
    handleClick,
    handleClose,
    handleUnpin,
    closeOtherTabs,
    closeAllTabs,
    closeRightTabs,
    initAffixTabs,
  };
}