import axios, { InternalAxiosRequestConfig, AxiosResponse } from "axios";
import { useUserStoreHook } from "@/store/modules/user";

// 请求拦截器
axios.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    console.log("请求拦截了");
    const accessToken = localStorage.getItem("token");
    if (accessToken) {
      config.headers.Authorization = accessToken;
    }
    return config;
  },
  (error: any) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
axios.interceptors.response.use(
  (response: AxiosResponse) => {
    console.log("ddddddddd");
    const { code, msg } = response.data;
    console.log("响应拦截了", JSON.stringify(response.data));

    if (code === "200") {
      return response.data;
    }
    // 响应数据为二进制流处理(Excel导出)
    if (response.data instanceof ArrayBuffer) {
      return response;
    }

    // token 过期,重新登录
    if (code === "4106") {
      ElMessageBox.confirm("当前页面已失效，请重新登录", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        const userStore = useUserStoreHook();
        userStore.resetToken().then(() => {
          location.reload();
        });
      });
    } else {
      ElMessage.error(msg || "系统出错");
    }

    return Promise.reject(new Error(msg || "Error"));
  },
  (error: any) => {
    console.log("aaaaaa");
    if (error.response.data) {
      const { code, msg } = error.response.data;
    }
    return Promise.reject(error.message);
  }
);

export default axios;
