// usePermissionStore.js
import { defineStore } from 'pinia';
import { asyncRouterMap, constantRouterMap } from '@/router';

export const usePermissionStore = defineStore('permission', {
  state: () => ({
    // routers: constantRouterMap,
    addRouters: [],
    activeMenu: 'first'
  }),
  
  actions: {
    async GenerateRoutes(data) {
      const { perms, needHandleWork } = data;

      if (needHandleWork) {
        const orderRouters = asyncRouterMap.filter(router => router.name === "order");
        if (orderRouters.length > 0) {
          orderRouters[0].children.forEach(ch => {
            needHandleWork.forEach(work => {
              if (work.menuName === ch.name)
                ch.meta.amount = work.amount;
            });
          });
        }
      }

      let accessedRouters;
      if (perms.includes('*')) {
        accessedRouters = asyncRouterMap;
      } else {
        accessedRouters = this.filterAsyncRouter(asyncRouterMap, perms);
      }
      this.setRouters(accessedRouters);
    },

    setRouters(routers) {
      this.addRouters = routers;
      this.routers = [...constantRouterMap, ...routers];
    },

    filterAsyncRouter(routes, perms) {
      const res = [];
      routes.forEach(route => {
        const tmp = { ...route };
        if (tmp.children) {
          tmp.children = this.filterAsyncRouter(tmp.children, perms);
          if (tmp.children && tmp.children.length > 0) {
            res.push(tmp);
          }
        } else {
          if (this.hasPermission(perms, tmp)) {
            res.push(tmp);
          }
        }
      });
      return res;
    },

    hasPermission(perms, route) {
      if (route.meta && route.meta.perms) {
        return perms.some(perm => route.meta.perms.includes(perm));
      } else {
        return true;
      }
    },

    async ReduceRemindsAmount(data) {
      const { reduce } = data;
      let routers = this.routers;
      routers.forEach(item => {
        if (item.name === "order") {
          item.children.forEach(ch => {
            if (ch.name === reduce.name)
              ch.meta.amount = ch.meta.amount - reduce.reduce;
          });
        }
      });
    },

    async ResetRemindsAmount(data) {
      const needHandleWork = data;
      if (needHandleWork) {
        let routers = this.routers;
        const orderRouters = routers.filter(router => router.name === "order");
        if (orderRouters.length > 0) {
          orderRouters[0].children.forEach(ch => {
            needHandleWork.forEach(work => {
              if (work.menuName === ch.name)
                ch.meta.amount = work.amount;
            });
          });
        }
      }
    }
  },
  persist: true
});