import axios from "axios";
import { ElMessage, ElMessageBox } from "element-plus";
import router from "../router"; // 确保路径正确

const instance = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  timeout: 5000,
});
// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    // 添加 token 等通用处理
    // config.headers["Content-Type"] = "application/json;charset=utf-8";
    const token = localStorage.getItem("token");
    const userhead = localStorage.getItem("userhead");
    if (token) {
      config.headers["token"] = `${token}`;
      config.headers["user_head"] = `${userhead}`;
    } else {
      console.log("无权限进入");
      router.push({
        path: `/login`,
      });
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);
// 响应拦截器
instance.interceptors.response.use(
  (response) => {
    if (
      response.data.message == "登录凭证已过期，请重新登录！" ||
      response.data.message == "无效token"
    ) {
      localStorage.removeItem("token");
      localStorage.removeItem("userName");
      sessionStorage.removeItem("accountId");
      sessionStorage.removeItem("sidevarItem");
      router.push({
        path: `/login`,
      });
      console.log(response.data.message);
    }
    return response.data;
  },
  (error) => {
    // 统一错误处理
    console.log(error.response.data.message); // 查看错误信息
    return Promise.reject(error); // 返回拒绝的 Promise
  }
);

// 封装常用的请求方法
export const request = (
  url,
  flag,
  data = {},
  method = "GET",
  responseType = null
) => {
  return instance({
    url,
    params: flag == "params" ? data : null,
    data: flag == "data" ? data : null,
    method,
    responseType,
  });
};

const api = "/welcome/welcome_api"; // 代理地址
// const api = "/welcome/api"; // 代理地址
// 请求封装
export const https = {
  get(url, flag, params = {}) {
    return request(api + url, flag, params, "GET");
  },
  getBlob(url, flag, params = {}) {
    return request(api + url, flag, params, "GET", "blob");
  },
  post(url, flag, data = {}) {
    return request(api + url, flag, data, "POST");
  },
  put(url, flag, data = {}) {
    return request(api + url, flag, data, "PUT");
  },
  delete(url, flag, params = {}) {
    return request(api + url, flag, params, "DELETE");
  },
};
// // 封装 POST 请求
// export const post = (url: string, data: any = {}) => {
//   return request(api+url, data, 'POST');
// };
// // 封装 GET 请求
// export const get = (url: string, params: any = {}) => {
//   return request(api+url, params, 'GET');
// };
// // 封装 POST 请求
// export const put = (url: string, data: any = {}) => {
//   return request(api+url, data, 'PUT');
// };
// // 封装 POST 请求
// export const delete = (url: string, params: any = {}) => {
//   return request(api+url, params, 'DELETE');
// };
