import axios from "axios";
// import { ElMessage } from "element-plus";
import storage from "./storage";
// create an axios instance.
let w: any = window;
const service = axios.create({
  baseURL: JSON.parse(w.localStorage.getItem("visualDomain"))?.kms,
  withCredentials: true, // send cookies when cross-domain requests.
  timeout: Infinity, // request timeout.
});
// request interceptor
service.interceptors.request.use(
  (config: any) => {
    if (!config.headers) config.headers = {};
    const token = storage.getCookie("NETILERSESSION_C");
    if (token && token !== null) config.headers.Authorization = token;
    // const NETILER = storage.getCookie("NETILER_H145");
    // if (NETILER && NETILER !== null) config.headers.Authorization = NETILER;
    return config;
  },
  (error) => Promise.reject(error) // do something with request error.
);

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get 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 200, it is judged as an error.
    if (res && res.code && Number(res.code) !== 200) {
      // ElMessage({
      //   message: res.message || res.msg || "请检查数据返回格式",
      //   type: "error",
      //   dangerouslyUseHTMLString: true,
      //   duration: 5 * 1000,
      // });
      return Promise.reject(res.message || "error");
    }
    return res;
  },
  (error) => {
    // if (["401", "402"].includes(error.response?.data?.code)) {
    //   storage.setCookie("NETILERSESSION_C", "", -1);
    //   const toHtml = location.href;
    //   location.href =
    //     import.meta.env.VITE_BASE_LOGIN +
    //     "?redirectUrl=" +
    //     encodeURIComponent(toHtml);
    // }
    // ElMessage({
    //   message: error.message,
    //   type: "error",
    //   duration: 5 * 1000,
    // });
    console.log(error);
    return Promise.reject(error);
  }
);

export default service;
