import {BaseResultContent} from '@models';
import {userStore} from '@stores';
import {E2E_NETWORK_URL, NETWORK_ERROR_TIPS, NETWORK_URL} from '@utils';
import {message} from 'antd';
import axios from 'axios';

const http = axios.create({
  baseURL: process.env.IS_E2E ? E2E_NETWORK_URL : NETWORK_URL,
  headers: {
    'Content-Type': 'application/json',
    'Cache-Control': 'no-cache',
  },
  timeout: 5000,
});

const exportReg = /export/i;

http.interceptors.request.use(function(config) {
  if (config?.url) {
    const isExport = exportReg.test(config.url);
    isExport && (config.responseType = 'blob');
  }

  const token = userStore.getState().token;
  config.headers && (config.headers.token = token);

  return config;
});

export async function request<T, R extends BaseResultContent<any>>(options: {
  method: 'POST' | 'GET' | 'PUT' | 'DELETE';
  url: string;
  data?: T;
  skipError?: boolean;
}) {
  const {data, skipError, method, url} = options;

  let res: BaseResultContent<any>;
  const useData = method !== 'GET' && method !== 'DELETE';

  try {
    const result = await http.request<R>({
      method,
      url,
      data: useData ? data : void 0,
      params: !useData ? data : void 0,
    });

    res = result.data;

    if (res.msg !== '200' && !skipError) message.error(res.errMsg);
  } catch (error) {
    res = {msg: '510', errMsg: NETWORK_ERROR_TIPS};

    if (!skipError) message.error(res.errMsg);
  }

  return res;
}
