import Vue from "vue";
import axios from "axios";
import { loadProgressBar } from "axios-progress-bar";
import cachingGet from "./axiosCache";

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

const _axiosNoAuth = axios.create(config);

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

_axiosNoAuth.interceptors.request.use(
  function(config) {
    return config;
  },
  function(error) {
    Vue.prototype.$notify({
      showClose: true,
      message: error,
      type: "error",
    });
    return Promise.reject(error);
  }
);

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

    const data = error.response.data;
    if (data && data.desc) {
      Vue.prototype.$notify({
        showClose: true,
        message: data.desc,
        type: "error",
      });
    } else {
      Vue.prototype.$notify({
        showClose: true,
        message: `异常(${error.response.status}): ${error.config.url}`,
        type: "error",
      });
    }
    return Promise.reject(error);
  }
);

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

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

Vue.use(Plugin);

export default Plugin;

export const httpNoAuth = _axiosNoAuth;
