import { getAllDictionaryDataApi } from '@/api/system/systemData';
import { getUserPermissionsApi } from '@/api/system/user';
import { CommonStore } from '@/stores/common';

export const getAllDictDataFun = async (refresh?: boolean) => {
  const storageDictData = localStorage.getItem('TOTAL_DICTIONARY_DATA');
  if (storageDictData && !refresh) {
    CommonStore().setAllDictData(JSON.parse(storageDictData));
    // return; // TODO
  }
  const res: any = await getAllDictionaryDataApi({});
  if (res.code === 200) {
    const dictData: any = {};
    for (const key in res.data) {
      const arr: any = res.data[key].map((item: any) => {
        return {
          label: item.dictName,
          value: item.dictValue,
        };
      });
      const obj: any = Object.fromEntries(arr.map((item: any) => [item.value, item.label]));
      dictData[key] = {
        A: arr,
        O: obj,
      };
    }
    CommonStore().setAllDictData(dictData);
    localStorage.setItem('TOTAL_DICTIONARY_DATA', JSON.stringify(dictData));
  }
};

export const getUserPermissionsFun = () => {
  const params = {
    userId: localStorage.getItem('USER_ID'),
  };
  getUserPermissionsApi(params).then((res: any) => {
    const permissions = res.data ? JSON.stringify(res.data) : '';
    localStorage.setItem('USER_PERMISSIONS', permissions);
  });
};

/**
 * 数组去重
 * @param arr 须要去重的数组
 * @param type 1.普通数组去重2.对象类型数组去重
 * @returns  去重后的数组
 */
export const objectTypeArrayRemovesDuplicates = (arr: any[], type: number) => {
  if (type === 1) {
    return Array.from(new Set(arr));
  }
  if (type === 2) {
    return Array.from(
      new Set(
        arr.map((item1: any) => {
          return JSON.stringify(item1);
        })
      )
    ).map((item2: any) => {
      return JSON.parse(item2);
    });
  }
};

/**
 *
 * @param delayTime 延迟的时间
 */
export const delayTime = async (delayTime: number) => {
  await new Promise((resolve) => {
    setTimeout(() => {
      resolve('');
    }, delayTime);
  });
};
