import axios from "axios";
import Cookies from "js-cookie";
import { Notification } from "element-ui";
// import { getCookieDomain } from "@/util/util.js";
window._axiosPromiseArr = [];
//请求拦截器
axios.interceptors.request.use(
  request => {
    request.cancelToken = new axios.CancelToken(cancel => {
      window._axiosPromiseArr.push({ cancel });
    });
    let token = Cookies.get("OO-access_token");
    if (token) {
      token = JSON.parse(token).content;
      if (
        request.baseURL.indexOf("grafana") === -1 &&
        request.url.indexOf("oauth") === -1
      ) {
        // request.headers["Authorization"] = "Bearer " + token;
      }
    }
    return request;
  },
  err => {
    return Promise.reject(err);
  }
);

//响应拦截器
axios.interceptors.response.use(
  response => {
    if (response.status !== 200) {
      Notification({
        type: "warning",
        title: "接口响应异常"
      });
    }
    return response;
  },
  err => {
    // if (
    //   err.response &&
    //   err.response.status === 401 &&
    //   err.response.config.baseURL.indexOf("grafana") === -1
    // ) {
    //   Cookies.remove("OO-access_token", {
    //     path: "/",
    //     domain: getCookieDomain()
    //   });
    //   Cookies.remove("OO-refresh_userInfo", {
    //     path: "/",
    //     domain: getCookieDomain()
    //   });
    //   location.replace(`${location.origin}/#/login/?r_url=${location.href}`);
    // }
    return Promise.reject(err);
  }
);

export default {
  /**
   * @author create by liuwang
   * @param {String} method 请求方式
   * @param {String} url url
   * @param {*} data 默认post参数
   * @param {*} headers
   * @param {*} withCredentials 携带cookie
   * @param {String} responseType 返回类型
   */
  axios(
    method = "get",
    baseURL = "",
    url = null,
    data = null,
    headers = { "Content-Type": "application/json" },
    withCredentials = true,
    responseType = "json"
  ) {
    return new Promise((resolve, reject) => {
      axios({
        method: method,
        baseURL: baseURL ? baseURL : window.server,
        url: url,
        data: data,
        headers: headers,
        withCredentials,
        responseType,
        timeout: 120000
      }).then(
        result => {
          resolve(result.data);
        },
        err => {
          reject(err);
        }
      );
    });
  }
};
