import type { AxiosRequestConfig } from 'axios';
import { http } from '../util/http';
import { isFunction, isPlainObject, isString } from 'lodash-es';
import { usePath } from '/nerv-lib/use/use-path';
import { RequestEnum } from '/@/enum/http-enum.ts';

export type HttpRequestConfig = AxiosRequestConfig;

export interface HttpRequest {
  api: string | HttpRequestConfig | Function;
  pathParams?: Recordable; // 获取动态路径
  params?: Recordable;
  paramsFilter?: Function;
  requestConfig?: HttpRequestConfig;
}

export function useApi() {
  const { getPath } = usePath();

  function httpRequest({
    api,
    params = {},
    pathParams,
    paramsFilter,
    requestConfig = {},
  }: HttpRequest) {
    if (!pathParams) {
      pathParams = params;
    }

    let url = undefined;
    if (isString(api)) {
      url = getPath(api, pathParams);
    } else if (isPlainObject(api)) {
      requestConfig = Object.assign(requestConfig, api);
      console.log('rrrrr', requestConfig);
      if (requestConfig?.url) {
        url = getPath(requestConfig.url, pathParams);
      }
    }
    if (paramsFilter) {
      params = paramsFilter(params);
    }

    if (RequestEnum[requestConfig?.method?.toLocaleUpperCase()] === 'GET') {
      if (!requestConfig.params) requestConfig.params = params;
    } else {
      if (!requestConfig.data) requestConfig.data = params;
    }

    if (isFunction(api)) {
      return api(params);
    } else {
      return http.request({
        ...requestConfig,
        url,
      });
    }
  }
  return { httpRequest };
}
