import axios from 'axios';
import { Notify } from 'quasar';

import appConfig from 'src/config/app';

const $axios = axios.create();

// 请求方法
const request = (options: any) => {
  const defaultOptins = {
    baseURL: appConfig.base_url,
    timeout: 30000,
  };
  const config = Object.assign(defaultOptins, options);
  return $axios(config);
};

// http request 拦截器
$axios.interceptors.request.use(
  (config: any) => {
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// http response 拦截器
$axios.interceptors.response.use(
  (response: any) => {
    return response;
  },
  async (error) => {
    let msg = 'Unknown Error';
    if (error.response.status === 500 || error.response.status === 504) {
      msg = 'Internal Server Error';
    } else {
      msg = error.response.data.detail.msg; // 接口返回的错误信息
    }
    Notify.create({
      message: msg,
      type: 'negative',
      position: 'top-right',
    });
    return Promise.reject(error);
  }
);

export default request;
