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(params: any) {
      const path = params.link;
      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];
        }
      }
      if (params.keepalive) {
        const pageKeyIndex = findIndex(this.allPageKeys, function (o) {
          return o === params.name;
        });
        if (pageKeyIndex !== -1) {
          this.allPageKeys.splice(pageKeyIndex, 1);
        }
      }
      delArrObj(this.tabRouterList, { path: path });
      this.saveToSession();
    },
    removeNotCurrentPage(params: any) {
      const path = params.link;
      if (params.keepalive) {
        this.allPageKeys = [params.name];
      } else {
        this.allPageKeys = [];
      }

      this.tabRouterList = this.tabRouterList.filter((item) => {
        return item.path === path;
      });
      this.activeRouter = this.tabRouterList[0];
      this.saveToSession();
    },
    removeAllPage() {
      this.activeRouter = {} as RouterType;
      this.allPageKeys = [];
      this.tabRouterList = [];
      this.saveToSession();
    },
    saveToSession() {
      session.setItem(PAGE_STORE_KEY, JSON.stringify(this.$state));
    },
  },
});
export type { RouterType };
export { usePageStore, PAGE_STORE_KEY };
