import {getAllDepartment, getAllRoleList, getAllStorage} from '@apis';
import {BaseResult} from '@models';
import {useQuery} from '@tanstack/react-query';

function useQueryOptions<T extends {id: number | string}>(
  fn: () => BaseResult<T[]>,
  findName: (state: T) => string,
  addAll: boolean,
) {
  const {data} = useQuery(
    [fn.name],
    async function() {
      const data = await fn();

      if (data.msg === '200') {
        const list = data.data.map(function(value) {
          return {label: findName(value), value: String(value.id)};
        });

        if (addAll)
          list.unshift({label: '全部', value: ''});

        return list;
      }

      return [];
    },
    {initialData: [], cacheTime: 1000 * 60 * 10},
  );

  return data;
}

export function useDepartmentOptions(addAll = false) {
  return useQueryOptions(
    getAllDepartment,
    state => state.departmentName,
    addAll,
  );
}

export function useStorageOptions(addAll = false) {
  return useQueryOptions(
    getAllStorage,
    state => state.storageLocationName,
    addAll,
  );
}

export function useRoleOptions(addAll = false) {
  return useQueryOptions(
    getAllRoleList,
    state => state.roleName,
    addAll,
  );
}
