import axios from "axios";
import { resetMessage } from "./message";
import store from "../store";
import { MessageBox } from "element-ui";

// 请求队列
let requestList = [];
// 是否正在刷新中
let isRefreshToken = false;

const $axios = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API_TG
  // withCredentials: true
});

const loading = null;

/**
 * 请求拦截器
 * 用于处理请求前添加loading、判断是否已保存token，并在每次请求头部添加token
 */
$axios.interceptors.request.use(
  (config) => {
    config.baseURL = store.state.baseUrl;
    const token = store.state.token;
    const TenantId = store.state.TenantId;
    const projectId = store.state.projectId;
    config.headers["Authorization"] = "Bearer " + token;
    config.headers["Tenant-Id"] = TenantId;
    config.headers["terminal"] = 2; // 1 为管理后台 2 为前端项目
    config.headers["p-id"] = projectId;
    config.headers["locale"] = localStorage.getItem("language")|| "zh";
    console.log(config, store.state, "token信息验证");
    return config;
  },
  (error) => {
    console.log("请求出错");
    return Promise.reject(error);
  }
);
/**
 * 响应拦截器
 * 用于处理loading状态关闭、请求成功回调、响应错误处理
 */
$axios.interceptors.response.use(
  (response) => {
    console.log("请求的URL:", response.config.url);
    if (loading) {
      loading.close();
    }
    console.log("回应参数...", response);
    const status = response.status;
    const res = response.data;
    const config = response.config;
    // 请求成功返回response.data
    if ((status >= 200 && status < 300) || status === 304) {
      switch (res.code) {
        case 0:
          return Promise.resolve(res);

        case 401:
          // 如果未认证，并且未进行刷新令牌，说明可能是访问令牌过期了
          if (!isRefreshToken) {
            isRefreshToken = true;

            // 1. 如果获取不到刷新令牌，则只能执行登出操作
            if (!store.state.token) {
              return handleAuthorized();
            }
            // 2. 进行刷新访问令牌
            try {
              return new Promise((resolve, reject) => {
                window.$mmc_stl.app.$emit("refreshToken", {
                  callback(data) {
                    isRefreshToken = false;
                    if (data.code === 0) {
                      const token = data.token;

                      window.$mmc_stl.app.$store.commit(
                        "MMCFlightControlCenter/setState",
                        {
                          key: "token",
                          value: token,
                        }
                      );
                      config.headers.Authorization = "Bearer " + token;
                      requestList.forEach((cb) => {
                        cb();
                      });
                      requestList = [];
                      resolve($axios(config));
                    } else {
                      handleAuthorized();
                    }
                  },
                });
              });
            } catch (e) {
            } finally {
              requestList = [];
            }
          } else {
            // 添加到队列，等待刷新获取到新的令牌
            return new Promise((resolve) => {
              requestList.push(() => {
                const token = store.state.token;
                config.headers.Authorization = "Bearer " + token; // 让每个请求携带自定义token 请根据实际情况自行修改
                resolve($axios(config));
              });
            });
          }

          break;

        default:
          if (response.config.responseType === "blob") {
            return Promise.resolve(res);
          }
          resetMessage.error(res?.msg || "网络请求错误");
          return Promise.reject(res);
      }
    } else {
      return Promise.reject(response);
    }
  },
  (error) => {
    if (loading) {
      loading.close();
    }
    console.log(error);
    if (error.response) {
      switch (error.response.data.code) {
        case 401:
          // 返回401 清除token信息并跳转到登陆页面
          break;
        case 403:
          // 返回403 清除token信息并跳转到登陆页面
          resetMessage.error("token过期");
          break;
        case 404:
          resetMessage.error("网络请求不存在");
          break;
        default:
          // 统一错误提示弹窗
          resetMessage.error(error.response?.data?.msg || "网络请求错误");
      }
    } else {
      // 请求超时或者网络有问题
      if (error.message.includes("timeout")) {
        resetMessage.error("请求超时！请检查网络是否正常");
      } else {
        resetMessage.error("请求失败，请检查网络是否已连接");
      }
    }
    return Promise.reject(error);
  }
);

export default $axios;

function handleAuthorized() {
  MessageBox.alert("登录超时,请重新登录!", "提示", {
    confirmButtonText: "重新登录",
    callback: (action) => {
      window.$mmc_stl.app.$emit("tokenInvalid");
    },
  });
}
