import { defineStore } from "pinia";
import router from "@/router";
import { ref } from "vue";

export interface TabsMenuProps {
  icon: string;
  title: string;
  name: string;
  path: string;
  isKeepAlive: boolean;
  closable: boolean;
}

export const useTabsStore = defineStore(
  "tabs-store",
  () => {
    const tabList = ref<TabsMenuProps[]>([]);

    const addTab = (tabItem: TabsMenuProps) => {
      if (tabList.value.every((item) => item.path !== tabItem.path)) {
        tabList.value.push(tabItem);
      }
    };
    const closeTab = (tabPath: string, isCurrent: boolean = true) => {
      if (isCurrent) {
        tabList.value.forEach((item, index) => {
          if (item.path !== tabPath) return;
          const nextTab = tabList.value[index + 1] || tabList.value[index - 1];
          if (!nextTab) return;
          router.push(nextTab.path);
        });
      }
      tabList.value.splice(
        tabList.value.findIndex((i) => i.path === tabPath),
        1
      );
    };
    const closeMultipleTab = (tabPath?: string) =>
      (tabList.value = tabList.value.filter(
        (item) => item.path === tabPath || !item.closable
      ));
    const resetTab = () => {
      tabList.value = [];
    };
    const changeTabKeepAlive = (tabPath: string) => {
      tabList.value.forEach((e) => {
        if (e.path === tabPath) {
          e.isKeepAlive = !e.isKeepAlive;
        }
      });
    };

    return {
      tabList,
      addTab,
      closeTab,
      closeMultipleTab,
      resetTab,
      changeTabKeepAlive,
    };
  },
  {
    persist: {
      key: "tabs-store",
      storage: window.localStorage,
    },
  }
);
