import axios from "axios";
import router from "@/router";
import { tansParams, blobValidate } from "@/utils/trans";
import errorCode from "@/utils/errorCode";
import "vant/es/dialog/style";
import { showFailToast, showDialog } from "vant";

//创建axios实例，封装成request简写代码
const request = axios.create({
  baseURL: import.meta.env.VITE_BASE_API,
  timeout: 20000,
  // withCredentials: true,
});

// request 拦截器z
// 可以自请求发送前对请求做一些处理
// 比如统一加token，对请求参数统一加密
request.interceptors.request.use(
  (config) => {
    // 是否需要防止数据重复提交
    const isRepeatSubmit = (config.headers || {}).repeatSubmit === false;

    config.headers["Content-Type"] = "application/json;charset=utf-8";
    //   config.headers["Content-Type"] = "application/x-www-form-urlencoded; charset=UTF-8";

    // -----------------------------------------------发布前屏蔽--------------------------------

    // -----------------------------------------------发布前屏蔽--------------------------------

    if (config.method == "get" && config.params) {
      let url = config.url + "?" + tansParams(config.params);
      url = url.slice(0, -1);
      config.params = {};
      config.url = url;
    }
    if (config.method === "post" || config.method === "put") {
      config.data =
        typeof config.data === "object"
          ? JSON.stringify(config.data)
          : config.data;
    }

    console.log("-----------------", config);
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// response 拦截器
// 可以在接口响应后统一处理结果

request.interceptors.response.use(
  (response) => {
    console.log("response===", response);
    // console.log("------response1-------");
    if (response.status === 200) {
      return response.data;
    } else {
      // console.log("------response7-------");
      showFailToast(response.status + ":" + response.statusText);
    }
  },
  (error) => {
    // console.log("------respons4-------");
    let { message } = error;
    if (message == "Network Error") {
      message = "后端接口连接异常";
    } else if (message.includes("timeout")) {
      message = "系统接口请求超时";
    } else if (message.includes("Request failed with status code")) {
      message = "系统接口" + message.substr(message.length - 3) + "异常";
    }
    // console.log("------respons5-------");
    showFailToast(message);
    // console.log("------respons6-------");
    return Promise.reject(error);
  }
);
export default request;
