import api from "@/axios";
import { isEmpty, isNull } from "lodash-es";

type EnumType =
  | "EnableStatus"
  | "AnnouncementType"
  | "FileType"
  | "IndustryType"
  | "IsEnable"
  | "IsOrNot"
  | "MenuType"
  | "ProjectStatus"
  | "Sex";

export const initEnums = () => {
  api
    .get<Record<EnumType, SelectNodeVo<any>[]>>("/common/enums")
    .then((resp) => {
      sessionStorage.setItem("enumsMap", JSON.stringify(resp.data));
    });
};

export const enumSelectNodes = <T, E = any>(
  enumType: EnumType
): SelectNodeVo<T, E>[] =>
  JSON.parse(sessionStorage.getItem("enumsMap") as string)?.[enumType];

export const defaultAllEnumSelectNodes = <T, E = any>(
  enumType: EnumType
): SelectNodeVo<T, E>[] => {
  return [
    {
      value: null as T,
      label: "全部",
    },
    ...enumSelectNodes<T, E>(enumType),
  ];
};
export const getEnumByValue = <T, E = any>(
  enumType: EnumType,
  value: T
): null | SelectNodeVo<T, E> => {
  const enumsMap: Record<EnumType, SelectNodeVo<T, E>[]> = JSON.parse(
    sessionStorage.getItem("enumsMap") as string
  );
  if (isNull(enumsMap)) {
    return null;
  }
  const enumList = enumsMap[enumType];
  if (isEmpty(enumList)) {
    return null;
  }
  for (let i = 0; i < enumList.length; i++) {
    if (value === enumList[i].value) {
      return enumList[i];
    }
  }
  return null;
};

export const getEnumLabelByValue = <T>(
  enumType: EnumType,
  value: T
): string => {
  const enums = getEnumByValue(enumType, value);
  if (isNull(enums)) {
    return "-";
  }
  return enums.label;
};
