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: 10000,
});
// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    // ========== 新增：判断登录接口，登录接口不携带token ==========
    const loginApiList = [
      '/welcome/api/home/login'  // 你的登录接口完整路径，按你项目实际改
      // '/welcome/welcome_api/register' // 注册如果也不需要token一并加上
    ];
    // 判断当前请求地址是否包含登录接口
    const isLoginApi = loginApiList.some(api => config.url.includes(api));

    // 如果是登录接口，直接放行，不处理token逻辑
    if (isLoginApi) {
      return config;
    }

    // 非登录接口才执行token逻辑
    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");
  },
};
// 优化后的方法 （推荐这种，上门那种因为接口在优化前已写完没办法改）
// export const https = (method, url, flag, data = {}, responseType = null) => {
//   const config = {
//     url: `/welcome/welcome_api${url}`, // 代理地址
//     method,
//     responseType,
//   };

//   if (flag === "params") {
//     config.params = data;
//   } else if (flag === "data") {
//     config.data = data;
//   }

//   return instance(config);
// };

// GET 请求
// https("GET", "/example", "params", { id: 1 }).then((res) => {
//   console.log(res);
// });

// // POST 请求
// https("POST", "/example", "data", { name: "test" }).then((res) => {
//   console.log(res);
// });

// // GET Blob 请求
// https("GET", "/example", "params", { id: 1 }, "blob").then((res) => {
//   console.log(res);
// });
