import axios from 'axios';
import { MessagePlugin } from 'tdesign-vue-next';

const env = import.meta.env.MODE || 'development';

const instance: any = axios.create({
  // baseURL: host,
  timeout: 1000,
  //   access-control-allow-origin: * --该模式不可配置withCredentials
  withCredentials: false,
});
// 主动挂载all方法和spread方法，并发请求
instance.all = axios.all;
instance.spread = axios.spread;

instance.defaults.timeout = 60000;

instance.interceptors.response.use(
  (response: any) => {
    const { data } = response;
    return data;
  },
  (err: any) => {
    const { config } = err;
    const { message: msg } = err.response.data;
    MessagePlugin.error(msg || '请求错误,请稍后重试');
    if (!config || !config.retry) return Promise.reject(err);

    config.retryCount = config.retryCount || 0;

    if (config.retryCount >= config.retry) {
      return Promise.reject(err);
    }

    config.retryCount += 1;

    const backoff = new Promise((resolve) => {
      setTimeout(() => {
        resolve(null);
      }, config.retryDelay || 1);
    });

    return backoff.then(() => instance(config));
  }
);

export default instance;
