import axios from "axios";
import { message } from "@/utils/resetMessage.js";

let errTimer = null;
let setErrorMsg = function (err) {
  let err_msg = "请求失败";
  if (err.message.includes("timeout")) {
    err_msg = "请求超时，请刷新后重试！";
  } else if (err.message.includes("Network Error")) {
    err_msg = "网络连接错误,请刷新后重试！";
  }
  if (errTimer) {
    clearTimeout(errTimer);
    errTimer = null;
  }
  errTimer = setTimeout(() => {
    message.error(err_msg);
  }, 1500);
  err.message = err_msg;
  return err;
};
const http = axios.create({
  retry: 2,
  retryDelay: 1000,
  timeout: 1000 * window._config.axiosApiTimeout,
  validateStatus: function (status) {
    return status >= 200 && status <= 500; // 默认的
  },
  headers: {
    "Content-Type": "application/json"
  }
});

/**
 * HTTP request拦截
 */
http.interceptors.request.use(
  (config) => {
    // 登录后校验账号
    let xh_control_userInfo = localStorage.getItem("xh_control_userInfo");
    if (xh_control_userInfo) {
      xh_control_userInfo = JSON.parse(xh_control_userInfo).content;
      if (xh_control_userInfo) {
        config.headers["Token-Key"] = xh_control_userInfo["Xh-Token-Key"];
        config.headers["Token-Value"] = xh_control_userInfo["Xh-Token-Value"];
        // 验证登陆人
        config.headers["XH-UserId"] = xh_control_userInfo.adminid;
      }
    }
    config.headers.st = window._config.secret;
    if (window._config.secret) {
      let config_data_str = JSON.stringify(config.data);
      config.data = window.getEncryptedString(config_data_str);
    }
    return config;
  },
  (err) => {
    err.message = "请求失败";
    return Promise.reject(err);
  }
);

/**
 * HTTP response拦截
 */
http.interceptors.response.use(
  (response) => {
    let resData = response.data;
    if (resData.code === 2) {
      console.log(
        "文件名：httpRequest.js，退出原因：" +
          response.config.url +
          "返回code等于2"
      );
      window.vue.$router.push("/login");
    }
    return resData;
  },
  function axiosRetryInterceptor(err) {
    let config = (err && err.config) || {};
    if (!config.retry) {
      return Promise.reject(setErrorMsg(err));
    }
    config.__retryCount = config.__retryCount || 0;
    if (config.__retryCount >= config.retry) {
      return Promise.reject(setErrorMsg(err));
    }
    config.__retryCount += 1;
    let backoff = new Promise(function (resolve) {
      setTimeout(function () {
        resolve();
      }, config.retryDelay || 1);
    });
    return backoff.then(function () {
      if (window._config.secret) {
        let config_data_str = window.getDecryptString(config.data);
        config.data = JSON.parse(config_data_str);
      }
      return http(config);
    });
  }
);
/**
 * @param {*} url 不带前缀的url
 * @param {*} data 传参
 * @returns Promise
 */
export const setRequest = (url, data) =>
  http({
    url: `${window._config.baseUrl}${url}`,
    method: "post",
    data: data || {}
  });
