import axios, { AxiosInstance, AxiosError, AxiosRequestConfig, InternalAxiosRequestConfig, AxiosResponse } from "axios";
import { showFullScreenLoading, tryHideFullScreenLoading } from "@/components/Loading/fullScreen";
import { LOGIN_URL } from "@/config";
import { ElMessage } from "element-plus";
import { ResultData } from "@/api/interface";
import { ResultEnum } from "@/enums/httpEnum";
import { checkStatus } from "./helper/checkStatus";
import { AxiosCanceler } from "./helper/axiosCancel";
import { useUserStore } from "@/stores/modules/user";
import { localGet } from "@/utils";
import router from "@/routers";
import { cryptoUtil } from "@/utils/crypto";
import { cryptoStrategy } from "@/utils/cryptoStrategy";

export interface CustomAxiosRequestConfig extends InternalAxiosRequestConfig {
  loading?: boolean;
  cancel?: boolean;
  encrypt?: boolean; // 是否加密请求参数
}

const config = {
  // 默认地址请求地址，可在 .env.** 文件中修改
  baseURL: import.meta.env.VITE_API_URL_PLATFORM as string,
  // 设置超时时间
  timeout: ResultEnum.TIMEOUT as number,
  // 跨域时候允许携带凭证
  withCredentials: true
};

const axiosCanceler = new AxiosCanceler();

class RequestHttp {
  service: AxiosInstance;
  public constructor(config: AxiosRequestConfig) {
    // instantiation
    this.service = axios.create(config);

    /**
     * @description 请求拦截器
     * 客户端发送请求 -> [请求拦截器] -> 服务器
     * token校验(JWT) : 接受服务器返回的 token,存储到 vuex/pinia/本地储存当中
     */
    this.service.interceptors.request.use(
      (config: CustomAxiosRequestConfig) => {
        const userStore = useUserStore();
        // 重复请求不需要取消，在 api 服务中通过指定的第三个参数: { cancel: false } 来控制
        config.cancel ??= true;
        config.cancel && axiosCanceler.addPending(config);
        // 当前请求不需要显示 loading，在 api 服务中通过指定的第三个参数: { loading: false } 来控制
        config.loading ??= true;
        config.loading && showFullScreenLoading();
        if (config.headers && typeof config.headers.set === "function") {
          config.headers.set("Authorization", userStore.token);
        }

        // 加密处理
        if (cryptoStrategy.shouldEncrypt(config) && config.data) {
          try {
            config.data = cryptoUtil.encrypt(config.data);
          } catch (error) {
            return Promise.reject(error);
          }
        }

        return config;
      },
      (error: AxiosError) => {
        return Promise.reject(error);
      }
    );

    /**
     * @description 响应拦截器
     *  服务器换返回信息 -> [拦截统一处理] -> 客户端JS获取到信息
     */
    this.service.interceptors.response.use(
      (response: AxiosResponse & { config: CustomAxiosRequestConfig }) => {
        const { data, config, headers } = response;

        const userStore = useUserStore();
        axiosCanceler.removePending(config);
        config.loading && tryHideFullScreenLoading();

        // 解密处理
        if (cryptoStrategy.shouldDecrypt(config, headers, data)) {
          try {
            const decryptedData = cryptoUtil.decrypt(data);
            response.data = decryptedData;
          } catch (error) {
            console.error("解密失败:", error);
            ElMessage.error("响应数据解密失败");
            return Promise.reject(new Error("响应数据解密失败"));
          }
        }

        const processedData = response.data;

        // 登录失效
        if (processedData.code == ResultEnum.OVERDUE) {
          userStore.setToken("");
          router.replace(LOGIN_URL);
          ElMessage.error(processedData.msg);
          return Promise.reject(processedData);
        }
        // 全局错误信息拦截（防止下载文件的时候返回数据流，没有 code 直接报错）
        if (processedData.code && processedData.code !== ResultEnum.SUCCESS) {
          ElMessage.error(processedData.msg);
          return Promise.reject(processedData);
        }
        // 成功请求（在页面上除非特殊情况，否则不用处理失败逻辑）
        return processedData;
      },
      async (error: AxiosError) => {
        const { response } = error;
        tryHideFullScreenLoading();
        // 请求超时 && 网络错误单独判断，没有 response
        if (error.message.indexOf("timeout") !== -1) ElMessage.error("请求超时！请您稍后重试");
        if (error.message.indexOf("Network Error") !== -1) ElMessage.error("网络错误！请您稍后重试");
        // 根据服务器响应的错误状态码，做不同的处理
        if (response.data.message) {
          ElMessage.error(response.data.message);
        } else {
          if (response) checkStatus(response.status);
        }
        // 服务器结果都没有返回(可能服务器错误可能客户端断网)，断网处理:可以跳转到断网页面
        if (!window.navigator.onLine) router.replace("/500");
        return Promise.reject(error);
      }
    );
  }
  /**
   * @description 常用请求方法封装
   */
  get<T>(url: string, params?: object, _object = {}): Promise<ResultData<T>> {
    return this.service.get(url, { params, ..._object });
  }
  post<T>(url: string, params?: object | string, _object = {}): Promise<ResultData<T>> {
    console.log(config.baseURL, url, params);
    return this.service.post(url, params, _object);
  }
  put<T>(url: string, params?: object, _object = {}): Promise<ResultData<T>> {
    return this.service.put(url, params, _object);
  }
  delete<T>(url: string, params?: any, _object = {}): Promise<ResultData<T>> {
    return this.service.delete(url, { params, ..._object });
  }
  download(url: string, params?: object, _object = {}): Promise<BlobPart> {
    return this.service.post(url, params, { ..._object, responseType: "blob" });
  }

