import type { SysConfigInfo, UserInfo } from '@vben/types';

export const MAX_ORGANIZATION_LEVEL = 9;

export function normalizeOrganizationConfig(config?: null | Partial<SysConfigInfo>) {
  const level = Number(config?.currentOrganizationDefaultLevel);
  const workflowLevel = Number(config?.workflowDepartmentDisplayLevel);
  return {
    showRootOrganizationName: Number(config?.showRootOrganizationName) === 0 ? 0 : 1,
    currentOrganizationDefaultLevel: Number.isInteger(level) && level >= 0 && level <= MAX_ORGANIZATION_LEVEL ? level : 0,
    workflowDepartmentDisplayLevel: Number.isInteger(workflowLevel) && workflowLevel >= 0 && workflowLevel <= MAX_ORGANIZATION_LEVEL ? workflowLevel : 0,
  };
}

function getOrganizationAtLevel(id: string, organizationList: any[], level: number): string {
  if (!level) return id;
  const organization = organizationList.find((item) => item.id === id);
  const path = organization?.treeId;
  const ids = Array.isArray(path) ? path : typeof path === 'string' ? path.split(',') : [];
  const validIds = ids.map((item) => String(item).trim()).filter(Boolean);
  if (!validIds.length || validIds.at(-1) !== id) return id;
  return validIds[Math.min(level, validIds.length) - 1] || id;
}

export function resolveCurrentOrganizationDefaultIds(user: null | Partial<UserInfo> | undefined, level: number, multiple: boolean): string | string[] {
  const organizationList = Array.isArray(user?.organizeList) ? user.organizeList : [];
  if (multiple) {
    const ids = Array.isArray(user?.organizeIds) ? user.organizeIds : [];
    return [...new Set(ids.filter(Boolean).map((id) => getOrganizationAtLevel(id, organizationList, level)))];
  }
  const id = user?.organizeId;
  return id ? getOrganizationAtLevel(id, organizationList, level) : '';
}

export function formatOrganizationDisplayName(namePath: string | undefined, idPath: string | string[] | undefined, showRoot: number, level = 0): string {
  if (!namePath) return '';
  const names = namePath.split('/');
  const ids = Array.isArray(idPath) ? idPath : typeof idPath === 'string' ? idPath.split(',') : [];
  if (names.length <= 1 || ids.length <= 1 || names.length !== ids.length) return namePath;
  const start = Math.max(Number.isInteger(level) && level > 0 ? names.length - level : 0, showRoot === 0 ? 1 : 0);
  return names.slice(start).join('/');
}
