import axios from "axios";
import { MessageBox, Message } from "element-ui";
import store from "@/store";
import { getToken } from "@/utils/auth";
import Cookies from "js-cookie";
import Vue from "vue";

//获取当前url
const DoMainString = document.querySelector("html").getAttribute("domain");
var URL = process.env.VUE_APP_BASE_API;
if (DoMainString) {
  URL = DoMainString;
}

var reg =
  /(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)/;
var browserUrl = window.location.hostname;
console.log("========url===", reg.test(browserUrl));
// if (reg.test(browserUrl)){
//   URL = window.location.protocol +"//"+ browserUrl + ":8082"
// }

Cookies.set("url", URL);
console.log(process.env.VUE_APP_BASE_API, "===========URL1111");
console.log(URL, "===========URL");

const service = axios.create({
  baseURL: URL, // url = base url + request url
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 60000, // request timeout
});
// request interceptor
service.interceptors.request.use(
  (config) => {
    // en-US zh-CN
    // config.headers['lang']=localStorage.getItem('lang') || navigator.language
    // do something before request is sent
    // config.headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'  //此处是增加的代码，设置请求头的类型
    if (process.env.VUE_APP_BASE_API !== "/dev-api") {
      config.headers["Content-Type"] =
        "application/x-www-form-urlencoded;charset=UTF-8";
      config.withCredentials = false;
    }

    if (store.getters.token) {
      // let each request carry token
      // ['Authorization'] is a custom headers key
      // please modify it according to the actual situation
      if (process.env.VUE_APP_BASE_API === "/dev-api") {
        config.headers["X-Token"] = getToken();
      } else {
        config.headers["token"] = getToken();
      }
    }
    console.log(config.headers, "hss");
    return config;
  },
  (error) => {
    // do something with request error
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  (response) => {
    const res = response.data;

    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== 200) {
      Message({
        // message: res.msg + res.code,
        message: Vue.$t("common.requestMsg"),
        type: "error",
        duration: 5 * 1000,
      });

      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
        // to re-login
        MessageBox.confirm("你已经注销登陆,你可以取消或重新登陆", "确认注销", {
          confirmButtonText: "重新登陆",
          cancelButtonText: Vue.$t("common.cancel"),
          type: "warning",
        }).then(() => {
          store.dispatch("user/resetToken").then(() => {
            location.reload();
          });
        });
      }
      if (res.code === 20002) {
        store.dispatch("user/resetToken").then(() => {
          location.reload();
        });
      }
      if (res.code === undefined) {
        return res;
      } else {
        return Promise.reject(new Error(res.message || "Error"));
      }
    } else {
      return res;
    }
  },
  (error) => {
    console.log("err" + error); // for debug
    let config = error.config;
    if (!config) {
      Message({ message: error.message, type: "error", duration: 5 * 1000 });
      return Promise.reject(error);
    }
    console.log("config==>", config); // for debug
    console.log("config.__retryCount==>", config.__retryCount); // for debug
    // 设置请求超时次数
    config.__retryCount = config.__retryCount || 0;
    if (config.__retryCount >= 3) {
      // Message({ message:error.message, type: 'error', duration: 5 * 1000 })
      Message({
        message: Vue.$t("common.requestMsg"),
        type: "error",
        duration: 5 * 1000,
      });
      // Message.error((error && error.data && error.data.msg) || '请求超时')
      return Promise.reject(error);
    }
    config.__retryCount += 1;
    let backoff = new Promise((resolve) => {
      setTimeout(() => {
        resolve();
      }, config.retryDelay || 1000);
    });
    return backoff.then(() => {
      return service(config);
    });
    // Message({
    //   message: error.message,
    //   type: 'error',
    //   duration: 5 * 1000
    // })
    // return Promise.reject(error)
  }
);

export default service;