  /**
   * @description 文件上传方法（基于 XMLHttpRequest）
   * @param url 上传地址
   * @param formData FormData 对象
   * @param onProgress 上传进度回调函数 (progress: number) => void
   * @param baseURL 可选的基础URL，不传则使用默认baseURL
   * @returns Promise<ResultData<T>>
   */
  upload<T = any>(
    url: string,
    formData: FormData,
    onProgress?: (progress: number) => void,
    baseURL?: string
  ): Promise<ResultData<T>> {
    return new Promise((resolve, reject) => {
      const xhr = new XMLHttpRequest();
      const userStore = useUserStore();
      // 如果传入了 baseURL，使用传入的 baseURL；如果 URL 是完整 URL（以 http 开头），直接使用；否则使用默认 baseURL
      const fullUrl = baseURL ? `${baseURL}${url}` : url.startsWith("http") ? url : `${config.baseURL}${url}`;

      // 监听上传进度
      if (onProgress) {
        xhr.upload.addEventListener("progress", e => {
          if (e.lengthComputable) {
            const percentComplete = Math.round((e.loaded / e.total) * 100);
            onProgress(percentComplete);
          }
        });
      }

      // 监听请求完成
      xhr.addEventListener("load", () => {
        if (xhr.status >= 200 && xhr.status < 300) {
          try {
            const response = JSON.parse(xhr.responseText);
            // 统一处理响应，与 axios 拦截器保持一致
            if (response.code == ResultEnum.OVERDUE) {
              userStore.setToken("");
              router.replace(LOGIN_URL);
              ElMessage.error(response.msg);
              reject(response);
              return;
            }
            if (response.code && response.code !== ResultEnum.SUCCESS) {
              ElMessage.error(response.msg);
              reject(response);
              return;
            }
            resolve(response);
          } catch (error) {
            reject(new Error("响应解析失败"));
          }
        } else {
          const errorMsg = `上传失败: ${xhr.status} ${xhr.statusText}`;
          ElMessage.error(errorMsg);
          reject(new Error(errorMsg));
        }
      });

      // 监听请求错误
      xhr.addEventListener("error", () => {
        const errorMsg = "网络错误！请您稍后重试";
        ElMessage.error(errorMsg);
        reject(new Error(errorMsg));
      });

      // 监听请求中止
      xhr.addEventListener("abort", () => {
        reject(new Error("上传已取消"));
      });

      // 打开请求
      xhr.open("POST", fullUrl, true);

      // 设置请求头
      const token = userStore.token || localGet("geeker-user")?.token;
      if (token) {
        xhr.setRequestHeader("Authorization", token);
      }

      // 设置超时
      xhr.timeout = config.timeout;
      xhr.addEventListener("timeout", () => {
        const errorMsg = "请求超时！请您稍后重试";
        ElMessage.error(errorMsg);
        reject(new Error(errorMsg));
      });

      // 发送请求
      xhr.withCredentials = config.withCredentials;
      xhr.send(formData);
    });
  }
}

export default new RequestHttp(config);
