import axios from "axios";
import md5 from "js-md5";
import { Base64 } from "js-base64";
import { ElMessage } from "element-plus";
import router from "@/router/index";
import { localGet } from "./index";
import config from "~/config";
import { token } from '../proto/data/pd'

axios.defaults.baseURL = config[import.meta.env.MODE].baseUrl;
axios.defaults.withCredentials = true;
// 请求头，headers 信息
axios.defaults.headers["X-Requested-With"] = "XMLHttpRequest";

// axios.defaults.headers = getNeedToken();


// function getNeedToken() {
//   console.log(333, localGet("token"));
//   const ret_token = localGet("token");
//   if (ret_token) {
//     ret_token.timestamp = new Date().getTime();
//     const tokenInfo = token.encode(ret_token).finish();
//     // 直接转换为string丢到header里，header的key为"cdcm"
//     const cdcm = tokenInfo.slice(0, tokenInfo.length).toString()
//     return { cdcm };
//   }
  
// }

// 请求拦截器，内部根据返回值，重新组装，统一管理。
axios.interceptors.response.use(
  (res) => {
    return res.data;
  },
  (error) => {
    ElMessage.closeAll();
    ElMessage.error(error || "401 Unauthorized");
    router.push({ path: "/login" });
    return Promise.reject(error);
  }
);
// post请求
export function postJsonRequest(url, params) {
  return axios({
    method: "post",
    url: url,
    data: params,
    // responseType: 'arraybuffer',
    headers: {
      "Content-Type": "application/json",
    },
  });
}
// get请求
export function getRequest(url, params) {
  return axios({
    method: "get",
    // responseType: 'arraybuffer',
    params: {
      ...params,
    },
    url: url,
  });
}

export function deleteRequest(url, params) {
  return axios({
    method: "delete",
    data: params,
    // responseType: 'arraybuffer',
    url: url,
  });
}
export const putRequest = (url, params) => {
  return axios({
    method: "put",
    data: params,
    // responseType: 'arraybuffer',
    url: url,
    headers: {
      "Content-Type": "application/json",
    },
  });
};
