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

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);
  });
};

export const getRoleDisciplineFun = async () => {
  const params = {
    paramName: 'ROLE_DISCIPLINE',
  };
  const res: any = await querySystemParamConfigureApi(params);
  if (res.code === 200) {
    localStorage.setItem('ROLE_DISCIPLINE', JSON.stringify(res.data.values));
  }
};

/**
 * 数组去重
 * @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);
  });
};

const win: any = window;
export const jumpPage = (location: any) => {
  if (win.__POWERED_BY_WUJIE__) {
    if (typeof location === 'object') {
      location.path = `/spdm${location.path}`;
    } else {
      location = `/spdm${location}`;
    }
    // 在无界微服务内部署
    win.$wujie?.props.jump(location);
  } else {
    // 独立部署
    router.push(location);
  }
};

const defaultRateData: any = {
  project: {}, // 项目列表
  user: {}, // 人员列表
};
const rateObjData = JSON.parse(
  localStorage.getItem('DATA_USE_RATE') || JSON.stringify(defaultRateData)
);
export const dataUseRate = (id: any, mode: any) => {
  const rateData = rateObjData[mode];
  if (!rateData[id]) {
    rateData[id] = 0;
  }
  // 每触发一次change 权重增加一次
  rateData[id] = rateData[id] + 1;
  defaultRateData[mode] = rateData;
  localStorage.setItem('DATA_USE_RATE', JSON.stringify(defaultRateData));
};
export const dataUserRateSort = (key: any, list: any, mode: any) => {
  const rateData = rateObjData[mode];
  // 更具权重重新排序
  const data = list.sort((x: any, y: any) => {
    const weightX = rateData[x[key]] ?? 0;
    const weightY = rateData[y[key]] ?? 0;
    return weightY - weightX;
  });
  return data;
};
