import axios from "axios";
import { BASE_URL, TIMEOUT } from "./config";

//添加配置
const INSTANCE = axios.create({
  baseURL: BASE_URL,
  timeout: TIMEOUT,
});

//添加拦截
INSTANCE.interceptors.request.use(
  (config) => {
    if (sessionStorage.getItem("token")) {
      config.headers["TOKENFLAG"] = sessionStorage.getItem("token");
    }
    if (sessionStorage.getItem("username")) {
      config.headers["USERFLAG"] = sessionStorage.getItem("username");
    }
    return config;
  },
  (error) => {
    throw error.message;
  }
);

//添加拦截
INSTANCE.interceptors.response.use(
  (res) => {
    if (res.data instanceof Blob) {
      return res;
    } else if (res.data.code == 9000) {
      return res.data.data;
    } else {
      throw res.data.message;
    }
  },
  (error) => {
    throw error.message;
  }
);

/* 统一封装get请求 */
export const GET = (url, params, config = {}) => {
  return new Promise((resolve, reject) => {
    INSTANCE({
      method: "get",
      url,
      params,
      ...config,
    })
      .then((response) => {
        resolve(response);
      })
      .catch((error) => {
        reject(error);
      });
  });
};

/* 统一封装post请求  */
export const POST = (url, data, config = {}) => {
  return new Promise((resolve, reject) => {
    INSTANCE({
      method: "post",
      url,
      data,
      ...config,
    })
      .then((response) => {
        resolve(response);
      })
      .catch((error) => {
        reject(error);
      });
  });
};

//下载
export const DOWNLOAD = (url, params, filename, config = {}) => {
  return new Promise((resolve: any, reject) => {
    INSTANCE({
      method: "post",
      url,
      params,
      responseType: "blob",
      ...config,
    })
      .then((response) => {
        if (!filename) {
          let content_disposition = response.headers["content-disposition"];
          if (content_disposition && content_disposition.match("filename=")) {
            filename = decodeURIComponent(
              content_disposition.split("filename=")[1]
            );
          } else {
            filename = new Date().getTime();
          }
        }
        let href = window.URL.createObjectURL(response.data); //创建下载链接
        let downloadElement = document.createElement("a");
        downloadElement.href = href;
        downloadElement.download = filename;
        downloadElement.click();
        window.URL.revokeObjectURL(href);
        resolve();
      })
      .catch((error) => {
        reject(error);
      });
  });
};
