import axios from "axios";
import {
  ElMessage
} from "element-plus";
import router from "@/router/index";
import {
  localSet,
  localGet,
  localRemove,
} from "./index";
import config from "~/config";
import {Base64} from 'js-base64';

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

axios.interceptors.request.use(
    (req) => {
        req.headers["cdcm"] = localGet("token");
        return req;
    }
);

axios.interceptors.response.use(
  (res) => {

    for (const key in res.headers) {
      if (Object.hasOwnProperty.call(res.headers, "token")) {
        const token = res.headers["token"];
        if (typeof (token) != "undefined") {
          localSet("token", token);
        }
      }
    }
    // console.log(123,res);
    if(!res.request || res.request.responseType ===  'blob') { // 特殊情况处理，导出文件
      return Promise.resolve(res);
    }
    // token过期 
    if (res.data.code === 3004) {
      localRemove("token");
      ElMessage.closeAll();
      ElMessage.error(res.data.message || "Token异常,请重新登录");
      router.push({
        path: "/login"
      });
      return Promise.reject(res.data);
    } 
    return Promise.resolve(res.data);
  },
  (error) => {
    ElMessage.closeAll();
    ElMessage.error("请求错误");
    router.push({
      path: "/login"
    });
    return Promise.reject(error);
  }
);
// post请求
export function postPBRequest(url, params, actionNum, name) {
  const title = url === '/driver' ? {'driver_name': name }: {'template_name': name}
  return axios({
    method: "post",
    url: url,
    data: params,
    headers: {
      "action": actionNum,
      ...title
    },
  });
}