import axios from "axios";
import ViewUI from "iview";
import { router } from "../router/index";

const baseUrl =
  process.env.NODE_ENV === "production" ? process.env.VUE_APP_DOMAIN : "";
axios.defaults.baseURL = baseUrl;
axios.defaults.timeout = 10 * 60 * 1000; // 请求超时时间10min
axios.defaults.transformRequest = function (data, headers) {
  let token = localStorage.accessToken;
  let schoolId = localStorage.schoolId;
  headers.common["authorization-token"] = token;
  headers.common["schoolId"] = schoolId;
  if (headers["Content-Type"] === "application/json;charset=utf-8")
    return JSON.stringify(data);

  headers["Content-Type"] = "application/x-www-form-urlencoded;charset=UTF-8";
  if (data && data.constructor !== Object) {
    return data;
  }
  let params = new Array();
  for (let k in data) {
    if (data[k] != null && data[k] != undefined) {
      if (typeof data[k] === "string") {
        if (data[k].length > 0) {
          params.push(
            encodeURIComponent(k) + "=" + encodeURIComponent(data[k])
          );
        }
      } else {
        params.push(encodeURIComponent(k) + "=" + encodeURIComponent(data[k]));
      }
    }
  }
  params = params.length > 0 ? params.join("&") : "";
  return params;
};

// axios.interceptors.request.use(
//   function (config) {
//     return config;
//   },
//   function (error) {
//     return Promise.reject(error);
//   }
// );

axios.interceptors.response.use(
  function (response) {
    if (response && response.config && response.config.responseType) {
      let responseType = response.config.responseType;
      if (responseType.toLowerCase() == "blob") {
        return response;
      }
    }
    if (response.data) {
      let code = response.data.code;
      if (code != 0) {
        if (code != -501) {
          let message = response.data.message;
          message = message || "";
          ViewUI.Notice.error({
            title: "系统消息",
            desc: "<p>" + message + "</p>",
          });
          return Promise.reject(response.data);
        } else {
          ViewUI.Modal.confirm({
            title: "系统提示",
            content: "您长时间未进行任何操作，请重新登录",
            onOk() {
              router.replace({ name: "login" });
            },
          });
        }
      }
    }
    return response;
  },
  function (error) {
    ViewUI.Notice.error({
      title: "服务端响应失败",
      desc: "<p>" + error + "</p>",
    });
    return Promise.reject(error);
  }
);

export { axios, baseUrl };
