"use strict";
const common_vendor = require("../common/vendor.js");
const api_config = require("./config.js");
const requestQueue = [];
let isRefreshing = false;
class Request {
  constructor() {
    this.baseURL = api_config.config.baseURL;
    this.timeout = api_config.config.timeout;
    this.interceptors = {
      request: [],
      response: []
    };
  }
  // 添加请求拦截器
  addRequestInterceptor(interceptor) {
    this.interceptors.request.push(interceptor);
  }
  // 添加响应拦截器
  addResponseInterceptor(interceptor) {
    this.interceptors.response.push(interceptor);
  }
  // 执行请求拦截器
  async runRequestInterceptors(config) {
    for (const interceptor of this.interceptors.request) {
      config = await interceptor(config);
    }
    return config;
  }
  // 执行响应拦截器
  async runResponseInterceptors(response) {
    for (const interceptor of this.interceptors.response) {
      response = await interceptor(response);
    }
    return response;
  }
  // 核心请求方法
  async request(options) {
    try {
      const requestConfig = {
        url: options.url.startsWith("http") ? options.url : `${this.baseURL}${options.url}`,
        method: options.method || "GET",
        header: {
          "Content-Type": "application/json",
          ...options.header
        },
        data: options.data,
        timeout: this.timeout
      };
      const finalConfig = await this.runRequestInterceptors(requestConfig);
      const response = await common_vendor.index.request(finalConfig);
      const finalResponse = await this.runResponseInterceptors(response);
      return finalResponse[1];
    } catch (error) {
      common_vendor.index.__f__("error", "at api/request.js:69", "Request error:", error);
      throw error;
    }
  }
  // GET请求
  get(url, data = {}, options = {}) {
    return this.request({
      url,
      method: "GET",
      data,
      ...options
    });
  }
  // POST请求
  post(url, data = {}, options = {}) {
    return this.request({
      url,
      method: "POST",
      data,
      ...options
    });
  }
  // PUT请求
  put(url, data = {}, options = {}) {
    return this.request({
      url,
      method: "PUT",
      data,
      ...options
    });
  }
  // DELETE请求
  delete(url, data = {}, options = {}) {
    return this.request({
      url,
      method: "DELETE",
      data,
      ...options
    });
  }
  // 上传文件
  upload(url, filePath, formData = {}, options = {}) {
    return new Promise((resolve, reject) => {
      common_vendor.index.uploadFile({
        url: `${this.baseURL}${url}`,
        filePath,
        name: "file",
        formData,
        success: resolve,
        fail: reject,
        ...options
      });
    });
  }
  // 下载文件
  download(url, options = {}) {
    return new Promise((resolve, reject) => {
      common_vendor.index.downloadFile({
        url: `${this.baseURL}${url}`,
        success: resolve,
        fail: reject,
        ...options
      });
    });
  }
}
const request = new Request();
request.addRequestInterceptor(async (config) => {
  const token = common_vendor.index.getStorageSync("token");
  if (token) {
    config.header.Authorization = `Bearer ${token}`;
  }
  return config;
});
request.addResponseInterceptor(async (response) => {
  const { statusCode, data } = response;
  if (statusCode === 200) {
    if (data.code === 0) {
      return data.data;
    } else {
      const error = new Error(data.message || "业务错误");
      error.code = data.code;
      throw error;
    }
  } else if (statusCode === 401) {
    return handleTokenExpired(response);
  } else {
    throw new Error(`网络错误: ${statusCode}`);
  }
});
async function handleTokenExpired(response) {
  if (isRefreshing) {
    return new Promise((resolve) => {
      requestQueue.push(() => resolve(request.request(response.config)));
    });
  }
  isRefreshing = true;
  const refreshToken = common_vendor.index.getStorageSync("refreshToken");
  if (!refreshToken) {
    common_vendor.index.navigateTo({ url: "/pages/auth/login" });
    throw new Error("请重新登录");
  }
  try {
    const result = await request.post(api_config.config.endpoints.USER.REFRESH_TOKEN, {
      refreshToken
    });
    common_vendor.index.setStorageSync("token", result.token);
    common_vendor.index.setStorageSync("refreshToken", result.refreshToken);
    const retryResponse = await request.request(response.config);
    processRequestQueue();
    return retryResponse;
  } catch (error) {
    common_vendor.index.removeStorageSync("token");
    common_vendor.index.removeStorageSync("refreshToken");
    common_vendor.index.navigateTo({ url: "/pages/auth/login" });
    throw error;
  } finally {
    isRefreshing = false;
  }
}
function processRequestQueue() {
  while (requestQueue.length > 0) {
    const retry = requestQueue.shift();
    retry();
  }
}
exports.request = request;
//# sourceMappingURL=../../.sourcemap/mp-weixin/api/request.js.map
