import { defineStore } from "pinia";
export const useTagsStore = defineStore("tags", {
  state: () => ({
    list: [],
    caches: []
  }),
  actions: {
    add(route) {
      if (route.meta.public || route.path === "/login")
        return;
      const title = String(route.meta.title || route.name || route.path);
      const componentName = typeof route.meta.componentName === "string" ? route.meta.componentName : undefined;
      const keepAlive = route.meta.keepAlive !== false;
      if (componentName && keepAlive) {
        this.addCache(componentName);
      }
      const exists = this.list.find((t) => t.path === route.path);
      if (exists) {
        exists.fullPath = route.fullPath;
        exists.title = title;
        exists.componentName = componentName;
        exists.keepAlive = keepAlive;
        return;
      }
      this.list.push({
        path: route.path,
        fullPath: route.fullPath,
        title,
        name: route.name,
        componentName,
        keepAlive
      });
    },
    addCache(name) {
      if (!name || this.caches.includes(name))
        return;
      this.caches.push(name);
    },
    removeCache(name) {
      if (!name)
        return;
      this.caches = this.caches.filter((c) => c !== name);
    },
    remove(path) {
      const i = this.list.findIndex((t) => t.path === path);
      if (i < 0)
        return;
      const [tag] = this.list.splice(i, 1);
      const still = tag?.componentName && this.list.some((t) => t.componentName === tag.componentName);
      if (tag?.componentName && !still) {
        this.removeCache(tag.componentName);
      }
    },
    closeOthers(path) {
      const keep = this.list.filter((t) => t.path === path || t.path === "/");
      this.list = keep;
      this.caches = keep.filter((t) => t.keepAlive && t.componentName).map((t) => t.componentName).filter((n, i, arr) => arr.indexOf(n) === i);
    },
    clear() {
      this.list = this.list.filter((t) => t.path === "/");
      this.caches = [];
    }
  }
});
