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 {
  response
} 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.interceptors.request.use(
    (req) => {
        req.headers["cdcm"] = localGet("token");
        return req;
    }
);

axios.interceptors.response.use(
  (res) => {
    const token = res.headers["token"]
    // 如果token不为空，就缓存到本地
    if (typeof (token) != "undefined") {
      localSet("token", token);
    }
    const ret = res.data;
    // token过期 
    if (ret.code === 3004) {
      localRemove("token");
      ElMessage.closeAll();
      ElMessage.error(ret.message || "Token异常,请重新登录");
      router.push({
        path: "/login"
      });
      return Promise.reject(ret);
    } 
    return ret;
  },
  (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
    },
  });
}