87 lines
2.8 KiB
TypeScript
87 lines
2.8 KiB
TypeScript
import type { NdmPermissionResultVO, Station } from '@/apis';
|
||
import { NDM_PERMISSION_STORE_ID } from '@/constants';
|
||
import { PERMISSION_TYPE_NAMES, type PermissionType } from '@/enums';
|
||
import { useSettingStore, useStationStore } from '@/stores';
|
||
import { defineStore } from 'pinia';
|
||
import { computed, ref } from 'vue';
|
||
import { objectEntries } from '@vueuse/core';
|
||
|
||
type Permissions = Record<Station['code'], PermissionType[]>;
|
||
|
||
export const usePermissionStore = defineStore(
|
||
NDM_PERMISSION_STORE_ID,
|
||
() => {
|
||
const stationStore = useStationStore();
|
||
const settingStore = useSettingStore();
|
||
|
||
const permissionRecords = ref<NdmPermissionResultVO[] | null>(null);
|
||
|
||
const permissions = computed<Permissions>(() => {
|
||
const result: Permissions = {};
|
||
|
||
// 如果启用了mock用户,则授予所有车站全部权限
|
||
if (settingStore.mockUser) {
|
||
stationStore.stations.forEach((station) => {
|
||
result[station.code] = [...objectEntries(PERMISSION_TYPE_NAMES).map(([permType]) => permType)];
|
||
});
|
||
return result;
|
||
}
|
||
|
||
const records = permissionRecords.value;
|
||
|
||
// 如果权限记录不存在,则不做权限配置
|
||
if (!records) return result;
|
||
|
||
// 如果该用户没有任何权限记录,则开放所有权限,否则根据记录配置权限
|
||
if (records.length === 0) {
|
||
stationStore.stations.forEach((station) => {
|
||
result[station.code] = [...objectEntries(PERMISSION_TYPE_NAMES).map(([permType]) => permType)];
|
||
});
|
||
} else {
|
||
stationStore.stations.forEach((station) => {
|
||
result[station.code] = [];
|
||
const stationPermRecords = records.filter((record) => record.stationCode === station.code);
|
||
if (stationPermRecords.length === 0) return;
|
||
stationPermRecords.forEach(({ type: permType }) => {
|
||
if (!permType) return;
|
||
result[station.code]?.push(permType);
|
||
});
|
||
});
|
||
}
|
||
|
||
return result;
|
||
});
|
||
|
||
// 按权限对车站进行分类
|
||
const stations = computed(() => {
|
||
const result: Partial<Record<PermissionType, Station[]>> = {};
|
||
// 按原始的车站顺序进行遍历,保持显示顺序不变
|
||
stationStore.stations.forEach((station) => {
|
||
const permissionTypes = permissions.value[station.code];
|
||
if (!permissionTypes) return;
|
||
permissionTypes.forEach((permissionType) => {
|
||
if (!result[permissionType]) result[permissionType] = [];
|
||
result[permissionType].push(station);
|
||
});
|
||
});
|
||
return result;
|
||
});
|
||
|
||
const setPermRecords = (records: NdmPermissionResultVO[]) => {
|
||
permissionRecords.value = records;
|
||
};
|
||
|
||
return {
|
||
permissionRecords,
|
||
|
||
permissions,
|
||
stations,
|
||
|
||
setPermRecords,
|
||
};
|
||
},
|
||
{
|
||
persist: true,
|
||
},
|
||
);
|