import Vue from "vue";
import axios from "axios";
// @ts-ignore
import { loadProgressBar } from "axios-progress-bar";
import cachingGet from "./axiosCache";
import axiosRetry from "axios-retry";
import { message } from "ant-design-vue";

const config = {
  timeout: 60 * 1000, // Timeout
};
const cacheGetUrls: [RegExp] | [] = [];

const _axiosNoAuth = axios.create(config);
axiosRetry(_axiosNoAuth);

/**
 * 本应用的无auth api，或者第三方的api
 * 1. 统一使用的http api，方便使用，无需fetch
 * 2. 无默认headers
 */

_axiosNoAuth.interceptors.request.use(
  function (config) {
    return config;
  },
  function (error) {
    message.error({ content: error, duration: 10 });
    return Promise.reject(error);
  }
);

// Add a response interceptor
_axiosNoAuth.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    if (!error.response) {
      // "Network Error" 网络不通，直接返回
      message.error({
        content: "网络连接异常，请检查网络设置。",
        duration: 10,
      });
      return Promise.reject(error);
    }

    const data = error.response.data;
    if (data && data.desc) {
      message.error({ content: data.desc, duration: 10 });
    } else {
      message.error({
        content: `异常(${error.response.status}): ${error.config.url}`,
        duration: 10,
      });
    }
    return Promise.reject(error);
  }
);

_axiosNoAuth.get = cachingGet(_axiosNoAuth, cacheGetUrls);
loadProgressBar(null, _axiosNoAuth);

// Plugin.install = function (Vue) {
//   Object.defineProperties(Vue.prototype, {
//     $httpNoAuth: {
//       get() {
//         return _axiosNoAuth;
//       },
//     },
//   });
// };

// Vue.use(Plugin);

export default Plugin;

export const httpNoAuth = _axiosNoAuth;
