import { defineStore } from 'pinia';
import { useSessionStorage } from './index';
import { some, delArrObj, findIndex } from '../utils';
const PAGE_STORE_KEY = 'MAIN_PAGES';
const session = useSessionStorage();

interface RouterType {
  fullPath: string;
  path: string;
  hash?: string;
  href?: string;
  matched?: any[];
  meta?: any;
  name?: string;
  params?: any;
  query?: any;
  redirectedFrom?: any;
  [proppName: string]: any;
}

const usePageStore = defineStore(PAGE_STORE_KEY, {
  state: () => {
    const routersItem = JSON.parse(session.getItem(PAGE_STORE_KEY) as string);
    return {
      activeRouter: (routersItem?.activeRouter as RouterType) || null,
      tabRouterList: (routersItem?.tabRouterList as RouterType[]) || [],
      allPageKeys: routersItem?.allPageKeys || [],
    };
  },
  getters: {},
  actions: {
    addRoute(route: RouterType) {
      const item: RouterType = {
        fullPath: route.fullPath,
        path: route.path,
        name: route.name,
        meta: route.meta,
        params: route.params,
        query: route.query,
      };
      this.activeRouter = item;
      const flag = some(this.tabRouterList, (item: RouterType) => {
        return item.fullPath === route.fullPath;
      });
      if (!flag) {
        this.tabRouterList.push(item);
        if (item.meta.keepalive) {
          this.allPageKeys.push(route.name);
        }
      }
      this.saveToSession();
    },
    removePage(path: string) {
      const index = findIndex(this.tabRouterList, ['path', path]);
      if (path === this.activeRouter.path) {
        if (index > 0) {
          this.activeRouter = this.tabRouterList[index - 1];
        } else {
          this.activeRouter = this.tabRouterList[index + 1];
        }
      }
      this.allPageKeys.splice(index, 1);
      delArrObj(this.tabRouterList, { path: path });
      this.saveToSession();
    },
    saveToSession() {
      session.setItem(PAGE_STORE_KEY, JSON.stringify(this.$state));
    },
  },
});
export type { RouterType };
export { usePageStore, PAGE_STORE_KEY };
