import router from '@/router';
import { defineStore } from 'pinia';
import { getUrlWithParams } from '@/utils';
import { useKeepAliveStore } from './keepAlive';
import piniaPersistConfig from '@/stores/helper/persist';

// const keepAliveStore = useKeepAliveStore();

export const useTabsStore = defineStore({
  id: 'admin-tabs',
  state: () => ({
    tabsMenuList: [],
  }),
  actions: {
    // Add Tabs
    async addTabs(tabItem) {
      if (this.tabsMenuList.every((item) => item.path !== tabItem.path)) {
        this.tabsMenuList.push(tabItem);
      }
      const keepAliveStore = useKeepAliveStore();
      // add keepalive
      if (!keepAliveStore.keepAliveName.includes(tabItem.name) && tabItem.isKeepAlive) {
        keepAliveStore.addKeepAliveName(tabItem.path);
      }
    },
    // Remove Tabs
    async removeTabs(tabPath, isCurrent = true) {
      if (isCurrent) {
        this.tabsMenuList.forEach((item, index) => {
          if (item.path !== tabPath) return;
          const nextTab = this.tabsMenuList[index + 1] || this.tabsMenuList[index - 1];
          if (!nextTab) return;
          router.push(nextTab.path);
        });
      }
      const keepAliveStore = useKeepAliveStore();
      // remove keepalive
      const tabItem = this.tabsMenuList.find((item) => item.path === tabPath);
      tabItem?.isKeepAlive && keepAliveStore.removeKeepAliveName(tabItem.path);
      // set tabs
      this.tabsMenuList = this.tabsMenuList.filter((item) => item.path !== tabPath);
    },
    // Close Tabs On Side
    async closeTabsOnSide(path, type) {
      const currentIndex = this.tabsMenuList.findIndex((item) => item.path === path);
      if (currentIndex !== -1) {
        const range =
          type === 'left' ? [0, currentIndex] : [currentIndex + 1, this.tabsMenuList.length];
        this.tabsMenuList = this.tabsMenuList.filter((item, index) => {
          return index < range[0] || index >= range[1] || !item.close;
        });
      }
      const keepAliveStore = useKeepAliveStore();
      // set keepalive
      const KeepAliveList = this.tabsMenuList.filter((item) => item.isKeepAlive);
      keepAliveStore.setKeepAliveName(KeepAliveList.map((item) => item.path));
    },
    // Close MultipleTab
    async closeMultipleTab(tabsMenuValue) {
      this.tabsMenuList = this.tabsMenuList.filter((item) => {
        return item.path === tabsMenuValue || !item.close;
      });
      const keepAliveStore = useKeepAliveStore();
      // set keepalive
      const KeepAliveList = this.tabsMenuList.filter((item) => item.isKeepAlive);
      keepAliveStore.setKeepAliveName(KeepAliveList.map((item) => item.path));
    },
    // Set Tabs
    async setTabs(tabsMenuList) {
      this.tabsMenuList = tabsMenuList;
    },
    // Set Tabs Title
    async setTabsTitle(title) {
      this.tabsMenuList.forEach((item) => {
        if (item.path == getUrlWithParams()) item.title = title;
      });
    },
  },
  persist: piniaPersistConfig('admin-tabs'),
});
