import axios, {
  type AxiosResponse,
  type AxiosInstance,
  type InternalAxiosRequestConfig,
  type AxiosRequestConfig,
} from "axios";
import { AGENT_ID } from "../common/config";
import storage, { actions } from "./storage";
import { toast } from "./toast";
import ToolsBase from "@/socket/tools/ToolsBase.js";

const toolsBase = new ToolsBase();
import { useUserStoreWithOut } from "@/stores/modules/user";
import { useGameStoreWithOut } from "@/stores/modules/game";
import { getLocationParams } from "./index";
const getApiData = () => {
  let url = import.meta.env.VITE_APP_BASE_URL;
  let data = {};
  return fetch(url)
    .then((response) => {
      if (!response.ok) {
        throw new Error("Network response was not ok " + response.statusText);
      }
      return response.text();
    })
    .then((responseData) => {
      data = responseData;
      const apiData = toolsBase.deData(data);
      console.log(apiData);
      
      storage.setSessionStorage(actions.API_BASE_URL, JSON.stringify(apiData.center));
    })
    .catch((error) => {
      console.error(
        "There has been a problem with your fetch operation:",
        error
      );
    });
};
const reg = /^[0-9]+.?[0-9]*$/;
// 定义axios实例对象的接口，包括自定义参数
interface CustomAxiosInstance extends AxiosInstance {
  currentURLIndex: Number;
}

// 创建带有自定义参数的axios实例对象
export const instance: CustomAxiosInstance = axios.create({
  baseURL: "",
  timeout: 10000,
  headers: { "content-type": "application/x-www-form-urlencoded", lang: "pt" },
  currentURLIndex: 0,
});

instance.interceptors.request.use(
  async (config: InternalAxiosRequestConfig) => {
    if (!storage.getSessionStorage(actions.API_BASE_URL)) {
      await getApiData(); // 只有在 API_BASE_URL 不存在时才执行 getApiData
    }
    // 继续执行请求前的逻辑 API_BASE_IMG_URL
    config.baseURL = JSON.parse(storage.getSessionStorage(actions.API_BASE_URL) || "")[
      config.currentURLIndex
    ];
    const token = storage.getStorage(actions.USER_TOEKN);
    let lp = getLocationParams(window.window.location.href);
    if (lp.a && reg.test(lp.a)) {
      config.headers.agentId = lp.a;
    } else {
      config.headers.agentId = AGENT_ID;
    }
    if (token) {
      config.headers.token = token;
    }
    if (
      config.url.includes("mobileLogin") ||
      config.url.includes("mobileReg")
    ) {
      return config;
    }
    return config;
  },
  (error: any) => {
    return Promise.reject(error);
  }
);
instance.interceptors.response.use(
  (response: AxiosResponse) => {
    if (response.data.code !== 0) {
      if (!import.meta.env.VITE_OPEN_CONSOLE) {
        toast(`request error !,url:${response.config.url}`);
      }
    }
    if (response.data.code == 107) {
      storage.clearStorage();
      useUserStoreWithOut().clearUser();
      useGameStoreWithOut().clearGameUrl();
    }
    let newArr = JSON.parse(storage.getSessionStorage(actions.API_BASE_URL) || "");
    [newArr[0],newArr[response.config.currentURLIndex]] = [newArr[response.config.currentURLIndex],newArr[0]]
    storage.setSessionStorage(actions.API_BASE_URL, JSON.stringify(newArr));
    return response.data;
  },
  (error) => {
    if (error.response?.data.code == 107) {
      storage.clearStorage();
      useUserStoreWithOut().clearUser();
      useGameStoreWithOut().clearGameUrl();
    }
    const apiBaseURLArray = JSON.parse(
      storage.getSessionStorage(actions.API_BASE_URL) || ""
    );
    if (error.config.currentURLIndex < apiBaseURLArray.length - 1) {
      instance.defaults.baseURL =
        apiBaseURLArray[error.config.currentURLIndex + 1];
      error.config.currentURLIndex += 1;
      return instance.request(error.config);
    } else {
      return Promise.reject(error);
    }
  }
);
export function get<T>(
  url: string,
  params?: CustomObject,
  config?: AxiosRequestConfig
): Promise<ResultData> {
  return instance.get(url, { params, ...config });
}

export function post<T>(
  url: string,
  data?: CustomObject,
  config?: AxiosRequestConfig
): Promise<ResultData> {
  return instance.post(url, data, config);
}

export function put<T>(
  url: string,
  params?: CustomObject,
  config?: AxiosRequestConfig
): Promise<ResultData> {
  return instance.put(url, params, config);
}
