Files
im_manager/web/src/views/imTenantOptions.ts
T

89 lines
2.6 KiB
TypeScript

import { Ref } from 'vue';
import { List as TenantList } from '@/api/imTenant';
import { useUserStore } from '@/store/modules/user';
export interface ImTenantOption {
label: string;
value: number;
code?: string;
name?: string;
}
export function formatImTenantLabel(item: any): string {
const code = item?.code || item?.tenantCode || '';
const name = item?.name || item?.tenantName || '当前商户';
return code ? `${name} (${code})` : name;
}
export function getDefaultTenantValue(options: any[]) {
const defaultTenant = options.find(
(item) => item.code === 'default' || String(item.label || '').includes('(default)')
);
return defaultTenant?.value || options.find((item) => Number(item.value) > 0)?.value || 0;
}
export async function loadImTenantOptions(
target: Ref<ImTenantOption[]>,
params: Record<string, any> = { page: 1, perPage: 100 }
) {
const userStore = useUserStore();
const userInfo = { ...readTokenUserInfo(userStore.getToken), ...(userStore.getUserInfo as any) };
const boundTenantId = Number(userInfo?.tenantId || userInfo?.tenantID || 0);
if (!userStore.isCompanyDept) {
if (boundTenantId <= 0) {
target.value = [];
return target.value;
}
let tenant: any = null;
try {
const res = await TenantList({ ...params, id: boundTenantId, page: 1, perPage: 1 });
tenant = (res?.list || []).find((item) => Number(item.id) === boundTenantId);
} catch {
tenant = null;
}
target.value = [
tenant
? toTenantOption(tenant)
: {
label: formatImTenantLabel({
id: boundTenantId,
name: userInfo?.tenantName,
code: userInfo?.tenantCode,
}),
value: boundTenantId,
code: userInfo?.tenantCode,
name: userInfo?.tenantName,
},
];
return target.value;
}
const res = await TenantList(params);
target.value = (res?.list || []).map(toTenantOption);
return target.value;
}
function toTenantOption(item: any): ImTenantOption {
return {
label: formatImTenantLabel(item),
value: Number(item.id),
code: item.code,
name: item.name,
};
}
function readTokenUserInfo(token: string) {
try {
const payload = token.split('.')[1];
if (!payload) return {};
const normalized = payload.replace(/-/g, '+').replace(/_/g, '/');
const padded = normalized.padEnd(Math.ceil(normalized.length / 4) * 4, '=');
const binary = window.atob(padded);
const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
return JSON.parse(new TextDecoder().decode(bytes));
} catch {
return {};
}
}