import axios from "axios";
import { Message, MessageBox } from "element-ui";
import store from "@/store";
import { getToken } from "@/utils/auth";
import { removeToken } from "@/utils/auth";
import { resetRouter } from "@/router";
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 30000,
});

service.interceptors.request.use(
  (config) => {
    const Authorization = config.headers["ssdmn-token"];
    if (store.getters.token && !Authorization) {
      // if (config.method === "POST") {
      // config.header["Content-Type"] = "application/json; charset=UTF-8";
      // }
      config.headers["ssdmn-token"] = getToken();
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

/**
 * 异常处理
 * @param error
 * @returns {Promise<never>}
 */
const errorHandler = (error) => {
  console.log(error);
  if (error.response) {
    const response = error.response;
    const status = Number(response.status) || 200;
    const responseData = response.data;
    const responseMsg = responseData.message || response["error_description"];
    if (status === 403) {
      Message({
        message: "请求失败，暂无权限",
        type: "error",
      });
    } else if (status === 401) {
      /*
      Message({
        message: '令牌状态已过期，请点击重新登录',
        type: 'error'
      })*/
      MessageBox.confirm("令牌状态已过期，请点击重新登录", "系统提示", {
        confirmButtonText: "重新登录",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          store.dispatch("user/logout").then(() => {
            // 刷新登录页面，避免多次弹框
            window.location.reload();
          });
        })
        .catch(() => {});
    } else {
      Message({
        message: responseMsg,
        type: "error",
      });
    }
  }
  return Promise.reject(error);
};

// HTTP response 拦截
service.interceptors.response.use((response) => {
  console.log(response);
  if (response.status === 200 && response.data.code === 0) {
    Message({ type: "error", message: response.data.message });
    return Promise.reject(response);
  }
  if (response.request.responseType === "blob") {
    return response;
  }
  if (response.data.code === 200 || response.data.code === 204) {
    return response.data;
  } else if (response.data.code === 401) {
    Message({ type: "error", message: "登录信息已过期，请重新登录" });
    removeToken(); // must remove  token  first
    resetRouter();
    this.$store.commit("RESET_STATE");
    this.$router.push(`/login`);
  } else {
    Message({ type: "error", message: response.data.msg });
  }
}, errorHandler);

export default service;
