import {getBaseUrl, isArray} from '~/utils/tool';
import {MODULES_API_URL, TENANT_ID} from "~/config";

type FetchType = typeof $fetch;
export type FetchOptions = Parameters<FetchType>[1];

export const useClientRequest = <T = unknown>(url: string, opts?: FetchOptions) => {
  // 配置信息
  const runtimeConfig = useRuntimeConfig();
  // 请求接口
  const baseUrl = ref('');
  baseUrl.value = runtimeConfig.public.apiServer;
  // 开发环境
  if(process.env.NODE_ENV === 'development'){
    baseUrl.value = `http://127.0.0.1:9002/api`
  }
  // 登录凭证token
  const token = useToken();
  const _token = localStorage.getItem('token');
  if(_token){
    token.value = _token
  }

  const defaultOptions: FetchOptions = {
    baseURL: baseUrl.value,
    onRequest({ options }) {
      // @ts-ignore
      options.headers = (options.headers || {}) as { [key: string]: string };
      if (token.value) {
        // @ts-ignore
        options.headers.Authorization = token.value;
      }
    },
    onResponse({ response }) {
      if (+response.status === 0 && +response._data.code !== 0) {
        ElMessage.error(response._data.message);
      }
    },
    onResponseError({ response }) {
      ElMessage.error(isArray(response._data.data.message) ? response._data.data.message[0] : response._data.data.message);
    }
  };

  return $fetch<T>(runtimeConfig.public.apiServer + url, { ...defaultOptions, ...opts });
};
