import { AxiosError, AxiosInstance } from 'axios';
import { VAxios } from './Axios';
import { RequestOptions } from '/#/axios';
/**
 *  请求重试机制
 */

export class AxiosRetry {
  /**
   * 重试
   */
  retry(AxiosInstance: AxiosInstance, error: AxiosError) {
    // @ts-ignore
    const { config } = error.response;
    const { waitTime, count } = config?.requestOptions?.retryRequest;
    config.__retryCount = config.__retryCount || 0;
    if (config.__retryCount >= count) {
      return Promise.reject(error);
    }
    config.__retryCount += 1;
    return this.delay(waitTime).then(() => AxiosInstance(config));
  }

  /**
   * 重试
   */
  retryRefresh(res, options) {
    // 重试
    const { config } = res;
    const { waitTime } = options.retryRequest;
    const axios = new VAxios(options);
    const AxiosInstance = axios.getAxios();
    if (config?.method == 'get') {
      return this.delay(waitTime).then(() => AxiosInstance(config));
    }
  }

  /**
   * 延迟
   */
  private delay(waitTime: number) {
    return new Promise(resolve => setTimeout(resolve, waitTime));
  }
}
