import axios from "axios";
import { Message } from "element-ui";

const service = axios.create({
  baseURL: window?._BASE_CONFIG?.API || "/api",
  withCredentials: true,
  timeout: 5000,
});

const writeList = ["/api/energy-manage-service/sysuserinfo/open/userLogin"];

/**
 * 请求拦截器
 * 统一处理请求拦截，如：添加token等
 */
service.interceptors.request.use(
  (config) => {
    if (!writeList.includes(config.url)) {
      const token = JSON.parse(sessionStorage.getItem("vuex"))?.auth?.userInfo
        ?.token;
      if (token) {
        config.headers.token = token;
      }
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

/**
 * 响应拦截器
 * 统一处理响应拦截
 * 如：重定向、消息提示等操作
 */
service.interceptors.response.use(
  async (response) => {
    const { data } = response;
    if (data?.code) {
      if (data.code !== 200) {
        Message({
          message: data.msg || "Error",
          type: "error",
          duration: 5 * 1000,
        });
        return Promise.reject(new Error(data.msg || "Error"));
      } else {
        return data;
      }
    } else if (data.type === "application/octet-stream") {
      return response;
    } else if (data.type === "application/json") {
      const resData = JSON.parse(await data.text());
      if (resData.code !== 200) {
        Message({
          message: resData.msg || "Error",
          type: "error",
          duration: 5 * 1000,
        });
        return Promise.reject(new Error(resData.msg || "Error"));
      } else {
        return resData;
      }
    }
  },
  (error) => {
    const { response } = error;
    if (response) {
      if (response.status === 401) {
        window.location = response.data;
      } else {
        Message({
          message: response.data.message || error.message,
          type: "error",
          duration: 5 * 1000,
        });
      }
    } else {
      Message({
        message: error.message,
        type: "error",
        duration: 5 * 1000,
      });
    }
    return Promise.reject(error);
  }
);

/**
 * 统一处理请求
 * @param {Object} requestObj 请求参数
 */
const request = async (requestObj) => {
  try {
    const {
      url,
      method,
      data = {},
      timeout,
      params,
      responseType,
    } = requestObj;
    const response = await service({
      url,
      method: method || "post",
      data,
      timeout: timeout || 300000,
      params: params || (method && method.toLowerCase() === "get" ? data : {}),
      responseType: responseType || "json",
    });
    return response;
  } catch (error) {
    // console.error("Request error:", error);
    throw error;
  }
};

export default request;
