import { defineStore } from "pinia";
import {
  type cacheType,
  store,
  ascending,
  getKeyList,
  filterTree,
  constantMenus,
  filterNoPermissionTree,
  formatFlatteningRoutes
} from "../utils";
import { useMultiTagsStoreHook } from "./multiTags";

export const usePermissionStore = defineStore("pure-permission", {
  state: () => ({
    // 静态路由生成的菜单
    constantMenus,
    // 整体路由生成的菜单（静态、动态）
    wholeMenus: [],
    // 整体路由（一维数组格式）
    flatteningRoutes: [],
    // 缓存页面keepAlive
    cachePageList: []
  }),
  actions: {
    /** 组装整体路由生成的菜单 */
    handleWholeMenus(routes: any[]) {
      // 合并静态和动态路由，按 path 去重（动态路由 backstage 优先）
      const merged = this.constantMenus.concat(routes);
      console.log("[handleWholeMenus] constantMenus ranks:",
        this.constantMenus.map((m: any) => `${m.meta?.title}(${m.meta?.rank},${m.path})`));
      console.log("[handleWholeMenus] routes ranks:",
        routes.map((m: any) => `${m.meta?.title}(${m.meta?.rank},${m.path})`));
      const pathMap = new Map<string, any>();
      for (const r of merged as any[]) {
        if (!pathMap.has(r.path)) {
          pathMap.set(r.path, r);
        } else if (r.meta?.backstage) {
          // 后端路由覆盖静态路由时，若后端无 rank 则继承静态的 rank
          const existing = pathMap.get(r.path);
          if (r.meta?.rank == null && existing?.meta?.rank != null) {
            console.log(`[handleWholeMenus] inherit rank: ${r.path} ← ${existing.meta.rank}`);
            r.meta.rank = existing.meta.rank;
          }
          pathMap.set(r.path, r);
        }
      }
      const deduplicated = Array.from(pathMap.values());
      this.wholeMenus = filterNoPermissionTree(
        filterTree(ascending(deduplicated))
      );
      this.flatteningRoutes = formatFlatteningRoutes(
        this.constantMenus.concat(routes) as any
      );
    },
    /** 监听缓存页面是否存在于标签页，不存在则删除 */
    clearCache() {
      let cacheLength = this.cachePageList.length;
      const nameList = getKeyList(useMultiTagsStoreHook().multiTags, "name");
      while (cacheLength > 0) {
        nameList.findIndex(v => v === this.cachePageList[cacheLength - 1]) ===
          -1 &&
          this.cachePageList.splice(
            this.cachePageList.indexOf(this.cachePageList[cacheLength - 1]),
            1
          );
        cacheLength--;
      }
    },
    cacheOperate({ mode, name }: cacheType) {
      const delIndex = this.cachePageList.findIndex(v => v === name);
      switch (mode) {
        case "refresh":
          this.cachePageList = this.cachePageList.filter(v => v !== name);
          this.clearCache();
          break;
        case "add":
          this.cachePageList.push(name);
          break;
        case "delete":
          delIndex !== -1 && this.cachePageList.splice(delIndex, 1);
          this.clearCache();
          break;
      }
    },
    /** 清空缓存页面 */
    clearAllCachePage() {
      this.wholeMenus = [];
      this.cachePageList = [];
    }
  }
});

export function usePermissionStoreHook() {
  return usePermissionStore(store);
}
