import { useUserStore } from '@/store';
import { reactive } from 'vue';
import { useRoute } from 'vue-router';

export default function usePermission() {
  const userStore = useUserStore();
  const route = useRoute();
  const perm = reactive({});

  function checkPrivilege(type, field, routeAlias = null) {
    let routerName = routeAlias || route.meta.alias;
    const keys = field
      .split(',')
      .map((item) => `${routerName}_${type}_${item}`);

    return keys.some((key) => userStore.finePermissionIds.includes(key));
  }

  function updatePerm() {
    const routeAlias = route.meta.alias + '_';
    const validKeys = userStore.finePermissionIds
      .filter((item) => item.startsWith(routeAlias))
      .map((item) => item.replace(routeAlias, ''));

    validKeys.forEach((key) => {
      perm[key] = true;
    });
  }
  updatePerm();

  return {
    checkPrivilege,
    updatePerm,
    perm,
  };
}
