import { defineStore } from 'pinia';
import { constantRoutes, notFoundRouter } from '@/router';
import { createAsyncRoutes, filterAsyncRoutes, filterKeepAlive } from '@/utils/router';
import { useUserStore } from '@/store/modules/user';
import { getTree } from '@/utils';
import { GenKey } from '@/config';

export const usePermissionStore = defineStore({
  id: GenKey('permissionStore'),
  state: () => ({
    // 路由
    routes: [],
    // 动态路由
    asyncRoutes: [],
    // 缓存路由
    cacheRoutes: {},
  }),
  getters: {
    permissionRoutes: (state) => {
      return state.routes;
    },
    keepAliveRoutes: (state) => {
      return filterKeepAlive(state.asyncRoutes);
    },
  },
  actions: {
    generateRoutes(roles) {
      return new Promise((resolve) => {
        // 在这判断是否有权限，哪些角色拥有哪些权限
        const UserStore = useUserStore();
        this.asyncRoutes = createAsyncRoutes(getTree(UserStore.getMenus()));
        let accessedRoutes;
        if (roles && roles.length && !roles.includes('admin')) {
          accessedRoutes = filterAsyncRoutes(this.asyncRoutes, roles);
        } else {
          accessedRoutes = this.asyncRoutes || [];
        }
        accessedRoutes = accessedRoutes.concat(notFoundRouter);
        this.routes = constantRoutes.concat(accessedRoutes);
        resolve(accessedRoutes);
      });
    },
    clearRoutes() {
      this.routes = [];
      this.asyncRoutes = [];
      this.cacheRoutes = [];
    },
    getCacheRoutes() {
      this.cacheRoutes = filterKeepAlive(this.asyncRoutes);
      return this.cacheRoutes;
    },
  },
});
